diff --git a/.golangci.yml b/.golangci.yml index c16c4b1..db4e5e6 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -14,6 +14,7 @@ run: skip-dirs: - (^|/)vendor($|/) + - (^|/)test($|/) skip-files: - .*_test.go diff --git a/delivery/http_server/admin/admin/get_all_agent.go b/delivery/http_server/admin/admin/get_all_agent.go index 1cedf42..5d058dd 100644 --- a/delivery/http_server/admin/admin/get_all_agent.go +++ b/delivery/http_server/admin/admin/get_all_agent.go @@ -15,7 +15,7 @@ import ( // @Success 200 {object} adminserviceparam.GetAllAgentResponse // @Failure 400 {string} "Bad request" // @Security AuthBearerAdmin -// @Router /admins/agents [get] +// @Router /admins/agents [get]. func (h Handler) GetAllAgent(c echo.Context) error { resp, sErr := h.adminSvc.GetAllAgent(c.Request().Context()) if sErr != nil { diff --git a/delivery/http_server/admin/kind_box_req/deliver.go b/delivery/http_server/admin/kind_box_req/deliver.go index d8460ae..e0b2a4b 100644 --- a/delivery/http_server/admin/kind_box_req/deliver.go +++ b/delivery/http_server/admin/kind_box_req/deliver.go @@ -2,12 +2,13 @@ package adminkindboxreqhandler import ( "context" + "net/http" + param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg" querier "git.gocasts.ir/ebhomengo/niki/pkg/query_transaction/sql" echo "github.com/labstack/echo/v4" - "net/http" ) // Deliver godoc @@ -53,5 +54,6 @@ func (h Handler) Deliver(c echo.Context) error { if cErr != nil { return echo.NewHTTPError(http.StatusInternalServerError, errmsg.ErrorMsgSomethingWentWrong) } + return c.JSON(http.StatusOK, resp) } diff --git a/delivery/http_server/admin/kind_box_req/get.go b/delivery/http_server/admin/kind_box_req/get.go index 9b707d9..3b07f5d 100644 --- a/delivery/http_server/admin/kind_box_req/get.go +++ b/delivery/http_server/admin/kind_box_req/get.go @@ -21,7 +21,7 @@ import ( // @Failure 422 {object} httpmsg.ErrorResponse // @Failure 500 {string} "something went wrong" // @Security AuthBearerAdmin -// @Router /admins/kindboxreqs/{id} [get] +// @Router /admins/kindboxreqs/{id} [get]. func (h Handler) Get(c echo.Context) error { var req param.GetKindBoxReqRequest if err := c.Bind(&req); err != nil { diff --git a/delivery/http_server/admin/kind_box_req/get_all.go b/delivery/http_server/admin/kind_box_req/get_all.go index 59667d1..64074e0 100644 --- a/delivery/http_server/admin/kind_box_req/get_all.go +++ b/delivery/http_server/admin/kind_box_req/get_all.go @@ -1,11 +1,12 @@ package adminkindboxreqhandler import ( + "net/http" + param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req" httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg" queryparam "git.gocasts.ir/ebhomengo/niki/pkg/query_param" echo "github.com/labstack/echo/v4" - "net/http" ) // GetAll godoc diff --git a/delivery/http_server/admin/kind_box_req/get_all_delivery_awaiting.go b/delivery/http_server/admin/kind_box_req/get_all_delivery_awaiting.go index 5b4f803..7bff6c7 100644 --- a/delivery/http_server/admin/kind_box_req/get_all_delivery_awaiting.go +++ b/delivery/http_server/admin/kind_box_req/get_all_delivery_awaiting.go @@ -1,11 +1,11 @@ package adminkindboxreqhandler import ( - "git.gocasts.ir/ebhomengo/niki/entity" - "git.gocasts.ir/ebhomengo/niki/pkg/claim" "net/http" + "git.gocasts.ir/ebhomengo/niki/entity" param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req" + "git.gocasts.ir/ebhomengo/niki/pkg/claim" httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg" queryparam "git.gocasts.ir/ebhomengo/niki/pkg/query_param" "github.com/labstack/echo/v4" @@ -32,12 +32,11 @@ import ( // @Success 200 {object} param.DeliveryAwaitingGetAllResponse // @Failure 400 {string} "Bad request" // @Security AuthBearerAdmin -// @Router /admin/kindboxreqs/awaiting-delivery [get] +// @Router /admin/kindboxreqs/awaiting-delivery [get]. func (h Handler) GetAllAwaitingDelivery(c echo.Context) error { var req param.DeliveryAwaitingGetAllRequest if bErr := c.Bind(&req); bErr != nil { - return echo.NewHTTPError(http.StatusBadRequest) } diff --git a/delivery/http_server/admin/kind_box_req/get_delivery_awaiting.go b/delivery/http_server/admin/kind_box_req/get_delivery_awaiting.go index 5c00947..6586aa0 100644 --- a/delivery/http_server/admin/kind_box_req/get_delivery_awaiting.go +++ b/delivery/http_server/admin/kind_box_req/get_delivery_awaiting.go @@ -18,11 +18,10 @@ import ( // @Success 200 {object} param.DeliveryAwaitingGetResponse // @Failure 400 {string} "Bad request" // @Security AuthBearerAdmin -// @Router /admin/kindboxreqs/awaiting-delivery/{id} [get] +// @Router /admin/kindboxreqs/awaiting-delivery/{id} [get]. func (h Handler) GetAwaitingDelivery(c echo.Context) error { var req param.DeliveryAwaitingGetRequest if bErr := c.Bind(&req); bErr != nil { - return echo.NewHTTPError(http.StatusBadRequest) } diff --git a/delivery/http_server/admin/kind_box_req/route.go b/delivery/http_server/admin/kind_box_req/route.go index 8ecb4f9..fcde626 100644 --- a/delivery/http_server/admin/kind_box_req/route.go +++ b/delivery/http_server/admin/kind_box_req/route.go @@ -20,5 +20,4 @@ func (h Handler) SetRoutes(e *echo.Echo) { r.GET("/awaiting-delivery", h.GetAllAwaitingDelivery, middleware.AdminAuthorization(h.adminAuthorizeSvc, entity.AdminKindBoxReqGetAwaitingDeliveryPermission)) r.PUT("/:id", h.Update, middleware.AdminAuthorization(h.adminAuthorizeSvc, entity.AdminKindBoxReqUpdatePermission)) r.GET("/:id", h.Get, middleware.AdminAuthorization(h.adminAuthorizeSvc, entity.AdminKindBoxReqGetPermission)) - } diff --git a/delivery/http_server/admin/kind_box_req/update.go b/delivery/http_server/admin/kind_box_req/update.go index 6a0b493..98b8ba4 100644 --- a/delivery/http_server/admin/kind_box_req/update.go +++ b/delivery/http_server/admin/kind_box_req/update.go @@ -1,10 +1,11 @@ package adminkindboxreqhandler import ( + "net/http" + param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req" httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg" "github.com/labstack/echo/v4" - "net/http" ) // Update godoc diff --git a/delivery/http_server/agent/kind_box/get.go b/delivery/http_server/agent/kind_box/get.go index 6d21ef9..65f6ae7 100644 --- a/delivery/http_server/agent/kind_box/get.go +++ b/delivery/http_server/agent/kind_box/get.go @@ -22,7 +22,7 @@ import ( // @Failure 422 {object} httpmsg.ErrorResponse // @Failure 500 {string} "something went wrong" // @Security AuthBearerAdmin -// @Router /agents/kindboxes/{id} [get] +// @Router /agents/kindboxes/{id} [get]. func (h Handler) Get(c echo.Context) error { var req param.GetKindBoxRequest if bErr := c.Bind(&req); bErr != nil { diff --git a/delivery/http_server/agent/kind_box/get_all.go b/delivery/http_server/agent/kind_box/get_all.go index 9723ebe..3790c4b 100644 --- a/delivery/http_server/agent/kind_box/get_all.go +++ b/delivery/http_server/agent/kind_box/get_all.go @@ -1,11 +1,11 @@ package agentkindboxhandler import ( - "git.gocasts.ir/ebhomengo/niki/entity" - "git.gocasts.ir/ebhomengo/niki/pkg/claim" "net/http" + "git.gocasts.ir/ebhomengo/niki/entity" param "git.gocasts.ir/ebhomengo/niki/param/agent/kind_box" + "git.gocasts.ir/ebhomengo/niki/pkg/claim" httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg" queryparam "git.gocasts.ir/ebhomengo/niki/pkg/query_param" "github.com/labstack/echo/v4" @@ -35,7 +35,7 @@ import ( // @Failure 422 {object} httpmsg.ErrorResponse // @Failure 500 {string} "something went wrong" // @Security AuthBearerAdmin -// @Router /agents/kindboxes [get] +// @Router /agents/kindboxes [get]. func (h Handler) GetAll(c echo.Context) error { var req param.GetAllRequest diff --git a/delivery/http_server/agent/kind_box/return.go b/delivery/http_server/agent/kind_box/return.go index 746227f..14542e7 100644 --- a/delivery/http_server/agent/kind_box/return.go +++ b/delivery/http_server/agent/kind_box/return.go @@ -1,11 +1,12 @@ package agentkindboxhandler import ( + "net/http" + param "git.gocasts.ir/ebhomengo/niki/param/agent/kind_box" "git.gocasts.ir/ebhomengo/niki/pkg/claim" httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg" echo "github.com/labstack/echo/v4" - "net/http" ) // Return godoc @@ -42,7 +43,6 @@ func (h Handler) Return(c echo.Context) error { } err := h.agentKindBoxSvc.Return(c.Request().Context(), req) - if err != nil { msg, code := httpmsg.Error(err) diff --git a/delivery/http_server/benefactor/address/delete.go b/delivery/http_server/benefactor/address/delete.go index 95111bd..5862d43 100644 --- a/delivery/http_server/benefactor/address/delete.go +++ b/delivery/http_server/benefactor/address/delete.go @@ -17,12 +17,11 @@ import ( // @Success 204 // @Failure 400 {string} "Bad request" // @Security AuthBearerBenefactor -// @Router /address/{id} [delete] +// @Router /address/{id} [delete]. func (h Handler) DeleteAddress(c echo.Context) error { var req param.DeleteAddressRequest if bErr := echo.PathParamsBinder(c).Uint("id", &req.AddressID).BindError(); bErr != nil { - return echo.NewHTTPError(http.StatusBadRequest) } claims := claim.GetClaimsFromEchoContext(c) diff --git a/delivery/http_server/benefactor/address/update.go b/delivery/http_server/benefactor/address/update.go index 3d7b338..7fff73d 100644 --- a/delivery/http_server/benefactor/address/update.go +++ b/delivery/http_server/benefactor/address/update.go @@ -19,16 +19,14 @@ import ( // @Success 204 // @Failure 400 {string} "Bad request" // @Security AuthBearerBenefactor -// @Router /address/{id} [patch] +// @Router /address/{id} [patch]. func (h Handler) UpdateAddress(c echo.Context) error { var req param.UpdateAddressRequest if bErr := c.Bind(&req); bErr != nil { - return echo.NewHTTPError(http.StatusBadRequest) } if bErr := echo.PathParamsBinder(c).Uint("id", &req.ID).BindError(); bErr != nil { - return echo.NewHTTPError(http.StatusBadRequest) } diff --git a/delivery/http_server/benefactor/kind_box/get_all.go b/delivery/http_server/benefactor/kind_box/get_all.go index 5f84056..7f923df 100644 --- a/delivery/http_server/benefactor/kind_box/get_all.go +++ b/delivery/http_server/benefactor/kind_box/get_all.go @@ -1,10 +1,10 @@ package benefactorkindboxhandler import ( - "git.gocasts.ir/ebhomengo/niki/pkg/claim" "net/http" param "git.gocasts.ir/ebhomengo/niki/param/benefactor/kind_box" + "git.gocasts.ir/ebhomengo/niki/pkg/claim" httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg" queryparam "git.gocasts.ir/ebhomengo/niki/pkg/query_param" "github.com/labstack/echo/v4" diff --git a/delivery/http_server/benefactor/kind_box_req/add.go b/delivery/http_server/benefactor/kind_box_req/add.go index 3fed6f8..2d32ee6 100644 --- a/delivery/http_server/benefactor/kind_box_req/add.go +++ b/delivery/http_server/benefactor/kind_box_req/add.go @@ -1,12 +1,13 @@ package benefactorkindboxreqhandler import ( + "net/http" + param "git.gocasts.ir/ebhomengo/niki/param/benefactor/kind_box_req" "git.gocasts.ir/ebhomengo/niki/pkg/claim" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg" echo "github.com/labstack/echo/v4" - "net/http" ) // Add godoc diff --git a/delivery/http_server/benefactor/kind_box_req/get_all.go b/delivery/http_server/benefactor/kind_box_req/get_all.go index e0c3d0d..bb419db 100644 --- a/delivery/http_server/benefactor/kind_box_req/get_all.go +++ b/delivery/http_server/benefactor/kind_box_req/get_all.go @@ -1,12 +1,13 @@ package benefactorkindboxreqhandler import ( + "net/http" + param "git.gocasts.ir/ebhomengo/niki/param/benefactor/kind_box_req" "git.gocasts.ir/ebhomengo/niki/pkg/claim" httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg" queryparam "git.gocasts.ir/ebhomengo/niki/pkg/query_param" "github.com/labstack/echo/v4" - "net/http" ) // GetAll godoc @@ -31,12 +32,11 @@ import ( // @Success 200 {object} param.GetAllResponse // @Failure 400 {string} "Bad request" // @Security AuthBearerBenefactor -// @Router /benefactor/kindboxreqs/ [get] +// @Router /benefactor/kindboxreqs/ [get]. func (h Handler) GetAll(c echo.Context) error { var req param.GetAllRequest if bErr := c.Bind(&req); bErr != nil { - return echo.NewHTTPError(http.StatusBadRequest) } diff --git a/delivery/http_server/benefactor/kind_box_req/update.go b/delivery/http_server/benefactor/kind_box_req/update.go index 65cec5f..34e9290 100644 --- a/delivery/http_server/benefactor/kind_box_req/update.go +++ b/delivery/http_server/benefactor/kind_box_req/update.go @@ -1,11 +1,12 @@ package benefactorkindboxreqhandler import ( - param "git.gocasts.ir/ebhomengo/niki/param/benefactor/kind_box_req" - httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg" - "git.gocasts.ir/ebhomengo/niki/pkg/claim" - "github.com/labstack/echo/v4" "net/http" + + param "git.gocasts.ir/ebhomengo/niki/param/benefactor/kind_box_req" + "git.gocasts.ir/ebhomengo/niki/pkg/claim" + httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg" + "github.com/labstack/echo/v4" ) // Update godoc @@ -22,9 +23,8 @@ import ( // @Failure 422 {object} httpmsg.ErrorResponse // @Failure 500 {string} "something went wrong" // @Security AuthBearerBenefactor -// @Router /benefactor/kindboxreqs/{id} [put] +// @Router /benefactor/kindboxreqs/{id} [put]. func (h Handler) Update(c echo.Context) error { - var req param.KindBoxReqUpdateRequest if bErr := c.Bind(&req); bErr != nil { return echo.NewHTTPError(http.StatusBadRequest) diff --git a/delivery/http_server/server.go b/delivery/http_server/server.go index 77291fc..82c407f 100644 --- a/delivery/http_server/server.go +++ b/delivery/http_server/server.go @@ -2,10 +2,8 @@ package httpserver import ( "fmt" - agentkindboxservice "git.gocasts.ir/ebhomengo/niki/service/agent/kind_box" - agentkindboxvalidator "git.gocasts.ir/ebhomengo/niki/validator/agent/kind_box" - config "git.gocasts.ir/ebhomengo/niki/config" + "git.gocasts.ir/ebhomengo/niki/config" adminhandler "git.gocasts.ir/ebhomengo/niki/delivery/http_server/admin/admin" adminKindBoxHandler "git.gocasts.ir/ebhomengo/niki/delivery/http_server/admin/kind_box" adminkindboxreqhandler "git.gocasts.ir/ebhomengo/niki/delivery/http_server/admin/kind_box_req" @@ -19,6 +17,7 @@ import ( adminauthorizationservice "git.gocasts.ir/ebhomengo/niki/service/admin/authorization" adminkindboxservice "git.gocasts.ir/ebhomengo/niki/service/admin/kind_box" adminkindboxreqservice "git.gocasts.ir/ebhomengo/niki/service/admin/kind_box_req" + agentkindboxservice "git.gocasts.ir/ebhomengo/niki/service/agent/kind_box" authservice "git.gocasts.ir/ebhomengo/niki/service/auth" benefactoraddressservice "git.gocasts.ir/ebhomengo/niki/service/benefactor/address" benefactorservice "git.gocasts.ir/ebhomengo/niki/service/benefactor/benefactor" @@ -27,6 +26,7 @@ import ( adminvalidator "git.gocasts.ir/ebhomengo/niki/validator/admin/admin" adminkindboxvalidator "git.gocasts.ir/ebhomengo/niki/validator/admin/kind_box" adminkindboxreqvalidator "git.gocasts.ir/ebhomengo/niki/validator/admin/kind_box_req" + agentkindboxvalidator "git.gocasts.ir/ebhomengo/niki/validator/agent/kind_box" benefactoraddressvalidator "git.gocasts.ir/ebhomengo/niki/validator/benefactor/address" benefactorvalidator "git.gocasts.ir/ebhomengo/niki/validator/benefactor/benefactor" benefactorkindboxvalidator "git.gocasts.ir/ebhomengo/niki/validator/benefactor/kind_box" @@ -109,13 +109,12 @@ func (s Server) Serve() { } } -func RegisterSwagger(s *echo.Echo, config config.Config) { +func RegisterSwagger(s *echo.Echo, c config.Config) { // TODO: move this to a better place and make it more dynamic and configurable docs.SwaggerInfo.Title = "NIKI API" docs.SwaggerInfo.Description = "This is the API documentation for the NIKI project" docs.SwaggerInfo.Version = "1.0.0" - // docs.SwaggerInfo.BasePath = "/api/v1" - docs.SwaggerInfo.Host = fmt.Sprintf("localhost:%d", config.HTTPServer.Port) + docs.SwaggerInfo.Host = fmt.Sprintf("localhost:%d", c.HTTPServer.Port) s.GET("/swagger/*any", echoSwagger.WrapHandler) } diff --git a/internal/initial/service.go b/internal/initial/service.go index 5c8504b..91b6ff0 100644 --- a/internal/initial/service.go +++ b/internal/initial/service.go @@ -42,6 +42,7 @@ func initSms(cfg config.Config) *kavenegarotp.Adapter { func InitAdminService(cfg config.Config, db *mysql.DB) adminservice.Service { return adminservice.New(InitAdminMysql(db), InitAdminAuthService(cfg)) } + func InitBenefactorForAdminService(db *mysql.DB) benefactorforadminservice.Service { return benefactorforadminservice.New(InitAdminMysql(db)) } diff --git a/main.go b/main.go index 3b69adb..da75bd2 100644 --- a/main.go +++ b/main.go @@ -2,6 +2,8 @@ package main import ( "flag" + "fmt" + "git.gocasts.ir/ebhomengo/niki/adapter/redis" "git.gocasts.ir/ebhomengo/niki/config" httpserver "git.gocasts.ir/ebhomengo/niki/delivery/http_server" @@ -22,6 +24,7 @@ type Dependencies struct { func parseFlags() bool { migrateFlag := flag.Bool("migrate", false, "perform database migration") flag.Parse() + return *migrateFlag } @@ -32,13 +35,17 @@ func parseFlags() bool { // @securityDefinitions.apikey AuthBearerAdmin // @in header // @name Authorization -// @description Type the word 'Bearer' followed by a space and Admin JWT token +// @description Type the word 'Bearer' followed by a space and Admin JWT token. func main() { migrate := parseFlags() cfg := config.C() db := initDatabase(cfg, migrate) - defer db.CloseStatements() + defer func() { + if err := db.CloseStatements(); err != nil { + fmt.Printf("Error closing statements: %v\n", err) + } + }() redisAdapter := initRedis(cfg) dependencies := initDependencies(cfg, redisAdapter, db) diff --git a/param/benefactor/kind_box_req/add.go b/param/benefactor/kind_box_req/add.go index 06f0772..05e41dd 100644 --- a/param/benefactor/kind_box_req/add.go +++ b/param/benefactor/kind_box_req/add.go @@ -1,8 +1,9 @@ package benefactorkindboxreqparam import ( - entity "git.gocasts.ir/ebhomengo/niki/entity" "time" + + entity "git.gocasts.ir/ebhomengo/niki/entity" ) type KindBoxReqAddRequest struct { diff --git a/param/benefactor/kind_box_req/update.go b/param/benefactor/kind_box_req/update.go index 33a6d89..af62620 100644 --- a/param/benefactor/kind_box_req/update.go +++ b/param/benefactor/kind_box_req/update.go @@ -7,8 +7,8 @@ import ( ) type KindBoxReqUpdateRequest struct { - KindBoxReqID uint `json:"-" param:"id" example:"1"` - BenefactorID uint `json:"-" example: "1"` + KindBoxReqID uint `json:"-" param:"id" example:"1"` + BenefactorID uint `json:"-" example:"1"` KindBoxType entity.KindBoxType `json:"kind_box_type" example:"2"` CountRequested uint `json:"count_requested" example:"5"` Description string `json:"description" example:"description"` @@ -17,7 +17,4 @@ type KindBoxReqUpdateRequest struct { DeliverAddressID uint `json:"deliver_address_id" example:"1"` } - -type KindBoxReqUpdateResponse struct { - -} +type KindBoxReqUpdateResponse struct{} diff --git a/pkg/query_builder/mysql/filter.go b/pkg/query_builder/mysql/filter.go index aab04fe..a6457a9 100644 --- a/pkg/query_builder/mysql/filter.go +++ b/pkg/query_builder/mysql/filter.go @@ -2,12 +2,7 @@ package mysqlquerybuilder import "fmt" -func BuildFilterQuery(filter map[string]interface{}) (string, []any) { - var ( - filterQuery string - args = []any{} - ) - +func BuildFilterQuery(filter map[string]interface{}) (filterQuery string, args []any) { for key, value := range filter { filterQuery += fmt.Sprintf("AND %s = ? ", key) args = append(args, value) diff --git a/pkg/query_builder/mysql/get_all.go b/pkg/query_builder/mysql/get_all.go index ad3368c..0acc222 100644 --- a/pkg/query_builder/mysql/get_all.go +++ b/pkg/query_builder/mysql/get_all.go @@ -6,17 +6,15 @@ import ( "git.gocasts.ir/ebhomengo/niki/param" ) -func BuildGetAllQuery(baseQuery string, filter param.FilterRequest, pagination param.PaginationRequest, sort param.SortRequest) (string, []any) { - +func BuildGetAllQuery(baseQuery string, filter param.FilterRequest, pagination param.PaginationRequest, sort param.SortRequest) (query string, args []any) { filterQuery, fArgs := BuildFilterQuery(filter) paginationQuery, pArgs := BuildPaginationQuery(pagination) sortQuery := BuildSortQuery(sort) - args := []any{} args = append(args, fArgs...) args = append(args, pArgs...) - query := baseQuery + query = baseQuery if filterQuery != "" { query = fmt.Sprintf("%s %s", query, filterQuery) } diff --git a/pkg/query_builder/mysql/pagination.go b/pkg/query_builder/mysql/pagination.go index 0399e44..4e75ccd 100644 --- a/pkg/query_builder/mysql/pagination.go +++ b/pkg/query_builder/mysql/pagination.go @@ -4,6 +4,6 @@ import ( "git.gocasts.ir/ebhomengo/niki/param" ) -func BuildPaginationQuery(pagination param.PaginationRequest) (string, []any) { +func BuildPaginationQuery(pagination param.PaginationRequest) (query string, args []any) { return "LIMIT ? OFFSET ?", []any{pagination.GetPageSize(), pagination.GetOffset()} } diff --git a/pkg/query_builder/mysql/sort.go b/pkg/query_builder/mysql/sort.go index 6880c3b..14e1abd 100644 --- a/pkg/query_builder/mysql/sort.go +++ b/pkg/query_builder/mysql/sort.go @@ -10,5 +10,6 @@ func BuildSortQuery(sort param.SortRequest) string { if sort.Field == "" && sort.Direction == "" { return "" } + return fmt.Sprintf("ORDER BY %s %s", sort.Field, sort.Direction) } diff --git a/pkg/query_transaction/sql/querier.go b/pkg/query_transaction/sql/querier.go index a4f1163..72d40d2 100644 --- a/pkg/query_transaction/sql/querier.go +++ b/pkg/query_transaction/sql/querier.go @@ -7,9 +7,9 @@ import ( "sync/atomic" ) -const ( - QuerierContextKey = "querier" -) +type contextKey string + +const QuerierContextKey contextKey = "querier" type conn interface { Commit() error @@ -22,72 +22,82 @@ type conn interface { ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) } -type querier struct { +type Querier struct { txRequested atomic.Bool initOnce sync.Once conn conn } -func GetQuerierFromContextOrNew(ctx context.Context) *querier { - q, ok := ctx.Value(QuerierContextKey).(*querier) +func GetQuerierFromContextOrNew(ctx context.Context) *Querier { + q, ok := ctx.Value(QuerierContextKey).(*Querier) if !ok { - q = &querier{ + q = &Querier{ txRequested: atomic.Bool{}, initOnce: sync.Once{}, conn: nil, } } + return q } -func (q *querier) Begin() *querier { + +func (q *Querier) Begin() *Querier { q.txRequested.Store(true) + return q } -func (q *querier) Continue(ctx context.Context, conn *SqlDB) (*querier, error) { + +func (q *Querier) Continue(ctx context.Context, conn *SQLDB) (*Querier, error) { var iErr error q.initOnce.Do(func() { if q.txRequested.Load() { tx, bErr := conn.BeginTx(ctx, nil) if bErr != nil { iErr = bErr + return } - q.conn = &SqlTx{tx} + q.conn = &SQLTx{tx} } else { q.conn = conn } }) + return q, iErr } -func (q *querier) Commit() error { + +func (q *Querier) Commit() error { return q.conn.Commit() } -func (q *querier) Rollback() error { + +func (q *Querier) Rollback() error { return q.conn.Rollback() } -func (q *querier) Conn() conn { + +func (q *Querier) Conn() conn { return q.conn } -type SqlTx struct { +type SQLTx struct { *sql.Tx } -func (tx *SqlTx) Begin() (*sql.Tx, error) { - return &sql.Tx{}, nil -} -func (tx *SqlTx) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) { +func (tx *SQLTx) Begin() (*sql.Tx, error) { return &sql.Tx{}, nil } -type SqlDB struct { +func (tx *SQLTx) BeginTx(_ context.Context, _ *sql.TxOptions) (*sql.Tx, error) { + return &sql.Tx{}, nil +} + +type SQLDB struct { *sql.DB } -func (db *SqlDB) Commit() error { +func (db *SQLDB) Commit() error { return nil } -func (db *SqlDB) Rollback() error { +func (db *SQLDB) Rollback() error { return nil } diff --git a/repository/mysql/address/delete.go b/repository/mysql/address/delete.go index 3da9712..a356d98 100644 --- a/repository/mysql/address/delete.go +++ b/repository/mysql/address/delete.go @@ -7,12 +7,11 @@ import ( richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" ) -func (d *DB) DeleteBenefactorAddress(ctx context.Context, addressID uint, benefactorID uint) error { +func (d *DB) DeleteBenefactorAddress(ctx context.Context, addressID, benefactorID uint) error { const op = "mysqladdress.DeleteBenefactorAddress" _, err := d.conn.Conn().ExecContext(ctx, `UPDATE addresses SET deleted_at = CURRENT_TIMESTAMP WHERE id = ? AND benefactor_id = ? AND deleted_at IS NULL`, addressID, benefactorID) if err != nil { - return richerror.New(op).WithErr(err).WithKind(richerror.KindUnexpected).WithMessage(errmsg.ErrorMsgCantDeleteAddress) } diff --git a/repository/mysql/address/exist_address.go b/repository/mysql/address/exist_address.go index dc8eebb..80db5f6 100644 --- a/repository/mysql/address/exist_address.go +++ b/repository/mysql/address/exist_address.go @@ -9,7 +9,7 @@ import ( richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" ) -func (d *DB) IsExistAddressByID(ctx context.Context, addressID uint, benefactorID uint) (bool, error) { +func (d *DB) IsExistAddressByID(ctx context.Context, addressID, benefactorID uint) (bool, error) { const op = "mysqladdress.IsExistAddressByID" row := d.conn.Conn().QueryRowContext(ctx, `select * from addresses where id = ? and benefactor_id = ? and deleted_at is null `, addressID, benefactorID) diff --git a/repository/mysql/address/get.go b/repository/mysql/address/get.go index cd0ff1f..e482356 100644 --- a/repository/mysql/address/get.go +++ b/repository/mysql/address/get.go @@ -35,7 +35,7 @@ func (d *DB) GetAddressByID(ctx context.Context, id uint) (*entity.Address, erro return &address, nil } -func (d *DB) GetAddress(ctx context.Context, addressID uint, benefactorID uint) (entity.Address, error) { +func (d *DB) GetAddress(ctx context.Context, addressID, benefactorID uint) (entity.Address, error) { const op = "mysqladdress.GetAddress" row := d.conn.Conn().QueryRowContext(ctx, `select * from addresses where id = ? and benefactor_id = ? and deleted_at is null`, addressID, benefactorID) diff --git a/repository/mysql/address/update.go b/repository/mysql/address/update.go index ee249f4..c555908 100644 --- a/repository/mysql/address/update.go +++ b/repository/mysql/address/update.go @@ -13,7 +13,6 @@ func (d *DB) UpdateAddress(ctx context.Context, address entity.Address) error { provinceID, err := d.getProvinceIDByCityID(ctx, address.CityID) if err != nil { - return err } @@ -22,7 +21,6 @@ func (d *DB) UpdateAddress(ctx context.Context, address entity.Address) error { WHERE id = ? AND benefactor_id = ? AND deleted_at IS NULL` _, uErr := d.conn.Conn().ExecContext(ctx, query, address.PostalCode, address.Address, address.Lat, address.Lon, address.Name, address.CityID, provinceID, address.ID, address.BenefactorID) if err != nil { - return richerror.New(op).WithErr(uErr).WithMessage(errmsg.ErrorMsgCantUpdateRecord). WithKind(richerror.KindUnexpected) } diff --git a/repository/mysql/admin/exist_benefactor.go b/repository/mysql/admin/exist_benefactor.go index f953cd9..45e8692 100644 --- a/repository/mysql/admin/exist_benefactor.go +++ b/repository/mysql/admin/exist_benefactor.go @@ -4,11 +4,12 @@ import ( "context" "database/sql" "errors" + "time" + "git.gocasts.ir/ebhomengo/niki/entity" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" "git.gocasts.ir/ebhomengo/niki/repository/mysql" - "time" ) func (d *DB) IsExistBenefactorByID(ctx context.Context, id uint) (bool, error) { @@ -53,10 +54,8 @@ func scanBenefactor(scanner mysql.Scanner) (entity.Benefactor, error) { type benefactorNullableFields struct { firstName sql.NullString lastName sql.NullString - address sql.NullString description sql.NullString email sql.NullString - city sql.NullString genderStr sql.NullString birthdate sql.NullTime } diff --git a/repository/mysql/admin/get_all_agent.go b/repository/mysql/admin/get_all_agent.go index 432e362..a2e918b 100644 --- a/repository/mysql/admin/get_all_agent.go +++ b/repository/mysql/admin/get_all_agent.go @@ -2,8 +2,8 @@ package mysqladmin import ( "context" - "git.gocasts.ir/ebhomengo/niki/entity" + "git.gocasts.ir/ebhomengo/niki/entity" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" ) @@ -15,7 +15,6 @@ func (d DB) GetAllAgent(ctx context.Context) ([]entity.Admin, error) { query := `SELECT id, first_name, last_name, phone_number FROM admins WHERE role = 'agent' AND status = 'active'` rows, err := d.conn.Conn().QueryContext(ctx, query) if err != nil { - return nil, richerror.New(op).WithErr(err).WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected) } defer rows.Close() @@ -24,7 +23,6 @@ func (d DB) GetAllAgent(ctx context.Context) ([]entity.Admin, error) { var agent entity.Admin sErr := rows.Scan(&agent.ID, &agent.FirstName, &agent.LastName, &agent.PhoneNumber) if err != nil { - return nil, richerror.New(op).WithErr(sErr). WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected) } @@ -32,7 +30,6 @@ func (d DB) GetAllAgent(ctx context.Context) ([]entity.Admin, error) { } if rErr := rows.Err(); rErr != nil { - return nil, richerror.New(op).WithErr(rErr). WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected) } diff --git a/repository/mysql/admin/get_benefactor_address.go b/repository/mysql/admin/get_benefactor_address.go index 4dd451f..2b74304 100644 --- a/repository/mysql/admin/get_benefactor_address.go +++ b/repository/mysql/admin/get_benefactor_address.go @@ -4,11 +4,12 @@ import ( "context" "database/sql" "errors" + "time" + "git.gocasts.ir/ebhomengo/niki/entity" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" "git.gocasts.ir/ebhomengo/niki/repository/mysql" - "time" ) func (d *DB) GetAddressByID(ctx context.Context, id uint) (*entity.Address, error) { diff --git a/repository/mysql/benefactor/exist_benefactor.go b/repository/mysql/benefactor/exist_benefactor.go index 35a75ab..d86ddae 100644 --- a/repository/mysql/benefactor/exist_benefactor.go +++ b/repository/mysql/benefactor/exist_benefactor.go @@ -76,10 +76,8 @@ func scanBenefactor(scanner mysql.Scanner) (entity.Benefactor, error) { type nullableFields struct { firstName sql.NullString lastName sql.NullString - address sql.NullString description sql.NullString email sql.NullString - city sql.NullString genderStr sql.NullString birthdate sql.NullTime } diff --git a/repository/mysql/db.go b/repository/mysql/db.go index 20d6cfc..666f3a8 100644 --- a/repository/mysql/db.go +++ b/repository/mysql/db.go @@ -1,89 +1,91 @@ package mysql import ( - "database/sql" - "fmt" - querier "git.gocasts.ir/ebhomengo/niki/pkg/query_transaction/sql" - "sync" - "time" + "database/sql" + "fmt" + "sync" + "time" + + querier "git.gocasts.ir/ebhomengo/niki/pkg/query_transaction/sql" ) type Config struct { - Username string `koanf:"username"` - Password string `koanf:"password"` - Port int `koanf:"port"` - Host string `koanf:"host"` - DBName string `koanf:"db_name"` + Username string `koanf:"username"` + Password string `koanf:"password"` + Port int `koanf:"port"` + Host string `koanf:"host"` + DBName string `koanf:"db_name"` } type DB struct { - config Config - db *querier.SqlDB - mu sync.Mutex - statements map[string]*sql.Stmt + config Config + db *querier.SQLDB + mu sync.Mutex + statements map[string]*sql.Stmt } -func (db *DB) Conn() *querier.SqlDB { - return db.db +func (db *DB) Conn() *querier.SQLDB { + return db.db } // TODO: this temporary to ignore linter error (magic number). const ( - dbMaxConnLifetime = time.Minute * 3 - dbMaxOpenConns = 10 - dbMaxIdleConns = 10 + dbMaxConnLifetime = time.Minute * 3 + dbMaxOpenConns = 10 + dbMaxIdleConns = 10 ) func New(config Config) *DB { - // parseTime=true changes the output type of DATE and DATETIME values to time.Time - // instead of []byte / string - // The date or datetime like 0000-00-00 00:00:00 is converted into zero value of time.Time - db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@(%s:%d)/%s?parseTime=true", - config.Username, config.Password, config.Host, config.Port, config.DBName)) - if err != nil { - panic(fmt.Errorf("can't open mysql db: %w", err)) - } + // parseTime=true changes the output type of DATE and DATETIME values to time.Time + // instead of []byte / string + // The date or datetime like 0000-00-00 00:00:00 is converted into zero value of time.Time + db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@(%s:%d)/%s?parseTime=true", + config.Username, config.Password, config.Host, config.Port, config.DBName)) + if err != nil { + panic(fmt.Errorf("can't open mysql db: %w", err)) + } - // See "Important settings" section. - db.SetConnMaxLifetime(dbMaxConnLifetime) - db.SetMaxOpenConns(dbMaxOpenConns) - db.SetMaxIdleConns(dbMaxIdleConns) + // See "Important settings" section. + db.SetConnMaxLifetime(dbMaxConnLifetime) + db.SetMaxOpenConns(dbMaxOpenConns) + db.SetMaxIdleConns(dbMaxIdleConns) - return &DB{ - config: config, - db: &querier.SqlDB{DB: db}, - statements: make(map[string]*sql.Stmt), - } + return &DB{ + config: config, + db: &querier.SQLDB{DB: db}, + statements: make(map[string]*sql.Stmt), + } } -func (p *DB) PrepareStatement(key string, query string) (*sql.Stmt, error) { - p.mu.Lock() - defer p.mu.Unlock() +func (db *DB) PrepareStatement(key, query string) (*sql.Stmt, error) { + db.mu.Lock() + defer db.mu.Unlock() - if stmt, ok := p.statements[key]; ok { - return stmt, nil - } + if stmt, ok := db.statements[key]; ok { + return stmt, nil + } - stmt, err := p.db.Prepare(query) - if err != nil { - return nil, err - } - p.statements[key] = stmt + stmt, err := db.db.Prepare(query) + if err != nil { + return nil, err + } + db.statements[key] = stmt - return stmt, nil + return stmt, nil } -func (p *DB) CloseStatements() error { - p.mu.Lock() - defer p.mu.Unlock() +func (db *DB) CloseStatements() error { + db.mu.Lock() + defer db.mu.Unlock() - for _, stmt := range p.statements { - err := stmt.Close() - if err != nil { - return err - } - } + for _, stmt := range db.statements { + err := stmt.Close() + if err != nil { + return err + } + } - p.statements = make(map[string]*sql.Stmt) - return nil + db.statements = make(map[string]*sql.Stmt) + + return nil } diff --git a/repository/mysql/kind_box/add.go b/repository/mysql/kind_box/add.go index ced975d..9441997 100644 --- a/repository/mysql/kind_box/add.go +++ b/repository/mysql/kind_box/add.go @@ -3,6 +3,7 @@ package mysqlkindbox import ( "context" "database/sql" + "git.gocasts.ir/ebhomengo/niki/entity" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" querytransaction "git.gocasts.ir/ebhomengo/niki/pkg/query_transaction/sql" @@ -48,5 +49,6 @@ func (d DB) AddBatchKindBox(ctx context.Context, kindBoxes []entity.KindBox) err return richerror.New(op).WithErr(aErr). WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected) } + return nil } diff --git a/repository/mysql/kind_box/enumerate.go b/repository/mysql/kind_box/enumerate.go index 8f62378..7f44dde 100644 --- a/repository/mysql/kind_box/enumerate.go +++ b/repository/mysql/kind_box/enumerate.go @@ -8,7 +8,7 @@ import ( richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" ) -func (d DB) EnumerateKindBox(ctx context.Context, kindBoxID uint, amount uint) error { +func (d DB) EnumerateKindBox(ctx context.Context, kindBoxID, amount uint) error { const op = "mysqlkindbox.EnumerateKindBox" query := `UPDATE kind_boxes SET amount = ?, status = ? WHERE id = ?` diff --git a/repository/mysql/kind_box/exist_kindbox.go b/repository/mysql/kind_box/exist_kindbox.go index 8524869..24536cc 100644 --- a/repository/mysql/kind_box/exist_kindbox.go +++ b/repository/mysql/kind_box/exist_kindbox.go @@ -2,8 +2,8 @@ package mysqlkindbox import ( "context" - "git.gocasts.ir/ebhomengo/niki/entity" + "git.gocasts.ir/ebhomengo/niki/entity" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" ) @@ -13,7 +13,6 @@ func (d DB) BenefactorKindBoxExist(ctx context.Context, benefactorID, kindBoxID var count int if err := d.conn.Conn().QueryRowContext(ctx, `SELECT COUNT(*) FROM kind_boxes WHERE benefactor_id = ? AND id = ?`, benefactorID, kindBoxID).Scan(&count); err != nil { - return false, richerror.New(op).WithErr(err). WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected) } @@ -25,6 +24,7 @@ func (d DB) KindBoxExistForAgent(ctx context.Context, kindBoxID, agentID uint) ( const op = "mysqlkindbox.KindBoxExistForAgent" query := `SELECT COUNT(*) FROM kind_boxes WHERE id = ? AND receiver_agent_id = ? AND status = ? AND deleted_at IS NULL` + //nolint stmt, err := d.conn.PrepareStatement(op, query) if err != nil { return false, richerror.New(op).WithErr(err). @@ -45,7 +45,6 @@ func (d DB) KindBoxExist(ctx context.Context, kindBoxID uint) (bool, error) { var count int if err := d.conn.Conn().QueryRowContext(ctx, `SELECT COUNT(*) FROM kind_boxes WHERE id = ?`, kindBoxID).Scan(&count); err != nil { - return false, richerror.New(op).WithErr(err). WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected) } diff --git a/repository/mysql/kind_box/get.go b/repository/mysql/kind_box/get.go index ac2ce58..f1717c1 100644 --- a/repository/mysql/kind_box/get.go +++ b/repository/mysql/kind_box/get.go @@ -3,6 +3,7 @@ package mysqlkindbox import ( "context" "database/sql" + "errors" "git.gocasts.ir/ebhomengo/niki/entity" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" @@ -16,7 +17,7 @@ func (d DB) GetKindBox(ctx context.Context, kindBoxID uint) (entity.KindBox, err row := d.conn.Conn().QueryRowContext(ctx, query, kindBoxID) k, err := scanKindBox(row) if err != nil { - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { return entity.KindBox{}, richerror.New(op).WithErr(err). WithMessage(errmsg.ErrorMsgNotFound).WithKind(richerror.KindNotFound) } diff --git a/repository/mysql/kind_box/get_awaiting_return.go b/repository/mysql/kind_box/get_awaiting_return.go index bb030e9..f9a8fcb 100644 --- a/repository/mysql/kind_box/get_awaiting_return.go +++ b/repository/mysql/kind_box/get_awaiting_return.go @@ -4,15 +4,17 @@ import ( "context" "database/sql" "errors" + "git.gocasts.ir/ebhomengo/niki/entity" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" ) -func (d DB) GetAwaitingReturnByAgent(ctx context.Context, kindBoxID uint, agentID uint) (entity.KindBox, error) { +func (d DB) GetAwaitingReturnByAgent(ctx context.Context, kindBoxID, agentID uint) (entity.KindBox, error) { const op = "mysqlkindbox.GetAwaitingReturnByAgent" query := `SELECT * FROM kind_boxes WHERE id = ? AND receiver_agent_id = ? AND status = ? AND deleted_at IS NULL` + //nolint stmt, err := d.conn.PrepareStatement(op, query) if err != nil { return entity.KindBox{}, richerror.New(op).WithErr(err). diff --git a/repository/mysql/kind_box/return.go b/repository/mysql/kind_box/return.go index 546b811..f44544b 100644 --- a/repository/mysql/kind_box/return.go +++ b/repository/mysql/kind_box/return.go @@ -2,9 +2,9 @@ package mysqlkindbox import ( "context" - "git.gocasts.ir/ebhomengo/niki/entity" "time" + "git.gocasts.ir/ebhomengo/niki/entity" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" ) @@ -13,6 +13,7 @@ func (d DB) ReturnKindBox(ctx context.Context, kindBoxID uint, serialNumber stri const op = "mysqlkindbox.ReturnKindBox" query := `update kind_boxes set serial_number = ?, status = ?, returned_at = ? where id = ?` + //nolint stmt, err := d.conn.PrepareStatement(op, query) if err != nil { return richerror.New(op).WithErr(err). diff --git a/repository/mysql/kind_box/scan.go b/repository/mysql/kind_box/scan.go index cb862d3..33864cc 100644 --- a/repository/mysql/kind_box/scan.go +++ b/repository/mysql/kind_box/scan.go @@ -2,7 +2,6 @@ package mysqlkindbox import ( "database/sql" - "fmt" "time" "git.gocasts.ir/ebhomengo/niki/entity" @@ -51,7 +50,6 @@ func scanKindBox(scanner mysql.Scanner) (entity.KindBox, error) { &deletedAt, ) if err != nil { - fmt.Println(err) return entity.KindBox{}, err } diff --git a/repository/mysql/kind_box_req/add.go b/repository/mysql/kind_box_req/add.go index 79f5e2a..dbd3abf 100644 --- a/repository/mysql/kind_box_req/add.go +++ b/repository/mysql/kind_box_req/add.go @@ -2,6 +2,7 @@ package mysqlkindboxreq import ( "context" + "git.gocasts.ir/ebhomengo/niki/entity" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" diff --git a/repository/mysql/kind_box_req/delete.go b/repository/mysql/kind_box_req/delete.go index 0db9554..1d56ed0 100644 --- a/repository/mysql/kind_box_req/delete.go +++ b/repository/mysql/kind_box_req/delete.go @@ -15,5 +15,6 @@ func (d DB) DeleteKindBoxReqByID(ctx context.Context, kindBoxReqID uint) error { return richerror.New(op).WithErr(dErr). WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected) } + return nil } diff --git a/repository/mysql/kind_box_req/deliver.go b/repository/mysql/kind_box_req/deliver.go index d9bc568..8e2405c 100644 --- a/repository/mysql/kind_box_req/deliver.go +++ b/repository/mysql/kind_box_req/deliver.go @@ -2,11 +2,11 @@ package mysqlkindboxreq import ( "context" - querier "git.gocasts.ir/ebhomengo/niki/pkg/query_transaction/sql" "time" entity "git.gocasts.ir/ebhomengo/niki/entity" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" + querier "git.gocasts.ir/ebhomengo/niki/pkg/query_transaction/sql" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" ) @@ -23,5 +23,6 @@ func (d DB) DeliverKindBoxReq(ctx context.Context, kindBoxReqID uint) error { return richerror.New(op).WithErr(uErr). WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected) } + return nil } diff --git a/repository/mysql/kind_box_req/get.go b/repository/mysql/kind_box_req/get.go index caaf088..809e579 100644 --- a/repository/mysql/kind_box_req/get.go +++ b/repository/mysql/kind_box_req/get.go @@ -3,6 +3,8 @@ package mysqlkindboxreq import ( "context" "database/sql" + "errors" + "git.gocasts.ir/ebhomengo/niki/entity" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" querier "git.gocasts.ir/ebhomengo/niki/pkg/query_transaction/sql" @@ -32,10 +34,11 @@ func (d DB) GetKindBoxReqByID(ctx context.Context, kindBoxReqID uint) (entity.Ki "select * from kind_box_reqs where id = ? and deleted_at is null", kindBoxReqID) k, err := scanKindBoxReq(row) if err != nil { - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { return entity.KindBoxReq{}, richerror.New(op).WithErr(err). WithMessage(errmsg.ErrorMsgNotFound).WithKind(richerror.KindNotFound) } + return entity.KindBoxReq{}, richerror.New(op).WithErr(err). WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected) } diff --git a/repository/mysql/kind_box_req/get_all.go b/repository/mysql/kind_box_req/get_all.go index c496a59..ea4d6f7 100644 --- a/repository/mysql/kind_box_req/get_all.go +++ b/repository/mysql/kind_box_req/get_all.go @@ -2,11 +2,11 @@ package mysqlkindboxreq import ( "context" - "git.gocasts.ir/ebhomengo/niki/param" - builder "git.gocasts.ir/ebhomengo/niki/pkg/query_builder/mysql" "git.gocasts.ir/ebhomengo/niki/entity" + "git.gocasts.ir/ebhomengo/niki/param" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" + builder "git.gocasts.ir/ebhomengo/niki/pkg/query_builder/mysql" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" ) diff --git a/repository/mysql/kind_box_req/get_delivery_awaiting.go b/repository/mysql/kind_box_req/get_delivery_awaiting.go index 66d647a..87b3e33 100644 --- a/repository/mysql/kind_box_req/get_delivery_awaiting.go +++ b/repository/mysql/kind_box_req/get_delivery_awaiting.go @@ -3,21 +3,21 @@ package mysqlkindboxreq import ( "context" "database/sql" + "errors" "git.gocasts.ir/ebhomengo/niki/entity" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" ) -func (d DB) GetAwaitingDeliveryByAgent(ctx context.Context, kindBoxReqID uint, agentID uint) (entity.KindBoxReq, error) { +func (d DB) GetAwaitingDeliveryByAgent(ctx context.Context, kindBoxReqID, agentID uint) (entity.KindBoxReq, error) { const op = "mysqlkindboxreq.GetAwaitingDeliveryByAgent" query := `SELECT * FROM kind_box_reqs WHERE id = ? AND sender_agent_id = ? AND status = ? AND deleted_at IS NULL ` row := d.conn.Conn().QueryRowContext(ctx, query, kindBoxReqID, agentID, entity.KindBoxReqAssignedSenderAgentStatus.String()) k, err := scanKindBoxReq(row) if err != nil { - if err == sql.ErrNoRows { - + if errors.Is(err, sql.ErrNoRows) { return entity.KindBoxReq{}, richerror.New(op).WithErr(err). WithMessage(errmsg.ErrorMsgNotFound).WithKind(richerror.KindNotFound) } diff --git a/repository/mysql/kind_box_req/kind_box_req.go b/repository/mysql/kind_box_req/kind_box_req.go index 1833978..a3d8cce 100644 --- a/repository/mysql/kind_box_req/kind_box_req.go +++ b/repository/mysql/kind_box_req/kind_box_req.go @@ -14,6 +14,7 @@ func (d DB) KindBoxRequestExist(id uint) (bool, error) { const op = "mysqlkindboxreq.KindBoxRequestExist" query := `select * from kind_box_reqs where id = ?` + //nolint stmt, err := d.conn.PrepareStatement(op, query) if err != nil { return false, richerror.New(op).WithErr(err). diff --git a/repository/mysql/kind_box_req/scan.go b/repository/mysql/kind_box_req/scan.go index 9930128..5dcf1ca 100644 --- a/repository/mysql/kind_box_req/scan.go +++ b/repository/mysql/kind_box_req/scan.go @@ -40,7 +40,6 @@ func scanKindBoxReq(scanner mysql.Scanner) (entity.KindBoxReq, error) { &deletedAt, ) if err != nil { - return entity.KindBoxReq{}, err } diff --git a/repository/mysql/refer_time/get.go b/repository/mysql/refer_time/get.go index a4d7668..bb92b22 100644 --- a/repository/mysql/refer_time/get.go +++ b/repository/mysql/refer_time/get.go @@ -2,6 +2,7 @@ package mysqlrefertime import ( "context" + "git.gocasts.ir/ebhomengo/niki/entity" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" @@ -16,5 +17,6 @@ func (d DB) Get(ctx context.Context, referTimeID uint) (entity.ReferTime, error) return entity.ReferTime{}, richerror.New(op).WithErr(err). WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected) } + return r, nil } diff --git a/repository/mysql/refer_time/scan.go b/repository/mysql/refer_time/scan.go index 480b3bc..43b694f 100644 --- a/repository/mysql/refer_time/scan.go +++ b/repository/mysql/refer_time/scan.go @@ -2,9 +2,10 @@ package mysqlrefertime import ( "database/sql" + "time" + "git.gocasts.ir/ebhomengo/niki/entity" "git.gocasts.ir/ebhomengo/niki/repository/mysql" - "time" ) func scanReferTime(scanner mysql.Scanner) (entity.ReferTime, error) { @@ -27,5 +28,6 @@ func scanReferTime(scanner mysql.Scanner) (entity.ReferTime, error) { return entity.ReferTime{}, err } referTime.Status = entity.MapToReferTimeStatus(status) + return referTime, nil } diff --git a/service/admin/admin/get_all_agent.go b/service/admin/admin/get_all_agent.go index 5973892..e8e06de 100644 --- a/service/admin/admin/get_all_agent.go +++ b/service/admin/admin/get_all_agent.go @@ -14,7 +14,6 @@ func (s Service) GetAllAgent(ctx context.Context) (param.GetAllAgentResponse, er agents, err := s.repo.GetAllAgent(ctx) if err != nil { - return param.GetAllAgentResponse{}, richerror.New(op).WithErr(err).WithKind(richerror.KindUnexpected) } diff --git a/service/admin/benefactor/address.go b/service/admin/benefactor/address.go index 03c98c8..584dbc5 100644 --- a/service/admin/benefactor/address.go +++ b/service/admin/benefactor/address.go @@ -2,6 +2,7 @@ package benefactor import ( "context" + param "git.gocasts.ir/ebhomengo/niki/param/admin/admin" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" ) diff --git a/service/admin/benefactor/get.go b/service/admin/benefactor/get.go index 8c5d783..18e4bca 100644 --- a/service/admin/benefactor/get.go +++ b/service/admin/benefactor/get.go @@ -2,6 +2,7 @@ package benefactor import ( "context" + param "git.gocasts.ir/ebhomengo/niki/param/admin/admin" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" ) diff --git a/service/admin/benefactor/service.go b/service/admin/benefactor/service.go index 3a8ee6b..7d18ca9 100644 --- a/service/admin/benefactor/service.go +++ b/service/admin/benefactor/service.go @@ -2,6 +2,7 @@ package benefactor import ( "context" + "git.gocasts.ir/ebhomengo/niki/entity" param "git.gocasts.ir/ebhomengo/niki/param/admin/admin" ) @@ -10,14 +11,13 @@ type Repository interface { IsExistBenefactorByID(ctx context.Context, id uint) (bool, error) GetAddressByID(ctx context.Context, id uint) (*entity.Address, error) } -type BenefactorForAdminSvc interface { +type ForAdminSvc interface { BenefactorExistByID(ctx context.Context, request param.BenefactorExistByIDRequest) (param.BenefactorExistByIDResponse, error) AddressExistByID(ctx context.Context, request param.GetAddressByIDRequest) (param.GetAddressByIDResponse, error) } type Service struct { - repo Repository - benefactorSvc BenefactorForAdminSvc + repo Repository } func New(repo Repository) Service { diff --git a/service/admin/kind_box/add.go b/service/admin/kind_box/add.go index ba0aae6..9befaea 100644 --- a/service/admin/kind_box/add.go +++ b/service/admin/kind_box/add.go @@ -2,6 +2,7 @@ package adminkindboxservice import ( "context" + entity "git.gocasts.ir/ebhomengo/niki/entity" param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" @@ -31,5 +32,6 @@ func (s Service) AddBatchKindBox(ctx context.Context, req param.AddKindBoxReques if aErr != nil { return param.AddKindBoxResponse{}, richerror.New(op).WithErr(aErr).WithKind(richerror.KindUnexpected) } + return param.AddKindBoxResponse{}, nil } diff --git a/service/admin/kind_box_req/deliver.go b/service/admin/kind_box_req/deliver.go index 8779ff3..20704f9 100644 --- a/service/admin/kind_box_req/deliver.go +++ b/service/admin/kind_box_req/deliver.go @@ -35,5 +35,6 @@ func (s Service) Deliver(ctx context.Context, req param.DeliverKindBoxReqRequest if dErr != nil { return param.DeliverKindBoxReqResponse{}, richerror.New(op).WithErr(dErr).WithKind(richerror.KindUnexpected) } + return param.DeliverKindBoxReqResponse{}, nil } diff --git a/service/admin/kind_box_req/get_all_delivery_awaiting.go b/service/admin/kind_box_req/get_all_delivery_awaiting.go index a2be8fd..3144b60 100644 --- a/service/admin/kind_box_req/get_all_delivery_awaiting.go +++ b/service/admin/kind_box_req/get_all_delivery_awaiting.go @@ -13,7 +13,6 @@ func (s Service) GetAllAwaitingDelivery(ctx context.Context, req param.DeliveryA allAwaitingKindBoxReq, total, err := s.repo.GetAllKindBoxReq(ctx, req.Filter, req.Pagination, req.Sort) if err != nil { - return param.DeliveryAwaitingGetAllResponse{}, richerror.New(op).WithErr(err) } diff --git a/service/admin/kind_box_req/get_delivery_awaiting.go b/service/admin/kind_box_req/get_delivery_awaiting.go index 8b257b4..92edb06 100644 --- a/service/admin/kind_box_req/get_delivery_awaiting.go +++ b/service/admin/kind_box_req/get_delivery_awaiting.go @@ -4,6 +4,7 @@ import ( "context" param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req" + richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" ) func (s Service) GetAwaitingDelivery(ctx context.Context, req param.DeliveryAwaitingGetRequest) (param.DeliveryAwaitingGetResponse, error) { @@ -11,8 +12,7 @@ func (s Service) GetAwaitingDelivery(ctx context.Context, req param.DeliveryAwai kindBoxReq, err := s.repo.GetAwaitingDeliveryByAgent(ctx, req.KindBoxReqID, req.AgentID) if err != nil { - - return param.DeliveryAwaitingGetResponse{}, err + return param.DeliveryAwaitingGetResponse{}, richerror.New(op).WithErr(err) } return param.DeliveryAwaitingGetResponse{ diff --git a/service/admin/refer_time/get.go b/service/admin/refer_time/get.go index 1ba10ce..5f0dee0 100644 --- a/service/admin/refer_time/get.go +++ b/service/admin/refer_time/get.go @@ -2,6 +2,7 @@ package adminrefertimeservice import ( "context" + param "git.gocasts.ir/ebhomengo/niki/param/admin/refer_time" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" ) @@ -12,5 +13,6 @@ func (s Service) GetReferTimeByID(ctx context.Context, req param.GetReferTimeReq if gErr != nil { return param.GetReferTimeResponse{}, richerror.New(op).WithErr(gErr).WithKind(richerror.KindUnexpected) } + return param.GetReferTimeResponse{ReferTime: referTime}, nil } diff --git a/service/admin/refer_time/service.go b/service/admin/refer_time/service.go index 740f882..1326fa4 100644 --- a/service/admin/refer_time/service.go +++ b/service/admin/refer_time/service.go @@ -2,6 +2,7 @@ package adminrefertimeservice import ( "context" + "git.gocasts.ir/ebhomengo/niki/entity" ) diff --git a/service/agent/kind_box/get.go b/service/agent/kind_box/get.go index dba9376..bfe0f5b 100644 --- a/service/agent/kind_box/get.go +++ b/service/agent/kind_box/get.go @@ -2,6 +2,7 @@ package agentkindboxservice import ( "context" + param "git.gocasts.ir/ebhomengo/niki/param/agent/kind_box" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" ) diff --git a/service/agent/kind_box/get_all.go b/service/agent/kind_box/get_all.go index 510c509..235f0eb 100644 --- a/service/agent/kind_box/get_all.go +++ b/service/agent/kind_box/get_all.go @@ -2,6 +2,7 @@ package agentkindboxservice import ( "context" + paginationparam "git.gocasts.ir/ebhomengo/niki/param" param "git.gocasts.ir/ebhomengo/niki/param/agent/kind_box" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" diff --git a/service/agent/kind_box/return.go b/service/agent/kind_box/return.go index b374a7f..9496f36 100644 --- a/service/agent/kind_box/return.go +++ b/service/agent/kind_box/return.go @@ -2,6 +2,7 @@ package agentkindboxservice import ( "context" + param "git.gocasts.ir/ebhomengo/niki/param/agent/kind_box" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" ) diff --git a/service/agent/kind_box/service.go b/service/agent/kind_box/service.go index 9e69a19..68b3cdb 100644 --- a/service/agent/kind_box/service.go +++ b/service/agent/kind_box/service.go @@ -2,6 +2,7 @@ package agentkindboxservice import ( "context" + "git.gocasts.ir/ebhomengo/niki/entity" params "git.gocasts.ir/ebhomengo/niki/param" ) diff --git a/service/benefactor/address/service.go b/service/benefactor/address/service.go index 6c6fe01..5817bca 100644 --- a/service/benefactor/address/service.go +++ b/service/benefactor/address/service.go @@ -2,6 +2,7 @@ package benefactoraddressservice import ( "context" + "git.gocasts.ir/ebhomengo/niki/entity" ) diff --git a/service/benefactor/address/update.go b/service/benefactor/address/update.go index 51dc71c..1790df5 100644 --- a/service/benefactor/address/update.go +++ b/service/benefactor/address/update.go @@ -22,7 +22,6 @@ func (s Service) Update(ctx context.Context, req param.UpdateAddressRequest) err BenefactorID: req.BenefactorID, }) if err != nil { - return richerror.New(op).WithErr(err) } diff --git a/service/benefactor/benefactor/login_register.go b/service/benefactor/benefactor/login_register.go index 6a00881..a0243d8 100644 --- a/service/benefactor/benefactor/login_register.go +++ b/service/benefactor/benefactor/login_register.go @@ -2,10 +2,10 @@ package benefactorservice import ( "context" - "fmt" "git.gocasts.ir/ebhomengo/niki/entity" benefactoreparam "git.gocasts.ir/ebhomengo/niki/param/benefactor/benefactore" + errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" ) @@ -17,8 +17,7 @@ func (s Service) LoginOrRegister(ctx context.Context, req benefactoreparam.Login return benefactoreparam.LoginOrRegisterResponse{}, richerror.New(op).WithErr(gErr).WithKind(richerror.KindUnexpected) } if code == "" || code != req.VerificationCode { - fmt.Print() - //return benefactoreparam.LoginOrRegisterResponse{}, richerror.New(op).WithMessage(errmsg.ErrorMsgOtpCodeIsNotValid).WithKind(richerror.KindForbidden) + return benefactoreparam.LoginOrRegisterResponse{}, richerror.New(op).WithMessage(errmsg.ErrorMsgOtpCodeIsNotValid).WithKind(richerror.KindForbidden) } _, dErr := s.redisOtp.DeleteCodeByPhoneNumber(ctx, req.PhoneNumber) diff --git a/service/benefactor/kind_box/get_all.go b/service/benefactor/kind_box/get_all.go index b5b4897..1243247 100644 --- a/service/benefactor/kind_box/get_all.go +++ b/service/benefactor/kind_box/get_all.go @@ -2,6 +2,7 @@ package benefactorkindboxservice import ( "context" + params "git.gocasts.ir/ebhomengo/niki/param" param "git.gocasts.ir/ebhomengo/niki/param/benefactor/kind_box" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" @@ -12,7 +13,6 @@ func (s Service) GetAll(ctx context.Context, req param.KindBoxGetAllRequest) (pa allKindBox, total, err := s.repo.GetAllKindBox(ctx, req.Filter, req.Pagination, req.Sort) if err != nil { - return param.KindBoxGetAllResponse{}, richerror.New(op).WithErr(err) } diff --git a/service/benefactor/kind_box_req/add.go b/service/benefactor/kind_box_req/add.go index 023df71..ea07a0d 100644 --- a/service/benefactor/kind_box_req/add.go +++ b/service/benefactor/kind_box_req/add.go @@ -2,6 +2,7 @@ package benefactorkindboxreqservice import ( "context" + "git.gocasts.ir/ebhomengo/niki/entity" param "git.gocasts.ir/ebhomengo/niki/param/benefactor/kind_box_req" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" diff --git a/service/benefactor/kind_box_req/delete.go b/service/benefactor/kind_box_req/delete.go index becedd0..070b7d1 100644 --- a/service/benefactor/kind_box_req/delete.go +++ b/service/benefactor/kind_box_req/delete.go @@ -13,5 +13,6 @@ func (s Service) Delete(ctx context.Context, req param.KindBoxReqDeleteRequest) if dErr != nil { return param.KindBoxReqDeleteResponse{}, richerror.New(op).WithErr(dErr).WithKind(richerror.KindUnexpected) } + return param.KindBoxReqDeleteResponse{}, nil } diff --git a/service/benefactor/kind_box_req/get_all.go b/service/benefactor/kind_box_req/get_all.go index aff8b53..55cb7d0 100644 --- a/service/benefactor/kind_box_req/get_all.go +++ b/service/benefactor/kind_box_req/get_all.go @@ -2,6 +2,7 @@ package benefactorkindboxreqservice import ( "context" + params "git.gocasts.ir/ebhomengo/niki/param" param "git.gocasts.ir/ebhomengo/niki/param/benefactor/kind_box_req" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" @@ -12,7 +13,6 @@ func (s Service) GetAll(ctx context.Context, req param.GetAllRequest) (param.Get allKindBoxReq, total, err := s.repo.GetAllKindBoxReq(ctx, req.Filter, req.Pagination, req.Sort) if err != nil { - return param.GetAllResponse{}, richerror.New(op).WithErr(err) } diff --git a/service/benefactor/kind_box_req/service.go b/service/benefactor/kind_box_req/service.go index 548d850..2d9e1ae 100644 --- a/service/benefactor/kind_box_req/service.go +++ b/service/benefactor/kind_box_req/service.go @@ -2,9 +2,9 @@ package benefactorkindboxreqservice import ( "context" - params "git.gocasts.ir/ebhomengo/niki/param" entity "git.gocasts.ir/ebhomengo/niki/entity" + params "git.gocasts.ir/ebhomengo/niki/param" ) type Repository interface { diff --git a/validator/admin/kind_box/get_all.go b/validator/admin/kind_box/get_all.go index 60549f7..1a797fc 100644 --- a/validator/admin/kind_box/get_all.go +++ b/validator/admin/kind_box/get_all.go @@ -2,11 +2,11 @@ package adminkindboxvalidator import ( "errors" - "git.gocasts.ir/ebhomengo/niki/validator" param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" + "git.gocasts.ir/ebhomengo/niki/validator" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/validator/admin/kind_box/validator.go b/validator/admin/kind_box/validator.go index 1b5650c..8bbfc49 100644 --- a/validator/admin/kind_box/validator.go +++ b/validator/admin/kind_box/validator.go @@ -3,6 +3,7 @@ package adminkindboxvalidator import ( "context" "fmt" + "git.gocasts.ir/ebhomengo/niki/entity" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" ) diff --git a/validator/admin/kind_box_req/get.go b/validator/admin/kind_box_req/get.go index eeec291..863550f 100644 --- a/validator/admin/kind_box_req/get.go +++ b/validator/admin/kind_box_req/get.go @@ -2,6 +2,7 @@ package adminkindboxreqvalidator import ( "errors" + param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" diff --git a/validator/admin/kind_box_req/get_all.go b/validator/admin/kind_box_req/get_all.go index 172bc20..0b97cc2 100644 --- a/validator/admin/kind_box_req/get_all.go +++ b/validator/admin/kind_box_req/get_all.go @@ -2,6 +2,7 @@ package adminkindboxreqvalidator import ( "errors" + param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" diff --git a/validator/admin/kind_box_req/update.go b/validator/admin/kind_box_req/update.go index dbaadbc..b6448d0 100644 --- a/validator/admin/kind_box_req/update.go +++ b/validator/admin/kind_box_req/update.go @@ -24,9 +24,9 @@ func (v Validator) ValidateUpdateRequest(req param.KindBoxReqUpdateRequest) (map validation.Max(uint(MaxKindBoxReq)), ), validation.Field(&req.CountAccepted, - validation.Min(uint(MinKindBoxReq)), - validation.Max(uint(MaxKindBoxReq)), - validation.When(req.CountRequested > 0, validation.Max(uint(req.CountRequested))), + validation.Min(MinKindBoxReq), + validation.Max(MaxKindBoxReq), + validation.When(req.CountRequested > 0, validation.Max(req.CountRequested)), validation.By(v.checkCountAcceptedMustBeLessThanCountRequested(req.ID)), ), validation.Field(&req.KindBoxType, diff --git a/validator/admin/kind_box_req/validator.go b/validator/admin/kind_box_req/validator.go index a331d36..56ed185 100644 --- a/validator/admin/kind_box_req/validator.go +++ b/validator/admin/kind_box_req/validator.go @@ -145,6 +145,7 @@ func (v Validator) checkCountAcceptedMustBeLessThanCountRequested(kindboxreqID u if kindBoxReq.CountRequested < countAccepted { return fmt.Errorf(errmsg.ErrorMsgCountAcceptedOverflow) } + return nil } } @@ -178,6 +179,7 @@ func (v Validator) areFilterFieldsValid(validFilters []string) validation.RuleFu return fmt.Errorf(errmsg.ErrorMsgFiltersAreNotValid) } } + return nil } } @@ -197,6 +199,7 @@ func (v Validator) areSortFieldsValid(validSortFields []string) validation.RuleF if sort.Field != "" && !slices.Contains(validSortFields, sort.Field) { return fmt.Errorf(errmsg.ErrorMsgSortFieldIsNotValid) } + return nil } } @@ -215,6 +218,7 @@ func (v Validator) isReferTimeIDValid(value interface{}) error { if resp.ReferTime.Status != entity.ReferTimeActiveStatus { return fmt.Errorf(errmsg.ErrorMsgReferTimeIsNotActive) } + return nil } @@ -274,6 +278,7 @@ func (v Validator) IsSerialNumbersCountValid(kindBoxReqID uint) validation.RuleF if len(serialNumbers) != 0 && len(serialNumbers) > int(kindBoxReq.CountAccepted) { return fmt.Errorf(errmsg.ErrorMsgInvalidSerialNumberRange) } + return nil } } diff --git a/validator/agent/kind_box/get.go b/validator/agent/kind_box/get.go index 95f070e..b84bbbb 100644 --- a/validator/agent/kind_box/get.go +++ b/validator/agent/kind_box/get.go @@ -2,6 +2,7 @@ package agentkindboxvalidator import ( "errors" + param "git.gocasts.ir/ebhomengo/niki/param/agent/kind_box" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" diff --git a/validator/agent/kind_box/get_all.go b/validator/agent/kind_box/get_all.go index b3e1e10..2d27ea3 100644 --- a/validator/agent/kind_box/get_all.go +++ b/validator/agent/kind_box/get_all.go @@ -2,6 +2,7 @@ package agentkindboxvalidator import ( "errors" + param "git.gocasts.ir/ebhomengo/niki/param/agent/kind_box" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" diff --git a/validator/agent/kind_box/return.go b/validator/agent/kind_box/return.go index afc68e9..2206e0b 100644 --- a/validator/agent/kind_box/return.go +++ b/validator/agent/kind_box/return.go @@ -2,6 +2,7 @@ package agentkindboxvalidator import ( "errors" + param "git.gocasts.ir/ebhomengo/niki/param/agent/kind_box" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" diff --git a/validator/agent/kind_box/validator.go b/validator/agent/kind_box/validator.go index e1428f9..b3201c9 100644 --- a/validator/agent/kind_box/validator.go +++ b/validator/agent/kind_box/validator.go @@ -3,6 +3,7 @@ package agentkindboxvalidator import ( "context" "fmt" + errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" ) diff --git a/validator/benefactor/address/validator.go b/validator/benefactor/address/validator.go index 7c78923..9dbed02 100644 --- a/validator/benefactor/address/validator.go +++ b/validator/benefactor/address/validator.go @@ -55,7 +55,6 @@ func (v Validator) doesCityExist(value interface{}) error { } func (v Validator) doesAddressExist(benefactorID uint) validation.RuleFunc { - return func(value interface{}) error { addressID, ok := value.(uint) if !ok { diff --git a/validator/benefactor/kind_box/validator.go b/validator/benefactor/kind_box/validator.go index e57981f..ccd615f 100644 --- a/validator/benefactor/kind_box/validator.go +++ b/validator/benefactor/kind_box/validator.go @@ -3,11 +3,11 @@ package benefactorkindboxvalidator import ( "context" "fmt" - params "git.gocasts.ir/ebhomengo/niki/param" "slices" "time" "git.gocasts.ir/ebhomengo/niki/entity" + params "git.gocasts.ir/ebhomengo/niki/param" refertimeparam "git.gocasts.ir/ebhomengo/niki/param/admin/refer_time" addressparam "git.gocasts.ir/ebhomengo/niki/param/benefactor/address" param "git.gocasts.ir/ebhomengo/niki/param/benefactor/benefactore" @@ -121,6 +121,7 @@ func (v Validator) isReferTimeIDValid(value interface{}) error { if resp.ReferTime.Status != entity.ReferTimeActiveStatus { return fmt.Errorf(errmsg.ErrorMsgReferTimeIsNotActive) } + return nil } @@ -151,6 +152,7 @@ func (v Validator) areFilterFieldsValid(validFilters []string) validation.RuleFu return fmt.Errorf(errmsg.ErrorMsgFiltersAreNotValid) } } + return nil } } @@ -170,6 +172,7 @@ func (v Validator) areSortFieldsValid(validSortFields []string) validation.RuleF if sort.Field != "" && !slices.Contains(validSortFields, sort.Field) { return fmt.Errorf(errmsg.ErrorMsgSortFieldIsNotValid) } + return nil } } diff --git a/validator/benefactor/kind_box_req/update.go b/validator/benefactor/kind_box_req/update.go index 0bd0c07..e03da84 100644 --- a/validator/benefactor/kind_box_req/update.go +++ b/validator/benefactor/kind_box_req/update.go @@ -21,8 +21,8 @@ func (v Validator) ValidateUpdateRequest(req param.KindBoxReqUpdateRequest) (map ), validation.Field(&req.CountRequested, validation.Required, - validation.Min(uint(MinKindBoxReq)), - validation.Max(uint(MaxKindBoxReq)), + validation.Min(MinKindBoxReq), + validation.Max(MaxKindBoxReq), ), validation.Field(&req.KindBoxType, validation.Required, @@ -40,7 +40,6 @@ func (v Validator) ValidateUpdateRequest(req param.KindBoxReqUpdateRequest) (map validation.Required, validation.By(v.isReferTimeIDValid), ), - ); err != nil { fieldErrors := make(map[string]string) diff --git a/validator/benefactor/kind_box_req/validator.go b/validator/benefactor/kind_box_req/validator.go index 31dd3b7..7408749 100644 --- a/validator/benefactor/kind_box_req/validator.go +++ b/validator/benefactor/kind_box_req/validator.go @@ -2,13 +2,13 @@ package benefactorkindboxreqvalidator import ( "context" + "errors" "fmt" - params "git.gocasts.ir/ebhomengo/niki/param" "slices" "time" - "errors" "git.gocasts.ir/ebhomengo/niki/entity" + params "git.gocasts.ir/ebhomengo/niki/param" refertimeparam "git.gocasts.ir/ebhomengo/niki/param/admin/refer_time" addressparam "git.gocasts.ir/ebhomengo/niki/param/benefactor/address" param "git.gocasts.ir/ebhomengo/niki/param/benefactor/benefactore" @@ -136,6 +136,7 @@ func (v Validator) isReferTimeIDValid(value interface{}) error { if resp.ReferTime.Status != entity.ReferTimeActiveStatus { return fmt.Errorf(errmsg.ErrorMsgReferTimeIsNotActive) } + return nil } @@ -152,6 +153,7 @@ func (v Validator) doesKindBoxBelongToBenefactor(benefactorID uint) validation.R if kindBoxReq.BenefactorID != benefactorID { return fmt.Errorf(errmsg.ErrorMsgKindBoxReqDoesntBelongToBenefactor) } + return nil } } @@ -168,6 +170,7 @@ func (v Validator) doesKindBoxRequestHavePendingStatus(value interface{}) error if kindBoxReq.Status != entity.KindBoxReqPendingStatus { return fmt.Errorf(errmsg.ErrorMsgInvalidStatus) } + return nil } @@ -182,6 +185,7 @@ func (v Validator) areFilterFieldsValid(validFilters []string) validation.RuleFu return fmt.Errorf(errmsg.ErrorMsgFiltersAreNotValid) } } + return nil } } @@ -201,6 +205,7 @@ func (v Validator) areSortFieldsValid(validSortFields []string) validation.RuleF if sort.Field != "" && !slices.Contains(validSortFields, sort.Field) { return fmt.Errorf(errmsg.ErrorMsgSortFieldIsNotValid) } + return nil } } diff --git a/validator/filter.go b/validator/filter.go index 205729c..4e30ac8 100644 --- a/validator/filter.go +++ b/validator/filter.go @@ -2,10 +2,11 @@ package validator import ( "fmt" + "slices" + params "git.gocasts.ir/ebhomengo/niki/param" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" validation "github.com/go-ozzo/ozzo-validation/v4" - "slices" ) func AreFilterFieldsValid(validFilters []string) validation.RuleFunc { @@ -19,6 +20,7 @@ func AreFilterFieldsValid(validFilters []string) validation.RuleFunc { return fmt.Errorf(errmsg.ErrorMsgFiltersAreNotValid) } } + return nil } } diff --git a/validator/sort.go b/validator/sort.go index 864c030..64d777e 100644 --- a/validator/sort.go +++ b/validator/sort.go @@ -2,10 +2,11 @@ package validator import ( "fmt" + "slices" + params "git.gocasts.ir/ebhomengo/niki/param" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" validation "github.com/go-ozzo/ozzo-validation/v4" - "slices" ) func AreSortFieldsValid(validSortFields []string) validation.RuleFunc { @@ -23,6 +24,7 @@ func AreSortFieldsValid(validSortFields []string) validation.RuleFunc { if sort.Field != "" && !slices.Contains(validSortFields, sort.Field) { return fmt.Errorf(errmsg.ErrorMsgSortFieldIsNotValid) } + return nil } } diff --git a/vendor/github.com/KyleBanks/depth/depth.go b/vendor/github.com/KyleBanks/depth/depth.go index 75f7ea9..fa9d2cf 100644 --- a/vendor/github.com/KyleBanks/depth/depth.go +++ b/vendor/github.com/KyleBanks/depth/depth.go @@ -1,29 +1,55 @@ // Package depth provides the ability to traverse and retrieve Go source code dependencies in the form of + // internal and external packages. + // + // For example, the dependencies of the stdlib `strings` package can be resolved like so: + // + // import "github.com/KyleBanks/depth" + // + // var t depth.Tree + // err := t.Resolve("strings") + // if err != nil { + // log.Fatal(err) + // } + // + // // Output: "strings has 4 dependencies." + // log.Printf("%v has %v dependencies.", t.Root.Name, len(t.Root.Deps)) + // + // For additional customization, simply set the appropriate flags on the `Tree` before resolving: + // + // import "github.com/KyleBanks/depth" + // + // t := depth.Tree { + // ResolveInternal: true, + // ResolveTest: true, + // MaxDepth: 10, + // } + // err := t.Resolve("strings") + package depth import ( @@ -33,22 +59,29 @@ import ( ) // ErrRootPkgNotResolved is returned when the root Pkg of the Tree cannot be resolved, + // typically because it does not exist. + var ErrRootPkgNotResolved = errors.New("unable to resolve root package") // Importer defines a type that can import a package and return its details. + type Importer interface { Import(name, srcDir string, im build.ImportMode) (*build.Package, error) } // Tree represents the top level of a Pkg and the configuration used to + // initialize and represent its contents. + type Tree struct { Root *Pkg ResolveInternal bool - ResolveTest bool - MaxDepth int + + ResolveTest bool + + MaxDepth int Importer Importer @@ -56,74 +89,122 @@ type Tree struct { } // Resolve recursively finds all dependencies for the root Pkg name provided, + // and the packages it depends on. + func (t *Tree) Resolve(name string) error { + pwd, err := os.Getwd() + if err != nil { + return err + } t.Root = &Pkg{ - Name: name, - Tree: t, + + Name: name, + + Tree: t, + SrcDir: pwd, - Test: false, + + Test: false, } // Reset the import cache each time to ensure a reused Tree doesn't + // reuse the same cache. + t.importCache = nil // Allow custom importers, but use build.Default if none is provided. + if t.Importer == nil { + t.Importer = &build.Default + } t.Root.Resolve(t.Importer) + if !t.Root.Resolved { + return ErrRootPkgNotResolved + } return nil + } // shouldResolveInternal determines if internal packages should be further resolved beyond the + // current parent. + // + // For example, if the parent Pkg is `github.com/foo/bar` and true is returned, all the + // internal dependencies it relies on will be resolved. If for example `strings` is one of those + // dependencies, and it is passed as the parent here, false may be returned and its internal + // dependencies will not be resolved. + func (t *Tree) shouldResolveInternal(parent *Pkg) bool { + if t.ResolveInternal { + return true + } return parent == t.Root + } // isAtMaxDepth returns true when the depth of the Pkg provided is at or beyond the maximum + // depth allowed by the tree. + // + // If the Tree has a MaxDepth of zero, true is never returned. + func (t *Tree) isAtMaxDepth(p *Pkg) bool { + if t.MaxDepth == 0 { + return false + } return p.depth() >= t.MaxDepth + } // hasSeenImport returns true if the import name provided has already been seen within the tree. + // This function only returns false for a name once. + func (t *Tree) hasSeenImport(name string) bool { + if t.importCache == nil { + t.importCache = make(map[string]struct{}) + } if _, ok := t.importCache[name]; ok { + return true + } + t.importCache[name] = struct{}{} + return false + } diff --git a/vendor/github.com/KyleBanks/depth/pkg.go b/vendor/github.com/KyleBanks/depth/pkg.go index 1d54d71..c2d8490 100644 --- a/vendor/github.com/KyleBanks/depth/pkg.go +++ b/vendor/github.com/KyleBanks/depth/pkg.go @@ -9,176 +9,280 @@ import ( ) // Pkg represents a Go source package, and its dependencies. + type Pkg struct { - Name string `json:"name"` + Name string `json:"name"` + SrcDir string `json:"-"` Internal bool `json:"internal"` - Resolved bool `json:"resolved"` - Test bool `json:"-"` - Tree *Tree `json:"-"` - Parent *Pkg `json:"-"` - Deps []Pkg `json:"deps"` + Resolved bool `json:"resolved"` + + Test bool `json:"-"` + + Tree *Tree `json:"-"` + + Parent *Pkg `json:"-"` + + Deps []Pkg `json:"deps"` Raw *build.Package `json:"-"` } // Resolve recursively finds all dependencies for the Pkg and the packages it depends on. + func (p *Pkg) Resolve(i Importer) { + // Resolved is always true, regardless of if we skip the import, + // it is only false if there is an error while importing. + p.Resolved = true name := p.cleanName() + if name == "" { + return + } // Stop resolving imports if we've reached max depth or found a duplicate. + var importMode build.ImportMode + if p.Tree.hasSeenImport(name) || p.Tree.isAtMaxDepth(p) { + importMode = build.FindOnly + } pkg, err := i.Import(name, p.SrcDir, importMode) + if err != nil { + // TODO: Check the error type? + p.Resolved = false + return + } + p.Raw = pkg // Update the name with the fully qualified import path. + p.Name = pkg.ImportPath // If this is an internal dependency, we may need to skip it. + if pkg.Goroot { + p.Internal = true + if !p.Tree.shouldResolveInternal(p) { + return + } + } //first we set the regular dependencies, then we add the test dependencies + //sharing the same set. This allows us to mark all test-only deps linearly + unique := make(map[string]struct{}) + p.setDeps(i, pkg.Imports, pkg.Dir, unique, false) + if p.Tree.ResolveTest { + p.setDeps(i, append(pkg.TestImports, pkg.XTestImports...), pkg.Dir, unique, true) + } + } // setDeps takes a slice of import paths and the source directory they are relative to, + // and creates the Deps of the Pkg. Each dependency is also further resolved prior to being added + // to the Pkg. + func (p *Pkg) setDeps(i Importer, imports []string, srcDir string, unique map[string]struct{}, isTest bool) { + for _, imp := range imports { + // Mostly for testing files where cyclic imports are allowed. + if imp == p.Name { + continue + } // Skip duplicates. + if _, ok := unique[imp]; ok { + continue + } + unique[imp] = struct{}{} p.addDep(i, imp, srcDir, isTest) + } sort.Sort(byInternalAndName(p.Deps)) + } // addDep creates a Pkg and it's dependencies from an imported package name. + func (p *Pkg) addDep(i Importer, name string, srcDir string, isTest bool) { + dep := Pkg{ - Name: name, + + Name: name, + SrcDir: srcDir, - Tree: p.Tree, + + Tree: p.Tree, + Parent: p, - Test: isTest, + + Test: isTest, } + dep.Resolve(i) p.Deps = append(p.Deps, dep) + } // isParent goes recursively up the chain of Pkgs to determine if the name provided is ever a + // parent of the current Pkg. + func (p *Pkg) isParent(name string) bool { + if p.Parent == nil { + return false + } if p.Parent.Name == name { + return true + } return p.Parent.isParent(name) + } // depth returns the depth of the Pkg within the Tree. + func (p *Pkg) depth() int { + if p.Parent == nil { + return 0 + } return p.Parent.depth() + 1 + } // cleanName returns a cleaned version of the Pkg name used for resolving dependencies. + // + // If an empty string is returned, dependencies should not be resolved. + func (p *Pkg) cleanName() string { + name := p.Name // C 'package' cannot be resolved. + if name == "C" { + return "" + } // Internal golang_org/* packages must be prefixed with vendor/ + // + // Thanks to @davecheney for this: + // https://github.com/davecheney/graphpkg/blob/master/main.go#L46 + if strings.HasPrefix(name, "golang_org") { + name = path.Join("vendor", name) + } return name + } // String returns a string representation of the Pkg containing the Pkg name and status. + func (p *Pkg) String() string { + b := bytes.NewBufferString(p.Name) if !p.Resolved { + b.Write([]byte(" (unresolved)")) + } return b.String() + } // byInternalAndName ensures a slice of Pkgs are sorted such that the internal stdlib + // packages are always above external packages (ie. github.com/whatever). + type byInternalAndName []Pkg func (b byInternalAndName) Len() int { + return len(b) + } func (b byInternalAndName) Swap(i, j int) { + b[i], b[j] = b[j], b[i] + } func (b byInternalAndName) Less(i, j int) bool { + if b[i].Internal && !b[j].Internal { + return true + } else if !b[i].Internal && b[j].Internal { + return false + } return b[i].Name < b[j].Name + } diff --git a/vendor/github.com/asaskevich/govalidator/converter.go b/vendor/github.com/asaskevich/govalidator/converter.go index cf1e5d5..f8f557a 100644 --- a/vendor/github.com/asaskevich/govalidator/converter.go +++ b/vendor/github.com/asaskevich/govalidator/converter.go @@ -8,57 +8,99 @@ import ( ) // ToString convert the input to a string. + func ToString(obj interface{}) string { + res := fmt.Sprintf("%v", obj) + return string(res) + } // ToJSON convert the input to a valid JSON string + func ToJSON(obj interface{}) (string, error) { + res, err := json.Marshal(obj) + if err != nil { + res = []byte("") + } + return string(res), err + } // ToFloat convert the input string to a float, or 0.0 if the input is not a float. + func ToFloat(str string) (float64, error) { + res, err := strconv.ParseFloat(str, 64) + if err != nil { + res = 0.0 + } + return res, err + } // ToInt convert the input string or any int type to an integer type 64, or 0 if the input is not an integer. + func ToInt(value interface{}) (res int64, err error) { + val := reflect.ValueOf(value) switch value.(type) { + case int, int8, int16, int32, int64: + res = val.Int() + case uint, uint8, uint16, uint32, uint64: + res = int64(val.Uint()) + case string: + if IsInt(val.String()) { + res, err = strconv.ParseInt(val.String(), 0, 64) + if err != nil { + res = 0 + } + } else { + err = fmt.Errorf("math: square root of negative number %g", value) + res = 0 + } + default: + err = fmt.Errorf("math: square root of negative number %g", value) + res = 0 + } return + } // ToBoolean convert the input string to a boolean. + func ToBoolean(str string) (bool, error) { + return strconv.ParseBool(str) + } diff --git a/vendor/github.com/asaskevich/govalidator/numerics.go b/vendor/github.com/asaskevich/govalidator/numerics.go index 7e6c652..1eb6d17 100644 --- a/vendor/github.com/asaskevich/govalidator/numerics.go +++ b/vendor/github.com/asaskevich/govalidator/numerics.go @@ -6,92 +6,155 @@ import ( ) // Abs returns absolute value of number + func Abs(value float64) float64 { + return math.Abs(value) + } // Sign returns signum of number: 1 in case of value > 0, -1 in case of value < 0, 0 otherwise + func Sign(value float64) float64 { + if value > 0 { + return 1 + } else if value < 0 { + return -1 + } else { + return 0 + } + } // IsNegative returns true if value < 0 + func IsNegative(value float64) bool { + return value < 0 + } // IsPositive returns true if value > 0 + func IsPositive(value float64) bool { + return value > 0 + } // IsNonNegative returns true if value >= 0 + func IsNonNegative(value float64) bool { + return value >= 0 + } // IsNonPositive returns true if value <= 0 + func IsNonPositive(value float64) bool { + return value <= 0 + } // InRange returns true if value lies between left and right border + func InRangeInt(value, left, right interface{}) bool { + value64, _ := ToInt(value) + left64, _ := ToInt(left) + right64, _ := ToInt(right) + if left64 > right64 { + left64, right64 = right64, left64 + } + return value64 >= left64 && value64 <= right64 + } // InRange returns true if value lies between left and right border + func InRangeFloat32(value, left, right float32) bool { + if left > right { + left, right = right, left + } + return value >= left && value <= right + } // InRange returns true if value lies between left and right border + func InRangeFloat64(value, left, right float64) bool { + if left > right { + left, right = right, left + } + return value >= left && value <= right + } // InRange returns true if value lies between left and right border, generic type to handle int, float32 or float64, all types must the same type + func InRange(value interface{}, left interface{}, right interface{}) bool { reflectValue := reflect.TypeOf(value).Kind() + reflectLeft := reflect.TypeOf(left).Kind() + reflectRight := reflect.TypeOf(right).Kind() if reflectValue == reflect.Int && reflectLeft == reflect.Int && reflectRight == reflect.Int { + return InRangeInt(value.(int), left.(int), right.(int)) + } else if reflectValue == reflect.Float32 && reflectLeft == reflect.Float32 && reflectRight == reflect.Float32 { + return InRangeFloat32(value.(float32), left.(float32), right.(float32)) + } else if reflectValue == reflect.Float64 && reflectLeft == reflect.Float64 && reflectRight == reflect.Float64 { + return InRangeFloat64(value.(float64), left.(float64), right.(float64)) + } else { + return false + } + } // IsWhole returns true if value is whole number + func IsWhole(value float64) bool { + return math.Remainder(value, 1) == 0 + } // IsNatural returns true if value is natural number (positive and whole) + func IsNatural(value float64) bool { + return IsWhole(value) && IsPositive(value) + } diff --git a/vendor/github.com/asaskevich/govalidator/types.go b/vendor/github.com/asaskevich/govalidator/types.go index 62f8b0d..cdb6fda 100644 --- a/vendor/github.com/asaskevich/govalidator/types.go +++ b/vendor/github.com/asaskevich/govalidator/types.go @@ -8,78 +8,120 @@ import ( ) // Validator is a wrapper for a validator function that returns bool and accepts string. + type Validator func(str string) bool // CustomTypeValidator is a wrapper for validator functions that returns bool and accepts any type. + // The second parameter should be the context (in the case of validating a struct: the whole object being validated). + type CustomTypeValidator func(i interface{}, o interface{}) bool // ParamValidator is a wrapper for validator functions that accepts additional parameters. + type ParamValidator func(str string, params ...string) bool + type InterfaceParamValidator func(in interface{}, params ...string) bool + type tagOptionsMap map[string]tagOption func (t tagOptionsMap) orderedKeys() []string { + var keys []string + for k := range t { + keys = append(keys, k) + } sort.Slice(keys, func(a, b int) bool { + return t[keys[a]].order < t[keys[b]].order + }) return keys + } type tagOption struct { - name string + name string + customErrorMessage string - order int + + order int } // UnsupportedTypeError is a wrapper for reflect.Type + type UnsupportedTypeError struct { Type reflect.Type } // stringValues is a slice of reflect.Value holding *reflect.StringValue. + // It implements the methods to sort by string. + type stringValues []reflect.Value // InterfaceParamTagMap is a map of functions accept variants parameters for an interface value + var InterfaceParamTagMap = map[string]InterfaceParamValidator{ + "type": IsType, } // InterfaceParamTagRegexMap maps interface param tags to their respective regexes. + var InterfaceParamTagRegexMap = map[string]*regexp.Regexp{ + "type": regexp.MustCompile(`^type\((.*)\)$`), } // ParamTagMap is a map of functions accept variants parameters + var ParamTagMap = map[string]ParamValidator{ - "length": ByteLength, - "range": Range, - "runelength": RuneLength, - "stringlength": StringLength, - "matches": StringMatches, - "in": IsInRaw, - "rsapub": IsRsaPub, + + "length": ByteLength, + + "range": Range, + + "runelength": RuneLength, + + "stringlength": StringLength, + + "matches": StringMatches, + + "in": IsInRaw, + + "rsapub": IsRsaPub, + "minstringlength": MinStringLength, + "maxstringlength": MaxStringLength, } // ParamTagRegexMap maps param tags to their respective regexes. + var ParamTagRegexMap = map[string]*regexp.Regexp{ - "range": regexp.MustCompile("^range\\((\\d+)\\|(\\d+)\\)$"), - "length": regexp.MustCompile("^length\\((\\d+)\\|(\\d+)\\)$"), - "runelength": regexp.MustCompile("^runelength\\((\\d+)\\|(\\d+)\\)$"), - "stringlength": regexp.MustCompile("^stringlength\\((\\d+)\\|(\\d+)\\)$"), - "in": regexp.MustCompile(`^in\((.*)\)`), - "matches": regexp.MustCompile(`^matches\((.+)\)$`), - "rsapub": regexp.MustCompile("^rsapub\\((\\d+)\\)$"), + + "range": regexp.MustCompile("^range\\((\\d+)\\|(\\d+)\\)$"), + + "length": regexp.MustCompile("^length\\((\\d+)\\|(\\d+)\\)$"), + + "runelength": regexp.MustCompile("^runelength\\((\\d+)\\|(\\d+)\\)$"), + + "stringlength": regexp.MustCompile("^stringlength\\((\\d+)\\|(\\d+)\\)$"), + + "in": regexp.MustCompile(`^in\((.*)\)`), + + "matches": regexp.MustCompile(`^matches\((.+)\)$`), + + "rsapub": regexp.MustCompile("^rsapub\\((\\d+)\\)$"), + "minstringlength": regexp.MustCompile("^minstringlength\\((\\d+)\\)$"), + "maxstringlength": regexp.MustCompile("^maxstringlength\\((\\d+)\\)$"), } @@ -90,563 +132,1099 @@ type customTypeTagMap struct { } func (tm *customTypeTagMap) Get(name string) (CustomTypeValidator, bool) { + tm.RLock() + defer tm.RUnlock() + v, ok := tm.validators[name] + return v, ok + } func (tm *customTypeTagMap) Set(name string, ctv CustomTypeValidator) { + tm.Lock() + defer tm.Unlock() + tm.validators[name] = ctv + } // CustomTypeTagMap is a map of functions that can be used as tags for ValidateStruct function. + // Use this to validate compound or custom types that need to be handled as a whole, e.g. + // `type UUID [16]byte` (this would be handled as an array of bytes). + var CustomTypeTagMap = &customTypeTagMap{validators: make(map[string]CustomTypeValidator)} // TagMap is a map of functions, that can be used as tags for ValidateStruct function. + var TagMap = map[string]Validator{ - "email": IsEmail, - "url": IsURL, - "dialstring": IsDialString, - "requrl": IsRequestURL, - "requri": IsRequestURI, - "alpha": IsAlpha, - "utfletter": IsUTFLetter, - "alphanum": IsAlphanumeric, - "utfletternum": IsUTFLetterNumeric, - "numeric": IsNumeric, - "utfnumeric": IsUTFNumeric, - "utfdigit": IsUTFDigit, - "hexadecimal": IsHexadecimal, - "hexcolor": IsHexcolor, - "rgbcolor": IsRGBcolor, - "lowercase": IsLowerCase, - "uppercase": IsUpperCase, - "int": IsInt, - "float": IsFloat, - "null": IsNull, - "notnull": IsNotNull, - "uuid": IsUUID, - "uuidv3": IsUUIDv3, - "uuidv4": IsUUIDv4, - "uuidv5": IsUUIDv5, - "creditcard": IsCreditCard, - "isbn10": IsISBN10, - "isbn13": IsISBN13, - "json": IsJSON, - "multibyte": IsMultibyte, - "ascii": IsASCII, - "printableascii": IsPrintableASCII, - "fullwidth": IsFullWidth, - "halfwidth": IsHalfWidth, - "variablewidth": IsVariableWidth, - "base64": IsBase64, - "datauri": IsDataURI, - "ip": IsIP, - "port": IsPort, - "ipv4": IsIPv4, - "ipv6": IsIPv6, - "dns": IsDNSName, - "host": IsHost, - "mac": IsMAC, - "latitude": IsLatitude, - "longitude": IsLongitude, - "ssn": IsSSN, - "semver": IsSemver, - "rfc3339": IsRFC3339, + + "email": IsEmail, + + "url": IsURL, + + "dialstring": IsDialString, + + "requrl": IsRequestURL, + + "requri": IsRequestURI, + + "alpha": IsAlpha, + + "utfletter": IsUTFLetter, + + "alphanum": IsAlphanumeric, + + "utfletternum": IsUTFLetterNumeric, + + "numeric": IsNumeric, + + "utfnumeric": IsUTFNumeric, + + "utfdigit": IsUTFDigit, + + "hexadecimal": IsHexadecimal, + + "hexcolor": IsHexcolor, + + "rgbcolor": IsRGBcolor, + + "lowercase": IsLowerCase, + + "uppercase": IsUpperCase, + + "int": IsInt, + + "float": IsFloat, + + "null": IsNull, + + "notnull": IsNotNull, + + "uuid": IsUUID, + + "uuidv3": IsUUIDv3, + + "uuidv4": IsUUIDv4, + + "uuidv5": IsUUIDv5, + + "creditcard": IsCreditCard, + + "isbn10": IsISBN10, + + "isbn13": IsISBN13, + + "json": IsJSON, + + "multibyte": IsMultibyte, + + "ascii": IsASCII, + + "printableascii": IsPrintableASCII, + + "fullwidth": IsFullWidth, + + "halfwidth": IsHalfWidth, + + "variablewidth": IsVariableWidth, + + "base64": IsBase64, + + "datauri": IsDataURI, + + "ip": IsIP, + + "port": IsPort, + + "ipv4": IsIPv4, + + "ipv6": IsIPv6, + + "dns": IsDNSName, + + "host": IsHost, + + "mac": IsMAC, + + "latitude": IsLatitude, + + "longitude": IsLongitude, + + "ssn": IsSSN, + + "semver": IsSemver, + + "rfc3339": IsRFC3339, + "rfc3339WithoutZone": IsRFC3339WithoutZone, - "ISO3166Alpha2": IsISO3166Alpha2, - "ISO3166Alpha3": IsISO3166Alpha3, - "ISO4217": IsISO4217, + + "ISO3166Alpha2": IsISO3166Alpha2, + + "ISO3166Alpha3": IsISO3166Alpha3, + + "ISO4217": IsISO4217, } // ISO3166Entry stores country codes + type ISO3166Entry struct { EnglishShortName string - FrenchShortName string - Alpha2Code string - Alpha3Code string - Numeric string + + FrenchShortName string + + Alpha2Code string + + Alpha3Code string + + Numeric string } // ISO3166List based on https://www.iso.org/obp/ui/#search/code/ Code Type "Officially Assigned Codes" + var ISO3166List = []ISO3166Entry{ + {"Afghanistan", "Afghanistan (l')", "AF", "AFG", "004"}, + {"Albania", "Albanie (l')", "AL", "ALB", "008"}, + {"Antarctica", "Antarctique (l')", "AQ", "ATA", "010"}, + {"Algeria", "Algérie (l')", "DZ", "DZA", "012"}, + {"American Samoa", "Samoa américaines (les)", "AS", "ASM", "016"}, + {"Andorra", "Andorre (l')", "AD", "AND", "020"}, + {"Angola", "Angola (l')", "AO", "AGO", "024"}, + {"Antigua and Barbuda", "Antigua-et-Barbuda", "AG", "ATG", "028"}, + {"Azerbaijan", "Azerbaïdjan (l')", "AZ", "AZE", "031"}, + {"Argentina", "Argentine (l')", "AR", "ARG", "032"}, + {"Australia", "Australie (l')", "AU", "AUS", "036"}, + {"Austria", "Autriche (l')", "AT", "AUT", "040"}, + {"Bahamas (the)", "Bahamas (les)", "BS", "BHS", "044"}, + {"Bahrain", "Bahreïn", "BH", "BHR", "048"}, + {"Bangladesh", "Bangladesh (le)", "BD", "BGD", "050"}, + {"Armenia", "Arménie (l')", "AM", "ARM", "051"}, + {"Barbados", "Barbade (la)", "BB", "BRB", "052"}, + {"Belgium", "Belgique (la)", "BE", "BEL", "056"}, + {"Bermuda", "Bermudes (les)", "BM", "BMU", "060"}, + {"Bhutan", "Bhoutan (le)", "BT", "BTN", "064"}, + {"Bolivia (Plurinational State of)", "Bolivie (État plurinational de)", "BO", "BOL", "068"}, + {"Bosnia and Herzegovina", "Bosnie-Herzégovine (la)", "BA", "BIH", "070"}, + {"Botswana", "Botswana (le)", "BW", "BWA", "072"}, + {"Bouvet Island", "Bouvet (l'Île)", "BV", "BVT", "074"}, + {"Brazil", "Brésil (le)", "BR", "BRA", "076"}, + {"Belize", "Belize (le)", "BZ", "BLZ", "084"}, + {"British Indian Ocean Territory (the)", "Indien (le Territoire britannique de l'océan)", "IO", "IOT", "086"}, + {"Solomon Islands", "Salomon (Îles)", "SB", "SLB", "090"}, + {"Virgin Islands (British)", "Vierges britanniques (les Îles)", "VG", "VGB", "092"}, + {"Brunei Darussalam", "Brunéi Darussalam (le)", "BN", "BRN", "096"}, + {"Bulgaria", "Bulgarie (la)", "BG", "BGR", "100"}, + {"Myanmar", "Myanmar (le)", "MM", "MMR", "104"}, + {"Burundi", "Burundi (le)", "BI", "BDI", "108"}, + {"Belarus", "Bélarus (le)", "BY", "BLR", "112"}, + {"Cambodia", "Cambodge (le)", "KH", "KHM", "116"}, + {"Cameroon", "Cameroun (le)", "CM", "CMR", "120"}, + {"Canada", "Canada (le)", "CA", "CAN", "124"}, + {"Cabo Verde", "Cabo Verde", "CV", "CPV", "132"}, + {"Cayman Islands (the)", "Caïmans (les Îles)", "KY", "CYM", "136"}, + {"Central African Republic (the)", "République centrafricaine (la)", "CF", "CAF", "140"}, + {"Sri Lanka", "Sri Lanka", "LK", "LKA", "144"}, + {"Chad", "Tchad (le)", "TD", "TCD", "148"}, + {"Chile", "Chili (le)", "CL", "CHL", "152"}, + {"China", "Chine (la)", "CN", "CHN", "156"}, + {"Taiwan (Province of China)", "Taïwan (Province de Chine)", "TW", "TWN", "158"}, + {"Christmas Island", "Christmas (l'Île)", "CX", "CXR", "162"}, + {"Cocos (Keeling) Islands (the)", "Cocos (les Îles)/ Keeling (les Îles)", "CC", "CCK", "166"}, + {"Colombia", "Colombie (la)", "CO", "COL", "170"}, + {"Comoros (the)", "Comores (les)", "KM", "COM", "174"}, + {"Mayotte", "Mayotte", "YT", "MYT", "175"}, + {"Congo (the)", "Congo (le)", "CG", "COG", "178"}, + {"Congo (the Democratic Republic of the)", "Congo (la République démocratique du)", "CD", "COD", "180"}, + {"Cook Islands (the)", "Cook (les Îles)", "CK", "COK", "184"}, + {"Costa Rica", "Costa Rica (le)", "CR", "CRI", "188"}, + {"Croatia", "Croatie (la)", "HR", "HRV", "191"}, + {"Cuba", "Cuba", "CU", "CUB", "192"}, + {"Cyprus", "Chypre", "CY", "CYP", "196"}, + {"Czech Republic (the)", "tchèque (la République)", "CZ", "CZE", "203"}, + {"Benin", "Bénin (le)", "BJ", "BEN", "204"}, + {"Denmark", "Danemark (le)", "DK", "DNK", "208"}, + {"Dominica", "Dominique (la)", "DM", "DMA", "212"}, + {"Dominican Republic (the)", "dominicaine (la République)", "DO", "DOM", "214"}, + {"Ecuador", "Équateur (l')", "EC", "ECU", "218"}, + {"El Salvador", "El Salvador", "SV", "SLV", "222"}, + {"Equatorial Guinea", "Guinée équatoriale (la)", "GQ", "GNQ", "226"}, + {"Ethiopia", "Éthiopie (l')", "ET", "ETH", "231"}, + {"Eritrea", "Érythrée (l')", "ER", "ERI", "232"}, + {"Estonia", "Estonie (l')", "EE", "EST", "233"}, + {"Faroe Islands (the)", "Féroé (les Îles)", "FO", "FRO", "234"}, + {"Falkland Islands (the) [Malvinas]", "Falkland (les Îles)/Malouines (les Îles)", "FK", "FLK", "238"}, + {"South Georgia and the South Sandwich Islands", "Géorgie du Sud-et-les Îles Sandwich du Sud (la)", "GS", "SGS", "239"}, + {"Fiji", "Fidji (les)", "FJ", "FJI", "242"}, + {"Finland", "Finlande (la)", "FI", "FIN", "246"}, + {"Åland Islands", "Åland(les Îles)", "AX", "ALA", "248"}, + {"France", "France (la)", "FR", "FRA", "250"}, + {"French Guiana", "Guyane française (la )", "GF", "GUF", "254"}, + {"French Polynesia", "Polynésie française (la)", "PF", "PYF", "258"}, + {"French Southern Territories (the)", "Terres australes françaises (les)", "TF", "ATF", "260"}, + {"Djibouti", "Djibouti", "DJ", "DJI", "262"}, + {"Gabon", "Gabon (le)", "GA", "GAB", "266"}, + {"Georgia", "Géorgie (la)", "GE", "GEO", "268"}, + {"Gambia (the)", "Gambie (la)", "GM", "GMB", "270"}, + {"Palestine, State of", "Palestine, État de", "PS", "PSE", "275"}, + {"Germany", "Allemagne (l')", "DE", "DEU", "276"}, + {"Ghana", "Ghana (le)", "GH", "GHA", "288"}, + {"Gibraltar", "Gibraltar", "GI", "GIB", "292"}, + {"Kiribati", "Kiribati", "KI", "KIR", "296"}, + {"Greece", "Grèce (la)", "GR", "GRC", "300"}, + {"Greenland", "Groenland (le)", "GL", "GRL", "304"}, + {"Grenada", "Grenade (la)", "GD", "GRD", "308"}, + {"Guadeloupe", "Guadeloupe (la)", "GP", "GLP", "312"}, + {"Guam", "Guam", "GU", "GUM", "316"}, + {"Guatemala", "Guatemala (le)", "GT", "GTM", "320"}, + {"Guinea", "Guinée (la)", "GN", "GIN", "324"}, + {"Guyana", "Guyana (le)", "GY", "GUY", "328"}, + {"Haiti", "Haïti", "HT", "HTI", "332"}, + {"Heard Island and McDonald Islands", "Heard-et-Îles MacDonald (l'Île)", "HM", "HMD", "334"}, + {"Holy See (the)", "Saint-Siège (le)", "VA", "VAT", "336"}, + {"Honduras", "Honduras (le)", "HN", "HND", "340"}, + {"Hong Kong", "Hong Kong", "HK", "HKG", "344"}, + {"Hungary", "Hongrie (la)", "HU", "HUN", "348"}, + {"Iceland", "Islande (l')", "IS", "ISL", "352"}, + {"India", "Inde (l')", "IN", "IND", "356"}, + {"Indonesia", "Indonésie (l')", "ID", "IDN", "360"}, + {"Iran (Islamic Republic of)", "Iran (République Islamique d')", "IR", "IRN", "364"}, + {"Iraq", "Iraq (l')", "IQ", "IRQ", "368"}, + {"Ireland", "Irlande (l')", "IE", "IRL", "372"}, + {"Israel", "Israël", "IL", "ISR", "376"}, + {"Italy", "Italie (l')", "IT", "ITA", "380"}, + {"Côte d'Ivoire", "Côte d'Ivoire (la)", "CI", "CIV", "384"}, + {"Jamaica", "Jamaïque (la)", "JM", "JAM", "388"}, + {"Japan", "Japon (le)", "JP", "JPN", "392"}, + {"Kazakhstan", "Kazakhstan (le)", "KZ", "KAZ", "398"}, + {"Jordan", "Jordanie (la)", "JO", "JOR", "400"}, + {"Kenya", "Kenya (le)", "KE", "KEN", "404"}, + {"Korea (the Democratic People's Republic of)", "Corée (la République populaire démocratique de)", "KP", "PRK", "408"}, + {"Korea (the Republic of)", "Corée (la République de)", "KR", "KOR", "410"}, + {"Kuwait", "Koweït (le)", "KW", "KWT", "414"}, + {"Kyrgyzstan", "Kirghizistan (le)", "KG", "KGZ", "417"}, + {"Lao People's Democratic Republic (the)", "Lao, République démocratique populaire", "LA", "LAO", "418"}, + {"Lebanon", "Liban (le)", "LB", "LBN", "422"}, + {"Lesotho", "Lesotho (le)", "LS", "LSO", "426"}, + {"Latvia", "Lettonie (la)", "LV", "LVA", "428"}, + {"Liberia", "Libéria (le)", "LR", "LBR", "430"}, + {"Libya", "Libye (la)", "LY", "LBY", "434"}, + {"Liechtenstein", "Liechtenstein (le)", "LI", "LIE", "438"}, + {"Lithuania", "Lituanie (la)", "LT", "LTU", "440"}, + {"Luxembourg", "Luxembourg (le)", "LU", "LUX", "442"}, + {"Macao", "Macao", "MO", "MAC", "446"}, + {"Madagascar", "Madagascar", "MG", "MDG", "450"}, + {"Malawi", "Malawi (le)", "MW", "MWI", "454"}, + {"Malaysia", "Malaisie (la)", "MY", "MYS", "458"}, + {"Maldives", "Maldives (les)", "MV", "MDV", "462"}, + {"Mali", "Mali (le)", "ML", "MLI", "466"}, + {"Malta", "Malte", "MT", "MLT", "470"}, + {"Martinique", "Martinique (la)", "MQ", "MTQ", "474"}, + {"Mauritania", "Mauritanie (la)", "MR", "MRT", "478"}, + {"Mauritius", "Maurice", "MU", "MUS", "480"}, + {"Mexico", "Mexique (le)", "MX", "MEX", "484"}, + {"Monaco", "Monaco", "MC", "MCO", "492"}, + {"Mongolia", "Mongolie (la)", "MN", "MNG", "496"}, + {"Moldova (the Republic of)", "Moldova , République de", "MD", "MDA", "498"}, + {"Montenegro", "Monténégro (le)", "ME", "MNE", "499"}, + {"Montserrat", "Montserrat", "MS", "MSR", "500"}, + {"Morocco", "Maroc (le)", "MA", "MAR", "504"}, + {"Mozambique", "Mozambique (le)", "MZ", "MOZ", "508"}, + {"Oman", "Oman", "OM", "OMN", "512"}, + {"Namibia", "Namibie (la)", "NA", "NAM", "516"}, + {"Nauru", "Nauru", "NR", "NRU", "520"}, + {"Nepal", "Népal (le)", "NP", "NPL", "524"}, + {"Netherlands (the)", "Pays-Bas (les)", "NL", "NLD", "528"}, + {"Curaçao", "Curaçao", "CW", "CUW", "531"}, + {"Aruba", "Aruba", "AW", "ABW", "533"}, + {"Sint Maarten (Dutch part)", "Saint-Martin (partie néerlandaise)", "SX", "SXM", "534"}, + {"Bonaire, Sint Eustatius and Saba", "Bonaire, Saint-Eustache et Saba", "BQ", "BES", "535"}, + {"New Caledonia", "Nouvelle-Calédonie (la)", "NC", "NCL", "540"}, + {"Vanuatu", "Vanuatu (le)", "VU", "VUT", "548"}, + {"New Zealand", "Nouvelle-Zélande (la)", "NZ", "NZL", "554"}, + {"Nicaragua", "Nicaragua (le)", "NI", "NIC", "558"}, + {"Niger (the)", "Niger (le)", "NE", "NER", "562"}, + {"Nigeria", "Nigéria (le)", "NG", "NGA", "566"}, + {"Niue", "Niue", "NU", "NIU", "570"}, + {"Norfolk Island", "Norfolk (l'Île)", "NF", "NFK", "574"}, + {"Norway", "Norvège (la)", "NO", "NOR", "578"}, + {"Northern Mariana Islands (the)", "Mariannes du Nord (les Îles)", "MP", "MNP", "580"}, + {"United States Minor Outlying Islands (the)", "Îles mineures éloignées des États-Unis (les)", "UM", "UMI", "581"}, + {"Micronesia (Federated States of)", "Micronésie (États fédérés de)", "FM", "FSM", "583"}, + {"Marshall Islands (the)", "Marshall (Îles)", "MH", "MHL", "584"}, + {"Palau", "Palaos (les)", "PW", "PLW", "585"}, + {"Pakistan", "Pakistan (le)", "PK", "PAK", "586"}, + {"Panama", "Panama (le)", "PA", "PAN", "591"}, + {"Papua New Guinea", "Papouasie-Nouvelle-Guinée (la)", "PG", "PNG", "598"}, + {"Paraguay", "Paraguay (le)", "PY", "PRY", "600"}, + {"Peru", "Pérou (le)", "PE", "PER", "604"}, + {"Philippines (the)", "Philippines (les)", "PH", "PHL", "608"}, + {"Pitcairn", "Pitcairn", "PN", "PCN", "612"}, + {"Poland", "Pologne (la)", "PL", "POL", "616"}, + {"Portugal", "Portugal (le)", "PT", "PRT", "620"}, + {"Guinea-Bissau", "Guinée-Bissau (la)", "GW", "GNB", "624"}, + {"Timor-Leste", "Timor-Leste (le)", "TL", "TLS", "626"}, + {"Puerto Rico", "Porto Rico", "PR", "PRI", "630"}, + {"Qatar", "Qatar (le)", "QA", "QAT", "634"}, + {"Réunion", "Réunion (La)", "RE", "REU", "638"}, + {"Romania", "Roumanie (la)", "RO", "ROU", "642"}, + {"Russian Federation (the)", "Russie (la Fédération de)", "RU", "RUS", "643"}, + {"Rwanda", "Rwanda (le)", "RW", "RWA", "646"}, + {"Saint Barthélemy", "Saint-Barthélemy", "BL", "BLM", "652"}, + {"Saint Helena, Ascension and Tristan da Cunha", "Sainte-Hélène, Ascension et Tristan da Cunha", "SH", "SHN", "654"}, + {"Saint Kitts and Nevis", "Saint-Kitts-et-Nevis", "KN", "KNA", "659"}, + {"Anguilla", "Anguilla", "AI", "AIA", "660"}, + {"Saint Lucia", "Sainte-Lucie", "LC", "LCA", "662"}, + {"Saint Martin (French part)", "Saint-Martin (partie française)", "MF", "MAF", "663"}, + {"Saint Pierre and Miquelon", "Saint-Pierre-et-Miquelon", "PM", "SPM", "666"}, + {"Saint Vincent and the Grenadines", "Saint-Vincent-et-les Grenadines", "VC", "VCT", "670"}, + {"San Marino", "Saint-Marin", "SM", "SMR", "674"}, + {"Sao Tome and Principe", "Sao Tomé-et-Principe", "ST", "STP", "678"}, + {"Saudi Arabia", "Arabie saoudite (l')", "SA", "SAU", "682"}, + {"Senegal", "Sénégal (le)", "SN", "SEN", "686"}, + {"Serbia", "Serbie (la)", "RS", "SRB", "688"}, + {"Seychelles", "Seychelles (les)", "SC", "SYC", "690"}, + {"Sierra Leone", "Sierra Leone (la)", "SL", "SLE", "694"}, + {"Singapore", "Singapour", "SG", "SGP", "702"}, + {"Slovakia", "Slovaquie (la)", "SK", "SVK", "703"}, + {"Viet Nam", "Viet Nam (le)", "VN", "VNM", "704"}, + {"Slovenia", "Slovénie (la)", "SI", "SVN", "705"}, + {"Somalia", "Somalie (la)", "SO", "SOM", "706"}, + {"South Africa", "Afrique du Sud (l')", "ZA", "ZAF", "710"}, + {"Zimbabwe", "Zimbabwe (le)", "ZW", "ZWE", "716"}, + {"Spain", "Espagne (l')", "ES", "ESP", "724"}, + {"South Sudan", "Soudan du Sud (le)", "SS", "SSD", "728"}, + {"Sudan (the)", "Soudan (le)", "SD", "SDN", "729"}, + {"Western Sahara*", "Sahara occidental (le)*", "EH", "ESH", "732"}, + {"Suriname", "Suriname (le)", "SR", "SUR", "740"}, + {"Svalbard and Jan Mayen", "Svalbard et l'Île Jan Mayen (le)", "SJ", "SJM", "744"}, + {"Swaziland", "Swaziland (le)", "SZ", "SWZ", "748"}, + {"Sweden", "Suède (la)", "SE", "SWE", "752"}, + {"Switzerland", "Suisse (la)", "CH", "CHE", "756"}, + {"Syrian Arab Republic", "République arabe syrienne (la)", "SY", "SYR", "760"}, + {"Tajikistan", "Tadjikistan (le)", "TJ", "TJK", "762"}, + {"Thailand", "Thaïlande (la)", "TH", "THA", "764"}, + {"Togo", "Togo (le)", "TG", "TGO", "768"}, + {"Tokelau", "Tokelau (les)", "TK", "TKL", "772"}, + {"Tonga", "Tonga (les)", "TO", "TON", "776"}, + {"Trinidad and Tobago", "Trinité-et-Tobago (la)", "TT", "TTO", "780"}, + {"United Arab Emirates (the)", "Émirats arabes unis (les)", "AE", "ARE", "784"}, + {"Tunisia", "Tunisie (la)", "TN", "TUN", "788"}, + {"Turkey", "Turquie (la)", "TR", "TUR", "792"}, + {"Turkmenistan", "Turkménistan (le)", "TM", "TKM", "795"}, + {"Turks and Caicos Islands (the)", "Turks-et-Caïcos (les Îles)", "TC", "TCA", "796"}, + {"Tuvalu", "Tuvalu (les)", "TV", "TUV", "798"}, + {"Uganda", "Ouganda (l')", "UG", "UGA", "800"}, + {"Ukraine", "Ukraine (l')", "UA", "UKR", "804"}, + {"Macedonia (the former Yugoslav Republic of)", "Macédoine (l'ex‑République yougoslave de)", "MK", "MKD", "807"}, + {"Egypt", "Égypte (l')", "EG", "EGY", "818"}, + {"United Kingdom of Great Britain and Northern Ireland (the)", "Royaume-Uni de Grande-Bretagne et d'Irlande du Nord (le)", "GB", "GBR", "826"}, + {"Guernsey", "Guernesey", "GG", "GGY", "831"}, + {"Jersey", "Jersey", "JE", "JEY", "832"}, + {"Isle of Man", "Île de Man", "IM", "IMN", "833"}, + {"Tanzania, United Republic of", "Tanzanie, République-Unie de", "TZ", "TZA", "834"}, + {"United States of America (the)", "États-Unis d'Amérique (les)", "US", "USA", "840"}, + {"Virgin Islands (U.S.)", "Vierges des États-Unis (les Îles)", "VI", "VIR", "850"}, + {"Burkina Faso", "Burkina Faso (le)", "BF", "BFA", "854"}, + {"Uruguay", "Uruguay (l')", "UY", "URY", "858"}, + {"Uzbekistan", "Ouzbékistan (l')", "UZ", "UZB", "860"}, + {"Venezuela (Bolivarian Republic of)", "Venezuela (République bolivarienne du)", "VE", "VEN", "862"}, + {"Wallis and Futuna", "Wallis-et-Futuna", "WF", "WLF", "876"}, + {"Samoa", "Samoa (le)", "WS", "WSM", "882"}, + {"Yemen", "Yémen (le)", "YE", "YEM", "887"}, + {"Zambia", "Zambie (la)", "ZM", "ZMB", "894"}, } // ISO4217List is the list of ISO currency codes + var ISO4217List = []string{ + "AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", + "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", "BOB", "BOV", "BRL", "BSD", "BTN", "BWP", "BYN", "BZD", + "CAD", "CDF", "CHE", "CHF", "CHW", "CLF", "CLP", "CNY", "COP", "COU", "CRC", "CUC", "CUP", "CVE", "CZK", + "DJF", "DKK", "DOP", "DZD", + "EGP", "ERN", "ETB", "EUR", + "FJD", "FKP", + "GBP", "GEL", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", + "HKD", "HNL", "HRK", "HTG", "HUF", + "IDR", "ILS", "INR", "IQD", "IRR", "ISK", + "JMD", "JOD", "JPY", + "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT", + "LAK", "LBP", "LKR", "LRD", "LSL", "LYD", + "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRO", "MUR", "MVR", "MWK", "MXN", "MXV", "MYR", "MZN", + "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", + "OMR", + "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG", + "QAR", + "RON", "RSD", "RUB", "RWF", + "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SLL", "SOS", "SRD", "SSP", "STD", "SVC", "SYP", "SZL", + "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TWD", "TZS", + "UAH", "UGX", "USD", "USN", "UYI", "UYU", "UZS", + "VEF", "VND", "VUV", + "WST", + "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XOF", "XPD", "XPF", "XPT", "XSU", "XTS", "XUA", "XXX", + "YER", + "ZAR", "ZMW", "ZWL", } // ISO693Entry stores ISO language codes + type ISO693Entry struct { Alpha3bCode string - Alpha2Code string - English string + + Alpha2Code string + + English string } // ISO693List based on http://data.okfn.org/data/core/language-codes/r/language-codes-3b2.json + var ISO693List = []ISO693Entry{ + {Alpha3bCode: "aar", Alpha2Code: "aa", English: "Afar"}, + {Alpha3bCode: "abk", Alpha2Code: "ab", English: "Abkhazian"}, + {Alpha3bCode: "afr", Alpha2Code: "af", English: "Afrikaans"}, + {Alpha3bCode: "aka", Alpha2Code: "ak", English: "Akan"}, + {Alpha3bCode: "alb", Alpha2Code: "sq", English: "Albanian"}, + {Alpha3bCode: "amh", Alpha2Code: "am", English: "Amharic"}, + {Alpha3bCode: "ara", Alpha2Code: "ar", English: "Arabic"}, + {Alpha3bCode: "arg", Alpha2Code: "an", English: "Aragonese"}, + {Alpha3bCode: "arm", Alpha2Code: "hy", English: "Armenian"}, + {Alpha3bCode: "asm", Alpha2Code: "as", English: "Assamese"}, + {Alpha3bCode: "ava", Alpha2Code: "av", English: "Avaric"}, + {Alpha3bCode: "ave", Alpha2Code: "ae", English: "Avestan"}, + {Alpha3bCode: "aym", Alpha2Code: "ay", English: "Aymara"}, + {Alpha3bCode: "aze", Alpha2Code: "az", English: "Azerbaijani"}, + {Alpha3bCode: "bak", Alpha2Code: "ba", English: "Bashkir"}, + {Alpha3bCode: "bam", Alpha2Code: "bm", English: "Bambara"}, + {Alpha3bCode: "baq", Alpha2Code: "eu", English: "Basque"}, + {Alpha3bCode: "bel", Alpha2Code: "be", English: "Belarusian"}, + {Alpha3bCode: "ben", Alpha2Code: "bn", English: "Bengali"}, + {Alpha3bCode: "bih", Alpha2Code: "bh", English: "Bihari languages"}, + {Alpha3bCode: "bis", Alpha2Code: "bi", English: "Bislama"}, + {Alpha3bCode: "bos", Alpha2Code: "bs", English: "Bosnian"}, + {Alpha3bCode: "bre", Alpha2Code: "br", English: "Breton"}, + {Alpha3bCode: "bul", Alpha2Code: "bg", English: "Bulgarian"}, + {Alpha3bCode: "bur", Alpha2Code: "my", English: "Burmese"}, + {Alpha3bCode: "cat", Alpha2Code: "ca", English: "Catalan; Valencian"}, + {Alpha3bCode: "cha", Alpha2Code: "ch", English: "Chamorro"}, + {Alpha3bCode: "che", Alpha2Code: "ce", English: "Chechen"}, + {Alpha3bCode: "chi", Alpha2Code: "zh", English: "Chinese"}, + {Alpha3bCode: "chu", Alpha2Code: "cu", English: "Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic"}, + {Alpha3bCode: "chv", Alpha2Code: "cv", English: "Chuvash"}, + {Alpha3bCode: "cor", Alpha2Code: "kw", English: "Cornish"}, + {Alpha3bCode: "cos", Alpha2Code: "co", English: "Corsican"}, + {Alpha3bCode: "cre", Alpha2Code: "cr", English: "Cree"}, + {Alpha3bCode: "cze", Alpha2Code: "cs", English: "Czech"}, + {Alpha3bCode: "dan", Alpha2Code: "da", English: "Danish"}, + {Alpha3bCode: "div", Alpha2Code: "dv", English: "Divehi; Dhivehi; Maldivian"}, + {Alpha3bCode: "dut", Alpha2Code: "nl", English: "Dutch; Flemish"}, + {Alpha3bCode: "dzo", Alpha2Code: "dz", English: "Dzongkha"}, + {Alpha3bCode: "eng", Alpha2Code: "en", English: "English"}, + {Alpha3bCode: "epo", Alpha2Code: "eo", English: "Esperanto"}, + {Alpha3bCode: "est", Alpha2Code: "et", English: "Estonian"}, + {Alpha3bCode: "ewe", Alpha2Code: "ee", English: "Ewe"}, + {Alpha3bCode: "fao", Alpha2Code: "fo", English: "Faroese"}, + {Alpha3bCode: "fij", Alpha2Code: "fj", English: "Fijian"}, + {Alpha3bCode: "fin", Alpha2Code: "fi", English: "Finnish"}, + {Alpha3bCode: "fre", Alpha2Code: "fr", English: "French"}, + {Alpha3bCode: "fry", Alpha2Code: "fy", English: "Western Frisian"}, + {Alpha3bCode: "ful", Alpha2Code: "ff", English: "Fulah"}, + {Alpha3bCode: "geo", Alpha2Code: "ka", English: "Georgian"}, + {Alpha3bCode: "ger", Alpha2Code: "de", English: "German"}, + {Alpha3bCode: "gla", Alpha2Code: "gd", English: "Gaelic; Scottish Gaelic"}, + {Alpha3bCode: "gle", Alpha2Code: "ga", English: "Irish"}, + {Alpha3bCode: "glg", Alpha2Code: "gl", English: "Galician"}, + {Alpha3bCode: "glv", Alpha2Code: "gv", English: "Manx"}, + {Alpha3bCode: "gre", Alpha2Code: "el", English: "Greek, Modern (1453-)"}, + {Alpha3bCode: "grn", Alpha2Code: "gn", English: "Guarani"}, + {Alpha3bCode: "guj", Alpha2Code: "gu", English: "Gujarati"}, + {Alpha3bCode: "hat", Alpha2Code: "ht", English: "Haitian; Haitian Creole"}, + {Alpha3bCode: "hau", Alpha2Code: "ha", English: "Hausa"}, + {Alpha3bCode: "heb", Alpha2Code: "he", English: "Hebrew"}, + {Alpha3bCode: "her", Alpha2Code: "hz", English: "Herero"}, + {Alpha3bCode: "hin", Alpha2Code: "hi", English: "Hindi"}, + {Alpha3bCode: "hmo", Alpha2Code: "ho", English: "Hiri Motu"}, + {Alpha3bCode: "hrv", Alpha2Code: "hr", English: "Croatian"}, + {Alpha3bCode: "hun", Alpha2Code: "hu", English: "Hungarian"}, + {Alpha3bCode: "ibo", Alpha2Code: "ig", English: "Igbo"}, + {Alpha3bCode: "ice", Alpha2Code: "is", English: "Icelandic"}, + {Alpha3bCode: "ido", Alpha2Code: "io", English: "Ido"}, + {Alpha3bCode: "iii", Alpha2Code: "ii", English: "Sichuan Yi; Nuosu"}, + {Alpha3bCode: "iku", Alpha2Code: "iu", English: "Inuktitut"}, + {Alpha3bCode: "ile", Alpha2Code: "ie", English: "Interlingue; Occidental"}, + {Alpha3bCode: "ina", Alpha2Code: "ia", English: "Interlingua (International Auxiliary Language Association)"}, + {Alpha3bCode: "ind", Alpha2Code: "id", English: "Indonesian"}, + {Alpha3bCode: "ipk", Alpha2Code: "ik", English: "Inupiaq"}, + {Alpha3bCode: "ita", Alpha2Code: "it", English: "Italian"}, + {Alpha3bCode: "jav", Alpha2Code: "jv", English: "Javanese"}, + {Alpha3bCode: "jpn", Alpha2Code: "ja", English: "Japanese"}, + {Alpha3bCode: "kal", Alpha2Code: "kl", English: "Kalaallisut; Greenlandic"}, + {Alpha3bCode: "kan", Alpha2Code: "kn", English: "Kannada"}, + {Alpha3bCode: "kas", Alpha2Code: "ks", English: "Kashmiri"}, + {Alpha3bCode: "kau", Alpha2Code: "kr", English: "Kanuri"}, + {Alpha3bCode: "kaz", Alpha2Code: "kk", English: "Kazakh"}, + {Alpha3bCode: "khm", Alpha2Code: "km", English: "Central Khmer"}, + {Alpha3bCode: "kik", Alpha2Code: "ki", English: "Kikuyu; Gikuyu"}, + {Alpha3bCode: "kin", Alpha2Code: "rw", English: "Kinyarwanda"}, + {Alpha3bCode: "kir", Alpha2Code: "ky", English: "Kirghiz; Kyrgyz"}, + {Alpha3bCode: "kom", Alpha2Code: "kv", English: "Komi"}, + {Alpha3bCode: "kon", Alpha2Code: "kg", English: "Kongo"}, + {Alpha3bCode: "kor", Alpha2Code: "ko", English: "Korean"}, + {Alpha3bCode: "kua", Alpha2Code: "kj", English: "Kuanyama; Kwanyama"}, + {Alpha3bCode: "kur", Alpha2Code: "ku", English: "Kurdish"}, + {Alpha3bCode: "lao", Alpha2Code: "lo", English: "Lao"}, + {Alpha3bCode: "lat", Alpha2Code: "la", English: "Latin"}, + {Alpha3bCode: "lav", Alpha2Code: "lv", English: "Latvian"}, + {Alpha3bCode: "lim", Alpha2Code: "li", English: "Limburgan; Limburger; Limburgish"}, + {Alpha3bCode: "lin", Alpha2Code: "ln", English: "Lingala"}, + {Alpha3bCode: "lit", Alpha2Code: "lt", English: "Lithuanian"}, + {Alpha3bCode: "ltz", Alpha2Code: "lb", English: "Luxembourgish; Letzeburgesch"}, + {Alpha3bCode: "lub", Alpha2Code: "lu", English: "Luba-Katanga"}, + {Alpha3bCode: "lug", Alpha2Code: "lg", English: "Ganda"}, + {Alpha3bCode: "mac", Alpha2Code: "mk", English: "Macedonian"}, + {Alpha3bCode: "mah", Alpha2Code: "mh", English: "Marshallese"}, + {Alpha3bCode: "mal", Alpha2Code: "ml", English: "Malayalam"}, + {Alpha3bCode: "mao", Alpha2Code: "mi", English: "Maori"}, + {Alpha3bCode: "mar", Alpha2Code: "mr", English: "Marathi"}, + {Alpha3bCode: "may", Alpha2Code: "ms", English: "Malay"}, + {Alpha3bCode: "mlg", Alpha2Code: "mg", English: "Malagasy"}, + {Alpha3bCode: "mlt", Alpha2Code: "mt", English: "Maltese"}, + {Alpha3bCode: "mon", Alpha2Code: "mn", English: "Mongolian"}, + {Alpha3bCode: "nau", Alpha2Code: "na", English: "Nauru"}, + {Alpha3bCode: "nav", Alpha2Code: "nv", English: "Navajo; Navaho"}, + {Alpha3bCode: "nbl", Alpha2Code: "nr", English: "Ndebele, South; South Ndebele"}, + {Alpha3bCode: "nde", Alpha2Code: "nd", English: "Ndebele, North; North Ndebele"}, + {Alpha3bCode: "ndo", Alpha2Code: "ng", English: "Ndonga"}, + {Alpha3bCode: "nep", Alpha2Code: "ne", English: "Nepali"}, + {Alpha3bCode: "nno", Alpha2Code: "nn", English: "Norwegian Nynorsk; Nynorsk, Norwegian"}, + {Alpha3bCode: "nob", Alpha2Code: "nb", English: "Bokmål, Norwegian; Norwegian Bokmål"}, + {Alpha3bCode: "nor", Alpha2Code: "no", English: "Norwegian"}, + {Alpha3bCode: "nya", Alpha2Code: "ny", English: "Chichewa; Chewa; Nyanja"}, + {Alpha3bCode: "oci", Alpha2Code: "oc", English: "Occitan (post 1500); Provençal"}, + {Alpha3bCode: "oji", Alpha2Code: "oj", English: "Ojibwa"}, + {Alpha3bCode: "ori", Alpha2Code: "or", English: "Oriya"}, + {Alpha3bCode: "orm", Alpha2Code: "om", English: "Oromo"}, + {Alpha3bCode: "oss", Alpha2Code: "os", English: "Ossetian; Ossetic"}, + {Alpha3bCode: "pan", Alpha2Code: "pa", English: "Panjabi; Punjabi"}, + {Alpha3bCode: "per", Alpha2Code: "fa", English: "Persian"}, + {Alpha3bCode: "pli", Alpha2Code: "pi", English: "Pali"}, + {Alpha3bCode: "pol", Alpha2Code: "pl", English: "Polish"}, + {Alpha3bCode: "por", Alpha2Code: "pt", English: "Portuguese"}, + {Alpha3bCode: "pus", Alpha2Code: "ps", English: "Pushto; Pashto"}, + {Alpha3bCode: "que", Alpha2Code: "qu", English: "Quechua"}, + {Alpha3bCode: "roh", Alpha2Code: "rm", English: "Romansh"}, + {Alpha3bCode: "rum", Alpha2Code: "ro", English: "Romanian; Moldavian; Moldovan"}, + {Alpha3bCode: "run", Alpha2Code: "rn", English: "Rundi"}, + {Alpha3bCode: "rus", Alpha2Code: "ru", English: "Russian"}, + {Alpha3bCode: "sag", Alpha2Code: "sg", English: "Sango"}, + {Alpha3bCode: "san", Alpha2Code: "sa", English: "Sanskrit"}, + {Alpha3bCode: "sin", Alpha2Code: "si", English: "Sinhala; Sinhalese"}, + {Alpha3bCode: "slo", Alpha2Code: "sk", English: "Slovak"}, + {Alpha3bCode: "slv", Alpha2Code: "sl", English: "Slovenian"}, + {Alpha3bCode: "sme", Alpha2Code: "se", English: "Northern Sami"}, + {Alpha3bCode: "smo", Alpha2Code: "sm", English: "Samoan"}, + {Alpha3bCode: "sna", Alpha2Code: "sn", English: "Shona"}, + {Alpha3bCode: "snd", Alpha2Code: "sd", English: "Sindhi"}, + {Alpha3bCode: "som", Alpha2Code: "so", English: "Somali"}, + {Alpha3bCode: "sot", Alpha2Code: "st", English: "Sotho, Southern"}, + {Alpha3bCode: "spa", Alpha2Code: "es", English: "Spanish; Castilian"}, + {Alpha3bCode: "srd", Alpha2Code: "sc", English: "Sardinian"}, + {Alpha3bCode: "srp", Alpha2Code: "sr", English: "Serbian"}, + {Alpha3bCode: "ssw", Alpha2Code: "ss", English: "Swati"}, + {Alpha3bCode: "sun", Alpha2Code: "su", English: "Sundanese"}, + {Alpha3bCode: "swa", Alpha2Code: "sw", English: "Swahili"}, + {Alpha3bCode: "swe", Alpha2Code: "sv", English: "Swedish"}, + {Alpha3bCode: "tah", Alpha2Code: "ty", English: "Tahitian"}, + {Alpha3bCode: "tam", Alpha2Code: "ta", English: "Tamil"}, + {Alpha3bCode: "tat", Alpha2Code: "tt", English: "Tatar"}, + {Alpha3bCode: "tel", Alpha2Code: "te", English: "Telugu"}, + {Alpha3bCode: "tgk", Alpha2Code: "tg", English: "Tajik"}, + {Alpha3bCode: "tgl", Alpha2Code: "tl", English: "Tagalog"}, + {Alpha3bCode: "tha", Alpha2Code: "th", English: "Thai"}, + {Alpha3bCode: "tib", Alpha2Code: "bo", English: "Tibetan"}, + {Alpha3bCode: "tir", Alpha2Code: "ti", English: "Tigrinya"}, + {Alpha3bCode: "ton", Alpha2Code: "to", English: "Tonga (Tonga Islands)"}, + {Alpha3bCode: "tsn", Alpha2Code: "tn", English: "Tswana"}, + {Alpha3bCode: "tso", Alpha2Code: "ts", English: "Tsonga"}, + {Alpha3bCode: "tuk", Alpha2Code: "tk", English: "Turkmen"}, + {Alpha3bCode: "tur", Alpha2Code: "tr", English: "Turkish"}, + {Alpha3bCode: "twi", Alpha2Code: "tw", English: "Twi"}, + {Alpha3bCode: "uig", Alpha2Code: "ug", English: "Uighur; Uyghur"}, + {Alpha3bCode: "ukr", Alpha2Code: "uk", English: "Ukrainian"}, + {Alpha3bCode: "urd", Alpha2Code: "ur", English: "Urdu"}, + {Alpha3bCode: "uzb", Alpha2Code: "uz", English: "Uzbek"}, + {Alpha3bCode: "ven", Alpha2Code: "ve", English: "Venda"}, + {Alpha3bCode: "vie", Alpha2Code: "vi", English: "Vietnamese"}, + {Alpha3bCode: "vol", Alpha2Code: "vo", English: "Volapük"}, + {Alpha3bCode: "wel", Alpha2Code: "cy", English: "Welsh"}, + {Alpha3bCode: "wln", Alpha2Code: "wa", English: "Walloon"}, + {Alpha3bCode: "wol", Alpha2Code: "wo", English: "Wolof"}, + {Alpha3bCode: "xho", Alpha2Code: "xh", English: "Xhosa"}, + {Alpha3bCode: "yid", Alpha2Code: "yi", English: "Yiddish"}, + {Alpha3bCode: "yor", Alpha2Code: "yo", English: "Yoruba"}, + {Alpha3bCode: "zha", Alpha2Code: "za", English: "Zhuang; Chuang"}, + {Alpha3bCode: "zul", Alpha2Code: "zu", English: "Zulu"}, } diff --git a/vendor/github.com/asaskevich/govalidator/utils.go b/vendor/github.com/asaskevich/govalidator/utils.go index f4c30f8..2341566 100644 --- a/vendor/github.com/asaskevich/govalidator/utils.go +++ b/vendor/github.com/asaskevich/govalidator/utils.go @@ -13,225 +13,393 @@ import ( ) // Contains checks if the string contains the substring. + func Contains(str, substring string) bool { + return strings.Contains(str, substring) + } // Matches checks if string matches the pattern (pattern is regular expression) + // In case of error return false + func Matches(str, pattern string) bool { + match, _ := regexp.MatchString(pattern, str) + return match + } // LeftTrim trims characters from the left side of the input. + // If second argument is empty, it will remove leading spaces. + func LeftTrim(str, chars string) string { + if chars == "" { + return strings.TrimLeftFunc(str, unicode.IsSpace) + } + r, _ := regexp.Compile("^[" + chars + "]+") + return r.ReplaceAllString(str, "") + } // RightTrim trims characters from the right side of the input. + // If second argument is empty, it will remove trailing spaces. + func RightTrim(str, chars string) string { + if chars == "" { + return strings.TrimRightFunc(str, unicode.IsSpace) + } + r, _ := regexp.Compile("[" + chars + "]+$") + return r.ReplaceAllString(str, "") + } // Trim trims characters from both sides of the input. + // If second argument is empty, it will remove spaces. + func Trim(str, chars string) string { + return LeftTrim(RightTrim(str, chars), chars) + } // WhiteList removes characters that do not appear in the whitelist. + func WhiteList(str, chars string) string { + pattern := "[^" + chars + "]+" + r, _ := regexp.Compile(pattern) + return r.ReplaceAllString(str, "") + } // BlackList removes characters that appear in the blacklist. + func BlackList(str, chars string) string { + pattern := "[" + chars + "]+" + r, _ := regexp.Compile(pattern) + return r.ReplaceAllString(str, "") + } // StripLow removes characters with a numerical value < 32 and 127, mostly control characters. + // If keep_new_lines is true, newline characters are preserved (\n and \r, hex 0xA and 0xD). + func StripLow(str string, keepNewLines bool) string { + chars := "" + if keepNewLines { + chars = "\x00-\x09\x0B\x0C\x0E-\x1F\x7F" + } else { + chars = "\x00-\x1F\x7F" + } + return BlackList(str, chars) + } // ReplacePattern replaces regular expression pattern in string + func ReplacePattern(str, pattern, replace string) string { + r, _ := regexp.Compile(pattern) + return r.ReplaceAllString(str, replace) + } // Escape replaces <, >, & and " with HTML entities. + var Escape = html.EscapeString func addSegment(inrune, segment []rune) []rune { + if len(segment) == 0 { + return inrune + } + if len(inrune) != 0 { + inrune = append(inrune, '_') + } + inrune = append(inrune, segment...) + return inrune + } // UnderscoreToCamelCase converts from underscore separated form to camel case form. + // Ex.: my_func => MyFunc + func UnderscoreToCamelCase(s string) string { + return strings.Replace(strings.Title(strings.Replace(strings.ToLower(s), "_", " ", -1)), " ", "", -1) + } // CamelCaseToUnderscore converts from camel case form to underscore separated form. + // Ex.: MyFunc => my_func + func CamelCaseToUnderscore(str string) string { + var output []rune + var segment []rune + for _, r := range str { // not treat number as separate segment + if !unicode.IsLower(r) && string(r) != "_" && !unicode.IsNumber(r) { + output = addSegment(output, segment) + segment = nil + } + segment = append(segment, unicode.ToLower(r)) + } + output = addSegment(output, segment) + return string(output) + } // Reverse returns reversed string + func Reverse(s string) string { + r := []rune(s) + for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 { + r[i], r[j] = r[j], r[i] + } + return string(r) + } // GetLines splits string by "\n" and return array of lines + func GetLines(s string) []string { + return strings.Split(s, "\n") + } // GetLine returns specified line of multiline string + func GetLine(s string, index int) (string, error) { + lines := GetLines(s) + if index < 0 || index >= len(lines) { + return "", errors.New("line index out of bounds") + } + return lines[index], nil + } // RemoveTags removes all tags from HTML string + func RemoveTags(s string) string { + return ReplacePattern(s, "<[^>]*>", "") + } // SafeFileName returns safe string that can be used in file names + func SafeFileName(str string) string { + name := strings.ToLower(str) + name = path.Clean(path.Base(name)) + name = strings.Trim(name, " ") + separators, err := regexp.Compile(`[ &_=+:]`) + if err == nil { + name = separators.ReplaceAllString(name, "-") + } + legal, err := regexp.Compile(`[^[:alnum:]-.]`) + if err == nil { + name = legal.ReplaceAllString(name, "") + } + for strings.Contains(name, "--") { + name = strings.Replace(name, "--", "-", -1) + } + return name + } // NormalizeEmail canonicalize an email address. + // The local part of the email address is lowercased for all domains; the hostname is always lowercased and + // the local part of the email address is always lowercased for hosts that are known to be case-insensitive (currently only GMail). + // Normalization follows special rules for known providers: currently, GMail addresses have dots removed in the local part and + // are stripped of tags (e.g. some.one+tag@gmail.com becomes someone@gmail.com) and all @googlemail.com addresses are + // normalized to @gmail.com. + func NormalizeEmail(str string) (string, error) { + if !IsEmail(str) { + return "", fmt.Errorf("%s is not an email", str) + } + parts := strings.Split(str, "@") + parts[0] = strings.ToLower(parts[0]) + parts[1] = strings.ToLower(parts[1]) + if parts[1] == "gmail.com" || parts[1] == "googlemail.com" { + parts[1] = "gmail.com" + parts[0] = strings.Split(ReplacePattern(parts[0], `\.`, ""), "+")[0] + } + return strings.Join(parts, "@"), nil + } // Truncate a string to the closest length without breaking words. + func Truncate(str string, length int, ending string) string { + var aftstr, befstr string + if len(str) > length { + words := strings.Fields(str) + before, present := 0, 0 + for i := range words { + befstr = aftstr + before = present + aftstr = aftstr + words[i] + " " + present = len(aftstr) + if present > length && i != 0 { + if (length - before) < (present - length) { + return Trim(befstr, " /\\.,\"'#!?&@+-") + ending + } + return Trim(aftstr, " /\\.,\"'#!?&@+-") + ending + } + } + } return str + } // PadLeft pads left side of a string if size of string is less then indicated pad length + func PadLeft(str string, padStr string, padLen int) string { + return buildPadStr(str, padStr, padLen, true, false) + } // PadRight pads right side of a string if size of string is less then indicated pad length + func PadRight(str string, padStr string, padLen int) string { + return buildPadStr(str, padStr, padLen, false, true) + } // PadBoth pads both sides of a string if size of string is less then indicated pad length + func PadBoth(str string, padStr string, padLen int) string { + return buildPadStr(str, padStr, padLen, true, true) + } // PadString either left, right or both sides. + // Note that padding string can be unicode and more then one character + func buildPadStr(str string, padStr string, padLen int, padLeft bool, padRight bool) string { // When padded length is less then the current string size + if padLen < utf8.RuneCountInString(str) { + return str + } padLen -= utf8.RuneCountInString(str) @@ -239,32 +407,49 @@ func buildPadStr(str string, padStr string, padLen int, padLeft bool, padRight b targetLen := padLen targetLenLeft := targetLen + targetLenRight := targetLen + if padLeft && padRight { + targetLenLeft = padLen / 2 + targetLenRight = padLen - targetLenLeft + } strToRepeatLen := utf8.RuneCountInString(padStr) repeatTimes := int(math.Ceil(float64(targetLen) / float64(strToRepeatLen))) + repeatedString := strings.Repeat(padStr, repeatTimes) leftSide := "" + if padLeft { + leftSide = repeatedString[0:targetLenLeft] + } rightSide := "" + if padRight { + rightSide = repeatedString[0:targetLenRight] + } return leftSide + str + rightSide + } // TruncatingErrorf removes extra args from fmt.Errorf if not formatted in the str object + func TruncatingErrorf(str string, args ...interface{}) error { + n := strings.Count(str, "%s") + return fmt.Errorf(str, args[:n]...) + } diff --git a/vendor/github.com/asaskevich/govalidator/validator.go b/vendor/github.com/asaskevich/govalidator/validator.go index 439a45d..1843a99 100644 --- a/vendor/github.com/asaskevich/govalidator/validator.go +++ b/vendor/github.com/asaskevich/govalidator/validator.go @@ -1,4 +1,5 @@ // Package govalidator is package of validators and sanitizers for strings, structs and collections. + package govalidator import ( @@ -24,1508 +25,2659 @@ import ( var ( fieldsRequiredByDefault bool + nilPtrAllowedByRequired = false - notNumberRegexp = regexp.MustCompile("[^0-9]+") - whiteSpacesAndMinus = regexp.MustCompile(`[\s-]+`) - paramsRegexp = regexp.MustCompile(`\(.*\)$`) + + notNumberRegexp = regexp.MustCompile("[^0-9]+") + + whiteSpacesAndMinus = regexp.MustCompile(`[\s-]+`) + + paramsRegexp = regexp.MustCompile(`\(.*\)$`) ) const maxURLRuneCount = 2083 + const minURLRuneCount = 3 + const RF3339WithoutZone = "2006-01-02T15:04:05" // SetFieldsRequiredByDefault causes validation to fail when struct fields + // do not include validations or are not explicitly marked as exempt (using `valid:"-"` or `valid:"email,optional"`). + // This struct definition will fail govalidator.ValidateStruct() (and the field values do not matter): + // + // type exampleStruct struct { + // Name string `` + // Email string `valid:"email"` + // + // This, however, will only fail when Email is empty or an invalid email address: + // + // type exampleStruct2 struct { + // Name string `valid:"-"` + // Email string `valid:"email"` + // + // Lastly, this will only fail when Email is an invalid email address but not when it's empty: + // + // type exampleStruct2 struct { + // Name string `valid:"-"` + // Email string `valid:"email,optional"` + func SetFieldsRequiredByDefault(value bool) { + fieldsRequiredByDefault = value + } // SetNilPtrAllowedByRequired causes validation to pass for nil ptrs when a field is set to required. + // The validation will still reject ptr fields in their zero value state. Example with this enabled: + // + // type exampleStruct struct { + // Name *string `valid:"required"` + // + // With `Name` set to "", this will be considered invalid input and will cause a validation error. + // With `Name` set to nil, this will be considered valid by validation. + // By default this is disabled. + func SetNilPtrAllowedByRequired(value bool) { + nilPtrAllowedByRequired = value + } // IsEmail check if the string is an email. + func IsEmail(str string) bool { + // TODO uppercase letters are not supported + return rxEmail.MatchString(str) + } // IsExistingEmail check if the string is an email of existing domain + func IsExistingEmail(email string) bool { if len(email) < 6 || len(email) > 254 { + return false + } + at := strings.LastIndex(email, "@") + if at <= 0 || at > len(email)-3 { + return false + } + user := email[:at] + host := email[at+1:] + if len(user) > 64 { + return false + } + if userDotRegexp.MatchString(user) || !userRegexp.MatchString(user) || !hostRegexp.MatchString(host) { + return false + } + switch host { + case "localhost", "example.com": + return true + } + if _, err := net.LookupMX(host); err != nil { + if _, err := net.LookupIP(host); err != nil { + return false + } + } return true + } // IsURL check if the string is an URL. + func IsURL(str string) bool { + if str == "" || utf8.RuneCountInString(str) >= maxURLRuneCount || len(str) <= minURLRuneCount || strings.HasPrefix(str, ".") { + return false + } + strTemp := str + if strings.Contains(str, ":") && !strings.Contains(str, "://") { + // support no indicated urlscheme but with colon for port number + // http:// is appended so url.Parse will succeed, strTemp used so it does not impact rxURL.MatchString + strTemp = "http://" + str + } + u, err := url.Parse(strTemp) + if err != nil { + return false + } + if strings.HasPrefix(u.Host, ".") { + return false + } + if u.Host == "" && (u.Path != "" && !strings.Contains(u.Path, ".")) { + return false + } + return rxURL.MatchString(str) + } // IsRequestURL check if the string rawurl, assuming + // it was received in an HTTP request, is a valid + // URL confirm to RFC 3986 + func IsRequestURL(rawurl string) bool { + url, err := url.ParseRequestURI(rawurl) + if err != nil { + return false //Couldn't even parse the rawurl + } + if len(url.Scheme) == 0 { + return false //No Scheme found + } + return true + } // IsRequestURI check if the string rawurl, assuming + // it was received in an HTTP request, is an + // absolute URI or an absolute path. + func IsRequestURI(rawurl string) bool { + _, err := url.ParseRequestURI(rawurl) + return err == nil + } // IsAlpha check if the string contains only letters (a-zA-Z). Empty string is valid. + func IsAlpha(str string) bool { + if IsNull(str) { + return true + } + return rxAlpha.MatchString(str) + } // IsUTFLetter check if the string contains only unicode letter characters. + // Similar to IsAlpha but for all languages. Empty string is valid. + func IsUTFLetter(str string) bool { + if IsNull(str) { + return true + } for _, c := range str { + if !unicode.IsLetter(c) { + return false + } + } + return true } // IsAlphanumeric check if the string contains only letters and numbers. Empty string is valid. + func IsAlphanumeric(str string) bool { + if IsNull(str) { + return true + } + return rxAlphanumeric.MatchString(str) + } // IsUTFLetterNumeric check if the string contains only unicode letters and numbers. Empty string is valid. + func IsUTFLetterNumeric(str string) bool { + if IsNull(str) { + return true + } + for _, c := range str { + if !unicode.IsLetter(c) && !unicode.IsNumber(c) { //letters && numbers are ok + return false + } + } + return true } // IsNumeric check if the string contains only numbers. Empty string is valid. + func IsNumeric(str string) bool { + if IsNull(str) { + return true + } + return rxNumeric.MatchString(str) + } // IsUTFNumeric check if the string contains only unicode numbers of any kind. + // Numbers can be 0-9 but also Fractions ¾,Roman Ⅸ and Hangzhou 〩. Empty string is valid. + func IsUTFNumeric(str string) bool { + if IsNull(str) { + return true + } + if strings.IndexAny(str, "+-") > 0 { + return false + } + if len(str) > 1 { + str = strings.TrimPrefix(str, "-") + str = strings.TrimPrefix(str, "+") + } + for _, c := range str { + if !unicode.IsNumber(c) { //numbers && minus sign are ok + return false + } + } + return true } // IsUTFDigit check if the string contains only unicode radix-10 decimal digits. Empty string is valid. + func IsUTFDigit(str string) bool { + if IsNull(str) { + return true + } + if strings.IndexAny(str, "+-") > 0 { + return false + } + if len(str) > 1 { + str = strings.TrimPrefix(str, "-") + str = strings.TrimPrefix(str, "+") + } + for _, c := range str { + if !unicode.IsDigit(c) { //digits && minus sign are ok + return false + } + } + return true } // IsHexadecimal check if the string is a hexadecimal number. + func IsHexadecimal(str string) bool { + return rxHexadecimal.MatchString(str) + } // IsHexcolor check if the string is a hexadecimal color. + func IsHexcolor(str string) bool { + return rxHexcolor.MatchString(str) + } // IsRGBcolor check if the string is a valid RGB color in form rgb(RRR, GGG, BBB). + func IsRGBcolor(str string) bool { + return rxRGBcolor.MatchString(str) + } // IsLowerCase check if the string is lowercase. Empty string is valid. + func IsLowerCase(str string) bool { + if IsNull(str) { + return true + } + return str == strings.ToLower(str) + } // IsUpperCase check if the string is uppercase. Empty string is valid. + func IsUpperCase(str string) bool { + if IsNull(str) { + return true + } + return str == strings.ToUpper(str) + } // HasLowerCase check if the string contains at least 1 lowercase. Empty string is valid. + func HasLowerCase(str string) bool { + if IsNull(str) { + return true + } + return rxHasLowerCase.MatchString(str) + } // HasUpperCase check if the string contians as least 1 uppercase. Empty string is valid. + func HasUpperCase(str string) bool { + if IsNull(str) { + return true + } + return rxHasUpperCase.MatchString(str) + } // IsInt check if the string is an integer. Empty string is valid. + func IsInt(str string) bool { + if IsNull(str) { + return true + } + return rxInt.MatchString(str) + } // IsFloat check if the string is a float. + func IsFloat(str string) bool { + return str != "" && rxFloat.MatchString(str) + } // IsDivisibleBy check if the string is a number that's divisible by another. + // If second argument is not valid integer or zero, it's return false. + // Otherwise, if first argument is not valid integer or zero, it's return true (Invalid string converts to zero). + func IsDivisibleBy(str, num string) bool { + f, _ := ToFloat(str) + p := int64(f) + q, _ := ToInt(num) + if q == 0 { + return false + } + return (p == 0) || (p%q == 0) + } // IsNull check if the string is null. + func IsNull(str string) bool { + return len(str) == 0 + } // IsNotNull check if the string is not null. + func IsNotNull(str string) bool { + return !IsNull(str) + } // HasWhitespaceOnly checks the string only contains whitespace + func HasWhitespaceOnly(str string) bool { + return len(str) > 0 && rxHasWhitespaceOnly.MatchString(str) + } // HasWhitespace checks if the string contains any whitespace + func HasWhitespace(str string) bool { + return len(str) > 0 && rxHasWhitespace.MatchString(str) + } // IsByteLength check if the string's length (in bytes) falls in a range. + func IsByteLength(str string, min, max int) bool { + return len(str) >= min && len(str) <= max + } // IsUUIDv3 check if the string is a UUID version 3. + func IsUUIDv3(str string) bool { + return rxUUID3.MatchString(str) + } // IsUUIDv4 check if the string is a UUID version 4. + func IsUUIDv4(str string) bool { + return rxUUID4.MatchString(str) + } // IsUUIDv5 check if the string is a UUID version 5. + func IsUUIDv5(str string) bool { + return rxUUID5.MatchString(str) + } // IsUUID check if the string is a UUID (version 3, 4 or 5). + func IsUUID(str string) bool { + return rxUUID.MatchString(str) + } // IsCreditCard check if the string is a credit card. + func IsCreditCard(str string) bool { + sanitized := notNumberRegexp.ReplaceAllString(str, "") + if !rxCreditCard.MatchString(sanitized) { + return false + } + var sum int64 + var digit string + var tmpNum int64 + var shouldDouble bool + for i := len(sanitized) - 1; i >= 0; i-- { + digit = sanitized[i:(i + 1)] + tmpNum, _ = ToInt(digit) + if shouldDouble { + tmpNum *= 2 + if tmpNum >= 10 { + sum += ((tmpNum % 10) + 1) + } else { + sum += tmpNum + } + } else { + sum += tmpNum + } + shouldDouble = !shouldDouble + } return sum%10 == 0 + } // IsISBN10 check if the string is an ISBN version 10. + func IsISBN10(str string) bool { + return IsISBN(str, 10) + } // IsISBN13 check if the string is an ISBN version 13. + func IsISBN13(str string) bool { + return IsISBN(str, 13) + } // IsISBN check if the string is an ISBN (version 10 or 13). + // If version value is not equal to 10 or 13, it will be check both variants. + func IsISBN(str string, version int) bool { + sanitized := whiteSpacesAndMinus.ReplaceAllString(str, "") + var checksum int32 + var i int32 + if version == 10 { + if !rxISBN10.MatchString(sanitized) { + return false + } + for i = 0; i < 9; i++ { + checksum += (i + 1) * int32(sanitized[i]-'0') + } + if sanitized[9] == 'X' { + checksum += 10 * 10 + } else { + checksum += 10 * int32(sanitized[9]-'0') + } + if checksum%11 == 0 { + return true + } + return false + } else if version == 13 { + if !rxISBN13.MatchString(sanitized) { + return false + } + factor := []int32{1, 3} + for i = 0; i < 12; i++ { + checksum += factor[i%2] * int32(sanitized[i]-'0') + } + return (int32(sanitized[12]-'0'))-((10-(checksum%10))%10) == 0 + } + return IsISBN(str, 10) || IsISBN(str, 13) + } // IsJSON check if the string is valid JSON (note: uses json.Unmarshal). + func IsJSON(str string) bool { + var js json.RawMessage + return json.Unmarshal([]byte(str), &js) == nil + } // IsMultibyte check if the string contains one or more multibyte chars. Empty string is valid. + func IsMultibyte(str string) bool { + if IsNull(str) { + return true + } + return rxMultibyte.MatchString(str) + } // IsASCII check if the string contains ASCII chars only. Empty string is valid. + func IsASCII(str string) bool { + if IsNull(str) { + return true + } + return rxASCII.MatchString(str) + } // IsPrintableASCII check if the string contains printable ASCII chars only. Empty string is valid. + func IsPrintableASCII(str string) bool { + if IsNull(str) { + return true + } + return rxPrintableASCII.MatchString(str) + } // IsFullWidth check if the string contains any full-width chars. Empty string is valid. + func IsFullWidth(str string) bool { + if IsNull(str) { + return true + } + return rxFullWidth.MatchString(str) + } // IsHalfWidth check if the string contains any half-width chars. Empty string is valid. + func IsHalfWidth(str string) bool { + if IsNull(str) { + return true + } + return rxHalfWidth.MatchString(str) + } // IsVariableWidth check if the string contains a mixture of full and half-width chars. Empty string is valid. + func IsVariableWidth(str string) bool { + if IsNull(str) { + return true + } + return rxHalfWidth.MatchString(str) && rxFullWidth.MatchString(str) + } // IsBase64 check if a string is base64 encoded. + func IsBase64(str string) bool { + return rxBase64.MatchString(str) + } // IsFilePath check is a string is Win or Unix file path and returns it's type. + func IsFilePath(str string) (bool, int) { + if rxWinPath.MatchString(str) { + //check windows path limit see: + // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath + if len(str[3:]) > 32767 { + return false, Win + } + return true, Win + } else if rxUnixPath.MatchString(str) { + return true, Unix + } + return false, Unknown + } // IsDataURI checks if a string is base64 encoded data URI such as an image + func IsDataURI(str string) bool { + dataURI := strings.Split(str, ",") + if !rxDataURI.MatchString(dataURI[0]) { + return false + } + return IsBase64(dataURI[1]) + } // IsMagnetURI checks if a string is valid magnet URI + func IsMagnetURI(str string) bool { + return rxMagnetURI.MatchString(str) + } // IsISO3166Alpha2 checks if a string is valid two-letter country code + func IsISO3166Alpha2(str string) bool { + for _, entry := range ISO3166List { + if str == entry.Alpha2Code { + return true + } + } + return false + } // IsISO3166Alpha3 checks if a string is valid three-letter country code + func IsISO3166Alpha3(str string) bool { + for _, entry := range ISO3166List { + if str == entry.Alpha3Code { + return true + } + } + return false + } // IsISO693Alpha2 checks if a string is valid two-letter language code + func IsISO693Alpha2(str string) bool { + for _, entry := range ISO693List { + if str == entry.Alpha2Code { + return true + } + } + return false + } // IsISO693Alpha3b checks if a string is valid three-letter language code + func IsISO693Alpha3b(str string) bool { + for _, entry := range ISO693List { + if str == entry.Alpha3bCode { + return true + } + } + return false + } // IsDNSName will validate the given string as a DNS name + func IsDNSName(str string) bool { + if str == "" || len(strings.Replace(str, ".", "", -1)) > 255 { + // constraints already violated + return false + } + return !IsIP(str) && rxDNSName.MatchString(str) + } // IsHash checks if a string is a hash of type algorithm. + // Algorithm is one of ['md4', 'md5', 'sha1', 'sha256', 'sha384', 'sha512', 'ripemd128', 'ripemd160', 'tiger128', 'tiger160', 'tiger192', 'crc32', 'crc32b'] + func IsHash(str string, algorithm string) bool { + len := "0" + algo := strings.ToLower(algorithm) if algo == "crc32" || algo == "crc32b" { + len = "8" + } else if algo == "md5" || algo == "md4" || algo == "ripemd128" || algo == "tiger128" { + len = "32" + } else if algo == "sha1" || algo == "ripemd160" || algo == "tiger160" { + len = "40" + } else if algo == "tiger192" { + len = "48" + } else if algo == "sha256" { + len = "64" + } else if algo == "sha384" { + len = "96" + } else if algo == "sha512" { + len = "128" + } else { + return false + } return Matches(str, "^[a-f0-9]{"+len+"}$") + } // IsSHA512 checks is a string is a SHA512 hash. Alias for `IsHash(str, "sha512")` + func IsSHA512(str string) bool { + return IsHash(str, "sha512") + } // IsSHA384 checks is a string is a SHA384 hash. Alias for `IsHash(str, "sha384")` + func IsSHA384(str string) bool { + return IsHash(str, "sha384") + } // IsSHA256 checks is a string is a SHA256 hash. Alias for `IsHash(str, "sha256")` + func IsSHA256(str string) bool { + return IsHash(str, "sha256") + } // IsTiger192 checks is a string is a Tiger192 hash. Alias for `IsHash(str, "tiger192")` + func IsTiger192(str string) bool { + return IsHash(str, "tiger192") + } // IsTiger160 checks is a string is a Tiger160 hash. Alias for `IsHash(str, "tiger160")` + func IsTiger160(str string) bool { + return IsHash(str, "tiger160") + } // IsRipeMD160 checks is a string is a RipeMD160 hash. Alias for `IsHash(str, "ripemd160")` + func IsRipeMD160(str string) bool { + return IsHash(str, "ripemd160") + } // IsSHA1 checks is a string is a SHA-1 hash. Alias for `IsHash(str, "sha1")` + func IsSHA1(str string) bool { + return IsHash(str, "sha1") + } // IsTiger128 checks is a string is a Tiger128 hash. Alias for `IsHash(str, "tiger128")` + func IsTiger128(str string) bool { + return IsHash(str, "tiger128") + } // IsRipeMD128 checks is a string is a RipeMD128 hash. Alias for `IsHash(str, "ripemd128")` + func IsRipeMD128(str string) bool { + return IsHash(str, "ripemd128") + } // IsCRC32 checks is a string is a CRC32 hash. Alias for `IsHash(str, "crc32")` + func IsCRC32(str string) bool { + return IsHash(str, "crc32") + } // IsCRC32b checks is a string is a CRC32b hash. Alias for `IsHash(str, "crc32b")` + func IsCRC32b(str string) bool { + return IsHash(str, "crc32b") + } // IsMD5 checks is a string is a MD5 hash. Alias for `IsHash(str, "md5")` + func IsMD5(str string) bool { + return IsHash(str, "md5") + } // IsMD4 checks is a string is a MD4 hash. Alias for `IsHash(str, "md4")` + func IsMD4(str string) bool { + return IsHash(str, "md4") + } // IsDialString validates the given string for usage with the various Dial() functions + func IsDialString(str string) bool { + if h, p, err := net.SplitHostPort(str); err == nil && h != "" && p != "" && (IsDNSName(h) || IsIP(h)) && IsPort(p) { + return true + } return false + } // IsIP checks if a string is either IP version 4 or 6. Alias for `net.ParseIP` + func IsIP(str string) bool { + return net.ParseIP(str) != nil + } // IsPort checks if a string represents a valid port + func IsPort(str string) bool { + if i, err := strconv.Atoi(str); err == nil && i > 0 && i < 65536 { + return true + } + return false + } // IsIPv4 check if the string is an IP version 4. + func IsIPv4(str string) bool { + ip := net.ParseIP(str) + return ip != nil && strings.Contains(str, ".") + } // IsIPv6 check if the string is an IP version 6. + func IsIPv6(str string) bool { + ip := net.ParseIP(str) + return ip != nil && strings.Contains(str, ":") + } // IsCIDR check if the string is an valid CIDR notiation (IPV4 & IPV6) + func IsCIDR(str string) bool { + _, _, err := net.ParseCIDR(str) + return err == nil + } // IsMAC check if a string is valid MAC address. + // Possible MAC formats: + // 01:23:45:67:89:ab + // 01:23:45:67:89:ab:cd:ef + // 01-23-45-67-89-ab + // 01-23-45-67-89-ab-cd-ef + // 0123.4567.89ab + // 0123.4567.89ab.cdef + func IsMAC(str string) bool { + _, err := net.ParseMAC(str) + return err == nil + } // IsHost checks if the string is a valid IP (both v4 and v6) or a valid DNS name + func IsHost(str string) bool { + return IsIP(str) || IsDNSName(str) + } // IsMongoID check if the string is a valid hex-encoded representation of a MongoDB ObjectId. + func IsMongoID(str string) bool { + return rxHexadecimal.MatchString(str) && (len(str) == 24) + } // IsLatitude check if a string is valid latitude. + func IsLatitude(str string) bool { + return rxLatitude.MatchString(str) + } // IsLongitude check if a string is valid longitude. + func IsLongitude(str string) bool { + return rxLongitude.MatchString(str) + } // IsRsaPublicKey check if a string is valid public key with provided length + func IsRsaPublicKey(str string, keylen int) bool { + bb := bytes.NewBufferString(str) + pemBytes, err := ioutil.ReadAll(bb) + if err != nil { + return false + } + block, _ := pem.Decode(pemBytes) + if block != nil && block.Type != "PUBLIC KEY" { + return false + } + var der []byte if block != nil { + der = block.Bytes + } else { + der, err = base64.StdEncoding.DecodeString(str) + if err != nil { + return false + } + } key, err := x509.ParsePKIXPublicKey(der) + if err != nil { + return false + } + pubkey, ok := key.(*rsa.PublicKey) + if !ok { + return false + } + bitlen := len(pubkey.N.Bytes()) * 8 + return bitlen == int(keylen) + } func toJSONName(tag string) string { + if tag == "" { + return "" + } // JSON name always comes first. If there's no options then split[0] is + // JSON name, if JSON name is not set, then split[0] is an empty string. + split := strings.SplitN(tag, ",", 2) name := split[0] // However it is possible that the field is skipped when + // (de-)serializing from/to JSON, in which case assume that there is no + // tag name to use + if name == "-" { + return "" + } + return name + } func PrependPathToErrors(err error, path string) error { + switch err2 := err.(type) { + case Error: + err2.Path = append([]string{path}, err2.Path...) + return err2 + case Errors: + errors := err2.Errors() + for i, err3 := range errors { + errors[i] = PrependPathToErrors(err3, path) + } + return err2 + } + return err + } // ValidateMap use validation map for fields. + // result will be equal to `false` if there are any errors. + // m is the validation map in the form + // map[string]interface{}{"name":"required,alpha","address":map[string]interface{}{"line1":"required,alphanum"}} + func ValidateMap(s map[string]interface{}, m map[string]interface{}) (bool, error) { + if s == nil { + return true, nil + } + result := true + var err error + var errs Errors + var index int + val := reflect.ValueOf(s) + for key, value := range s { + presentResult := true + validator, ok := m[key] + if !ok { + presentResult = false + var err error + err = fmt.Errorf("all map keys has to be present in the validation map; got %s", key) + err = PrependPathToErrors(err, key) + errs = append(errs, err) + } + valueField := reflect.ValueOf(value) + mapResult := true + typeResult := true + structResult := true + resultField := true + switch subValidator := validator.(type) { + case map[string]interface{}: + var err error + if v, ok := value.(map[string]interface{}); !ok { + mapResult = false + err = fmt.Errorf("map validator has to be for the map type only; got %s", valueField.Type().String()) + err = PrependPathToErrors(err, key) + errs = append(errs, err) + } else { + mapResult, err = ValidateMap(v, subValidator) + if err != nil { + mapResult = false + err = PrependPathToErrors(err, key) + errs = append(errs, err) + } + } + case string: + if (valueField.Kind() == reflect.Struct || + (valueField.Kind() == reflect.Ptr && valueField.Elem().Kind() == reflect.Struct)) && + subValidator != "-" { + var err error + structResult, err = ValidateStruct(valueField.Interface()) + if err != nil { + err = PrependPathToErrors(err, key) + errs = append(errs, err) + } + } + resultField, err = typeCheck(valueField, reflect.StructField{ - Name: key, - PkgPath: "", - Type: val.Type(), - Tag: reflect.StructTag(fmt.Sprintf("%s:%q", tagName, subValidator)), - Offset: 0, - Index: []int{index}, + + Name: key, + + PkgPath: "", + + Type: val.Type(), + + Tag: reflect.StructTag(fmt.Sprintf("%s:%q", tagName, subValidator)), + + Offset: 0, + + Index: []int{index}, + Anonymous: false, }, val, nil) + if err != nil { + errs = append(errs, err) + } + case nil: + // already handlerd when checked before + default: + typeResult = false + err = fmt.Errorf("map validator has to be either map[string]interface{} or string; got %s", valueField.Type().String()) + err = PrependPathToErrors(err, key) + errs = append(errs, err) + } + result = result && presentResult && typeResult && resultField && structResult && mapResult + index++ + } + // check required keys + requiredResult := true + for key, value := range m { + if schema, ok := value.(string); ok { + tags := parseTagIntoMap(schema) + if required, ok := tags["required"]; ok { + if _, ok := s[key]; !ok { + requiredResult = false + if required.customErrorMessage != "" { + err = Error{key, fmt.Errorf(required.customErrorMessage), true, "required", []string{}} + } else { + err = Error{key, fmt.Errorf("required field missing"), false, "required", []string{}} + } + errs = append(errs, err) + } + } + } + } if len(errs) > 0 { + err = errs + } + return result && requiredResult, err + } // ValidateStruct use tags for fields. + // result will be equal to `false` if there are any errors. + // todo currently there is no guarantee that errors will be returned in predictable order (tests may to fail) + func ValidateStruct(s interface{}) (bool, error) { + if s == nil { + return true, nil + } + result := true + var err error + val := reflect.ValueOf(s) + if val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr { + val = val.Elem() + } + // we only accept structs + if val.Kind() != reflect.Struct { + return false, fmt.Errorf("function only accepts structs; got %s", val.Kind()) + } + var errs Errors + for i := 0; i < val.NumField(); i++ { + valueField := val.Field(i) + typeField := val.Type().Field(i) + if typeField.PkgPath != "" { + continue // Private field + } + structResult := true + if valueField.Kind() == reflect.Interface { + valueField = valueField.Elem() + } + if (valueField.Kind() == reflect.Struct || + (valueField.Kind() == reflect.Ptr && valueField.Elem().Kind() == reflect.Struct)) && + typeField.Tag.Get(tagName) != "-" { + var err error + structResult, err = ValidateStruct(valueField.Interface()) + if err != nil { + err = PrependPathToErrors(err, typeField.Name) + errs = append(errs, err) + } + } + resultField, err2 := typeCheck(valueField, typeField, val, nil) + if err2 != nil { // Replace structure name with JSON name if there is a tag on the variable + jsonTag := toJSONName(typeField.Tag.Get("json")) + if jsonTag != "" { + switch jsonError := err2.(type) { + case Error: + jsonError.Name = jsonTag + err2 = jsonError + case Errors: + for i2, err3 := range jsonError { + switch customErr := err3.(type) { + case Error: + customErr.Name = jsonTag + jsonError[i2] = customErr + } + } err2 = jsonError + } + } errs = append(errs, err2) + } + result = result && resultField && structResult + } + if len(errs) > 0 { + err = errs + } + return result, err + } // parseTagIntoMap parses a struct tag `valid:required~Some error message,length(2|3)` into map[string]string{"required": "Some error message", "length(2|3)": ""} + func parseTagIntoMap(tag string) tagOptionsMap { + optionsMap := make(tagOptionsMap) + options := strings.Split(tag, ",") for i, option := range options { + option = strings.TrimSpace(option) validationOptions := strings.Split(option, "~") + if !isValidTag(validationOptions[0]) { + continue + } + if len(validationOptions) == 2 { + optionsMap[validationOptions[0]] = tagOption{validationOptions[0], validationOptions[1], i} + } else { + optionsMap[validationOptions[0]] = tagOption{validationOptions[0], "", i} + } + } + return optionsMap + } func isValidTag(s string) bool { + if s == "" { + return false + } + for _, c := range s { + switch { + case strings.ContainsRune("\\'\"!#$%&()*+-./:<=>?@[]^_{|}~ ", c): + // Backslash and quote chars are reserved, but + // otherwise any punctuation chars are allowed + // in a tag name. + default: + if !unicode.IsLetter(c) && !unicode.IsDigit(c) { + return false + } + } + } + return true + } // IsSSN will validate the given string as a U.S. Social Security Number + func IsSSN(str string) bool { + if str == "" || len(str) != 11 { + return false + } + return rxSSN.MatchString(str) + } // IsSemver check if string is valid semantic version + func IsSemver(str string) bool { + return rxSemver.MatchString(str) + } // IsType check if interface is of some type + func IsType(v interface{}, params ...string) bool { + if len(params) == 1 { + typ := params[0] + return strings.Replace(reflect.TypeOf(v).String(), " ", "", -1) == strings.Replace(typ, " ", "", -1) + } + return false + } // IsTime check if string is valid according to given format + func IsTime(str string, format string) bool { + _, err := time.Parse(format, str) + return err == nil + } // IsUnixTime check if string is valid unix timestamp value + func IsUnixTime(str string) bool { + if _, err := strconv.Atoi(str); err == nil { + return true + } + return false + } // IsRFC3339 check if string is valid timestamp value according to RFC3339 + func IsRFC3339(str string) bool { + return IsTime(str, time.RFC3339) + } // IsRFC3339WithoutZone check if string is valid timestamp value according to RFC3339 which excludes the timezone. + func IsRFC3339WithoutZone(str string) bool { + return IsTime(str, RF3339WithoutZone) + } // IsISO4217 check if string is valid ISO currency code + func IsISO4217(str string) bool { + for _, currency := range ISO4217List { + if str == currency { + return true + } + } return false + } // ByteLength check string's length + func ByteLength(str string, params ...string) bool { + if len(params) == 2 { + min, _ := ToInt(params[0]) + max, _ := ToInt(params[1]) + return len(str) >= int(min) && len(str) <= int(max) + } return false + } // RuneLength check string's length + // Alias for StringLength + func RuneLength(str string, params ...string) bool { + return StringLength(str, params...) + } // IsRsaPub check whether string is valid RSA key + // Alias for IsRsaPublicKey + func IsRsaPub(str string, params ...string) bool { + if len(params) == 1 { + len, _ := ToInt(params[0]) + return IsRsaPublicKey(str, int(len)) + } return false + } // StringMatches checks if a string matches a given pattern. + func StringMatches(s string, params ...string) bool { + if len(params) == 1 { + pattern := params[0] + return Matches(s, pattern) + } + return false + } // StringLength check string's length (including multi byte strings) + func StringLength(str string, params ...string) bool { if len(params) == 2 { + strLength := utf8.RuneCountInString(str) + min, _ := ToInt(params[0]) + max, _ := ToInt(params[1]) + return strLength >= int(min) && strLength <= int(max) + } return false + } // MinStringLength check string's minimum length (including multi byte strings) + func MinStringLength(str string, params ...string) bool { if len(params) == 1 { + strLength := utf8.RuneCountInString(str) + min, _ := ToInt(params[0]) + return strLength >= int(min) + } return false + } // MaxStringLength check string's maximum length (including multi byte strings) + func MaxStringLength(str string, params ...string) bool { if len(params) == 1 { + strLength := utf8.RuneCountInString(str) + max, _ := ToInt(params[0]) + return strLength <= int(max) + } return false + } // Range check string's length + func Range(str string, params ...string) bool { + if len(params) == 2 { + value, _ := ToFloat(str) + min, _ := ToFloat(params[0]) + max, _ := ToFloat(params[1]) + return InRange(value, min, max) + } return false + } func IsInRaw(str string, params ...string) bool { + if len(params) == 1 { + rawParams := params[0] parsedParams := strings.Split(rawParams, "|") return IsIn(str, parsedParams...) + } return false + } // IsIn check if string str is a member of the set of strings params + func IsIn(str string, params ...string) bool { + for _, param := range params { + if str == param { + return true + } + } return false + } func checkRequired(v reflect.Value, t reflect.StructField, options tagOptionsMap) (bool, error) { + if nilPtrAllowedByRequired { + k := v.Kind() + if (k == reflect.Ptr || k == reflect.Interface) && v.IsNil() { + return true, nil + } + } if requiredOption, isRequired := options["required"]; isRequired { + if len(requiredOption.customErrorMessage) > 0 { + return false, Error{t.Name, fmt.Errorf(requiredOption.customErrorMessage), true, "required", []string{}} + } + return false, Error{t.Name, fmt.Errorf("non zero value required"), false, "required", []string{}} + } else if _, isOptional := options["optional"]; fieldsRequiredByDefault && !isOptional { + return false, Error{t.Name, fmt.Errorf("Missing required field"), false, "required", []string{}} + } + // not required and empty is valid + return true, nil + } func typeCheck(v reflect.Value, t reflect.StructField, o reflect.Value, options tagOptionsMap) (isValid bool, resultErr error) { + if !v.IsValid() { + return false, nil + } tag := t.Tag.Get(tagName) // Check if the field should be ignored + switch tag { + case "": + if v.Kind() != reflect.Slice && v.Kind() != reflect.Map { + if !fieldsRequiredByDefault { + return true, nil + } + return false, Error{t.Name, fmt.Errorf("All fields are required to at least have one validation defined"), false, "required", []string{}} + } + case "-": + return true, nil + } isRootType := false + if options == nil { + isRootType = true + options = parseTagIntoMap(tag) + } if !isFieldSet(v) { + // an empty value is not validated, check only required + isValid, resultErr = checkRequired(v, t, options) + for key := range options { + delete(options, key) + } + return isValid, resultErr + } var customTypeErrors Errors + optionsOrder := options.orderedKeys() + for _, validatorName := range optionsOrder { + validatorStruct := options[validatorName] + if validatefunc, ok := CustomTypeTagMap.Get(validatorName); ok { + delete(options, validatorName) if result := validatefunc(v.Interface(), o.Interface()); !result { + if len(validatorStruct.customErrorMessage) > 0 { + customTypeErrors = append(customTypeErrors, Error{Name: t.Name, Err: TruncatingErrorf(validatorStruct.customErrorMessage, fmt.Sprint(v), validatorName), CustomErrorMessageExists: true, Validator: stripParams(validatorName)}) + continue + } + customTypeErrors = append(customTypeErrors, Error{Name: t.Name, Err: fmt.Errorf("%s does not validate as %s", fmt.Sprint(v), validatorName), CustomErrorMessageExists: false, Validator: stripParams(validatorName)}) + } + } + } if len(customTypeErrors.Errors()) > 0 { + return false, customTypeErrors + } if isRootType { + // Ensure that we've checked the value by all specified validators before report that the value is valid + defer func() { + delete(options, "optional") + delete(options, "required") if isValid && resultErr == nil && len(options) != 0 { + optionsOrder := options.orderedKeys() + for _, validator := range optionsOrder { + isValid = false + resultErr = Error{t.Name, fmt.Errorf( + "The following validator is invalid or can't be applied to the field: %q", validator), false, stripParams(validator), []string{}} + return + } + } + }() + } for _, validatorSpec := range optionsOrder { + validatorStruct := options[validatorSpec] + var negate bool + validator := validatorSpec + customMsgExists := len(validatorStruct.customErrorMessage) > 0 // Check whether the tag looks like '!something' or 'something' + if validator[0] == '!' { + validator = validator[1:] + negate = true + } // Check for interface param validators + for key, value := range InterfaceParamTagRegexMap { + ps := value.FindStringSubmatch(validator) + if len(ps) == 0 { + continue + } validatefunc, ok := InterfaceParamTagMap[key] + if !ok { + continue + } delete(options, validatorSpec) field := fmt.Sprint(v) + if result := validatefunc(v.Interface(), ps[1:]...); (!result && !negate) || (result && negate) { + if customMsgExists { + return false, Error{t.Name, TruncatingErrorf(validatorStruct.customErrorMessage, field, validator), customMsgExists, stripParams(validatorSpec), []string{}} + } + if negate { + return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} + } + return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} + } + } + } switch v.Kind() { + case reflect.Bool, + reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, + reflect.Float32, reflect.Float64, + reflect.String: + // for each tag option check the map of validator functions + for _, validatorSpec := range optionsOrder { + validatorStruct := options[validatorSpec] + var negate bool + validator := validatorSpec + customMsgExists := len(validatorStruct.customErrorMessage) > 0 // Check whether the tag looks like '!something' or 'something' + if validator[0] == '!' { + validator = validator[1:] + negate = true + } // Check for param validators + for key, value := range ParamTagRegexMap { + ps := value.FindStringSubmatch(validator) + if len(ps) == 0 { + continue + } validatefunc, ok := ParamTagMap[key] + if !ok { + continue + } delete(options, validatorSpec) switch v.Kind() { + case reflect.String, + reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, + reflect.Float32, reflect.Float64: field := fmt.Sprint(v) // make value into string, then validate with regex + if result := validatefunc(field, ps[1:]...); (!result && !negate) || (result && negate) { + if customMsgExists { + return false, Error{t.Name, TruncatingErrorf(validatorStruct.customErrorMessage, field, validator), customMsgExists, stripParams(validatorSpec), []string{}} + } + if negate { + return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} + } + return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} + } + default: + // type not yet supported, fail + return false, Error{t.Name, fmt.Errorf("Validator %s doesn't support kind %s", validator, v.Kind()), false, stripParams(validatorSpec), []string{}} + } + } if validatefunc, ok := TagMap[validator]; ok { + delete(options, validatorSpec) switch v.Kind() { + case reflect.String, + reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, + reflect.Float32, reflect.Float64: + field := fmt.Sprint(v) // make value into string, then validate with regex + if result := validatefunc(field); !result && !negate || result && negate { + if customMsgExists { + return false, Error{t.Name, TruncatingErrorf(validatorStruct.customErrorMessage, field, validator), customMsgExists, stripParams(validatorSpec), []string{}} + } + if negate { + return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} + } + return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} + } + default: + //Not Yet Supported Types (Fail here!) + err := fmt.Errorf("Validator %s doesn't support kind %s for value %v", validator, v.Kind(), v) + return false, Error{t.Name, err, false, stripParams(validatorSpec), []string{}} + } + } + } + return true, nil + case reflect.Map: + if v.Type().Key().Kind() != reflect.String { + return false, &UnsupportedTypeError{v.Type()} + } + var sv stringValues + sv = v.MapKeys() + sort.Sort(sv) + result := true + for i, k := range sv { + var resultItem bool + var err error + if v.MapIndex(k).Kind() != reflect.Struct { + resultItem, err = typeCheck(v.MapIndex(k), t, o, options) + if err != nil { + return false, err + } + } else { + resultItem, err = ValidateStruct(v.MapIndex(k).Interface()) + if err != nil { + err = PrependPathToErrors(err, t.Name+"."+sv[i].Interface().(string)) + return false, err + } + } + result = result && resultItem + } + return result, nil + case reflect.Slice, reflect.Array: + result := true + for i := 0; i < v.Len(); i++ { + var resultItem bool + var err error + if v.Index(i).Kind() != reflect.Struct { + resultItem, err = typeCheck(v.Index(i), t, o, options) + if err != nil { + return false, err + } + } else { + resultItem, err = ValidateStruct(v.Index(i).Interface()) + if err != nil { + err = PrependPathToErrors(err, t.Name+"."+strconv.Itoa(i)) + return false, err + } + } + result = result && resultItem + } + return result, nil + case reflect.Interface: + // If the value is an interface then encode its element + if v.IsNil() { + return true, nil + } + return ValidateStruct(v.Interface()) + case reflect.Ptr: + // If the value is a pointer then check its element + if v.IsNil() { + return true, nil + } + return typeCheck(v.Elem(), t, o, options) + case reflect.Struct: + return true, nil + default: + return false, &UnsupportedTypeError{v.Type()} + } + } func stripParams(validatorString string) string { + return paramsRegexp.ReplaceAllString(validatorString, "") + } // isFieldSet returns false for nil pointers, interfaces, maps, and slices. For all other values, it returns true. + func isFieldSet(v reflect.Value) bool { + switch v.Kind() { + case reflect.Map, reflect.Slice, reflect.Interface, reflect.Ptr: + return !v.IsNil() + } return true + } // ErrorByField returns error for specified field of the struct + // validated by ValidateStruct or empty string if there are no errors + // or this field doesn't exists or doesn't have any errors. + func ErrorByField(e error, field string) string { + if e == nil { + return "" + } + return ErrorsByField(e)[field] + } // ErrorsByField returns map of errors of the struct validated + // by ValidateStruct or empty map if there are no errors. + func ErrorsByField(e error) map[string]string { + m := make(map[string]string) + if e == nil { + return m + } + // prototype for ValidateStruct switch e.(type) { + case Error: + m[e.(Error).Name] = e.(Error).Err.Error() + case Errors: + for _, item := range e.(Errors).Errors() { + n := ErrorsByField(item) + for k, v := range n { + m[k] = v + } + } + } return m + } // Error returns string equivalent for reflect.Type + func (e *UnsupportedTypeError) Error() string { + return "validator: unsupported type: " + e.Type.String() + } -func (sv stringValues) Len() int { return len(sv) } -func (sv stringValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] } +func (sv stringValues) Len() int { return len(sv) } + +func (sv stringValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] } + func (sv stringValues) Less(i, j int) bool { return sv.get(i) < sv.get(j) } -func (sv stringValues) get(i int) string { return sv[i].String() } + +func (sv stringValues) get(i int) string { return sv[i].String() } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/address.go b/vendor/github.com/brianvoe/gofakeit/v6/address.go index 3c8bc96..358ea10 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/address.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/address.go @@ -7,415 +7,662 @@ import ( ) // AddressInfo is a struct full of address information + type AddressInfo struct { - Address string `json:"address" xml:"address"` - Street string `json:"street" xml:"street"` - City string `json:"city" xml:"city"` - State string `json:"state" xml:"state"` - Zip string `json:"zip" xml:"zip"` - Country string `json:"country" xml:"country"` - Latitude float64 `json:"latitude" xml:"latitude"` + Address string `json:"address" xml:"address"` + + Street string `json:"street" xml:"street"` + + City string `json:"city" xml:"city"` + + State string `json:"state" xml:"state"` + + Zip string `json:"zip" xml:"zip"` + + Country string `json:"country" xml:"country"` + + Latitude float64 `json:"latitude" xml:"latitude"` + Longitude float64 `json:"longitude" xml:"longitude"` } // Address will generate a struct of address information + func Address() *AddressInfo { return address(globalFaker.Rand) } // Address will generate a struct of address information + func (f *Faker) Address() *AddressInfo { return address(f.Rand) } func address(r *rand.Rand) *AddressInfo { + street := street(r) + city := city(r) + state := state(r) + zip := zip(r) return &AddressInfo{ - Address: street + ", " + city + ", " + state + " " + zip, - Street: street, - City: city, - State: state, - Zip: zip, - Country: country(r), - Latitude: latitude(r), + + Address: street + ", " + city + ", " + state + " " + zip, + + Street: street, + + City: city, + + State: state, + + Zip: zip, + + Country: country(r), + + Latitude: latitude(r), + Longitude: longitude(r), } + } // Street will generate a random address street string + func Street() string { return street(globalFaker.Rand) } // Street will generate a random address street string + func (f *Faker) Street() string { return street(f.Rand) } func street(r *rand.Rand) string { + var street = "" + switch randInt := randIntRange(r, 1, 2); randInt { + case 1: + street = streetNumber(r) + " " + streetPrefix(r) + " " + streetName(r) + streetSuffix(r) + case 2: + street = streetNumber(r) + " " + streetName(r) + streetSuffix(r) + } return street + } // StreetNumber will generate a random address street number string + func StreetNumber() string { return streetNumber(globalFaker.Rand) } // StreetNumber will generate a random address street number string + func (f *Faker) StreetNumber() string { return streetNumber(f.Rand) } func streetNumber(r *rand.Rand) string { + return strings.TrimLeft(replaceWithNumbers(r, getRandValue(r, []string{"address", "number"})), "0") + } // StreetPrefix will generate a random address street prefix string + func StreetPrefix() string { return streetPrefix(globalFaker.Rand) } // StreetPrefix will generate a random address street prefix string + func (f *Faker) StreetPrefix() string { return streetPrefix(f.Rand) } func streetPrefix(r *rand.Rand) string { return getRandValue(r, []string{"address", "street_prefix"}) } // StreetName will generate a random address street name string + func StreetName() string { return streetName(globalFaker.Rand) } // StreetName will generate a random address street name string + func (f *Faker) StreetName() string { return streetName(f.Rand) } func streetName(r *rand.Rand) string { return getRandValue(r, []string{"address", "street_name"}) } // StreetSuffix will generate a random address street suffix string + func StreetSuffix() string { return streetSuffix(globalFaker.Rand) } // StreetSuffix will generate a random address street suffix string + func (f *Faker) StreetSuffix() string { return streetSuffix(f.Rand) } func streetSuffix(r *rand.Rand) string { return getRandValue(r, []string{"address", "street_suffix"}) } // City will generate a random city string + func City() string { return city(globalFaker.Rand) } // City will generate a random city string + func (f *Faker) City() string { return city(f.Rand) } func city(r *rand.Rand) string { return getRandValue(r, []string{"address", "city"}) } // State will generate a random state string + func State() string { return state(globalFaker.Rand) } // State will generate a random state string + func (f *Faker) State() string { return state(f.Rand) } func state(r *rand.Rand) string { return getRandValue(r, []string{"address", "state"}) } // StateAbr will generate a random abbreviated state string + func StateAbr() string { return stateAbr(globalFaker.Rand) } // StateAbr will generate a random abbreviated state string + func (f *Faker) StateAbr() string { return stateAbr(f.Rand) } func stateAbr(r *rand.Rand) string { return getRandValue(r, []string{"address", "state_abr"}) } // Zip will generate a random Zip code string + func Zip() string { return zip(globalFaker.Rand) } // Zip will generate a random Zip code string + func (f *Faker) Zip() string { return zip(f.Rand) } func zip(r *rand.Rand) string { + return replaceWithNumbers(r, getRandValue(r, []string{"address", "zip"})) + } // Country will generate a random country string + func Country() string { return country(globalFaker.Rand) } // Country will generate a random country string + func (f *Faker) Country() string { return country(f.Rand) } func country(r *rand.Rand) string { return getRandValue(r, []string{"address", "country"}) } // CountryAbr will generate a random abbreviated country string + func CountryAbr() string { return countryAbr(globalFaker.Rand) } // CountryAbr will generate a random abbreviated country string + func (f *Faker) CountryAbr() string { return countryAbr(f.Rand) } func countryAbr(r *rand.Rand) string { return getRandValue(r, []string{"address", "country_abr"}) } // Latitude will generate a random latitude float64 + func Latitude() float64 { return latitude(globalFaker.Rand) } // Latitude will generate a random latitude float64 + func (f *Faker) Latitude() float64 { return latitude(f.Rand) } func latitude(r *rand.Rand) float64 { return toFixed((r.Float64()*180)-90, 6) } // LatitudeInRange will generate a random latitude within the input range + func LatitudeInRange(min, max float64) (float64, error) { + return latitudeInRange(globalFaker.Rand, min, max) + } // LatitudeInRange will generate a random latitude within the input range + func (f *Faker) LatitudeInRange(min, max float64) (float64, error) { + return latitudeInRange(f.Rand, min, max) + } func latitudeInRange(r *rand.Rand, min, max float64) (float64, error) { + if min > max || min < -90 || min > 90 || max < -90 || max > 90 { + return 0, errors.New("invalid min or max range, must be valid floats and between -90 and 90") + } + return toFixed(float64Range(r, min, max), 6), nil + } // Longitude will generate a random longitude float64 + func Longitude() float64 { return longitude(globalFaker.Rand) } // Longitude will generate a random longitude float64 + func (f *Faker) Longitude() float64 { return longitude(f.Rand) } func longitude(r *rand.Rand) float64 { return toFixed((r.Float64()*360)-180, 6) } // LongitudeInRange will generate a random longitude within the input range + func LongitudeInRange(min, max float64) (float64, error) { + return longitudeInRange(globalFaker.Rand, min, max) + } // LongitudeInRange will generate a random longitude within the input range + func (f *Faker) LongitudeInRange(min, max float64) (float64, error) { + return longitudeInRange(f.Rand, min, max) + } func longitudeInRange(r *rand.Rand, min, max float64) (float64, error) { + if min > max || min < -180 || min > 180 || max < -180 || max > 180 { + return 0, errors.New("invalid min or max range, must be valid floats and between -180 and 180") + } + return toFixed(float64Range(r, min, max), 6), nil + } func addAddressLookup() { + AddFuncLookup("address", Info{ - Display: "Address", - Category: "address", + + Display: "Address", + + Category: "address", + Description: "Residential location including street, city, state, country and postal code", + Example: `{ + "address": "364 Unionsville, Norfolk, Ohio 99536", + "street": "364 Unionsville", + "city": "Norfolk", + "state": "Ohio", + "zip": "99536", + "country": "Lesotho", + "latitude": 88.792592, + "longitude": 174.504681 + }`, - Output: "map[string]any", + + Output: "map[string]any", + ContentType: "application/json", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return address(r), nil + }, }) AddFuncLookup("city", Info{ - Display: "City", - Category: "address", + + Display: "City", + + Category: "address", + Description: "Part of a country with significant population, often a central hub for culture and commerce", - Example: "Marcelside", - Output: "string", + + Example: "Marcelside", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return city(r), nil + }, }) AddFuncLookup("country", Info{ - Display: "Country", - Category: "address", + + Display: "Country", + + Category: "address", + Description: "Nation with its own government and defined territory", - Example: "United States of America", - Output: "string", + + Example: "United States of America", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return country(r), nil + }, }) AddFuncLookup("countryabr", Info{ - Display: "Country Abbreviation", - Category: "address", + + Display: "Country Abbreviation", + + Category: "address", + Description: "Shortened 2-letter form of a country's name", - Example: "US", - Output: "string", + + Example: "US", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return countryAbr(r), nil + }, }) AddFuncLookup("state", Info{ - Display: "State", - Category: "address", + + Display: "State", + + Category: "address", + Description: "Governmental division within a country, often having its own laws and government", - Example: "Illinois", - Output: "string", + + Example: "Illinois", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return state(r), nil + }, }) AddFuncLookup("stateabr", Info{ - Display: "State Abbreviation", - Category: "address", + + Display: "State Abbreviation", + + Category: "address", + Description: "Shortened 2-letter form of a country's state", - Example: "IL", - Output: "string", + + Example: "IL", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return stateAbr(r), nil + }, }) AddFuncLookup("street", Info{ - Display: "Street", - Category: "address", + + Display: "Street", + + Category: "address", + Description: "Public road in a city or town, typically with houses and buildings on each side", - Example: "364 East Rapidsborough", - Output: "string", + + Example: "364 East Rapidsborough", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return street(r), nil + }, }) AddFuncLookup("streetname", Info{ - Display: "Street Name", - Category: "address", + + Display: "Street Name", + + Category: "address", + Description: "Name given to a specific road or street", - Example: "View", - Output: "string", + + Example: "View", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return streetName(r), nil + }, }) AddFuncLookup("streetnumber", Info{ - Display: "Street Number", - Category: "address", + + Display: "Street Number", + + Category: "address", + Description: "Numerical identifier assigned to a street", - Example: "13645", - Output: "string", + + Example: "13645", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return streetNumber(r), nil + }, }) AddFuncLookup("streetprefix", Info{ - Display: "Street Prefix", - Category: "address", + + Display: "Street Prefix", + + Category: "address", + Description: "Directional or descriptive term preceding a street name, like 'East' or 'Main'", - Example: "Lake", - Output: "string", + + Example: "Lake", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return streetPrefix(r), nil + }, }) AddFuncLookup("streetsuffix", Info{ - Display: "Street Suffix", - Category: "address", + + Display: "Street Suffix", + + Category: "address", + Description: "Designation at the end of a street name indicating type, like 'Avenue' or 'Street'", - Example: "land", - Output: "string", + + Example: "land", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return streetSuffix(r), nil + }, }) AddFuncLookup("zip", Info{ - Display: "Zip", - Category: "address", + + Display: "Zip", + + Category: "address", + Description: "Numerical code for postal address sorting, specific to a geographic area", - Example: "13645", - Output: "string", + + Example: "13645", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return zip(r), nil + }, }) AddFuncLookup("latitude", Info{ - Display: "Latitude", - Category: "address", + + Display: "Latitude", + + Category: "address", + Description: "Geographic coordinate specifying north-south position on Earth's surface", - Example: "-73.534056", - Output: "float", + + Example: "-73.534056", + + Output: "float", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return latitude(r), nil + }, }) AddFuncLookup("latituderange", Info{ - Display: "Latitude Range", - Category: "address", + + Display: "Latitude Range", + + Category: "address", + Description: "Latitude number between the given range (default min=0, max=90)", - Example: "22.921026", - Output: "float", + + Example: "22.921026", + + Output: "float", + Params: []Param{ + {Field: "min", Display: "Min", Type: "float", Default: "0", Description: "Minimum range"}, + {Field: "max", Display: "Max", Type: "float", Default: "90", Description: "Maximum range"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + min, err := info.GetFloat64(m, "min") + if err != nil { + return nil, err + } max, err := info.GetFloat64(m, "max") + if err != nil { + return nil, err + } rangeOut, err := latitudeInRange(r, min, max) + if err != nil { + return nil, err + } return rangeOut, nil + }, }) AddFuncLookup("longitude", Info{ - Display: "Longitude", - Category: "address", + + Display: "Longitude", + + Category: "address", + Description: "Geographic coordinate indicating east-west position on Earth's surface", - Example: "-147.068112", - Output: "float", + + Example: "-147.068112", + + Output: "float", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return longitude(r), nil + }, }) AddFuncLookup("longituderange", Info{ - Display: "Longitude Range", - Category: "address", + + Display: "Longitude Range", + + Category: "address", + Description: "Longitude number between the given range (default min=0, max=180)", - Example: "-8.170450", - Output: "float", + + Example: "-8.170450", + + Output: "float", + Params: []Param{ + {Field: "min", Display: "Min", Type: "float", Default: "0", Description: "Minimum range"}, + {Field: "max", Display: "Max", Type: "float", Default: "180", Description: "Maximum range"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + min, err := info.GetFloat64(m, "min") + if err != nil { + return nil, err + } max, err := info.GetFloat64(m, "max") + if err != nil { + return nil, err + } rangeOut, err := longitudeInRange(r, min, max) + if err != nil { + return nil, err + } return rangeOut, nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/app.go b/vendor/github.com/brianvoe/gofakeit/v6/app.go index 172c817..c819f9a 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/app.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/app.go @@ -6,92 +6,152 @@ import ( ) // AppName will generate a random app name + func AppName() string { + return appName(globalFaker.Rand) + } // AppName will generate a random app name + func (f *Faker) AppName() string { + return appName(f.Rand) + } func appName(r *rand.Rand) string { + name := "" + switch number(r, 1, 3) { + case 1: + name = noun(r) + verb(r) + case 2: + name = color(r) + noun(r) + case 3: + name = animal(r) + verb(r) + } return title(name) + } // AppVersion will generate a random app version + func AppVersion() string { + return appVersion(globalFaker.Rand) + } // AppVersion will generate a random app version + func (f *Faker) AppVersion() string { + return appVersion(f.Rand) + } func appVersion(r *rand.Rand) string { + return fmt.Sprintf("%d.%d.%d", number(r, 1, 5), number(r, 1, 20), number(r, 1, 20)) + } // AppAuthor will generate a random company or person name + func AppAuthor() string { + return appAuthor(globalFaker.Rand) + } // AppAuthor will generate a random company or person name + func (f *Faker) AppAuthor() string { + return appAuthor(f.Rand) + } func appAuthor(r *rand.Rand) string { + if boolFunc(r) { + return name(r) + } return company(r) + } func addAppLookup() { + AddFuncLookup("appname", Info{ - Display: "App Name", - Category: "app", + + Display: "App Name", + + Category: "app", + Description: "Software program designed for a specific purpose or task on a computer or mobile device", - Example: "Parkrespond", - Output: "string", + + Example: "Parkrespond", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return appName(r), nil + }, }) AddFuncLookup("appversion", Info{ - Display: "App Version", - Category: "app", + + Display: "App Version", + + Category: "app", + Description: "Particular release of an application in Semantic Versioning format", - Example: "1.12.14", - Output: "string", + + Example: "1.12.14", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return appVersion(r), nil + }, }) AddFuncLookup("appauthor", Info{ - Display: "App Author", - Category: "app", + + Display: "App Author", + + Category: "app", + Description: "Person or group creating and developing an application", - Example: "Qado Energy, Inc.", - Output: "string", + + Example: "Qado Energy, Inc.", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return appAuthor(r), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/beer.go b/vendor/github.com/brianvoe/gofakeit/v6/beer.go index 292ae68..f411037 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/beer.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/beer.go @@ -6,203 +6,333 @@ import ( ) // BeerName will return a random beer name + func BeerName() string { + return beerName(globalFaker.Rand) + } // BeerName will return a random beer name + func (f *Faker) BeerName() string { + return beerName(f.Rand) + } func beerName(r *rand.Rand) string { + return getRandValue(r, []string{"beer", "name"}) + } // BeerStyle will return a random beer style + func BeerStyle() string { + return beerStyle(globalFaker.Rand) + } // BeerStyle will return a random beer style + func (f *Faker) BeerStyle() string { + return beerStyle(f.Rand) + } func beerStyle(r *rand.Rand) string { + return getRandValue(r, []string{"beer", "style"}) + } // BeerHop will return a random beer hop + func BeerHop() string { + return beerHop(globalFaker.Rand) + } // BeerHop will return a random beer hop + func (f *Faker) BeerHop() string { + return beerHop(f.Rand) + } func beerHop(r *rand.Rand) string { + return getRandValue(r, []string{"beer", "hop"}) + } // BeerYeast will return a random beer yeast + func BeerYeast() string { + return beerYeast(globalFaker.Rand) + } // BeerYeast will return a random beer yeast + func (f *Faker) BeerYeast() string { + return beerYeast(f.Rand) + } func beerYeast(r *rand.Rand) string { + return getRandValue(r, []string{"beer", "yeast"}) + } // BeerMalt will return a random beer malt + func BeerMalt() string { + return beerMalt(globalFaker.Rand) + } // BeerMalt will return a random beer malt + func (f *Faker) BeerMalt() string { + return beerMalt(f.Rand) + } func beerMalt(r *rand.Rand) string { + return getRandValue(r, []string{"beer", "malt"}) + } // BeerAlcohol will return a random beer alcohol level between 2.0 and 10.0 + func BeerAlcohol() string { + return beerAlcohol(globalFaker.Rand) + } // BeerAlcohol will return a random beer alcohol level between 2.0 and 10.0 + func (f *Faker) BeerAlcohol() string { + return beerAlcohol(f.Rand) + } func beerAlcohol(r *rand.Rand) string { + return strconv.FormatFloat(float64Range(r, 2.0, 10.0), 'f', 1, 64) + "%" + } // BeerIbu will return a random beer ibu value between 10 and 100 + func BeerIbu() string { + return beerIbu(globalFaker.Rand) + } // BeerIbu will return a random beer ibu value between 10 and 100 + func (f *Faker) BeerIbu() string { + return beerIbu(f.Rand) + } func beerIbu(r *rand.Rand) string { + return strconv.Itoa(randIntRange(r, 10, 100)) + " IBU" + } // BeerBlg will return a random beer blg between 5.0 and 20.0 + func BeerBlg() string { + return beerBlg(globalFaker.Rand) + } // BeerBlg will return a random beer blg between 5.0 and 20.0 + func (f *Faker) BeerBlg() string { + return beerBlg(f.Rand) + } func beerBlg(r *rand.Rand) string { + return strconv.FormatFloat(float64Range(r, 5.0, 20.0), 'f', 1, 64) + "°Blg" + } func addBeerLookup() { + AddFuncLookup("beername", Info{ - Display: "Beer Name", - Category: "beer", + + Display: "Beer Name", + + Category: "beer", + Description: "Specific brand or variety of beer", - Example: "Duvel", - Output: "string", + + Example: "Duvel", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return beerName(r), nil + }, }) AddFuncLookup("beerstyle", Info{ - Display: "Beer Style", - Category: "beer", + + Display: "Beer Style", + + Category: "beer", + Description: "Distinct characteristics and flavors of beer", - Example: "European Amber Lager", - Output: "string", + + Example: "European Amber Lager", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return beerStyle(r), nil + }, }) AddFuncLookup("beerhop", Info{ - Display: "Beer Hop", - Category: "beer", + + Display: "Beer Hop", + + Category: "beer", + Description: "The flower used in brewing to add flavor, aroma, and bitterness to beer", - Example: "Glacier", - Output: "string", + + Example: "Glacier", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return beerHop(r), nil + }, }) AddFuncLookup("beeryeast", Info{ - Display: "Beer Yeast", - Category: "beer", + + Display: "Beer Yeast", + + Category: "beer", + Description: "Microorganism used in brewing to ferment sugars, producing alcohol and carbonation in beer", - Example: "1388 - Belgian Strong Ale", - Output: "string", + + Example: "1388 - Belgian Strong Ale", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return beerYeast(r), nil + }, }) AddFuncLookup("beermalt", Info{ - Display: "Beer Malt", - Category: "beer", + + Display: "Beer Malt", + + Category: "beer", + Description: "Processed barley or other grains, provides sugars for fermentation and flavor to beer", - Example: "Munich", - Output: "string", + + Example: "Munich", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return beerMalt(r), nil + }, }) AddFuncLookup("beeralcohol", Info{ - Display: "Beer Alcohol", - Category: "beer", + + Display: "Beer Alcohol", + + Category: "beer", + Description: "Measures the alcohol content in beer", - Example: "2.7%", - Output: "string", + + Example: "2.7%", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return beerAlcohol(r), nil + }, }) AddFuncLookup("beeribu", Info{ - Display: "Beer IBU", - Category: "beer", + + Display: "Beer IBU", + + Category: "beer", + Description: "Scale measuring bitterness of beer from hops", - Example: "29 IBU", - Output: "string", + + Example: "29 IBU", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return beerIbu(r), nil + }, }) AddFuncLookup("beerblg", Info{ - Display: "Beer BLG", - Category: "beer", + + Display: "Beer BLG", + + Category: "beer", + Description: "Scale indicating the concentration of extract in worts", - Example: "6.4°Blg", - Output: "string", + + Example: "6.4°Blg", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return beerBlg(r), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/color.go b/vendor/github.com/brianvoe/gofakeit/v6/color.go index dce7db5..7cce998 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/color.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/color.go @@ -7,112 +7,176 @@ import ( ) // Color will generate a random color string + func Color() string { return color(globalFaker.Rand) } // Color will generate a random color string + func (f *Faker) Color() string { return color(f.Rand) } func color(r *rand.Rand) string { return getRandValue(r, []string{"color", "full"}) } // NiceColor will generate a random safe color string + func NiceColors() []string { return niceColors(globalFaker.Rand) } // NiceColor will generate a random safe color string + func (f *Faker) NiceColors() []string { return niceColors(f.Rand) } func niceColors(r *rand.Rand) []string { + return data.ColorsNice[randIntRange(r, 0, len(data.ColorsNice)-1)] + } // SafeColor will generate a random safe color string + func SafeColor() string { return safeColor(globalFaker.Rand) } // SafeColor will generate a random safe color string + func (f *Faker) SafeColor() string { return safeColor(f.Rand) } func safeColor(r *rand.Rand) string { return getRandValue(r, []string{"color", "safe"}) } // HexColor will generate a random hexadecimal color string + func HexColor() string { return hexColor(globalFaker.Rand) } // HexColor will generate a random hexadecimal color string + func (f *Faker) HexColor() string { return hexColor(f.Rand) } func hexColor(r *rand.Rand) string { + color := make([]byte, 6) + hashQuestion := []byte("?#") + for i := 0; i < 6; i++ { + color[i] = hashQuestion[r.Intn(2)] + } return "#" + replaceWithHexLetters(r, replaceWithNumbers(r, string(color))) + } // RGBColor will generate a random int slice color + func RGBColor() []int { return rgbColor(globalFaker.Rand) } // RGBColor will generate a random int slice color + func (f *Faker) RGBColor() []int { return rgbColor(f.Rand) } func rgbColor(r *rand.Rand) []int { + return []int{randIntRange(r, 0, 255), randIntRange(r, 0, 255), randIntRange(r, 0, 255)} + } func addColorLookup() { + AddFuncLookup("color", Info{ - Display: "Color", - Category: "color", + + Display: "Color", + + Category: "color", + Description: "Hue seen by the eye, returns the name of the color like red or blue", - Example: "MediumOrchid", - Output: "string", + + Example: "MediumOrchid", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return color(r), nil + }, }) AddFuncLookup("nicecolors", Info{ - Display: "Nice Colors", - Category: "color", + + Display: "Nice Colors", + + Category: "color", + Description: "Attractive and appealing combinations of colors, returns an list of color hex codes", - Example: `["#cfffdd","#b4dec1","#5c5863","#a85163","#ff1f4c"]`, - Output: "[]string", + + Example: `["#cfffdd","#b4dec1","#5c5863","#a85163","#ff1f4c"]`, + + Output: "[]string", + ContentType: "application/json", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return color(r), nil + }, }) AddFuncLookup("safecolor", Info{ - Display: "Safe Color", - Category: "color", + + Display: "Safe Color", + + Category: "color", + Description: "Colors displayed consistently on different web browsers and devices", - Example: "black", - Output: "string", + + Example: "black", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return safeColor(r), nil + }, }) AddFuncLookup("hexcolor", Info{ - Display: "Hex Color", - Category: "color", + + Display: "Hex Color", + + Category: "color", + Description: "Six-digit code representing a color in the color model", - Example: "#a99fb4", - Output: "string", + + Example: "#a99fb4", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return hexColor(r), nil + }, }) AddFuncLookup("rgbcolor", Info{ - Display: "RGB Color", - Category: "color", + + Display: "RGB Color", + + Category: "color", + Description: "Color defined by red, green, and blue light values", - Example: "[85, 224, 195]", - Output: "[]int", + + Example: "[85, 224, 195]", + + Output: "[]int", + ContentType: "application/json", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return rgbColor(r), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/csv.go b/vendor/github.com/brianvoe/gofakeit/v6/csv.go index 6a2310e..70708d9 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/csv.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/csv.go @@ -12,174 +12,287 @@ import ( ) // CSVOptions defines values needed for csv generation + type CSVOptions struct { - Delimiter string `json:"delimiter" xml:"delimiter" fake:"{randomstring:[,,tab]}"` - RowCount int `json:"row_count" xml:"row_count" fake:"{number:1,10}"` - Fields []Field `json:"fields" xml:"fields" fake:"{fields}"` + Delimiter string `json:"delimiter" xml:"delimiter" fake:"{randomstring:[,,tab]}"` + + RowCount int `json:"row_count" xml:"row_count" fake:"{number:1,10}"` + + Fields []Field `json:"fields" xml:"fields" fake:"{fields}"` } // CSV generates an object or an array of objects in json format + // A nil CSVOptions returns a randomly structured CSV. + func CSV(co *CSVOptions) ([]byte, error) { return csvFunc(globalFaker, co) } // CSV generates an object or an array of objects in json format + // A nil CSVOptions returns a randomly structured CSV. + func (f *Faker) CSV(co *CSVOptions) ([]byte, error) { return csvFunc(f, co) } func csvFunc(f *Faker, co *CSVOptions) ([]byte, error) { + if co == nil { + // We didn't get a CSVOptions, so create a new random one + err := f.Struct(&co) + if err != nil { + return nil, err + } + } // Check delimiter + if co.Delimiter == "" { + co.Delimiter = "," + } + if strings.ToLower(co.Delimiter) == "tab" { + co.Delimiter = "\t" + } + if co.Delimiter != "," && co.Delimiter != "\t" && co.Delimiter != ";" { + return nil, errors.New("invalid delimiter type") + } // Check fields + if co.Fields == nil || len(co.Fields) <= 0 { + return nil, errors.New("must pass fields in order to build json object(s)") + } // Make sure you set a row count + if co.RowCount <= 0 { + return nil, errors.New("must have row count") + } b := &bytes.Buffer{} + w := csv.NewWriter(b) + w.Comma = []rune(co.Delimiter)[0] // Add header row + header := make([]string, len(co.Fields)) + for i, field := range co.Fields { + header[i] = field.Name + } + w.Write(header) // Loop through row count +1(for header) and add fields + for i := 1; i < co.RowCount+1; i++ { + vr := make([]string, len(co.Fields)) // Loop through fields and add to them to map[string]any + for ii, field := range co.Fields { + if field.Function == "autoincrement" { + vr[ii] = fmt.Sprintf("%d", i) + continue + } // Get function info + funcInfo := GetFuncLookup(field.Function) + if funcInfo == nil { + return nil, errors.New("invalid function, " + field.Function + " does not exist") + } value, err := funcInfo.Generate(f.Rand, &field.Params, funcInfo) + if err != nil { + return nil, err + } if _, ok := value.([]byte); ok { + // If it's a slice of bytes or struct, unmarshal it into an interface + var v any + if err := json.Unmarshal(value.([]byte), &v); err != nil { + return nil, err + } + value = v + } // If the value is a list of possible values, marsha it into a string + if reflect.TypeOf(value).Kind() == reflect.Struct || + reflect.TypeOf(value).Kind() == reflect.Ptr || + reflect.TypeOf(value).Kind() == reflect.Map || + reflect.TypeOf(value).Kind() == reflect.Slice { + b, err := json.Marshal(value) + if err != nil { + return nil, err + } + value = string(b) + } vr[ii] = fmt.Sprintf("%v", value) + } w.Write(vr) + } w.Flush() if err := w.Error(); err != nil { + return nil, err + } return b.Bytes(), nil + } func addFileCSVLookup() { + AddFuncLookup("csv", Info{ - Display: "CSV", - Category: "file", + + Display: "CSV", + + Category: "file", + Description: "Individual lines or data entries within a CSV (Comma-Separated Values) format", + Example: `id,first_name,last_name,password + 1,Markus,Moen,Dc0VYXjkWABx + 2,Osborne,Hilll,XPJ9OVNbs5lm`, - Output: "[]byte", + + Output: "[]byte", + ContentType: "text/csv", + Params: []Param{ + {Field: "delimiter", Display: "Delimiter", Type: "string", Default: ",", Description: "Separator in between row values"}, + {Field: "rowcount", Display: "Row Count", Type: "int", Default: "100", Description: "Number of rows"}, + {Field: "fields", Display: "Fields", Type: "[]Field", Description: "Fields containing key name and function"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + co := CSVOptions{} delimiter, err := info.GetString(m, "delimiter") + if err != nil { + return nil, err + } + co.Delimiter = delimiter rowcount, err := info.GetInt(m, "rowcount") + if err != nil { + return nil, err + } + co.RowCount = rowcount fieldsStr, err := info.GetStringArray(m, "fields") + if err != nil { + return nil, err + } // Check to make sure fields has length + if len(fieldsStr) > 0 { + co.Fields = make([]Field, len(fieldsStr)) for i, f := range fieldsStr { + // Unmarshal fields string into fields array + err = json.Unmarshal([]byte(f), &co.Fields[i]) + if err != nil { + return nil, err + } + } + } f := &Faker{Rand: r} + csvOut, err := csvFunc(f, &co) + if err != nil { + return nil, err + } return csvOut, nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/error.go b/vendor/github.com/brianvoe/gofakeit/v6/error.go index b31d772..a3e090d 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/error.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/error.go @@ -6,228 +6,374 @@ import ( ) // Error will return a random generic error + func Error() error { + return err(globalFaker.Rand) + } // Error will return a random generic error + func (f *Faker) Error() error { + return err(f.Rand) + } func err(r *rand.Rand) error { + return errors.New(generate(r, getRandValue(r, []string{"error", "generic"}))) + } // ErrorObject will return a random error object word + func ErrorObject() error { + return errorObject(globalFaker.Rand) + } // ErrorObject will return a random error object word + func (f *Faker) ErrorObject() error { + return errorObject(f.Rand) + } func errorObject(r *rand.Rand) error { + return errors.New(generate(r, getRandValue(r, []string{"error", "object"}))) + } // ErrorDatabase will return a random database error + func ErrorDatabase() error { + return errorDatabase(globalFaker.Rand) + } // ErrorDatabase will return a random database error + func (f *Faker) ErrorDatabase() error { + return errorDatabase(f.Rand) + } func errorDatabase(r *rand.Rand) error { + return errors.New(generate(r, getRandValue(r, []string{"error", "database"}))) + } // ErrorGRPC will return a random gRPC error + func ErrorGRPC() error { + return errorGRPC(globalFaker.Rand) + } // ErrorGRPC will return a random gRPC error + func (f *Faker) ErrorGRPC() error { + return errorGRPC(f.Rand) + } func errorGRPC(r *rand.Rand) error { + return errors.New(generate(r, getRandValue(r, []string{"error", "grpc"}))) + } // ErrorHTTP will return a random HTTP error + func ErrorHTTP() error { + return errorHTTP(globalFaker.Rand) + } // ErrorHTTP will return a random HTTP error + func (f *Faker) ErrorHTTP() error { + return errorHTTP(f.Rand) + } func errorHTTP(r *rand.Rand) error { + return errors.New(generate(r, getRandValue(r, []string{"error", "http"}))) + } // ErrorHTTPClient will return a random HTTP client error response (400-418) + func ErrorHTTPClient() error { + return errorHTTPClient(globalFaker.Rand) + } // ErrorHTTPClient will return a random HTTP client error response (400-418) + func (f *Faker) ErrorHTTPClient() error { + return errorHTTPClient(f.Rand) + } func errorHTTPClient(r *rand.Rand) error { + return errors.New(generate(r, getRandValue(r, []string{"error", "http_client"}))) + } // ErrorHTTPServer will return a random HTTP server error response (500-511) + func ErrorHTTPServer() error { + return errorHTTPServer(globalFaker.Rand) + } // ErrorHTTPServer will return a random HTTP server error response (500-511) + func (f *Faker) ErrorHTTPServer() error { + return errorHTTPServer(f.Rand) + } func errorHTTPServer(r *rand.Rand) error { + return errors.New(generate(r, getRandValue(r, []string{"error", "http_server"}))) + } // ErrorRuntime will return a random runtime error + func ErrorRuntime() error { + return errorRuntime(globalFaker.Rand) + } // ErrorRuntime will return a random runtime error + func (f *Faker) ErrorRuntime() error { + return errorRuntime(f.Rand) + } func errorRuntime(r *rand.Rand) error { + return errors.New(generate(r, getRandValue(r, []string{"error", "runtime"}))) + } // ErrorValidation will return a random validation error + func ErrorValidation() error { + return errorValidation(globalFaker.Rand) + } // ErrorValidation will return a random validation error + func (f *Faker) ErrorValidation() error { + return errorValidation(f.Rand) + } func errorValidation(r *rand.Rand) error { + return errors.New(generate(r, getRandValue(r, []string{"error", "validation"}))) + } func addErrorLookup() { + AddFuncLookup("error", Info{ - Display: "Error", - Category: "error", + + Display: "Error", + + Category: "error", + Description: "Message displayed by a computer or software when a problem or mistake is encountered", - Example: "syntax error", - Output: "string", + + Example: "syntax error", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return err(r), nil + }, }) AddFuncLookup("errorobject", Info{ - Display: "Error object word", - Category: "error", + + Display: "Error object word", + + Category: "error", + Description: "Various categories conveying details about encountered errors", - Example: "protocol", - Output: "string", + + Example: "protocol", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return errorObject(r), nil + }, }) AddFuncLookup("errordatabase", Info{ - Display: "Database error", - Category: "error", + + Display: "Database error", + + Category: "error", + Description: "A problem or issue encountered while accessing or managing a database", - Example: "sql error", - Output: "string", + + Example: "sql error", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return errorDatabase(r), nil + }, }) AddFuncLookup("errorgrpc", Info{ - Display: "gRPC error", - Category: "error", + + Display: "gRPC error", + + Category: "error", + Description: "Communication failure in the high-performance, open-source universal RPC framework", - Example: "client protocol error", - Output: "string", + + Example: "client protocol error", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return errorGRPC(r), nil + }, }) AddFuncLookup("errorhttp", Info{ - Display: "HTTP error", - Category: "error", + + Display: "HTTP error", + + Category: "error", + Description: "A problem with a web http request", - Example: "invalid method", - Output: "string", + + Example: "invalid method", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return errorHTTP(r), nil + }, }) AddFuncLookup("errorhttpclient", Info{ - Display: "HTTP client error", - Category: "error", + + Display: "HTTP client error", + + Category: "error", + Description: "Failure or issue occurring within a client software that sends requests to web servers", - Example: "request timeout", - Output: "string", + + Example: "request timeout", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return errorHTTPClient(r), nil + }, }) AddFuncLookup("errorhttpserver", Info{ - Display: "HTTP server error", - Category: "error", + + Display: "HTTP server error", + + Category: "error", + Description: "Failure or issue occurring within a server software that recieves requests from clients", - Example: "internal server error", - Output: "string", + + Example: "internal server error", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return errorHTTPServer(r), nil + }, }) AddFuncLookup("errorruntime", Info{ - Display: "Runtime error", - Category: "error", + + Display: "Runtime error", + + Category: "error", + Description: "Malfunction occuring during program execution, often causing abrupt termination or unexpected behavior", - Example: "address out of bounds", - Output: "string", + + Example: "address out of bounds", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return errorRuntime(r), nil + }, }) AddFuncLookup("errorvalidation", Info{ - Display: "Validation error", - Category: "error", + + Display: "Validation error", + + Category: "error", + Description: "Occurs when input data fails to meet required criteria or format specifications", - Example: "missing required field", - Output: "string", + + Example: "missing required field", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return errorValidation(r), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/fakeable.go b/vendor/github.com/brianvoe/gofakeit/v6/fakeable.go index 1089fc3..15750d7 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/fakeable.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/fakeable.go @@ -7,77 +7,138 @@ import ( ) // Fakeable is an interface that can be implemented by a type to provide a custom fake value. + type Fakeable interface { + // Fake returns a fake value for the type. + Fake(faker *Faker) (any, error) } func isFakeable(t reflect.Type) bool { + fakeableTyp := reflect.TypeOf((*Fakeable)(nil)).Elem() return t.Implements(fakeableTyp) || reflect.PtrTo(t).Implements(fakeableTyp) + } func callFake(faker *Faker, v reflect.Value, possibleKinds ...reflect.Kind) (any, error) { + f, ok := v.Addr().Interface().(Fakeable) + if !ok { + return nil, errors.New("not a Fakeable type") + } fakedValue, err := f.Fake(faker) + if err != nil { + return nil, fmt.Errorf("error calling Fake: %w", err) + } + k := reflect.TypeOf(fakedValue).Kind() + if !containsKind(possibleKinds, k) { + return nil, fmt.Errorf("returned value kind %q is not amongst the valid ones: %v", k, possibleKinds) + } switch k { + case reflect.String: + return reflect.ValueOf(fakedValue).String(), nil + case reflect.Bool: + return reflect.ValueOf(fakedValue).Bool(), nil + case reflect.Int: + return int(reflect.ValueOf(fakedValue).Int()), nil + case reflect.Int8: + return int8(reflect.ValueOf(fakedValue).Int()), nil + case reflect.Int16: + return int16(reflect.ValueOf(fakedValue).Int()), nil + case reflect.Int32: + return int32(reflect.ValueOf(fakedValue).Int()), nil + case reflect.Int64: + return int64(reflect.ValueOf(fakedValue).Int()), nil + case reflect.Uint: + return uint(reflect.ValueOf(fakedValue).Uint()), nil + case reflect.Uint8: + return uint8(reflect.ValueOf(fakedValue).Uint()), nil + case reflect.Uint16: + return uint16(reflect.ValueOf(fakedValue).Uint()), nil + case reflect.Uint32: + return uint32(reflect.ValueOf(fakedValue).Uint()), nil + case reflect.Uint64: + return uint64(reflect.ValueOf(fakedValue).Uint()), nil + case reflect.Float32: + return float32(reflect.ValueOf(fakedValue).Float()), nil + case reflect.Float64: + return float64(reflect.ValueOf(fakedValue).Float()), nil + case reflect.Slice: + return reflect.ValueOf(fakedValue).Interface(), nil + case reflect.Map: + return reflect.ValueOf(fakedValue).Interface(), nil + case reflect.Struct: + return reflect.ValueOf(fakedValue).Interface(), nil + default: + return nil, fmt.Errorf("unsupported type %q", k) + } + } func containsKind(possibleKinds []reflect.Kind, kind reflect.Kind) bool { + for _, k := range possibleKinds { + if k == kind { + return true + } + } + return false + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/faker.go b/vendor/github.com/brianvoe/gofakeit/v6/faker.go index 715c67c..7fc2979 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/faker.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/faker.go @@ -8,96 +8,146 @@ import ( ) // Create global variable to deal with global function call. + var globalFaker *Faker = New(0) // Faker struct is the primary struct for using localized. + type Faker struct { Rand *rand.Rand } type lockedSource struct { - lk sync.Mutex + lk sync.Mutex + src rand.Source64 } func (r *lockedSource) Int63() (n int64) { + r.lk.Lock() + n = r.src.Int63() + r.lk.Unlock() return + } func (r *lockedSource) Uint64() (n uint64) { + r.lk.Lock() + n = r.src.Uint64() + r.lk.Unlock() + return + } func (r *lockedSource) Seed(seed int64) { + r.lk.Lock() + r.src.Seed(seed) + r.lk.Unlock() + } type cryptoRand struct { sync.Mutex + buf []byte } func (c *cryptoRand) Seed(seed int64) {} func (c *cryptoRand) Uint64() uint64 { + // Lock to make reading thread safe + c.Lock() + defer c.Unlock() crand.Read(c.buf) + return binary.BigEndian.Uint64(c.buf) + } func (c *cryptoRand) Int63() int64 { + return int64(c.Uint64() & ^uint64(1<<63)) + } // New will utilize math/rand for concurrent random usage. + // Setting seed to 0 will use crypto/rand for the initial seed number. + func New(seed int64) *Faker { + // If passing 0 create crypto safe int64 for initial seed number + if seed == 0 { + binary.Read(crand.Reader, binary.BigEndian, &seed) + } return &Faker{Rand: rand.New(&lockedSource{src: rand.NewSource(seed).(rand.Source64)})} + } // NewUnlocked will utilize math/rand for non concurrent safe random usage. + // Setting seed to 0 will use crypto/rand for the initial seed number. + // NewUnlocked is more performant but not safe to run concurrently. + func NewUnlocked(seed int64) *Faker { + // If passing 0 create crypto safe int64 for initial seed number + if seed == 0 { + binary.Read(crand.Reader, binary.BigEndian, &seed) + } return &Faker{Rand: rand.New(rand.NewSource(seed))} + } // NewCrypto will utilize crypto/rand for concurrent random usage. + func NewCrypto() *Faker { + return &Faker{Rand: rand.New(&cryptoRand{ + buf: make([]byte, 8), })} + } // NewCustom will utilize a custom rand.Source64 for concurrent random usage + // See https://golang.org/src/math/rand/rand.go for required interface methods + func NewCustom(source rand.Source64) *Faker { + return &Faker{Rand: rand.New(source)} + } // SetGlobalFaker will allow you to set what type of faker is globally used. Defailt is math/rand + func SetGlobalFaker(faker *Faker) { + globalFaker = faker + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/finance.go b/vendor/github.com/brianvoe/gofakeit/v6/finance.go index a46907a..e2f270a 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/finance.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/finance.go @@ -9,120 +9,205 @@ import ( const cusipStr = upperStr + numericStr // CUSIP + func Cusip() string { + return cusip(globalFaker.Rand) + } func (f *Faker) Cusip() string { + return cusip(f.Rand) + } func cusip(r *rand.Rand) string { + cusipBytes := make([]byte, 8) + for i := 0; i < len(cusipBytes); i++ { + cusipBytes[i] = byte(cusipStr[r.Intn(len(cusipStr))]) + } baseCusip := string(cusipBytes) chkDigit := cusipChecksumDigit(baseCusip) + return baseCusip + chkDigit + } // ISIN + func Isin() string { + return isin(globalFaker.Rand) + } func (f *Faker) Isin() string { + return isin(f.Rand) + } func isin(r *rand.Rand) string { + countryCode := CountryAbr() + nsin := cusip(r) + isinChkDig := isinChecksumDigit(countryCode + nsin) + return countryCode + nsin + isinChkDig + } // cusipChecksumDigit returns the checksum digit for a CUSIP + func cusipChecksumDigit(cusip string) string { + sum := 0 + for i, c := range cusip { + v := 0 + if unicode.IsDigit(c) { + v = int(c - '0') + } + if unicode.IsLetter(c) { + //0-indexed ordinal position of Letter + 10 + v = int(c-'A') + 10 + } + if i%2 != 0 { + // Multiply odd digits by two + v = v * 2 + } sum = sum + int(v/10) + v%10 + } return strconv.Itoa((10 - (sum % 10)) % 10) + } // isinChecksumDigit returns the checksum digit for an ISIN + func isinChecksumDigit(isin string) string { + isinDigits := make([]int, 0) + for _, c := range isin { + if unicode.IsLetter(c) { + letterVal := int(c) - 55 + // Each digit is added as a separate value + isinDigits = append(isinDigits, letterVal/10) + isinDigits = append(isinDigits, letterVal%10) + } + if unicode.IsDigit(c) { + isinDigits = append(isinDigits, int(c-'0')) + } + } oddSum := 0 + evenSum := 0 // Take the per digit sum of the digitized ISIN, doubling even indexed digits + for i, d := range isinDigits { + if i%2 == 0 { + elem := 2 * d + if elem > 9 { + // If the element now has two digits, sum those digits + elem = (elem % 10) + (elem / 10) + } + evenSum += elem + } else { + oddSum += d + } + } return strconv.Itoa((10 - (oddSum+evenSum)%10) % 10) + } // Lookup Adds + func addFinanceLookup() { + AddFuncLookup("cusip", Info{ - Display: "CUSIP", - Category: "finance", + + Display: "CUSIP", + + Category: "finance", + Description: "Unique identifier for securities, especially bonds, in the United States and Canada", - Example: "38259P508", - Output: "string", + + Example: "38259P508", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return cusip(r), nil + }, }) + AddFuncLookup("isin", Info{ - Display: "ISIN", - Category: "finance", + + Display: "ISIN", + + Category: "finance", + Description: "International standard code for uniquely identifying securities worldwide", - Example: "CVLRQCZBXQ97", - Output: "string", + + Example: "CVLRQCZBXQ97", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return isin(r), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/food.go b/vendor/github.com/brianvoe/gofakeit/v6/food.go index ae1bb2f..e3cd9c5 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/food.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/food.go @@ -6,173 +6,273 @@ import ( ) // Fruit will return a random fruit name + func Fruit() string { return fruit(globalFaker.Rand) } // Fruit will return a random fruit name + func (f *Faker) Fruit() string { return fruit(f.Rand) } func fruit(r *rand.Rand) string { return getRandValue(r, []string{"food", "fruit"}) } // Vegetable will return a random vegetable name + func Vegetable() string { return vegetable(globalFaker.Rand) } // Vegetable will return a random vegetable name + func (f *Faker) Vegetable() string { return vegetable(f.Rand) } func vegetable(r *rand.Rand) string { return getRandValue(r, []string{"food", "vegetable"}) } // Breakfast will return a random breakfast name + func Breakfast() string { return breakfast(globalFaker.Rand) } // Breakfast will return a random breakfast name + func (f *Faker) Breakfast() string { return breakfast(f.Rand) } func breakfast(r *rand.Rand) string { + v := getRandValue(r, []string{"food", "breakfast"}) + return strings.ToUpper(v[:1]) + v[1:] + } // Lunch will return a random lunch name + func Lunch() string { return lunch(globalFaker.Rand) } // Lunch will return a random lunch name + func (f *Faker) Lunch() string { return lunch(f.Rand) } func lunch(r *rand.Rand) string { + v := getRandValue(r, []string{"food", "lunch"}) + return strings.ToUpper(v[:1]) + v[1:] + } // Dinner will return a random dinner name + func Dinner() string { return dinner(globalFaker.Rand) } // Dinner will return a random dinner name + func (f *Faker) Dinner() string { return dinner(f.Rand) } func dinner(r *rand.Rand) string { + v := getRandValue(r, []string{"food", "dinner"}) + return strings.ToUpper(v[:1]) + v[1:] + } // Drink will return a random drink name + func Drink() string { return drink(globalFaker.Rand) } // Drink will return a random drink name + func (f *Faker) Drink() string { return drink(f.Rand) } func drink(r *rand.Rand) string { + v := getRandValue(r, []string{"food", "drink"}) + return strings.ToUpper(v[:1]) + v[1:] + } // Snack will return a random snack name + func Snack() string { return snack(globalFaker.Rand) } // Snack will return a random snack name + func (f *Faker) Snack() string { return snack(f.Rand) } func snack(r *rand.Rand) string { + v := getRandValue(r, []string{"food", "snack"}) + return strings.ToUpper(v[:1]) + v[1:] + } // Dessert will return a random dessert name + func Dessert() string { return dessert(globalFaker.Rand) } // Dessert will return a random dessert name + func (f *Faker) Dessert() string { return dessert(f.Rand) } func dessert(r *rand.Rand) string { + v := getRandValue(r, []string{"food", "dessert"}) + return strings.ToUpper(v[:1]) + v[1:] + } func addFoodLookup() { + AddFuncLookup("fruit", Info{ - Display: "Fruit", - Category: "food", + + Display: "Fruit", + + Category: "food", + Description: "Edible plant part, typically sweet, enjoyed as a natural snack or dessert", - Example: "Peach", - Output: "string", + + Example: "Peach", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return fruit(r), nil + }, }) AddFuncLookup("vegetable", Info{ - Display: "Vegetable", - Category: "food", + + Display: "Vegetable", + + Category: "food", + Description: "Edible plant or part of a plant, often used in savory cooking or salads", - Example: "Amaranth Leaves", - Output: "string", + + Example: "Amaranth Leaves", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return vegetable(r), nil + }, }) AddFuncLookup("breakfast", Info{ - Display: "Breakfast", - Category: "food", + + Display: "Breakfast", + + Category: "food", + Description: "First meal of the day, typically eaten in the morning", - Example: "Blueberry banana happy face pancakes", - Output: "string", + + Example: "Blueberry banana happy face pancakes", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return breakfast(r), nil + }, }) AddFuncLookup("lunch", Info{ - Display: "Lunch", - Category: "food", + + Display: "Lunch", + + Category: "food", + Description: "Midday meal, often lighter than dinner, eaten around noon", - Example: "No bake hersheys bar pie", - Output: "string", + + Example: "No bake hersheys bar pie", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return lunch(r), nil + }, }) AddFuncLookup("dinner", Info{ - Display: "Dinner", - Category: "food", + + Display: "Dinner", + + Category: "food", + Description: "Evening meal, typically the day's main and most substantial meal", - Example: "Wild addicting dip", - Output: "string", + + Example: "Wild addicting dip", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return dinner(r), nil + }, }) AddFuncLookup("drink", Info{ - Display: "Drink", - Category: "food", + + Display: "Drink", + + Category: "food", + Description: "Liquid consumed for hydration, pleasure, or nutritional benefits", - Example: "Soda", - Output: "string", + + Example: "Soda", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return drink(r), nil + }, }) AddFuncLookup("snack", Info{ - Display: "Snack", - Category: "food", + + Display: "Snack", + + Category: "food", + Description: "Random snack", - Example: "Small, quick food item eaten between meals", - Output: "string", + + Example: "Small, quick food item eaten between meals", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return snack(r), nil + }, }) AddFuncLookup("dessert", Info{ - Display: "Dessert", - Category: "food", + + Display: "Dessert", + + Category: "food", + Description: "Sweet treat often enjoyed after a meal", - Example: "French napoleons", - Output: "string", + + Example: "French napoleons", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return dessert(r), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/game.go b/vendor/github.com/brianvoe/gofakeit/v6/game.go index 5c1bc36..8827730 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/game.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/game.go @@ -7,96 +7,156 @@ import ( ) // Gamertag will generate a random video game username + func Gamertag() string { return gamertag(globalFaker.Rand) } // Gamertag will generate a random video game username + func (f *Faker) Gamertag() string { return gamertag(f.Rand) } func gamertag(r *rand.Rand) string { + str := "" + num := number(r, 1, 4) + switch num { + case 1: + str = fmt.Sprintf("%s%ser", title(nounConcrete(r)), title(verbAction(r))) + case 2: + str = fmt.Sprintf("%s%s", title(adjectiveDescriptive(r)), title(animal(r))) + case 3: + str = fmt.Sprintf("%s%s", title(adjectiveDescriptive(r)), title(nounConcrete(r))) + case 4: + str = fmt.Sprintf("%s%s", title(fruit(r)), title(adjectiveDescriptive(r))) + } // Randomly determine if we should add a number + if r.Intn(3) == 1 { + str += digitN(r, uint(number(r, 1, 3))) + } // Remove any spaces + str = strings.Replace(str, " ", "", -1) return str + } // Dice will generate a random set of dice + func Dice(numDice uint, sides []uint) []uint { return dice(globalFaker.Rand, numDice, sides) } // Dice will generate a random set of dice + func (f *Faker) Dice(numDice uint, sides []uint) []uint { return dice(f.Rand, numDice, sides) } func dice(r *rand.Rand, numDice uint, sides []uint) []uint { + dice := make([]uint, numDice) // If we dont have any sides well set the sides to 6 + if len(sides) == 0 { + sides = []uint{6} + } for i := range dice { + // If sides[i] doesnt exist use the first side + if len(sides)-1 < i { + dice[i] = uint(number(r, 1, int(sides[0]))) + } else { + dice[i] = uint(number(r, 1, int(sides[i]))) + } + } return dice + } func addGameLookup() { + AddFuncLookup("gamertag", Info{ - Display: "Gamertag", - Category: "game", + + Display: "Gamertag", + + Category: "game", + Description: "User-selected online username or alias used for identification in games", - Example: "footinterpret63", - Output: "string", + + Example: "footinterpret63", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return gamertag(r), nil + }, }) AddFuncLookup("dice", Info{ - Display: "Dice", - Category: "game", + + Display: "Dice", + + Category: "game", + Description: "Small, cube-shaped objects used in games of chance for random outcomes", - Example: "[5, 2, 3]", - Output: "[]uint", + + Example: "[5, 2, 3]", + + Output: "[]uint", + Params: []Param{ + {Field: "numdice", Display: "Number of Dice", Type: "uint", Default: "1", Description: "Number of dice to roll"}, + {Field: "sides", Display: "Number of Sides", Type: "[]uint", Default: "[6]", Description: "Number of sides on each dice"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + numDice, err := info.GetUint(m, "numdice") + if err != nil { + return nil, err + } sides, err := info.GetUintArray(m, "sides") + if err != nil { + return nil, err + } return dice(r, numDice, sides), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/generate.go b/vendor/github.com/brianvoe/gofakeit/v6/generate.go index 342a3a5..2d933c9 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/generate.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/generate.go @@ -11,511 +11,893 @@ import ( ) // Generate fake information from given string. + // Replaceable values should be within {} + // + // Functions + // Ex: {firstname} - billy + // Ex: {sentence:3} - Record river mind. + // Ex: {number:1,10} - 4 + // Ex: {uuid} - 590c1440-9888-45b0-bd51-a817ee07c3f2 + // + // Letters/Numbers + // Ex: ### - 481 - random numbers + // Ex: ??? - fda - random letters + // + // For a complete list of runnable functions use FuncsLookup + func Generate(dataVal string) string { return generate(globalFaker.Rand, dataVal) } // Generate fake information from given string. + // Replaceable values should be within {} + // + // Functions + // Ex: {firstname} - billy + // Ex: {sentence:3} - Record river mind. + // Ex: {number:1,10} - 4 + // Ex: {uuid} - 590c1440-9888-45b0-bd51-a817ee07c3f2 + // + // Letters/Numbers + // Ex: ### - 481 - random numbers + // Ex: ??? - fda - random letters + // + // For a complete list of runnable functions use FuncsLookup + func (f *Faker) Generate(dataVal string) string { return generate(f.Rand, dataVal) } func generate(r *rand.Rand, dataVal string) string { + // Replace # with numbers and ? with letters + dataVal = replaceWithNumbers(r, dataVal) + dataVal = replaceWithLetters(r, dataVal) // Check if string has any replaceable values + if !strings.Contains(dataVal, "{") && !strings.Contains(dataVal, "}") { + return dataVal + } // Variables to identify the index in which it exists + startCurly := -1 + startCurlyIgnore := []int{} + endCurly := -1 + endCurlyIgnore := []int{} // Loop through string characters + for i := 0; i < len(dataVal); i++ { + // Check for ignores if equal skip + shouldSkip := false + for _, igs := range startCurlyIgnore { + if i == igs { + shouldSkip = true + } + } + for _, ige := range endCurlyIgnore { + if i == ige { + shouldSkip = true + } + } + if shouldSkip { + continue + } // Identify items between brackets. Ex: {firstname} + if string(dataVal[i]) == "{" { + startCurly = i + continue + } + if startCurly != -1 && string(dataVal[i]) == "}" { + endCurly = i + } + if startCurly == -1 || endCurly == -1 { + continue + } // Get the value between brackets + fParts := dataVal[startCurly+1 : endCurly] // Check if has params separated by : + fNameSplit := strings.SplitN(fParts, ":", 2) + fName := "" + fParams := "" + if len(fNameSplit) >= 1 { + fName = fNameSplit[0] + } + if len(fNameSplit) >= 2 { + fParams = fNameSplit[1] + } // Check to see if its a replaceable lookup function + if info := GetFuncLookup(fName); info != nil { + // Get parameters, make sure params and the split both have values + mapParams := NewMapParams() + paramsLen := len(info.Params) // If just one param and its a string simply just pass it + if paramsLen == 1 && info.Params[0].Type == "string" { + mapParams.Add(info.Params[0].Field, fParams) + } else if paramsLen > 0 && fParams != "" { + splitVals := funcLookupSplit(fParams) + mapParams = addSplitValsToMapParams(splitVals, info, mapParams) + } + if mapParams.Size() == 0 { + mapParams = nil + } // Call function + fValue, err := info.Generate(r, mapParams, info) + if err != nil { + // If we came across an error just dont replace value + dataVal = strings.Replace(dataVal, "{"+fParts+"}", err.Error(), 1) + } else { + // Successfully found, run replace with new value + dataVal = strings.Replace(dataVal, "{"+fParts+"}", fmt.Sprintf("%v", fValue), 1) + } // Reset the curly index back to -1 and reset ignores + startCurly = -1 + startCurlyIgnore = []int{} + endCurly = -1 + endCurlyIgnore = []int{} + i = -1 // Reset back to the start of the string + continue + } // Couldnt find anything - mark curly brackets to skip and rerun + startCurlyIgnore = append(startCurlyIgnore, startCurly) + endCurlyIgnore = append(endCurlyIgnore, endCurly) // Reset the curly index back to -1 + startCurly = -1 + endCurly = -1 + i = -1 // Reset back to the start of the string + continue + } return dataVal + } // FixedWidthOptions defines values needed for csv generation + type FixedWidthOptions struct { - RowCount int `json:"row_count" xml:"row_count" fake:"{number:1,10}"` - Fields []Field `json:"fields" xml:"fields" fake:"{fields}"` + RowCount int `json:"row_count" xml:"row_count" fake:"{number:1,10}"` + + Fields []Field `json:"fields" xml:"fields" fake:"{fields}"` } // FixedWidth generates an table of random data in fixed width format + // A nil FixedWidthOptions returns a randomly structured FixedWidth. + func FixedWidth(co *FixedWidthOptions) (string, error) { return fixeWidthFunc(globalFaker.Rand, co) } // FixedWidth generates an table of random data in fixed width format + // A nil FixedWidthOptions returns a randomly structured FixedWidth. + func (f *Faker) FixedWidth(co *FixedWidthOptions) (string, error) { return fixeWidthFunc(f.Rand, co) } // Function to generate a fixed width document + func fixeWidthFunc(r *rand.Rand, co *FixedWidthOptions) (string, error) { + // If we didn't get FixedWidthOptions, create a new random one + if co == nil { + co = &FixedWidthOptions{} + } // Make sure you set a row count + if co.RowCount <= 0 { + co.RowCount = r.Intn(10) + 1 + } // Check fields + if len(co.Fields) <= 0 { + // Create random fields + co.Fields = []Field{ + {Name: "Name", Function: "{firstname} {lastname}"}, + {Name: "Email", Function: "email"}, + {Name: "Password", Function: "password", Params: MapParams{"special": {"false"}, "space": {"false"}}}, } + } data := [][]string{} + hasHeader := false // Loop through fields, generate data and add to data array + for _, field := range co.Fields { + // Start new row + row := []string{} // Add name to first value + if field.Name != "" { + hasHeader = true + } + row = append(row, field.Name) // Get function + funcInfo := GetFuncLookup(field.Function) + var value any + if funcInfo == nil { + // Try to run the function through generate + for i := 0; i < co.RowCount; i++ { + row = append(row, generate(r, field.Function)) + } + } else { + // Generate function value + var err error + for i := 0; i < co.RowCount; i++ { + value, err = funcInfo.Generate(r, &field.Params, funcInfo) + if err != nil { + value = "" + } // Add value to row + row = append(row, anyToString(value)) + } + } // Add row to data + data = append(data, row) + } var result strings.Builder // Calculate column widths + colWidths := make([]int, len(data)) + for i, row := range data { + for _, value := range row { + width := len(value) + 5 + if width > colWidths[i] { + colWidths[i] = width + } + } + } // Append table rows to the string, excluding the entire row if the first value is empty + for i := 0; i < len(data[0]); i++ { + if !hasHeader && i == 0 { + continue // Skip the entire column if the first value is empty + } var resultRow strings.Builder + for j, row := range data { + resultRow.WriteString(fmt.Sprintf("%-*s", colWidths[j], row[i])) + } // Trim trailing spaces + result.WriteString(strings.TrimRight(resultRow.String(), " ")) // Only add new line if not the last row + if i != len(data[0])-1 { + result.WriteString("\n") + } + } return result.String(), nil + } // Regex will generate a string based upon a RE2 syntax + func Regex(regexStr string) string { return regex(globalFaker.Rand, regexStr) } // Regex will generate a string based upon a RE2 syntax + func (f *Faker) Regex(regexStr string) string { return regex(f.Rand, regexStr) } func regex(r *rand.Rand, regexStr string) (gen string) { + re, err := syntax.Parse(regexStr, syntax.Perl) + if err != nil { + return "Could not parse regex string" + } // Panic catch + defer func() { + if r := recover(); r != nil { + gen = fmt.Sprint(r) + return } + }() return regexGenerate(r, re, len(regexStr)*100) + } func regexGenerate(ra *rand.Rand, re *syntax.Regexp, limit int) string { + if limit <= 0 { + panic("Length limit reached when generating output") + } op := re.Op + switch op { + case syntax.OpNoMatch: // matches no strings + // Do Nothing + case syntax.OpEmptyMatch: // matches empty string + return "" + case syntax.OpLiteral: // matches Runes sequence + var b strings.Builder + for _, ru := range re.Rune { + b.WriteRune(ru) + } + return b.String() + case syntax.OpCharClass: // matches Runes interpreted as range pair list + // number of possible chars + sum := 0 + for i := 0; i < len(re.Rune); i += 2 { + sum += int(re.Rune[i+1]-re.Rune[i]) + 1 + if re.Rune[i+1] == 0x10ffff { // rune range end + sum = -1 + break + } + } // pick random char in range (inverse match group) + if sum == -1 { + chars := []uint8{} + for j := 0; j < len(allStr); j++ { + c := allStr[j] // Check c in range + for i := 0; i < len(re.Rune); i += 2 { + if rune(c) >= re.Rune[i] && rune(c) <= re.Rune[i+1] { + chars = append(chars, c) + break + } + } + } + if len(chars) > 0 { + return string([]byte{chars[ra.Intn(len(chars))]}) + } + } r := ra.Intn(int(sum)) + var ru rune + sum = 0 + for i := 0; i < len(re.Rune); i += 2 { + gap := int(re.Rune[i+1]-re.Rune[i]) + 1 + if sum+gap > r { + ru = re.Rune[i] + rune(r-sum) + break + } + sum += gap + } return string(ru) + case syntax.OpAnyCharNotNL, syntax.OpAnyChar: // matches any character(and except newline) + return randCharacter(ra, allStr) + case syntax.OpBeginLine: // matches empty string at beginning of line + case syntax.OpEndLine: // matches empty string at end of line + case syntax.OpBeginText: // matches empty string at beginning of text + case syntax.OpEndText: // matches empty string at end of text + case syntax.OpWordBoundary: // matches word boundary `\b` + case syntax.OpNoWordBoundary: // matches word non-boundary `\B` + case syntax.OpCapture: // capturing subexpression with index Cap, optional name Name + return regexGenerate(ra, re.Sub0[0], limit) + case syntax.OpStar: // matches Sub[0] zero or more times + var b strings.Builder + for i := 0; i < number(ra, 0, 10); i++ { + for _, rs := range re.Sub { + b.WriteString(regexGenerate(ra, rs, limit-b.Len())) + } + } + return b.String() + case syntax.OpPlus: // matches Sub[0] one or more times + var b strings.Builder + for i := 0; i < number(ra, 1, 10); i++ { + for _, rs := range re.Sub { + b.WriteString(regexGenerate(ra, rs, limit-b.Len())) + } + } + return b.String() + case syntax.OpQuest: // matches Sub[0] zero or one times + var b strings.Builder + for i := 0; i < number(ra, 0, 1); i++ { + for _, rs := range re.Sub { + b.WriteString(regexGenerate(ra, rs, limit-b.Len())) + } + } + return b.String() + case syntax.OpRepeat: // matches Sub[0] at least Min times, at most Max (Max == -1 is no limit) + var b strings.Builder + count := 0 + re.Max = int(math.Min(float64(re.Max), float64(10))) + if re.Max > re.Min { + count = ra.Intn(re.Max - re.Min + 1) + } + for i := 0; i < re.Min || i < (re.Min+count); i++ { + for _, rs := range re.Sub { + b.WriteString(regexGenerate(ra, rs, limit-b.Len())) + } + } + return b.String() + case syntax.OpConcat: // matches concatenation of Subs + var b strings.Builder + for _, rs := range re.Sub { + b.WriteString(regexGenerate(ra, rs, limit-b.Len())) + } + return b.String() + case syntax.OpAlternate: // matches alternation of Subs + return regexGenerate(ra, re.Sub[number(ra, 0, len(re.Sub)-1)], limit) + } return "" + } // Map will generate a random set of map data + func Map() map[string]any { return mapFunc(globalFaker.Rand) } // Map will generate a random set of map data + func (f *Faker) Map() map[string]any { return mapFunc(f.Rand) } func mapFunc(r *rand.Rand) map[string]any { + m := map[string]any{} randWordType := func() string { + s := randomString(r, []string{"lorem", "bs", "job", "name", "address"}) + switch s { + case "bs": + return bs(r) + case "job": + return jobTitle(r) + case "name": + return name(r) + case "address": + return street(r) + ", " + city(r) + ", " + state(r) + " " + zip(r) + } + return word(r) + } randSlice := func() []string { + var sl []string + for ii := 0; ii < number(r, 3, 10); ii++ { + sl = append(sl, word(r)) + } + return sl + } for i := 0; i < number(r, 3, 10); i++ { + t := randomString(r, []string{"string", "int", "float", "slice", "map"}) + switch t { + case "string": + m[word(r)] = randWordType() + case "int": + m[word(r)] = number(r, 1, 10000000) + case "float": + m[word(r)] = float32Range(r, 1, 1000000) + case "slice": + m[word(r)] = randSlice() + case "map": + mm := map[string]any{} + tt := randomString(r, []string{"string", "int", "float", "slice"}) + switch tt { + case "string": + mm[word(r)] = randWordType() + case "int": + mm[word(r)] = number(r, 1, 10000000) + case "float": + mm[word(r)] = float32Range(r, 1, 1000000) + case "slice": + mm[word(r)] = randSlice() + } + m[word(r)] = mm + } + } return m + } func addGenerateLookup() { + AddFuncLookup("generate", Info{ - Display: "Generate", - Category: "generate", + + Display: "Generate", + + Category: "generate", + Description: "Random string generated from string value based upon available data sets", - Example: "{firstname} {lastname} {email} - Markus Moen markusmoen@pagac.net", - Output: "string", + + Example: "{firstname} {lastname} {email} - Markus Moen markusmoen@pagac.net", + + Output: "string", + Params: []Param{ + {Field: "str", Display: "String", Type: "string", Description: "String value to generate from"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + str, err := info.GetString(m, "str") + if err != nil { + return nil, err + } // Limit the length of the string passed + if len(str) > 1000 { + return nil, errors.New("string length is too large. limit to 1000 characters") + } return generate(r, str), nil + }, }) AddFuncLookup("fixed_width", Info{ - Display: "Fixed Width", - Category: "generate", + + Display: "Fixed Width", + + Category: "generate", + Description: "Fixed width rows of output data based on input fields", + Example: `Name Email Password Age + Markus Moen sylvanmraz@murphy.net 6VlvH6qqXc7g 13 + Alayna Wuckert santinostanton@carroll.biz g7sLrS0gEwLO 46 + Lura Lockman zacherykuhic@feil.name S8gV7Z64KlHG 12`, - Output: "[]byte", + + Output: "[]byte", + ContentType: "text/plain", + Params: []Param{ + {Field: "rowcount", Display: "Row Count", Type: "int", Default: "10", Description: "Number of rows"}, + {Field: "fields", Display: "Fields", Type: "[]Field", Description: "Fields name, function and params"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + co := FixedWidthOptions{} rowCount, err := info.GetInt(m, "rowcount") + if err != nil { + return nil, err + } co.RowCount = rowCount @@ -523,67 +905,115 @@ Lura Lockman zacherykuhic@feil.name S8gV7Z64KlHG 12`, fields, _ := info.GetStringArray(m, "fields") // Check to make sure fields has length + if len(fields) > 0 { + co.Fields = make([]Field, len(fields)) + for i, f := range fields { + // Unmarshal fields string into fields array + err = json.Unmarshal([]byte(f), &co.Fields[i]) + if err != nil { + return nil, err + } + } + } else { + return nil, errors.New("missing fields") + } out, err := fixeWidthFunc(r, &co) + if err != nil { + return nil, err + } return out, nil + }, }) AddFuncLookup("regex", Info{ - Display: "Regex", - Category: "generate", + + Display: "Regex", + + Category: "generate", + Description: "Pattern-matching tool used in text processing to search and manipulate strings", - Example: "[abcdef]{5} - affec", - Output: "string", + + Example: "[abcdef]{5} - affec", + + Output: "string", + Params: []Param{ + {Field: "str", Display: "String", Type: "string", Description: "Regex RE2 syntax string"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + str, err := info.GetString(m, "str") + if err != nil { + return nil, err + } // Limit the length of the string passed + if len(str) > 500 { + return nil, errors.New("string length is too large. limit to 500 characters") + } return regex(r, str), nil + }, }) AddFuncLookup("map", Info{ - Display: "Map", - Category: "generate", + + Display: "Map", + + Category: "generate", + Description: "Data structure that stores key-value pairs", + Example: `{ + "software": 7518355, + "that": ["despite", "pack", "whereas", "recently", "there", "anyone", "time", "read"], + "use": 683598, + "whom": "innovate", + "yourselves": 1987784 + }`, - Output: "map[string]any", + + Output: "map[string]any", + ContentType: "application/json", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return mapFunc(r), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/hacker.go b/vendor/github.com/brianvoe/gofakeit/v6/hacker.go index 393c558..0aef688 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/hacker.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/hacker.go @@ -6,131 +6,207 @@ import ( ) // HackerPhrase will return a random hacker sentence + func HackerPhrase() string { return hackerPhrase(globalFaker.Rand) } // HackerPhrase will return a random hacker sentence + func (f *Faker) HackerPhrase() string { return hackerPhrase(f.Rand) } func hackerPhrase(r *rand.Rand) string { + words := strings.Split(generate(r, getRandValue(r, []string{"hacker", "phrase"})), " ") + words[0] = strings.ToUpper(words[0][0:1]) + words[0][1:] + return strings.Join(words, " ") + } // HackerAbbreviation will return a random hacker abbreviation + func HackerAbbreviation() string { return hackerAbbreviation(globalFaker.Rand) } // HackerAbbreviation will return a random hacker abbreviation + func (f *Faker) HackerAbbreviation() string { return hackerAbbreviation(f.Rand) } func hackerAbbreviation(r *rand.Rand) string { + return getRandValue(r, []string{"hacker", "abbreviation"}) + } // HackerAdjective will return a random hacker adjective + func HackerAdjective() string { return hackerAdjective(globalFaker.Rand) } // HackerAdjective will return a random hacker adjective + func (f *Faker) HackerAdjective() string { return hackerAdjective(f.Rand) } func hackerAdjective(r *rand.Rand) string { + return getRandValue(r, []string{"hacker", "adjective"}) + } // HackerNoun will return a random hacker noun + func HackerNoun() string { return hackerNoun(globalFaker.Rand) } // HackerNoun will return a random hacker noun + func (f *Faker) HackerNoun() string { return hackerNoun(f.Rand) } func hackerNoun(r *rand.Rand) string { + return getRandValue(r, []string{"hacker", "noun"}) + } // HackerVerb will return a random hacker verb + func HackerVerb() string { return hackerVerb(globalFaker.Rand) } // HackerVerb will return a random hacker verb + func (f *Faker) HackerVerb() string { return hackerVerb(f.Rand) } func hackerVerb(r *rand.Rand) string { + return getRandValue(r, []string{"hacker", "verb"}) + } // HackeringVerb will return a random hacker ingverb + func HackeringVerb() string { return hackeringVerb(globalFaker.Rand) } // HackeringVerb will return a random hacker ingverb + func (f *Faker) HackeringVerb() string { return hackeringVerb(f.Rand) } func hackeringVerb(r *rand.Rand) string { + return getRandValue(r, []string{"hacker", "ingverb"}) + } func addHackerLookup() { + AddFuncLookup("hackerphrase", Info{ - Display: "Hacker Phrase", - Category: "hacker", + + Display: "Hacker Phrase", + + Category: "hacker", + Description: "Informal jargon and slang used in the hacking and cybersecurity community", - Example: "If we calculate the program, we can get to the AI pixel through the redundant XSS matrix!", - Output: "string", + + Example: "If we calculate the program, we can get to the AI pixel through the redundant XSS matrix!", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return hackerPhrase(r), nil + }, }) AddFuncLookup("hackerabbreviation", Info{ - Display: "Hacker Abbreviation", - Category: "hacker", + + Display: "Hacker Abbreviation", + + Category: "hacker", + Description: "Abbreviations and acronyms commonly used in the hacking and cybersecurity community", - Example: "ADP", - Output: "string", + + Example: "ADP", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return hackerAbbreviation(r), nil + }, }) AddFuncLookup("hackeradjective", Info{ - Display: "Hacker Adjective", - Category: "hacker", + + Display: "Hacker Adjective", + + Category: "hacker", + Description: "Adjectives describing terms often associated with hackers and cybersecurity experts", - Example: "wireless", - Output: "string", + + Example: "wireless", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return hackerAdjective(r), nil + }, }) AddFuncLookup("hackernoun", Info{ - Display: "Hacker Noun", - Category: "hacker", + + Display: "Hacker Noun", + + Category: "hacker", + Description: "Noun representing an element, tool, or concept within the realm of hacking and cybersecurity", - Example: "driver", - Output: "string", + + Example: "driver", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return hackerNoun(r), nil + }, }) AddFuncLookup("hackerverb", Info{ - Display: "Hacker Verb", - Category: "hacker", + + Display: "Hacker Verb", + + Category: "hacker", + Description: "Verbs associated with actions and activities in the field of hacking and cybersecurity", - Example: "synthesize", - Output: "string", + + Example: "synthesize", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return hackerVerb(r), nil + }, }) AddFuncLookup("hackeringverb", Info{ - Display: "Hackering Verb", - Category: "hacker", + + Display: "Hackering Verb", + + Category: "hacker", + Description: "Verb describing actions and activities related to hacking, often involving computer systems and security", - Example: "connecting", - Output: "string", + + Example: "connecting", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return hackeringVerb(r), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/helpers.go b/vendor/github.com/brianvoe/gofakeit/v6/helpers.go index 3dcf849..bd0ec83 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/helpers.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/helpers.go @@ -15,386 +15,673 @@ import ( ) const lowerStr = "abcdefghijklmnopqrstuvwxyz" + const upperStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + const numericStr = "0123456789" + const specialStr = "@#$%&?|!(){}<>=*+-_:;,." + const specialSafeStr = "@#$&?!-_*." + const spaceStr = " " + const allStr = lowerStr + upperStr + numericStr + specialStr + spaceStr + const vowels = "aeiou" + const hashtag = '#' + const questionmark = '?' + const dash = '-' + const base58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + const minUint = 0 + const maxUint = ^uint(0) + const minInt = -maxInt - 1 + const maxInt = int(^uint(0) >> 1) // Seed will set the global random value. Setting seed to 0 will use crypto/rand + func Seed(seed int64) { + if seed == 0 { + binary.Read(crand.Reader, binary.BigEndian, &seed) + globalFaker.Rand.Seed(seed) + } else { + globalFaker.Rand.Seed(seed) + } + } // Check if in lib + func dataCheck(dataVal []string) bool { + var checkOk bool if len(dataVal) == 2 { + _, checkOk = data.Data[dataVal[0]] + if checkOk { + _, checkOk = data.Data[dataVal[0]][dataVal[1]] + } + } return checkOk + } // Get Random Value + func getRandValue(r *rand.Rand, dataVal []string) string { + if !dataCheck(dataVal) { + return "" + } + return data.Data[dataVal[0]][dataVal[1]][r.Intn(len(data.Data[dataVal[0]][dataVal[1]]))] + } // Replace # with numbers + func replaceWithNumbers(r *rand.Rand, str string) string { + if str == "" { + return str + } + bytestr := []byte(str) + for i := 0; i < len(bytestr); i++ { + if bytestr[i] == hashtag { + bytestr[i] = byte(randDigit(r)) + } + } + if bytestr[0] == '0' { + bytestr[0] = byte(r.Intn(8)+1) + '0' + } return string(bytestr) + } // Replace ? with ASCII lowercase letters + func replaceWithLetters(r *rand.Rand, str string) string { + if str == "" { + return str + } + bytestr := []byte(str) + for i := 0; i < len(bytestr); i++ { + if bytestr[i] == questionmark { + bytestr[i] = byte(randLetter(r)) + } + } return string(bytestr) + } // Replace ? with ASCII lowercase letters between a and f + func replaceWithHexLetters(r *rand.Rand, str string) string { + if str == "" { + return str + } + bytestr := []byte(str) + for i := 0; i < len(bytestr); i++ { + if bytestr[i] == questionmark { + bytestr[i] = byte(randHexLetter(r)) + } + } return string(bytestr) + } // Generate random lowercase ASCII letter + func randLetter(r *rand.Rand) rune { + allLetters := upperStr + lowerStr + return rune(allLetters[r.Intn(len(allLetters))]) + } func randCharacter(r *rand.Rand, s string) string { + return string(s[r.Int63()%int64(len(s))]) + } // Generate random lowercase ASCII letter between a and f + func randHexLetter(r *rand.Rand) rune { + return rune(byte(r.Intn(6)) + 'a') + } // Generate random ASCII digit + func randDigit(r *rand.Rand) rune { + return rune(byte(r.Intn(10)) + '0') + } // Generate random integer between min and max + func randIntRange(r *rand.Rand, min, max int) int { + // If they pass in the same number, just return that number + if min == max { + return min + } // If they pass in a min that is bigger than max, swap them + if min > max { + ogmin := min + min = max + max = ogmin + } // Figure out if the min/max numbers calculation + // would cause a panic in the Int63() function. + if max-min+1 > 0 { + return min + int(r.Int63n(int64(max-min+1))) + } // Loop through the range until we find a number that fits + for { + v := int(r.Uint64()) + if (v >= min) && (v <= max) { + return v + } + } + } // Generate random uint between min and max + func randUintRange(r *rand.Rand, min, max uint) uint { + // If they pass in the same number, just return that number + if min == max { + return min + } // If they pass in a min that is bigger than max, swap them + if min > max { + ogmin := min + min = max + max = ogmin + } // Figure out if the min/max numbers calculation + // would cause a panic in the Int63() function. + if int(max)-int(min)+1 > 0 { + return uint(r.Intn(int(max)-int(min)+1) + int(min)) + } // Loop through the range until we find a number that fits + for { + v := uint(r.Uint64()) + if (v >= min) && (v <= max) { + return v + } + } + } func toFixed(num float64, precision int) float64 { + output := math.Pow(10, float64(precision)) + return float64(math.Floor(num*output)) / output + } func equalSliceString(a, b []string) bool { + sizeA, sizeB := len(a), len(b) + if sizeA != sizeB { + return false + } for i, va := range a { + vb := b[i] if va != vb { + return false + } + } + return true + } func equalSliceInt(a, b []int) bool { + sizeA, sizeB := len(a), len(b) + if sizeA != sizeB { + return false + } for i, va := range a { + vb := b[i] if va != vb { + return false + } + } + return true + } func equalSliceInterface(a, b []any) bool { + sizeA, sizeB := len(a), len(b) + if sizeA != sizeB { + return false + } for i, va := range a { + if !reflect.DeepEqual(va, b[i]) { + return false + } + } + return true + } func stringInSlice(a string, list []string) bool { + for _, b := range list { + if b == a { + return true + } + } + return false + } func anyToString(a any) string { + if a == nil { + return "" + } // If it's a slice of bytes or struct, unmarshal it into an interface + if bytes, ok := a.([]byte); ok { + return string(bytes) + } // If it's a struct, map, or slice, convert to JSON + switch reflect.TypeOf(a).Kind() { + case reflect.Struct, reflect.Map, reflect.Slice: + b, err := json.Marshal(a) + if err == nil { + return string(b) + } + } return fmt.Sprintf("%v", a) + } // Title returns a copy of the string s with all Unicode letters that begin words + // mapped to their Unicode title case + func title(s string) string { + // isSeparator reports whether the rune could mark a word boundary + isSeparator := func(r rune) bool { + // ASCII alphanumerics and underscore are not separators + if r <= 0x7F { + switch { + case '0' <= r && r <= '9': + return false + case 'a' <= r && r <= 'z': + return false + case 'A' <= r && r <= 'Z': + return false + case r == '_': + return false + } + return true + } // Letters and digits are not separators + if unicode.IsLetter(r) || unicode.IsDigit(r) { + return false + } // Otherwise, all we can do for now is treat spaces as separators. + return unicode.IsSpace(r) + } prev := ' ' + return strings.Map( + func(r rune) rune { + if isSeparator(prev) { + prev = r + return unicode.ToTitle(r) + } + prev = r + return r + }, + s) + } func funcLookupSplit(str string) []string { + out := []string{} + for str != "" { + if strings.HasPrefix(str, "[") { + startIndex := strings.Index(str, "[") + endIndex := strings.Index(str, "]") + val := str[(startIndex) : endIndex+1] + out = append(out, strings.TrimSpace(val)) + str = strings.Replace(str, val, "", 1) // Trim off comma if it has it + if strings.HasPrefix(str, ",") { + str = strings.Replace(str, ",", "", 1) + } + } else { + strSplit := strings.SplitN(str, ",", 2) + strSplitLen := len(strSplit) + if strSplitLen >= 1 { + out = append(out, strings.TrimSpace(strSplit[0])) + } + if strSplitLen >= 2 { + str = strSplit[1] + } else { + str = "" + } + } + } return out + } // Used for parsing the tag in a struct + func parseNameAndParamsFromTag(tag string) (string, string) { + // Trim the curly on the beginning and end + tag = strings.TrimLeft(tag, "{") + tag = strings.TrimRight(tag, "}") + // Check if has params separated by : + fNameSplit := strings.SplitN(tag, ":", 2) + fName := "" + fParams := "" + if len(fNameSplit) >= 1 { + fName = fNameSplit[0] + } + if len(fNameSplit) >= 2 { + fParams = fNameSplit[1] + } + return fName, fParams + } // Used for parsing map params + func parseMapParams(info *Info, fParams string) *MapParams { + // Get parameters, make sure params and the split both have values + mapParams := NewMapParams() + paramsLen := len(info.Params) // If just one param and its a string simply just pass it + if paramsLen == 1 && info.Params[0].Type == "string" { + mapParams.Add(info.Params[0].Field, fParams) + } else if paramsLen > 0 && fParams != "" { + splitVals := funcLookupSplit(fParams) + mapParams = addSplitValsToMapParams(splitVals, info, mapParams) + } + if mapParams.Size() > 0 { + return mapParams + } else { + return nil + } + } // Used for splitting the values + func addSplitValsToMapParams(splitVals []string, info *Info, mapParams *MapParams) *MapParams { + for ii := 0; ii < len(splitVals); ii++ { + if len(info.Params)-1 >= ii { + if strings.HasPrefix(splitVals[ii], "[") { + lookupSplits := funcLookupSplit(strings.TrimRight(strings.TrimLeft(splitVals[ii], "["), "]")) + for _, v := range lookupSplits { + mapParams.Add(info.Params[ii].Field, v) + } + } else { + mapParams.Add(info.Params[ii].Field, splitVals[ii]) + } + } + } + return mapParams + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/hipster.go b/vendor/github.com/brianvoe/gofakeit/v6/hipster.go index 0369f17..d9b8932 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/hipster.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/hipster.go @@ -6,126 +6,212 @@ import ( ) // HipsterWord will return a single hipster word + func HipsterWord() string { return hipsterWord(globalFaker.Rand) } // HipsterWord will return a single hipster word + func (f *Faker) HipsterWord() string { return hipsterWord(f.Rand) } func hipsterWord(r *rand.Rand) string { return getRandValue(r, []string{"hipster", "word"}) } // HipsterSentence will generate a random sentence + func HipsterSentence(wordCount int) string { return hipsterSentence(globalFaker.Rand, wordCount) } // HipsterSentence will generate a random sentence + func (f *Faker) HipsterSentence(wordCount int) string { return hipsterSentence(f.Rand, wordCount) } func hipsterSentence(r *rand.Rand, wordCount int) string { + return sentenceGen(r, wordCount, hipsterWord) + } // HipsterParagraph will generate a random paragraphGenerator + // Set Paragraph Count + // Set Sentence Count + // Set Word Count + // Set Paragraph Separator + func HipsterParagraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string { + return hipsterParagraph(globalFaker.Rand, paragraphCount, sentenceCount, wordCount, separator) + } // HipsterParagraph will generate a random paragraphGenerator + // Set Paragraph Count + // Set Sentence Count + // Set Word Count + // Set Paragraph Separator + func (f *Faker) HipsterParagraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string { + return hipsterParagraph(f.Rand, paragraphCount, sentenceCount, wordCount, separator) + } func hipsterParagraph(r *rand.Rand, paragraphCount int, sentenceCount int, wordCount int, separator string) string { + return paragraphGen(r, paragrapOptions{paragraphCount, sentenceCount, wordCount, separator}, hipsterSentence) + } func addHipsterLookup() { + AddFuncLookup("hipsterword", Info{ - Display: "Hipster Word", - Category: "hipster", + + Display: "Hipster Word", + + Category: "hipster", + Description: "Trendy and unconventional vocabulary used by hipsters to express unique cultural preferences", - Example: "microdosing", - Output: "string", + + Example: "microdosing", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return hipsterWord(r), nil + }, }) AddFuncLookup("hipstersentence", Info{ - Display: "Hipster Sentence", - Category: "hipster", + + Display: "Hipster Sentence", + + Category: "hipster", + Description: "Sentence showcasing the use of trendy and unconventional vocabulary associated with hipster culture", - Example: "Microdosing roof chia echo pickled.", - Output: "string", + + Example: "Microdosing roof chia echo pickled.", + + Output: "string", + Params: []Param{ + {Field: "wordcount", Display: "Word Count", Type: "int", Default: "5", Description: "Number of words in a sentence"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + wordCount, err := info.GetInt(m, "wordcount") + if err != nil { + return nil, err + } + if wordCount <= 0 || wordCount > 50 { + return nil, errors.New("invalid word count, must be greater than 0, less than 50") + } return hipsterSentence(r, wordCount), nil + }, }) AddFuncLookup("hipsterparagraph", Info{ - Display: "Hipster Paragraph", - Category: "hipster", + + Display: "Hipster Paragraph", + + Category: "hipster", + Description: "Paragraph showcasing the use of trendy and unconventional vocabulary associated with hipster culture", + Example: `Microdosing roof chia echo pickled meditation cold-pressed raw denim fingerstache normcore sriracha pork belly. Wolf try-hard pop-up blog tilde hashtag health butcher waistcoat paleo portland vinegar. Microdosing sartorial blue bottle slow-carb freegan five dollar toast you probably haven't heard of them asymmetrical chia farm-to-table narwhal banjo. Gluten-free blog authentic literally synth vinyl meh ethical health fixie banh mi Yuccie. Try-hard drinking squid seitan cray VHS echo chillwave hammock kombucha food truck sustainable. + + Pug bushwick hella tote bag cliche direct trade waistcoat yr waistcoat knausgaard pour-over master. Pitchfork jean shorts franzen flexitarian distillery hella meggings austin knausgaard crucifix wolf heirloom. Crucifix food truck you probably haven't heard of them trust fund fixie gentrify pitchfork stumptown mlkshk umami chambray blue bottle. 3 wolf moon swag +1 biodiesel knausgaard semiotics taxidermy meh artisan hoodie +1 blue bottle. Fashion axe forage mixtape Thundercats pork belly whatever 90's beard selfies chambray cred mlkshk. + + Shabby chic typewriter VHS readymade lo-fi bitters PBR&B gentrify lomo raw denim freegan put a bird on it. Raw denim cliche dreamcatcher pug fixie park trust fund migas fingerstache sriracha +1 mustache. Tilde shoreditch kickstarter franzen dreamcatcher green juice mustache neutra polaroid stumptown organic schlitz. Flexitarian ramps chicharrones kogi lo-fi mustache tilde forage street church-key williamsburg taxidermy. Chia mustache plaid mumblecore squid slow-carb disrupt Thundercats goth shoreditch master direct trade.`, + Output: "string", + Params: []Param{ + {Field: "paragraphcount", Display: "Paragraph Count", Type: "int", Default: "2", Description: "Number of paragraphs"}, + {Field: "sentencecount", Display: "Sentence Count", Type: "int", Default: "2", Description: "Number of sentences in a paragraph"}, + {Field: "wordcount", Display: "Word Count", Type: "int", Default: "5", Description: "Number of words in a sentence"}, + {Field: "paragraphseparator", Display: "Paragraph Separator", Type: "string", Default: "
", Description: "String value to add between paragraphs"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + paragraphCount, err := info.GetInt(m, "paragraphcount") + if err != nil { + return nil, err + } + if paragraphCount <= 0 || paragraphCount > 20 { + return nil, errors.New("invalid paragraph count, must be greater than 0, less than 20") + } sentenceCount, err := info.GetInt(m, "sentencecount") + if err != nil { + return nil, err + } + if sentenceCount <= 0 || sentenceCount > 20 { + return nil, errors.New("invalid sentence count, must be greater than 0, less than 20") + } wordCount, err := info.GetInt(m, "wordcount") + if err != nil { + return nil, err + } + if wordCount <= 0 || wordCount > 50 { + return nil, errors.New("invalid word count, must be greater than 0, less than 50") + } paragraphSeparator, err := info.GetString(m, "paragraphseparator") + if err != nil { + return nil, err + } return hipsterParagraph(r, paragraphCount, sentenceCount, wordCount, paragraphSeparator), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/html.go b/vendor/github.com/brianvoe/gofakeit/v6/html.go index a047617..5e9e6d8 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/html.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/html.go @@ -10,166 +10,276 @@ import ( ) // InputName will return a random input field name + func InputName() string { + return inputName(globalFaker.Rand) + } // InputName will return a random input field name + func (f *Faker) InputName() string { + return inputName(f.Rand) + } func inputName(r *rand.Rand) string { + return getRandValue(r, []string{"html", "input_name"}) + } type SVGOptions struct { Height int - Width int - Type string + + Width int + + Type string + Colors []string } // Generate a random svg generator + func Svg(options *SVGOptions) string { return svg(globalFaker.Rand, options) } // Generate a random svg generator + func (f *Faker) Svg(options *SVGOptions) string { return svg(f.Rand, options) } func svg(r *rand.Rand, options *SVGOptions) string { + // If options is nil, set it to empty struct + if options == nil { + options = &SVGOptions{} + } // If options height and weight is not set, set it to random number between 100 and 500 + if options.Width == 0 { + options.Width = number(r, 100, 500) + } + widthStr := strconv.Itoa(options.Width) + if options.Height == 0 { + options.Height = number(r, 100, 500) + } + heightStr := strconv.Itoa(options.Height) // Check if type is set, if not set to random type + if options.Type == "" { + options.Type = randomString(r, data.GetSubData("html", "svg")) + } // If the colors are not set, set it to a set of nice colors + if len(options.Colors) == 0 { + options.Colors = niceColors(r) + } // Start svg string + svgStr := `` // Add a rect for the background + svgStr += `` // Add a random number of shapes + for i := 0; i < number(r, 10, 20); i++ { + // Add a random shape + switch options.Type { + case "rect": + svgStr += `` + case "circle": + svgStr += `` + case "ellipse": + svgStr += `` + case "line": + svgStr += `` + case "polyline": + svgStr += `` + case "polygon": + svgStr += `` + } + } // End svg string + svgStr += `` return svgStr + } func addHtmlLookup() { + AddFuncLookup("inputname", Info{ - Display: "Input Name", - Category: "html", + + Display: "Input Name", + + Category: "html", + Description: "Attribute used to define the name of an input element in web forms", - Example: "first_name", - Output: "string", + + Example: "first_name", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return inputName(r), nil + }, }) AddFuncLookup("svg", Info{ - Display: "Image SVG", - Category: "html", + + Display: "Image SVG", + + Category: "html", + Description: "Scalable Vector Graphics used to display vector images in web content", + Example: ` + + + `, - Output: "string", + + Output: "string", + ContentType: "image/svg+xml", + Params: []Param{ + {Field: "width", Display: "Width", Type: "int", Default: "500", Description: "Width in px"}, + {Field: "height", Display: "Height", Type: "int", Default: "500", Description: "Height in px"}, + {Field: "type", Display: "Type", Type: "string", Optional: true, Options: data.GetSubData("html", "svg"), Description: "Sub child element type"}, + {Field: "colors", Display: "Colors", Type: "[]string", Optional: true, Description: "Hex or RGB array of colors to use"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + // Setup new options + options := SVGOptions{} + var err error options.Width, err = info.GetInt(m, "width") + if err != nil { + return nil, err + } + if options.Width < 10 || options.Width >= 1000 { + return nil, errors.New("invalid image width, must be greater than 10, less than 1000") + } options.Height, err = info.GetInt(m, "height") + if err != nil { + return nil, err + } + if options.Height < 10 || options.Height >= 1000 { + return nil, errors.New("invalid image height, must be greater than 10, less than 1000") + } options.Type, err = info.GetString(m, "type") + svgData := data.GetSubData("html", "svg") + if err != nil { + return nil, err + } // If type is empty, set with random type + if options.Type == "" { + options.Type = randomString(r, svgData) + } // If not in date html svg type array, return error + if !stringInSlice(options.Type, svgData) { + return nil, errors.New("invalid svg type, must be one of " + strings.Join(svgData, ",")) + } // Get colors + options.Colors, err = info.GetStringArray(m, "colors") + if err != nil { + return nil, err + } // If colors is empty, set with random colors + if len(options.Colors) == 0 { + options.Colors = niceColors(r) + } return svg(r, &options), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/image.go b/vendor/github.com/brianvoe/gofakeit/v6/image.go index e7c40dd..db40a06 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/image.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/image.go @@ -12,154 +12,253 @@ import ( ) // ImageURL will generate a random Image Based Upon Height And Width. https://picsum.photos/ + func ImageURL(width int, height int) string { return imageURL(globalFaker.Rand, width, height) } // ImageURL will generate a random Image Based Upon Height And Width. https://picsum.photos/ + func (f *Faker) ImageURL(width int, height int) string { return imageURL(f.Rand, width, height) } func imageURL(r *rand.Rand, width int, height int) string { + return "https://picsum.photos/" + strconv.Itoa(width) + "/" + strconv.Itoa(height) + } // Image generates a random rgba image + func Image(width int, height int) *img.RGBA { return image(globalFaker.Rand, width, height) } // Image generates a random rgba image + func (f *Faker) Image(width int, height int) *img.RGBA { return image(f.Rand, width, height) } func image(r *rand.Rand, width int, height int) *img.RGBA { + upLeft := img.Point{0, 0} + lowRight := img.Point{width, height} img := img.NewRGBA(img.Rectangle{upLeft, lowRight}) // Set color for each pixel + for x := 0; x < width; x++ { + for y := 0; y < height; y++ { + img.Set(x, y, imgCol.RGBA{uint8(number(r, 0, 255)), uint8(number(r, 0, 255)), uint8(number(r, 0, 255)), 0xff}) + } + } return img + } // ImageJpeg generates a random rgba jpeg image + func ImageJpeg(width int, height int) []byte { return imageJpeg(globalFaker.Rand, width, height) } // ImageJpeg generates a random rgba jpeg image + func (f *Faker) ImageJpeg(width int, height int) []byte { return imageJpeg(f.Rand, width, height) } func imageJpeg(r *rand.Rand, width int, height int) []byte { + buf := new(bytes.Buffer) + jpeg.Encode(buf, image(r, width, height), nil) + return buf.Bytes() + } // ImagePng generates a random rgba png image + func ImagePng(width int, height int) []byte { return imagePng(globalFaker.Rand, width, height) } // ImagePng generates a random rgba png image + func (f *Faker) ImagePng(width int, height int) []byte { return imagePng(f.Rand, width, height) } func imagePng(r *rand.Rand, width int, height int) []byte { + buf := new(bytes.Buffer) + png.Encode(buf, image(r, width, height)) + return buf.Bytes() + } func addImageLookup() { + AddFuncLookup("imageurl", Info{ - Display: "Image URL", - Category: "image", + + Display: "Image URL", + + Category: "image", + Description: "Web address pointing to an image file that can be accessed and displayed online", - Example: "https://picsum.photos/500/500", - Output: "string", + + Example: "https://picsum.photos/500/500", + + Output: "string", + Params: []Param{ + {Field: "width", Display: "Width", Type: "int", Default: "500", Description: "Image width in px"}, + {Field: "height", Display: "Height", Type: "int", Default: "500", Description: "Image height in px"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + width, err := info.GetInt(m, "width") + if err != nil { + return nil, err + } + if width < 10 || width >= 1000 { + return nil, errors.New("invalid image width, must be greater than 10, less than 1000") + } height, err := info.GetInt(m, "height") + if err != nil { + return nil, err + } + if height < 10 || height >= 1000 { + return nil, errors.New("invalid image height, must be greater than 10, less than 1000") + } return imageURL(r, width, height), nil + }, }) AddFuncLookup("imagejpeg", Info{ - Display: "Image JPEG", - Category: "image", + + Display: "Image JPEG", + + Category: "image", + Description: "Image file format known for its efficient compression and compatibility", - Example: "file.jpeg - bytes", - Output: "[]byte", + + Example: "file.jpeg - bytes", + + Output: "[]byte", + ContentType: "image/jpeg", + Params: []Param{ + {Field: "width", Display: "Width", Type: "int", Default: "500", Description: "Image width in px"}, + {Field: "height", Display: "Height", Type: "int", Default: "500", Description: "Image height in px"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + width, err := info.GetInt(m, "width") + if err != nil { + return nil, err + } + if width < 10 || width >= 1000 { + return nil, errors.New("invalid image width, must be greater than 10, less than 1000") + } height, err := info.GetInt(m, "height") + if err != nil { + return nil, err + } + if height < 10 || height >= 1000 { + return nil, errors.New("invalid image height, must be greater than 10, less than 1000") + } return imageJpeg(r, width, height), nil + }, }) AddFuncLookup("imagepng", Info{ - Display: "Image PNG", - Category: "image", + + Display: "Image PNG", + + Category: "image", + Description: "Image file format known for its lossless compression and support for transparency", - Example: "file.png - bytes", - Output: "[]byte", + + Example: "file.png - bytes", + + Output: "[]byte", + ContentType: "image/png", + Params: []Param{ + {Field: "width", Display: "Width", Type: "int", Default: "500", Description: "Image width in px"}, + {Field: "height", Display: "Height", Type: "int", Default: "500", Description: "Image height in px"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + width, err := info.GetInt(m, "width") + if err != nil { + return nil, err + } + if width < 10 || width >= 1000 { + return nil, errors.New("invalid image width, must be greater than 10, less than 1000") + } height, err := info.GetInt(m, "height") + if err != nil { + return nil, err + } + if height < 10 || height >= 1000 { + return nil, errors.New("invalid image height, must be greater than 10, less than 1000") + } return imagePng(r, width, height), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/internet.go b/vendor/github.com/brianvoe/gofakeit/v6/internet.go index a0fcd9b..dbfde43 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/internet.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/internet.go @@ -10,432 +10,679 @@ import ( ) // DomainName will generate a random url domain name + func DomainName() string { return domainName(globalFaker.Rand) } // DomainName will generate a random url domain name + func (f *Faker) DomainName() string { return domainName(f.Rand) } func domainName(r *rand.Rand) string { + name := strings.Replace(strings.ToLower(jobDescriptor(r)+bs(r)), " ", "", -1) return fmt.Sprintf("%s.%s", name, domainSuffix(r)) + } // DomainSuffix will generate a random domain suffix + func DomainSuffix() string { return domainSuffix(globalFaker.Rand) } // DomainSuffix will generate a random domain suffix + func (f *Faker) DomainSuffix() string { return domainSuffix(f.Rand) } func domainSuffix(r *rand.Rand) string { + return getRandValue(r, []string{"internet", "domain_suffix"}) + } // URL will generate a random url string + func URL() string { return url(globalFaker.Rand) } // URL will generate a random url string + func (f *Faker) URL() string { return url(f.Rand) } func url(r *rand.Rand) string { + // Slugs + num := number(r, 1, 4) + slug := make([]string, num) + for i := 0; i < num; i++ { + slug[i] = bs(r) + } scheme := randomString(r, []string{"https", "http"}) + path := strings.ToLower(strings.Join(slug, "/")) url := fmt.Sprintf("%s://www.%s/%s", scheme, domainName(r), path) + url = strings.Replace(url, " ", "", -1) return url + } // HTTPMethod will generate a random http method + func HTTPMethod() string { return httpMethod(globalFaker.Rand) } // HTTPMethod will generate a random http method + func (f *Faker) HTTPMethod() string { return httpMethod(f.Rand) } func httpMethod(r *rand.Rand) string { + return getRandValue(r, []string{"internet", "http_method"}) + } // IPv4Address will generate a random version 4 ip address + func IPv4Address() string { return ipv4Address(globalFaker.Rand) } // IPv4Address will generate a random version 4 ip address + func (f *Faker) IPv4Address() string { return ipv4Address(f.Rand) } func ipv4Address(r *rand.Rand) string { + num := func() int { return r.Intn(256) } return fmt.Sprintf("%d.%d.%d.%d", num(), num(), num(), num()) + } // IPv6Address will generate a random version 6 ip address + func IPv6Address() string { return ipv6Address(globalFaker.Rand) } // IPv6Address will generate a random version 6 ip address + func (f *Faker) IPv6Address() string { return ipv6Address(f.Rand) } func ipv6Address(r *rand.Rand) string { + num := func() int { return r.Intn(65536) } return fmt.Sprintf("%x:%x:%x:%x:%x:%x:%x:%x", num(), num(), num(), num(), num(), num(), num(), num()) + } // MacAddress will generate a random mac address + func MacAddress() string { return macAddress(globalFaker.Rand) } // MacAddress will generate a random mac address + func (f *Faker) MacAddress() string { return macAddress(f.Rand) } func macAddress(r *rand.Rand) string { + num := 255 return fmt.Sprintf("%02x:%02x:%02x:%02x:%02x:%02x", r.Intn(num), r.Intn(num), r.Intn(num), r.Intn(num), r.Intn(num), r.Intn(num)) + } // HTTPStatusCode will generate a random status code + func HTTPStatusCode() int { return httpStatusCode(globalFaker.Rand) } // HTTPStatusCode will generate a random status code + func (f *Faker) HTTPStatusCode() int { return httpStatusCode(f.Rand) } func httpStatusCode(r *rand.Rand) int { + randInt, _ := strconv.Atoi(getRandValue(r, []string{"internet", "http_status_general"})) + return randInt + } // HTTPStatusCodeSimple will generate a random simple status code + func HTTPStatusCodeSimple() int { return httpStatusCodeSimple(globalFaker.Rand) } // HTTPStatusCodeSimple will generate a random simple status code + func (f *Faker) HTTPStatusCodeSimple() int { return httpStatusCodeSimple(f.Rand) } func httpStatusCodeSimple(r *rand.Rand) int { + randInt, _ := strconv.Atoi(getRandValue(r, []string{"internet", "http_status_simple"})) + return randInt + } // LogLevel will generate a random log level + // See data/LogLevels for list of available levels + func LogLevel(logType string) string { return logLevel(globalFaker.Rand, logType) } // LogLevel will generate a random log level + // See data/LogLevels for list of available levels + func (f *Faker) LogLevel(logType string) string { return logLevel(f.Rand, logType) } func logLevel(r *rand.Rand, logType string) string { + if _, ok := data.LogLevels[logType]; ok { + return getRandValue(r, []string{"log_level", logType}) + } return getRandValue(r, []string{"log_level", "general"}) + } // UserAgent will generate a random broswer user agent + func UserAgent() string { return userAgent(globalFaker.Rand) } // UserAgent will generate a random broswer user agent + func (f *Faker) UserAgent() string { return userAgent(f.Rand) } func userAgent(r *rand.Rand) string { + randNum := randIntRange(r, 0, 4) + switch randNum { + case 0: + return chromeUserAgent(r) + case 1: + return firefoxUserAgent(r) + case 2: + return safariUserAgent(r) + case 3: + return operaUserAgent(r) + default: + return chromeUserAgent(r) + } + } // ChromeUserAgent will generate a random chrome browser user agent string + func ChromeUserAgent() string { return chromeUserAgent(globalFaker.Rand) } // ChromeUserAgent will generate a random chrome browser user agent string + func (f *Faker) ChromeUserAgent() string { return chromeUserAgent(f.Rand) } func chromeUserAgent(r *rand.Rand) string { + randNum1 := strconv.Itoa(randIntRange(r, 531, 536)) + strconv.Itoa(randIntRange(r, 0, 2)) + randNum2 := strconv.Itoa(randIntRange(r, 36, 40)) + randNum3 := strconv.Itoa(randIntRange(r, 800, 899)) + return "Mozilla/5.0 " + "(" + randomPlatform(r) + ") AppleWebKit/" + randNum1 + " (KHTML, like Gecko) Chrome/" + randNum2 + ".0." + randNum3 + ".0 Mobile Safari/" + randNum1 + } // FirefoxUserAgent will generate a random firefox broswer user agent string + func FirefoxUserAgent() string { return firefoxUserAgent(globalFaker.Rand) } // FirefoxUserAgent will generate a random firefox broswer user agent string + func (f *Faker) FirefoxUserAgent() string { return firefoxUserAgent(f.Rand) } func firefoxUserAgent(r *rand.Rand) string { + ver := "Gecko/" + date(r).Format("2006-01-02") + " Firefox/" + strconv.Itoa(randIntRange(r, 35, 37)) + ".0" + platforms := []string{ + "(" + windowsPlatformToken(r) + "; " + "en-US" + "; rv:1.9." + strconv.Itoa(randIntRange(r, 0, 3)) + ".20) " + ver, + "(" + linuxPlatformToken(r) + "; rv:" + strconv.Itoa(randIntRange(r, 5, 8)) + ".0) " + ver, + "(" + macPlatformToken(r) + " rv:" + strconv.Itoa(randIntRange(r, 2, 7)) + ".0) " + ver, } return "Mozilla/5.0 " + randomString(r, platforms) + } // SafariUserAgent will generate a random safari browser user agent string + func SafariUserAgent() string { return safariUserAgent(globalFaker.Rand) } // SafariUserAgent will generate a random safari browser user agent string + func (f *Faker) SafariUserAgent() string { return safariUserAgent(f.Rand) } func safariUserAgent(r *rand.Rand) string { + randNum := strconv.Itoa(randIntRange(r, 531, 536)) + "." + strconv.Itoa(randIntRange(r, 1, 51)) + "." + strconv.Itoa(randIntRange(r, 1, 8)) + ver := strconv.Itoa(randIntRange(r, 4, 6)) + "." + strconv.Itoa(randIntRange(r, 0, 2)) mobileDevices := []string{ + "iPhone; CPU iPhone OS", + "iPad; CPU OS", } platforms := []string{ + "(Windows; U; " + windowsPlatformToken(r) + ") AppleWebKit/" + randNum + " (KHTML, like Gecko) Version/" + ver + " Safari/" + randNum, + "(" + macPlatformToken(r) + " rv:" + strconv.Itoa(randIntRange(r, 4, 7)) + ".0; en-US) AppleWebKit/" + randNum + " (KHTML, like Gecko) Version/" + ver + " Safari/" + randNum, + "(" + randomString(r, mobileDevices) + " " + strconv.Itoa(randIntRange(r, 7, 9)) + "_" + strconv.Itoa(randIntRange(r, 0, 3)) + "_" + strconv.Itoa(randIntRange(r, 1, 3)) + " like Mac OS X; " + "en-US" + ") AppleWebKit/" + randNum + " (KHTML, like Gecko) Version/" + strconv.Itoa(randIntRange(r, 3, 5)) + ".0.5 Mobile/8B" + strconv.Itoa(randIntRange(r, 111, 120)) + " Safari/6" + randNum, } return "Mozilla/5.0 " + randomString(r, platforms) + } // OperaUserAgent will generate a random opera browser user agent string + func OperaUserAgent() string { return operaUserAgent(globalFaker.Rand) } // OperaUserAgent will generate a random opera browser user agent string + func (f *Faker) OperaUserAgent() string { return operaUserAgent(f.Rand) } func operaUserAgent(r *rand.Rand) string { + platform := "(" + randomPlatform(r) + "; en-US) Presto/2." + strconv.Itoa(randIntRange(r, 8, 13)) + "." + strconv.Itoa(randIntRange(r, 160, 355)) + " Version/" + strconv.Itoa(randIntRange(r, 10, 13)) + ".00" return "Opera/" + strconv.Itoa(randIntRange(r, 8, 10)) + "." + strconv.Itoa(randIntRange(r, 10, 99)) + " " + platform + } // linuxPlatformToken will generate a random linux platform + func linuxPlatformToken(r *rand.Rand) string { + return "X11; Linux " + getRandValue(r, []string{"computer", "linux_processor"}) + } // macPlatformToken will generate a random mac platform + func macPlatformToken(r *rand.Rand) string { + return "Macintosh; " + getRandValue(r, []string{"computer", "mac_processor"}) + " Mac OS X 10_" + strconv.Itoa(randIntRange(r, 5, 9)) + "_" + strconv.Itoa(randIntRange(r, 0, 10)) + } // windowsPlatformToken will generate a random windows platform + func windowsPlatformToken(r *rand.Rand) string { + return getRandValue(r, []string{"computer", "windows_platform"}) + } // randomPlatform will generate a random platform + func randomPlatform(r *rand.Rand) string { + platforms := []string{ + linuxPlatformToken(r), + macPlatformToken(r), + windowsPlatformToken(r), } return randomString(r, platforms) + } // HTTPVersion will generate a random http version + func HTTPVersion() string { return httpVersion(globalFaker.Rand) } // HTTPVersion will generate a random http version + func (f *Faker) HTTPVersion() string { return httpVersion(f.Rand) } func httpVersion(r *rand.Rand) string { + return getRandValue(r, []string{"internet", "http_version"}) + } func addInternetLookup() { + AddFuncLookup("url", Info{ - Display: "URL", - Category: "internet", + + Display: "URL", + + Category: "internet", + Description: "Web address that specifies the location of a resource on the internet", - Example: "http://www.principalproductize.biz/target", - Output: "string", + + Example: "http://www.principalproductize.biz/target", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return url(r), nil + }, }) AddFuncLookup("domainname", Info{ - Display: "Domain Name", - Category: "internet", + + Display: "Domain Name", + + Category: "internet", + Description: "Human-readable web address used to identify websites on the internet", - Example: "centraltarget.biz", - Output: "string", + + Example: "centraltarget.biz", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return domainName(r), nil + }, }) AddFuncLookup("domainsuffix", Info{ - Display: "Domain Suffix", - Category: "internet", + + Display: "Domain Suffix", + + Category: "internet", + Description: "The part of a domain name that comes after the last dot, indicating its type or purpose", - Example: "org", - Output: "string", + + Example: "org", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return domainSuffix(r), nil + }, }) AddFuncLookup("ipv4address", Info{ - Display: "IPv4 Address", - Category: "internet", + + Display: "IPv4 Address", + + Category: "internet", + Description: "Numerical label assigned to devices on a network for identification and communication", - Example: "222.83.191.222", - Output: "string", + + Example: "222.83.191.222", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return ipv4Address(r), nil + }, }) AddFuncLookup("ipv6address", Info{ - Display: "IPv6 Address", - Category: "internet", + + Display: "IPv6 Address", + + Category: "internet", + Description: "Numerical label assigned to devices on a network, providing a larger address space than IPv4 for internet communication", - Example: "2001:cafe:8898:ee17:bc35:9064:5866:d019", - Output: "string", + + Example: "2001:cafe:8898:ee17:bc35:9064:5866:d019", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return ipv6Address(r), nil + }, }) AddFuncLookup("httpmethod", Info{ - Display: "HTTP Method", - Category: "internet", + + Display: "HTTP Method", + + Category: "internet", + Description: "Verb used in HTTP requests to specify the desired action to be performed on a resource", - Example: "HEAD", - Output: "string", + + Example: "HEAD", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return httpMethod(r), nil + }, }) AddFuncLookup("loglevel", Info{ - Display: "Log Level", - Category: "internet", + + Display: "Log Level", + + Category: "internet", + Description: "Classification used in logging to indicate the severity or priority of a log entry", - Example: "error", - Output: "string", + + Example: "error", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return logLevel(r, ""), nil + }, }) AddFuncLookup("useragent", Info{ - Display: "User Agent", - Category: "internet", + + Display: "User Agent", + + Category: "internet", + Description: "String sent by a web browser to identify itself when requesting web content", - Example: "Mozilla/5.0 (Windows NT 5.0) AppleWebKit/5362 (KHTML, like Gecko) Chrome/37.0.834.0 Mobile Safari/5362", - Output: "string", + + Example: "Mozilla/5.0 (Windows NT 5.0) AppleWebKit/5362 (KHTML, like Gecko) Chrome/37.0.834.0 Mobile Safari/5362", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return userAgent(r), nil + }, }) AddFuncLookup("chromeuseragent", Info{ - Display: "Chrome User Agent", - Category: "internet", + + Display: "Chrome User Agent", + + Category: "internet", + Description: "The specific identification string sent by the Google Chrome web browser when making requests on the internet", - Example: "Mozilla/5.0 (X11; Linux i686) AppleWebKit/5312 (KHTML, like Gecko) Chrome/39.0.836.0 Mobile Safari/5312", - Output: "string", + + Example: "Mozilla/5.0 (X11; Linux i686) AppleWebKit/5312 (KHTML, like Gecko) Chrome/39.0.836.0 Mobile Safari/5312", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return chromeUserAgent(r), nil + }, }) AddFuncLookup("firefoxuseragent", Info{ - Display: "Firefox User Agent", - Category: "internet", + + Display: "Firefox User Agent", + + Category: "internet", + Description: "The specific identification string sent by the Firefox web browser when making requests on the internet", - Example: "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_8_3 rv:7.0) Gecko/1900-07-01 Firefox/37.0", - Output: "string", + + Example: "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_8_3 rv:7.0) Gecko/1900-07-01 Firefox/37.0", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return firefoxUserAgent(r), nil + }, }) AddFuncLookup("operauseragent", Info{ - Display: "Opera User Agent", - Category: "internet", + + Display: "Opera User Agent", + + Category: "internet", + Description: "The specific identification string sent by the Opera web browser when making requests on the internet", - Example: "Opera/8.39 (Macintosh; U; PPC Mac OS X 10_8_7; en-US) Presto/2.9.335 Version/10.00", - Output: "string", + + Example: "Opera/8.39 (Macintosh; U; PPC Mac OS X 10_8_7; en-US) Presto/2.9.335 Version/10.00", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return operaUserAgent(r), nil + }, }) AddFuncLookup("safariuseragent", Info{ - Display: "Safari User Agent", - Category: "internet", + + Display: "Safari User Agent", + + Category: "internet", + Description: "The specific identification string sent by the Safari web browser when making requests on the internet", - Example: "Mozilla/5.0 (iPad; CPU OS 8_3_2 like Mac OS X; en-US) AppleWebKit/531.15.6 (KHTML, like Gecko) Version/4.0.5 Mobile/8B120 Safari/6531.15.6", - Output: "string", + + Example: "Mozilla/5.0 (iPad; CPU OS 8_3_2 like Mac OS X; en-US) AppleWebKit/531.15.6 (KHTML, like Gecko) Version/4.0.5 Mobile/8B120 Safari/6531.15.6", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return safariUserAgent(r), nil + }, }) AddFuncLookup("httpstatuscode", Info{ - Display: "HTTP Status Code", - Category: "internet", + + Display: "HTTP Status Code", + + Category: "internet", + Description: "Random http status code", - Example: "200", - Output: "int", + + Example: "200", + + Output: "int", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return httpStatusCode(r), nil + }, }) AddFuncLookup("httpstatuscodesimple", Info{ - Display: "HTTP Status Code Simple", - Category: "internet", + + Display: "HTTP Status Code Simple", + + Category: "internet", + Description: "Three-digit number returned by a web server to indicate the outcome of an HTTP request", - Example: "404", - Output: "int", + + Example: "404", + + Output: "int", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return httpStatusCodeSimple(r), nil + }, }) AddFuncLookup("httpversion", Info{ - Display: "HTTP Version", - Category: "internet", + + Display: "HTTP Version", + + Category: "internet", + Description: "Number indicating the version of the HTTP protocol used for communication between a client and a server", - Example: "HTTP/1.1", - Output: "string", + + Example: "HTTP/1.1", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return httpVersion(r), nil + }, }) AddFuncLookup("macaddress", Info{ - Display: "MAC Address", - Category: "internet", + + Display: "MAC Address", + + Category: "internet", + Description: "Unique identifier assigned to network interfaces, often used in Ethernet networks", - Example: "cb:ce:06:94:22:e9", - Output: "string", + + Example: "cb:ce:06:94:22:e9", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return macAddress(r), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/json.go b/vendor/github.com/brianvoe/gofakeit/v6/json.go index 8edf5b4..2036ca0 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/json.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/json.go @@ -11,110 +11,175 @@ import ( ) // JSONOptions defines values needed for json generation + type JSONOptions struct { - Type string `json:"type" xml:"type" fake:"{randomstring:[array,object]}"` // array or object - RowCount int `json:"row_count" xml:"row_count" fake:"{number:1,10}"` - Indent bool `json:"indent" xml:"indent"` - Fields []Field `json:"fields" xml:"fields" fake:"{fields}"` + Type string `json:"type" xml:"type" fake:"{randomstring:[array,object]}"` // array or object + + RowCount int `json:"row_count" xml:"row_count" fake:"{number:1,10}"` + + Indent bool `json:"indent" xml:"indent"` + + Fields []Field `json:"fields" xml:"fields" fake:"{fields}"` } type jsonKeyVal struct { - Key string + Key string + Value any } type jsonOrderedKeyVal []*jsonKeyVal func (okv jsonOrderedKeyVal) MarshalJSON() ([]byte, error) { + var buf bytes.Buffer buf.WriteString("{") + for i, kv := range okv { + // Add comma to all except last one + if i != 0 { + buf.WriteString(",") + } // Marshal key and write + key, err := json.Marshal(kv.Key) + if err != nil { + return nil, err + } + buf.Write(key) // Write colon separator + buf.WriteString(":") // Marshal value and write + val, err := json.Marshal(kv.Value) + if err != nil { + return nil, err + } + buf.Write(val) + } + buf.WriteString("}") return buf.Bytes(), nil + } // JSON generates an object or an array of objects in json format. + // A nil JSONOptions returns a randomly structured JSON. + func JSON(jo *JSONOptions) ([]byte, error) { return jsonFunc(globalFaker, jo) } // JSON generates an object or an array of objects in json format. + // A nil JSONOptions returns a randomly structured JSON. + func (f *Faker) JSON(jo *JSONOptions) ([]byte, error) { return jsonFunc(f, jo) } // JSON generates an object or an array of objects in json format + func jsonFunc(f *Faker, jo *JSONOptions) ([]byte, error) { + if jo == nil { + // We didn't get a JSONOptions, so create a new random one + err := f.Struct(&jo) + if err != nil { + return nil, err + } + } // Check to make sure they passed in a type + if jo.Type != "array" && jo.Type != "object" { + return nil, errors.New("invalid type, must be array or object") + } if jo.Fields == nil || len(jo.Fields) <= 0 { + return nil, errors.New("must pass fields in order to build json object(s)") + } if jo.Type == "object" { + v := make(jsonOrderedKeyVal, len(jo.Fields)) // Loop through fields and add to them to map[string]any + for i, field := range jo.Fields { + if field.Function == "autoincrement" { + // Object only has one + v[i] = &jsonKeyVal{Key: field.Name, Value: 1} + continue + } // Get function info + funcInfo := GetFuncLookup(field.Function) + if funcInfo == nil { + return nil, errors.New("invalid function, " + field.Function + " does not exist") + } // Call function value + value, err := funcInfo.Generate(f.Rand, &field.Params, funcInfo) + if err != nil { + return nil, err + } if _, ok := value.([]byte); ok { + // If it's a slice, unmarshal it into an interface + var val any + err := json.Unmarshal(value.([]byte), &val) + if err != nil { + return nil, err + } + value = val + } v[i] = &jsonKeyVal{Key: field.Name, Value: value} @@ -122,214 +187,363 @@ func jsonFunc(f *Faker, jo *JSONOptions) ([]byte, error) { } // Marshal into bytes + if jo.Indent { + j, _ := json.MarshalIndent(v, "", " ") + return j, nil + } j, _ := json.Marshal(v) + return j, nil + } if jo.Type == "array" { + // Make sure you set a row count + if jo.RowCount <= 0 { + return nil, errors.New("must have row count") + } v := make([]jsonOrderedKeyVal, jo.RowCount) for i := 0; i < int(jo.RowCount); i++ { + vr := make(jsonOrderedKeyVal, len(jo.Fields)) // Loop through fields and add to them to map[string]any + for ii, field := range jo.Fields { + if field.Function == "autoincrement" { + vr[ii] = &jsonKeyVal{Key: field.Name, Value: i + 1} // +1 because index starts with 0 + continue + } // Get function info + funcInfo := GetFuncLookup(field.Function) + if funcInfo == nil { + return nil, errors.New("invalid function, " + field.Function + " does not exist") + } // Call function value + value, err := funcInfo.Generate(f.Rand, &field.Params, funcInfo) + if err != nil { + return nil, err + } if _, ok := value.([]byte); ok { + // If it's a slice, unmarshal it into an interface + var val any + err := json.Unmarshal(value.([]byte), &val) + if err != nil { + return nil, err + } + value = val + } vr[ii] = &jsonKeyVal{Key: field.Name, Value: value} + } v[i] = vr + } // Marshal into bytes + if jo.Indent { + j, _ := json.MarshalIndent(v, "", " ") + return j, nil + } j, _ := json.Marshal(v) + return j, nil + } return nil, errors.New("invalid type, must be array or object") + } func addFileJSONLookup() { + AddFuncLookup("json", Info{ - Display: "JSON", - Category: "file", + + Display: "JSON", + + Category: "file", + Description: "Format for structured data interchange used in programming, returns an object or an array of objects", + Example: `[ + { "first_name": "Markus", "last_name": "Moen", "password": "Dc0VYXjkWABx" }, + { "first_name": "Osborne", "last_name": "Hilll", "password": "XPJ9OVNbs5lm" }, + { "first_name": "Mertie", "last_name": "Halvorson", "password": "eyl3bhwfV8wA" } + ]`, - Output: "[]byte", + + Output: "[]byte", + ContentType: "application/json", + Params: []Param{ + {Field: "type", Display: "Type", Type: "string", Default: "object", Options: []string{"object", "array"}, Description: "Type of JSON, object or array"}, + {Field: "rowcount", Display: "Row Count", Type: "int", Default: "100", Description: "Number of rows in JSON array"}, + {Field: "indent", Display: "Indent", Type: "bool", Default: "false", Description: "Whether or not to add indents and newlines"}, + {Field: "fields", Display: "Fields", Type: "[]Field", Description: "Fields containing key name and function to run in json format"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + jo := JSONOptions{} typ, err := info.GetString(m, "type") + if err != nil { + return nil, err + } + jo.Type = typ rowcount, err := info.GetInt(m, "rowcount") + if err != nil { + return nil, err + } + jo.RowCount = rowcount indent, err := info.GetBool(m, "indent") + if err != nil { + return nil, err + } + jo.Indent = indent fieldsStr, err := info.GetStringArray(m, "fields") + if err != nil { + return nil, err + } // Check to make sure fields has length + if len(fieldsStr) > 0 { + jo.Fields = make([]Field, len(fieldsStr)) for i, f := range fieldsStr { + // Unmarshal fields string into fields array + err = json.Unmarshal([]byte(f), &jo.Fields[i]) + if err != nil { + return nil, err + } + } + } f := &Faker{Rand: r} + return jsonFunc(f, &jo) + }, }) + } // encoding/json.RawMessage is a special case of []byte + // it cannot be handled as a reflect.Array/reflect.Slice + // because it needs additional structure in the output + func rJsonRawMessage(f *Faker, t reflect.Type, v reflect.Value, tag string, size int) error { + b, err := f.JSON(nil) + if err != nil { + return err + } v.SetBytes(b) + return nil + } // encoding/json.Number is a special case of string + // that represents a JSON number literal. + // It cannot be handled as a string because it needs to + // represent an integer or a floating-point number. + func rJsonNumber(f *Faker, t reflect.Type, v reflect.Value, tag string, size int) error { + var ret json.Number var numberType string if tag == "" { + numberType = f.RandomString([]string{"int", "float"}) switch numberType { + case "int": + retInt := f.Int16() + ret = json.Number(strconv.Itoa(int(retInt))) + case "float": + retFloat := f.Float64() + ret = json.Number(strconv.FormatFloat(retFloat, 'f', -1, 64)) + } + } else { + fName, fParams := parseNameAndParamsFromTag(tag) + info := GetFuncLookup(fName) + if info == nil { + return fmt.Errorf("invalid function, %s does not exist", fName) + } // Parse map params + mapParams := parseMapParams(info, fParams) valueIface, err := info.Generate(f.Rand, mapParams, info) + if err != nil { + return err + } switch value := valueIface.(type) { + case int: + ret = json.Number(strconv.FormatInt(int64(value), 10)) + case int8: + ret = json.Number(strconv.FormatInt(int64(value), 10)) + case int16: + ret = json.Number(strconv.FormatInt(int64(value), 10)) + case int32: + ret = json.Number(strconv.FormatInt(int64(value), 10)) + case int64: + ret = json.Number(strconv.FormatInt(int64(value), 10)) + case uint: + ret = json.Number(strconv.FormatUint(uint64(value), 10)) + case uint8: + ret = json.Number(strconv.FormatUint(uint64(value), 10)) + case uint16: + ret = json.Number(strconv.FormatUint(uint64(value), 10)) + case uint32: + ret = json.Number(strconv.FormatUint(uint64(value), 10)) + case uint64: + ret = json.Number(strconv.FormatUint(uint64(value), 10)) + case float32: + ret = json.Number(strconv.FormatFloat(float64(value), 'f', -1, 64)) + case float64: + ret = json.Number(strconv.FormatFloat(float64(value), 'f', -1, 64)) + default: + return fmt.Errorf("invalid type, %s is not a valid type for json.Number", reflect.TypeOf(value)) + } + } + v.Set(reflect.ValueOf(ret)) + return nil + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/lookup.go b/vendor/github.com/brianvoe/gofakeit/v6/lookup.go index 9bb9e9d..fb07630 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/lookup.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/lookup.go @@ -11,501 +11,838 @@ import ( ) // FuncLookups is the primary map array with mapping to all available data + var FuncLookups map[string]Info + var lockFuncLookups sync.Mutex // MapParams is the values to pass into a lookup generate + type MapParams map[string]MapParamsValue type MapParamsValue []string // Info structures fields to better break down what each one generates + type Info struct { - Display string `json:"display"` - Category string `json:"category"` - Description string `json:"description"` - Example string `json:"example"` - Output string `json:"output"` - ContentType string `json:"content_type"` - Params []Param `json:"params"` - Any any `json:"any"` - Generate func(r *rand.Rand, m *MapParams, info *Info) (any, error) `json:"-"` + Display string `json:"display"` + + Category string `json:"category"` + + Description string `json:"description"` + + Example string `json:"example"` + + Output string `json:"output"` + + ContentType string `json:"content_type"` + + Params []Param `json:"params"` + + Any any `json:"any"` + + Generate func(r *rand.Rand, m *MapParams, info *Info) (any, error) `json:"-"` } // Param is a breakdown of param requirements and type definition + type Param struct { - Field string `json:"field"` - Display string `json:"display"` - Type string `json:"type"` - Optional bool `json:"optional"` - Default string `json:"default"` - Options []string `json:"options"` - Description string `json:"description"` + Field string `json:"field"` + + Display string `json:"display"` + + Type string `json:"type"` + + Optional bool `json:"optional"` + + Default string `json:"default"` + + Options []string `json:"options"` + + Description string `json:"description"` } // Field is used for defining what name and function you to generate for file outuputs + type Field struct { - Name string `json:"name"` - Function string `json:"function"` - Params MapParams `json:"params"` + Name string `json:"name"` + + Function string `json:"function"` + + Params MapParams `json:"params"` } func init() { initLookup() } // init will add all the functions to MapLookups + func initLookup() { + addAddressLookup() + addAnimalLookup() + addAppLookup() + addAuthLookup() + addBeerLookup() + addBookLookup() + addCarLookup() + addCelebrityLookup() + addColorLookup() + addCompanyLookup() + addDatabaseSQLLookup() + addDateTimeLookup() + addEmojiLookup() + addErrorLookup() + addFileCSVLookup() + addFileJSONLookup() + addFileLookup() + addFileXMLLookup() + addFinanceLookup() + addFoodLookup() + addGameLookup() + addGenerateLookup() + addHackerLookup() + addHipsterLookup() + addHtmlLookup() + addImageLookup() + addInternetLookup() + addLanguagesLookup() + addLoremLookup() + addMinecraftLookup() + addMiscLookup() + addMovieLookup() + addNumberLookup() + addPaymentLookup() + addPersonLookup() + addProductLookup() + addSchoolLookup() + addStringLookup() + addTemplateLookup() + addWeightedLookup() + addWordAdjectiveLookup() + addWordAdverbLookup() + addWordConnectiveLookup() + addWordGeneralLookup() + addWordGrammerLookup() + addWordNounLookup() + addWordPhraseLookup() + addWordPrepositionLookup() + addWordPronounLookup() + addWordSentenceLookup() + addWordVerbLookup() + addWordCommentLookup() + addWordMiscLookup() + } // internalFuncLookups is the internal map array with mapping to all available data + var internalFuncLookups map[string]Info = map[string]Info{ + "fields": { + Description: "Example fields for generating csv, json, xml, etc", - Output: "gofakeit.Field", + + Output: "gofakeit.Field", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + function, _ := GetRandomSimpleFunc(r) + return Field{ - Name: function, + + Name: function, + Function: function, }, nil + }, }, } // NewMapParams will create a new MapParams + func NewMapParams() *MapParams { + return &MapParams{} + } // Add will take in a field and value and add it to the map params type + func (m *MapParams) Add(field string, value string) { + _, ok := (*m)[field] + if !ok { + (*m)[field] = []string{value} + return + } (*m)[field] = append((*m)[field], value) + } // Get will return the array of string from the provided field + func (m *MapParams) Get(field string) []string { + return (*m)[field] + } // Size will return the total size of the underlying map + func (m *MapParams) Size() int { + size := 0 + for range *m { + size++ + } + return size + } // UnmarshalJSON will unmarshal the json into the []string + func (m *MapParamsValue) UnmarshalJSON(data []byte) error { + // check if the data is an array + // if so, marshal it into m + if data[0] == '[' { + var values []any + err := json.Unmarshal(data, &values) + if err != nil { + return err + } // convert the values to array of strings + for _, value := range values { + typeOf := reflect.TypeOf(value).Kind().String() if typeOf == "map" { + v, err := json.Marshal(value) + if err != nil { + return err + } + *m = append(*m, string(v)) + } else { + *m = append(*m, fmt.Sprintf("%v", value)) + } + } + return nil + } // if not, then convert into a string and add it to m + var s any + if err := json.Unmarshal(data, &s); err != nil { + return err + } *m = append(*m, fmt.Sprintf("%v", s)) + return nil + } func GetRandomSimpleFunc(r *rand.Rand) (string, Info) { + // Loop through all the functions and add them to a slice + var keys []string + for k, info := range FuncLookups { + // Only grab simple functions + if info.Params == nil { + keys = append(keys, k) + } + } // Randomly grab a function from the slice + randomKey := randomString(r, keys) // Return the function name and info + return randomKey, FuncLookups[randomKey] + } // AddFuncLookup takes a field and adds it to map + func AddFuncLookup(functionName string, info Info) { + if FuncLookups == nil { + FuncLookups = make(map[string]Info) + } // Check content type + if info.ContentType == "" { + info.ContentType = "text/plain" + } lockFuncLookups.Lock() + FuncLookups[functionName] = info + lockFuncLookups.Unlock() + } // GetFuncLookup will lookup + func GetFuncLookup(functionName string) *Info { + var info Info + var ok bool // Check internal functions first + info, ok = internalFuncLookups[functionName] + if ok { + return &info + } info, ok = FuncLookups[functionName] + if ok { + return &info + } return nil + } // RemoveFuncLookup will remove a function from lookup + func RemoveFuncLookup(functionName string) { + _, ok := FuncLookups[functionName] + if !ok { + return + } lockFuncLookups.Lock() + delete(FuncLookups, functionName) + lockFuncLookups.Unlock() + } // GetAny will retrieve Any field from Info + func (i *Info) GetAny(m *MapParams, field string) (any, error) { + _, value, err := i.GetField(m, field) + if err != nil { + return nil, err + } var anyValue any // Try to convert to int + valueInt, err := strconv.ParseInt(value[0], 10, 64) + if err == nil { + return int(valueInt), nil + } // Try to convert to float + valueFloat, err := strconv.ParseFloat(value[0], 64) + if err == nil { + return valueFloat, nil + } // Try to convert to boolean + valueBool, err := strconv.ParseBool(value[0]) + if err == nil { + return valueBool, nil + } err = json.Unmarshal([]byte(value[0]), &anyValue) + if err == nil { + return valueBool, nil + } return value[0], nil + } // GetMap will retrieve map[string]any field from data + func (i *Info) GetMap(m *MapParams, field string) (map[string]any, error) { + _, value, err := i.GetField(m, field) + if err != nil { + return nil, err + } var mapValue map[string]any + err = json.Unmarshal([]byte(value[0]), &mapValue) + if err != nil { + return nil, fmt.Errorf("%s field could not parse to map[string]any", field) + } return mapValue, nil + } // GetField will retrieve field from data + func (i *Info) GetField(m *MapParams, field string) (*Param, []string, error) { + // Get param + var p *Param + for _, param := range i.Params { + if param.Field == field { + p = ¶m + break + } + } + if p == nil { + return nil, nil, fmt.Errorf("could not find param field %s", field) + } // Get value from map + if m != nil { + value, ok := (*m)[field] + if !ok { + // If default isnt empty use default + if p.Default != "" { + return p, []string{p.Default}, nil + } return nil, nil, fmt.Errorf("could not find field: %s", field) + } return p, value, nil + } else if m == nil && p.Default != "" { + // If p.Type is []uint, then we need to convert it to []string + if strings.HasPrefix(p.Default, "[") { + // Remove [] from type + defaultClean := p.Default[1 : len(p.Default)-1] // Split on comma + defaultSplit := strings.Split(defaultClean, ",") return p, defaultSplit, nil + } // If default isnt empty use default + return p, []string{p.Default}, nil + } return nil, nil, fmt.Errorf("could not find field: %s", field) + } // GetBool will retrieve boolean field from data + func (i *Info) GetBool(m *MapParams, field string) (bool, error) { + p, value, err := i.GetField(m, field) + if err != nil { + return false, err + } // Try to convert to boolean + valueBool, err := strconv.ParseBool(value[0]) + if err != nil { + return false, fmt.Errorf("%s field could not parse to bool value", p.Field) + } return valueBool, nil + } // GetInt will retrieve int field from data + func (i *Info) GetInt(m *MapParams, field string) (int, error) { + p, value, err := i.GetField(m, field) + if err != nil { + return 0, err + } // Try to convert to int + valueInt, err := strconv.ParseInt(value[0], 10, 64) + if err != nil { + return 0, fmt.Errorf("%s field could not parse to int value", p.Field) + } return int(valueInt), nil + } // GetUint will retrieve uint field from data + func (i *Info) GetUint(m *MapParams, field string) (uint, error) { + p, value, err := i.GetField(m, field) + if err != nil { + return 0, err + } // Try to convert to int + valueUint, err := strconv.ParseUint(value[0], 10, 64) + if err != nil { + return 0, fmt.Errorf("%s field could not parse to int value", p.Field) + } return uint(valueUint), nil + } // GetFloat32 will retrieve int field from data + func (i *Info) GetFloat32(m *MapParams, field string) (float32, error) { + p, value, err := i.GetField(m, field) + if err != nil { + return 0, err + } // Try to convert to float + valueFloat, err := strconv.ParseFloat(value[0], 32) + if err != nil { + return 0, fmt.Errorf("%s field could not parse to float value", p.Field) + } return float32(valueFloat), nil + } // GetFloat64 will retrieve int field from data + func (i *Info) GetFloat64(m *MapParams, field string) (float64, error) { + p, value, err := i.GetField(m, field) + if err != nil { + return 0, err + } // Try to convert to float + valueFloat, err := strconv.ParseFloat(value[0], 64) + if err != nil { + return 0, fmt.Errorf("%s field could not parse to float value", p.Field) + } return valueFloat, nil + } // GetString will retrieve string field from data + func (i *Info) GetString(m *MapParams, field string) (string, error) { + _, value, err := i.GetField(m, field) + if err != nil { + return "", err + } return value[0], nil + } // GetStringArray will retrieve []string field from data + func (i *Info) GetStringArray(m *MapParams, field string) ([]string, error) { + _, values, err := i.GetField(m, field) + if err != nil { + return nil, err + } return values, nil + } // GetIntArray will retrieve []int field from data + func (i *Info) GetIntArray(m *MapParams, field string) ([]int, error) { + _, value, err := i.GetField(m, field) + if err != nil { + return nil, err + } var ints []int + for i := 0; i < len(value); i++ { + valueInt, err := strconv.ParseInt(value[i], 10, 64) + if err != nil { + return nil, fmt.Errorf("%s value could not parse to int", value[i]) + } + ints = append(ints, int(valueInt)) + } return ints, nil + } // GetUintArray will retrieve []uint field from data + func (i *Info) GetUintArray(m *MapParams, field string) ([]uint, error) { + _, value, err := i.GetField(m, field) + if err != nil { + return nil, err + } var uints []uint + for i := 0; i < len(value); i++ { + valueUint, err := strconv.ParseUint(value[i], 10, 64) + if err != nil { + return nil, fmt.Errorf("%s value could not parse to uint", value[i]) + } + uints = append(uints, uint(valueUint)) + } return uints, nil + } // GetFloat32Array will retrieve []float field from data + func (i *Info) GetFloat32Array(m *MapParams, field string) ([]float32, error) { + _, value, err := i.GetField(m, field) + if err != nil { + return nil, err + } var floats []float32 + for i := 0; i < len(value); i++ { + valueFloat, err := strconv.ParseFloat(value[i], 32) + if err != nil { + return nil, fmt.Errorf("%s value could not parse to float", value[i]) + } + floats = append(floats, float32(valueFloat)) + } return floats, nil + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/lorem.go b/vendor/github.com/brianvoe/gofakeit/v6/lorem.go index bf11bce..0293c52 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/lorem.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/lorem.go @@ -6,122 +6,204 @@ import ( ) // LoremIpsumWord will generate a random word + func LoremIpsumWord() string { return loremIpsumWord(globalFaker.Rand) } // LoremIpsumWord will generate a random word + func (f *Faker) LoremIpsumWord() string { return loremIpsumWord(f.Rand) } func loremIpsumWord(r *rand.Rand) string { return getRandValue(r, []string{"lorem", "word"}) } // LoremIpsumSentence will generate a random sentence + func LoremIpsumSentence(wordCount int) string { + return loremIpsumSentence(globalFaker.Rand, wordCount) + } // LoremIpsumSentence will generate a random sentence + func (f *Faker) LoremIpsumSentence(wordCount int) string { + return loremIpsumSentence(f.Rand, wordCount) + } func loremIpsumSentence(r *rand.Rand, wordCount int) string { + return sentenceGen(r, wordCount, loremIpsumWord) + } // LoremIpsumParagraph will generate a random paragraphGenerator + func LoremIpsumParagraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string { + return loremIpsumParagraph(globalFaker.Rand, paragraphCount, sentenceCount, wordCount, separator) + } // LoremIpsumParagraph will generate a random paragraphGenerator + func (f *Faker) LoremIpsumParagraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string { + return loremIpsumParagraph(f.Rand, paragraphCount, sentenceCount, wordCount, separator) + } func loremIpsumParagraph(r *rand.Rand, paragraphCount int, sentenceCount int, wordCount int, separator string) string { + return paragraphGen(r, paragrapOptions{paragraphCount, sentenceCount, wordCount, separator}, loremIpsumSentence) + } func addLoremLookup() { + AddFuncLookup("loremipsumword", Info{ - Display: "Lorem Ipsum Word", - Category: "word", + + Display: "Lorem Ipsum Word", + + Category: "word", + Description: "Word of the Lorem Ipsum placeholder text used in design and publishing", - Example: "quia", - Output: "string", + + Example: "quia", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return loremIpsumWord(r), nil + }, }) AddFuncLookup("loremipsumsentence", Info{ - Display: "Lorem Ipsum Sentence", - Category: "word", + + Display: "Lorem Ipsum Sentence", + + Category: "word", + Description: "Sentence of the Lorem Ipsum placeholder text used in design and publishing", - Example: "Quia quae repellat consequatur quidem.", - Output: "string", + + Example: "Quia quae repellat consequatur quidem.", + + Output: "string", + Params: []Param{ + {Field: "wordcount", Display: "Word Count", Type: "int", Default: "5", Description: "Number of words in a sentence"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + wordCount, err := info.GetInt(m, "wordcount") + if err != nil { + return nil, err + } + if wordCount <= 0 || wordCount > 50 { + return nil, errors.New("invalid word count, must be greater than 0, less than 50") + } return loremIpsumSentence(r, wordCount), nil + }, }) AddFuncLookup("loremipsumparagraph", Info{ - Display: "Lorem Ipsum Paragraph", - Category: "word", + + Display: "Lorem Ipsum Paragraph", + + Category: "word", + Description: "Paragraph of the Lorem Ipsum placeholder text used in design and publishing", + Example: `Quia quae repellat consequatur quidem nisi quo qui voluptatum accusantium quisquam amet. Quas et ut non dolorem ipsam aut enim assumenda mollitia harum ut. Dicta similique veniam nulla voluptas at excepturi non ad maxime at non. Eaque hic repellat praesentium voluptatem qui consequuntur dolor iusto autem velit aut. Fugit tempore exercitationem harum consequatur voluptatum modi minima aut eaque et et. + + Aut ea voluptatem dignissimos expedita odit tempore quod aut beatae ipsam iste. Minus voluptatibus dolorem maiores eius sed nihil vel enim odio voluptatem accusamus. Natus quibusdam temporibus tenetur cumque sint necessitatibus dolorem ex ducimus iusto ex. Voluptatem neque dicta explicabo officiis et ducimus sit ut ut praesentium pariatur. Illum molestias nisi at dolore ut voluptatem accusantium et fugiat et ut. + + Explicabo incidunt reprehenderit non quia dignissimos recusandae vitae soluta quia et quia. Aut veniam voluptas consequatur placeat sapiente non eveniet voluptatibus magni velit eum. Nobis vel repellendus sed est qui autem laudantium quidem quam ullam consequatur. Aut iusto ut commodi similique quae voluptatem atque qui fugiat eum aut. Quis distinctio consequatur voluptatem vel aliquid aut laborum facere officiis iure tempora.`, + Output: "string", + Params: []Param{ + {Field: "paragraphcount", Display: "Paragraph Count", Type: "int", Default: "2", Description: "Number of paragraphs"}, + {Field: "sentencecount", Display: "Sentence Count", Type: "int", Default: "2", Description: "Number of sentences in a paragraph"}, + {Field: "wordcount", Display: "Word Count", Type: "int", Default: "5", Description: "Number of words in a sentence"}, + {Field: "paragraphseparator", Display: "Paragraph Separator", Type: "string", Default: "
", Description: "String value to add between paragraphs"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + paragraphCount, err := info.GetInt(m, "paragraphcount") + if err != nil { + return nil, err + } + if paragraphCount <= 0 || paragraphCount > 20 { + return nil, errors.New("invalid paragraph count, must be greater than 0, less than 20") + } sentenceCount, err := info.GetInt(m, "sentencecount") + if err != nil { + return nil, err + } + if sentenceCount <= 0 || sentenceCount > 20 { + return nil, errors.New("invalid sentence count, must be greater than 0, less than 20") + } wordCount, err := info.GetInt(m, "wordcount") + if err != nil { + return nil, err + } + if wordCount <= 0 || wordCount > 50 { + return nil, errors.New("invalid word count, must be greater than 0, less than 50") + } paragraphSeparator, err := info.GetString(m, "paragraphseparator") + if err != nil { + return nil, err + } return loremIpsumParagraph(r, paragraphCount, sentenceCount, wordCount, paragraphSeparator), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/misc.go b/vendor/github.com/brianvoe/gofakeit/v6/misc.go index aa55911..48e8dc3 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/misc.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/misc.go @@ -9,160 +9,254 @@ import ( ) // Bool will generate a random boolean value + func Bool() bool { return boolFunc(globalFaker.Rand) } // Bool will generate a random boolean value + func (f *Faker) Bool() bool { return boolFunc(f.Rand) } func boolFunc(r *rand.Rand) bool { return randIntRange(r, 0, 1) == 1 } // UUID (version 4) will generate a random unique identifier based upon random numbers + // Format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + func UUID() string { return uuid(globalFaker.Rand) } // UUID (version 4) will generate a random unique identifier based upon random numbers + // Format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx 8-4-4-4-12 + func (f *Faker) UUID() string { return uuid(f.Rand) } func uuid(r *rand.Rand) string { + version := byte(4) + uuid := make([]byte, 16) // Commented out due to io.ReadFull not being race condition safe + // io.ReadFull(r, uuid[:]) // Read 16 random bytes + for i := 0; i < 16; i++ { + uuid[i] = byte(r.Intn(256)) + } // Set version + uuid[6] = (uuid[6] & 0x0f) | (version << 4) // Set variant + uuid[8] = (uuid[8] & 0xbf) | 0x80 buf := make([]byte, 36) + hex.Encode(buf[0:8], uuid[0:4]) + buf[8] = dash + hex.Encode(buf[9:13], uuid[4:6]) + buf[13] = dash + hex.Encode(buf[14:18], uuid[6:8]) + buf[18] = dash + hex.Encode(buf[19:23], uuid[8:10]) + buf[23] = dash + hex.Encode(buf[24:], uuid[10:]) return string(buf) + } // ShuffleAnySlice takes in a slice and outputs it in a random order + func ShuffleAnySlice(v any) { shuffleAnySlice(globalFaker.Rand, v) } // ShuffleAnySlice takes in a slice and outputs it in a random order + func (f *Faker) ShuffleAnySlice(v any) { shuffleAnySlice(f.Rand, v) } func shuffleAnySlice(r *rand.Rand, v any) { + if v == nil { + return + } // Check type of passed in value, if not a slice return with no action taken + typ := reflect.TypeOf(v) + if typ.Kind() != reflect.Slice { + return + } s := reflect.ValueOf(v) + n := s.Len() if n <= 1 { + return + } swap := func(i, j int) { + tmp := reflect.ValueOf(s.Index(i).Interface()) + s.Index(i).Set(s.Index(j)) + s.Index(j).Set(tmp) + } //if size is > int32 probably it will never finish, or ran out of entropy + i := n - 1 + for ; i > 0; i-- { + j := int(r.Int31n(int32(i + 1))) + swap(i, j) + } + } // FlipACoin will return a random value of Heads or Tails + func FlipACoin() string { return flipACoin(globalFaker.Rand) } // FlipACoin will return a random value of Heads or Tails + func (f *Faker) FlipACoin() string { return flipACoin(f.Rand) } func flipACoin(r *rand.Rand) string { + if boolFunc(r) { + return "Heads" + } return "Tails" + } // RandomMapKey will return a random key from a map + func RandomMapKey(mapI any) any { return randomMapKey(globalFaker.Rand, mapI) } // RandomMapKey will return a random key from a map + func (f *Faker) RandomMapKey(mapI any) any { return randomMapKey(f.Rand, mapI) } func randomMapKey(r *rand.Rand, mapI any) any { + keys := reflect.ValueOf(mapI).MapKeys() + return keys[r.Intn(len(keys))].Interface() + } // Categories will return a map string array of available data categories and sub categories + func Categories() map[string][]string { + types := make(map[string][]string) + for category, subCategoriesMap := range data.Data { + subCategories := make([]string, 0) + for subType := range subCategoriesMap { + subCategories = append(subCategories, subType) + } + types[category] = subCategories + } + return types + } func addMiscLookup() { + AddFuncLookup("uuid", Info{ - Display: "UUID", - Category: "misc", + + Display: "UUID", + + Category: "misc", + Description: "128-bit identifier used to uniquely identify objects or entities in computer systems", - Example: "590c1440-9888-45b0-bd51-a817ee07c3f2", - Output: "string", + + Example: "590c1440-9888-45b0-bd51-a817ee07c3f2", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return uuid(r), nil + }, }) AddFuncLookup("bool", Info{ - Display: "Boolean", - Category: "misc", + + Display: "Boolean", + + Category: "misc", + Description: "Data type that represents one of two possible values, typically true or false", - Example: "true", - Output: "bool", + + Example: "true", + + Output: "bool", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return boolFunc(r), nil + }, }) AddFuncLookup("flipacoin", Info{ - Display: "Flip A Coin", - Category: "misc", + + Display: "Flip A Coin", + + Category: "misc", + Description: "Decision-making method involving the tossing of a coin to determine outcomes", - Example: "Tails", - Output: "string", + + Example: "Tails", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return flipACoin(r), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/number.go b/vendor/github.com/brianvoe/gofakeit/v6/number.go index 7200a59..adbb2c2 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/number.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/number.go @@ -6,607 +6,969 @@ import ( ) // Number will generate a random number between given min And max + func Number(min int, max int) int { return number(globalFaker.Rand, min, max) } // Number will generate a random number between given min And max + func (f *Faker) Number(min int, max int) int { return number(f.Rand, min, max) } func number(r *rand.Rand, min int, max int) int { return randIntRange(r, min, max) } // Uint8 will generate a random uint8 value + func Uint8() uint8 { return uint8Func(globalFaker.Rand) } // Uint8 will generate a random uint8 value + func (f *Faker) Uint8() uint8 { return uint8Func(f.Rand) } func uint8Func(r *rand.Rand) uint8 { return uint8(randUintRange(r, minUint, math.MaxUint8)) } // Uint16 will generate a random uint16 value + func Uint16() uint16 { return uint16Func(globalFaker.Rand) } // Uint16 will generate a random uint16 value + func (f *Faker) Uint16() uint16 { return uint16Func(f.Rand) } func uint16Func(r *rand.Rand) uint16 { return uint16(randUintRange(r, minUint, math.MaxUint16)) } // Uint32 will generate a random uint32 value + func Uint32() uint32 { return uint32Func(globalFaker.Rand) } // Uint32 will generate a random uint32 value + func (f *Faker) Uint32() uint32 { return uint32Func(f.Rand) } func uint32Func(r *rand.Rand) uint32 { return uint32(randUintRange(r, minUint, math.MaxUint32)) } // Uint64 will generate a random uint64 value + func Uint64() uint64 { return uint64Func(globalFaker.Rand) } // Uint64 will generate a random uint64 value + func (f *Faker) Uint64() uint64 { return uint64Func(f.Rand) } func uint64Func(r *rand.Rand) uint64 { return uint64(randUintRange(r, minUint, maxUint)) } // UintRange will generate a random uint value between min and max + func UintRange(min, max uint) uint { return uintRangeFunc(globalFaker.Rand, min, max) } // UintRange will generate a random uint value between min and max + func (f *Faker) UintRange(min, max uint) uint { return uintRangeFunc(f.Rand, min, max) } func uintRangeFunc(r *rand.Rand, min, max uint) uint { return randUintRange(r, min, max) } // Int8 will generate a random Int8 value + func Int8() int8 { return int8Func(globalFaker.Rand) } // Int8 will generate a random Int8 value + func (f *Faker) Int8() int8 { return int8Func(f.Rand) } func int8Func(r *rand.Rand) int8 { return int8(randIntRange(r, math.MinInt8, math.MaxInt8)) } // Int16 will generate a random int16 value + func Int16() int16 { return int16Func(globalFaker.Rand) } // Int16 will generate a random int16 value + func (f *Faker) Int16() int16 { return int16Func(f.Rand) } func int16Func(r *rand.Rand) int16 { return int16(randIntRange(r, math.MinInt16, math.MaxInt16)) } // Int32 will generate a random int32 value + func Int32() int32 { return int32Func(globalFaker.Rand) } // Int32 will generate a random int32 value + func (f *Faker) Int32() int32 { return int32Func(f.Rand) } func int32Func(r *rand.Rand) int32 { return int32(randIntRange(r, math.MinInt32, math.MaxInt32)) } // Int64 will generate a random int64 value + func Int64() int64 { return int64Func(globalFaker.Rand) } // Int64 will generate a random int64 value + func (f *Faker) Int64() int64 { return int64Func(f.Rand) } func int64Func(r *rand.Rand) int64 { return int64(randIntRange(r, minInt, maxInt)) } // IntRange will generate a random int value between min and max + func IntRange(min, max int) int { return intRangeFunc(globalFaker.Rand, min, max) } // IntRange will generate a random int value between min and max + func (f *Faker) IntRange(min, max int) int { return intRangeFunc(f.Rand, min, max) } func intRangeFunc(r *rand.Rand, min, max int) int { return randIntRange(r, min, max) } // Float32 will generate a random float32 value + func Float32() float32 { return float32Func(globalFaker.Rand) } // Float32 will generate a random float32 value + func (f *Faker) Float32() float32 { return float32Func(f.Rand) } func float32Func(r *rand.Rand) float32 { + return float32Range(r, math.SmallestNonzeroFloat32, math.MaxFloat32) + } // Float32Range will generate a random float32 value between min and max + func Float32Range(min, max float32) float32 { + return float32Range(globalFaker.Rand, min, max) + } // Float32Range will generate a random float32 value between min and max + func (f *Faker) Float32Range(min, max float32) float32 { + return float32Range(f.Rand, min, max) + } func float32Range(r *rand.Rand, min, max float32) float32 { + if min == max { + return min + } + return r.Float32()*(max-min) + min + } // Float64 will generate a random float64 value + func Float64() float64 { + return float64Func(globalFaker.Rand) + } // Float64 will generate a random float64 value + func (f *Faker) Float64() float64 { + return float64Func(f.Rand) + } func float64Func(r *rand.Rand) float64 { + return float64Range(r, math.SmallestNonzeroFloat64, math.MaxFloat64) + } // Float64Range will generate a random float64 value between min and max + func Float64Range(min, max float64) float64 { + return float64Range(globalFaker.Rand, min, max) + } // Float64Range will generate a random float64 value between min and max + func (f *Faker) Float64Range(min, max float64) float64 { + return float64Range(f.Rand, min, max) + } func float64Range(r *rand.Rand, min, max float64) float64 { + if min == max { + return min + } + return r.Float64()*(max-min) + min + } // ShuffleInts will randomize a slice of ints + func ShuffleInts(a []int) { shuffleInts(globalFaker.Rand, a) } // ShuffleInts will randomize a slice of ints + func (f *Faker) ShuffleInts(a []int) { shuffleInts(f.Rand, a) } func shuffleInts(r *rand.Rand, a []int) { + for i := range a { + j := r.Intn(i + 1) + a[i], a[j] = a[j], a[i] + } + } // RandomInt will take in a slice of int and return a randomly selected value + func RandomInt(i []int) int { return randomInt(globalFaker.Rand, i) } // RandomInt will take in a slice of int and return a randomly selected value + func (f *Faker) RandomInt(i []int) int { return randomInt(f.Rand, i) } func randomInt(r *rand.Rand, i []int) int { + size := len(i) + if size == 0 { + return 0 + } + if size == 1 { + return i[0] + } + return i[r.Intn(size)] + } // RandomUint will take in a slice of uint and return a randomly selected value + func RandomUint(u []uint) uint { return randomUint(globalFaker.Rand, u) } // RandomUint will take in a slice of uint and return a randomly selected value + func (f *Faker) RandomUint(u []uint) uint { return randomUint(f.Rand, u) } func randomUint(r *rand.Rand, u []uint) uint { + size := len(u) + if size == 0 { + return 0 + } + if size == 1 { + return u[0] + } + return u[r.Intn(size)] + } // HexUint8 will generate a random uint8 hex value with "0x" prefix + func HexUint8() string { return hexUint(globalFaker.Rand, 8) } // HexUint8 will generate a random uint8 hex value with "0x" prefix + func (f *Faker) HexUint8() string { return hexUint(f.Rand, 8) } // HexUint16 will generate a random uint16 hex value with "0x" prefix + func HexUint16() string { return hexUint(globalFaker.Rand, 16) } // HexUint16 will generate a random uint16 hex value with "0x" prefix + func (f *Faker) HexUint16() string { return hexUint(f.Rand, 16) } // HexUint32 will generate a random uint32 hex value with "0x" prefix + func HexUint32() string { return hexUint(globalFaker.Rand, 32) } // HexUint32 will generate a random uint32 hex value with "0x" prefix + func (f *Faker) HexUint32() string { return hexUint(f.Rand, 32) } // HexUint64 will generate a random uint64 hex value with "0x" prefix + func HexUint64() string { return hexUint(globalFaker.Rand, 64) } // HexUint64 will generate a random uint64 hex value with "0x" prefix + func (f *Faker) HexUint64() string { return hexUint(f.Rand, 64) } // HexUint128 will generate a random uint128 hex value with "0x" prefix + func HexUint128() string { return hexUint(globalFaker.Rand, 128) } // HexUint128 will generate a random uint128 hex value with "0x" prefix + func (f *Faker) HexUint128() string { return hexUint(f.Rand, 128) } // HexUint256 will generate a random uint256 hex value with "0x" prefix + func HexUint256() string { return hexUint(globalFaker.Rand, 256) } // HexUint256 will generate a random uint256 hex value with "0x" prefix + func (f *Faker) HexUint256() string { return hexUint(f.Rand, 256) } func hexUint(r *rand.Rand, bitSize int) string { + digits := []byte("0123456789abcdef") + hexLen := (bitSize >> 2) + 2 + if hexLen <= 2 { + return "0x" + } s := make([]byte, hexLen) + s[0], s[1] = '0', 'x' + for i := 2; i < hexLen; i++ { + s[i] = digits[r.Intn(16)] + } + return string(s) + } func addNumberLookup() { + AddFuncLookup("number", Info{ - Display: "Number", - Category: "number", + + Display: "Number", + + Category: "number", + Description: "Mathematical concept used for counting, measuring, and expressing quantities or values", - Example: "14866", - Output: "int", + + Example: "14866", + + Output: "int", + Params: []Param{ + {Field: "min", Display: "Min", Type: "int", Default: "-2147483648", Description: "Minimum integer value"}, + {Field: "max", Display: "Max", Type: "int", Default: "2147483647", Description: "Maximum integer value"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + min, err := info.GetInt(m, "min") + if err != nil { + return nil, err + } max, err := info.GetInt(m, "max") + if err != nil { + return nil, err + } return number(r, min, max), nil + }, }) AddFuncLookup("uint8", Info{ - Display: "Uint8", - Category: "number", + + Display: "Uint8", + + Category: "number", + Description: "Unsigned 8-bit integer, capable of representing values from 0 to 255", - Example: "152", - Output: "uint8", + + Example: "152", + + Output: "uint8", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return uint8Func(r), nil + }, }) AddFuncLookup("uint16", Info{ - Display: "Uint16", - Category: "number", + + Display: "Uint16", + + Category: "number", + Description: "Unsigned 16-bit integer, capable of representing values from 0 to 65,535", - Example: "34968", - Output: "uint16", + + Example: "34968", + + Output: "uint16", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return uint16Func(r), nil + }, }) AddFuncLookup("uint32", Info{ - Display: "Uint32", - Category: "number", + + Display: "Uint32", + + Category: "number", + Description: "Unsigned 32-bit integer, capable of representing values from 0 to 4,294,967,295", - Example: "1075055705", - Output: "uint32", + + Example: "1075055705", + + Output: "uint32", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return uint32Func(r), nil + }, }) AddFuncLookup("uint64", Info{ - Display: "Uint64", - Category: "number", + + Display: "Uint64", + + Category: "number", + Description: "Unsigned 64-bit integer, capable of representing values from 0 to 18,446,744,073,709,551,615", - Example: "843730692693298265", - Output: "uint64", + + Example: "843730692693298265", + + Output: "uint64", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return uint64Func(r), nil + }, }) AddFuncLookup("uintrange", Info{ - Display: "UintRange", - Category: "number", + + Display: "UintRange", + + Category: "number", + Description: "Non-negative integer value between given range", - Example: "1075055705", - Output: "uint", + + Example: "1075055705", + + Output: "uint", + Params: []Param{ + {Field: "min", Display: "Min", Type: "uint", Default: "0", Description: "Minimum uint value"}, + {Field: "max", Display: "Max", Type: "uint", Default: "4294967295", Description: "Maximum uint value"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + min, err := info.GetUint(m, "min") + if err != nil { + return nil, err + } max, err := info.GetUint(m, "max") + if err != nil { + return nil, err + } return uintRangeFunc(r, min, max), nil + }, }) AddFuncLookup("int8", Info{ - Display: "Int8", - Category: "number", + + Display: "Int8", + + Category: "number", + Description: "Signed 8-bit integer, capable of representing values from -128 to 127", - Example: "24", - Output: "int8", + + Example: "24", + + Output: "int8", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return int8Func(r), nil + }, }) AddFuncLookup("int16", Info{ - Display: "Int16", - Category: "number", + + Display: "Int16", + + Category: "number", + Description: "Signed 16-bit integer, capable of representing values from 32,768 to 32,767", - Example: "2200", - Output: "int16", + + Example: "2200", + + Output: "int16", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return int16Func(r), nil + }, }) AddFuncLookup("int32", Info{ - Display: "Int32", - Category: "number", + + Display: "Int32", + + Category: "number", + Description: "Signed 32-bit integer, capable of representing values from -2,147,483,648 to 2,147,483,647", - Example: "-1072427943", - Output: "int32", + + Example: "-1072427943", + + Output: "int32", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return int32Func(r), nil + }, }) AddFuncLookup("int64", Info{ - Display: "Int64", - Category: "number", + + Display: "Int64", + + Category: "number", + Description: "Signed 64-bit integer, capable of representing values from -9,223,372,036,854,775,808 to -9,223,372,036,854,775,807", - Example: "-8379641344161477543", - Output: "int64", + + Example: "-8379641344161477543", + + Output: "int64", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return int64Func(r), nil + }, }) AddFuncLookup("intrange", Info{ - Display: "IntRange", - Category: "number", + + Display: "IntRange", + + Category: "number", + Description: "Integer value between given range", - Example: "-8379477543", - Output: "int", + + Example: "-8379477543", + + Output: "int", + Params: []Param{ + {Field: "min", Display: "Min", Type: "int", Description: "Minimum int value"}, + {Field: "max", Display: "Max", Type: "int", Description: "Maximum int value"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + min, err := info.GetInt(m, "min") + if err != nil { + return nil, err + } max, err := info.GetInt(m, "max") + if err != nil { + return nil, err + } return intRangeFunc(r, min, max), nil + }, }) AddFuncLookup("float32", Info{ - Display: "Float32", - Category: "number", + + Display: "Float32", + + Category: "number", + Description: "Data type representing floating-point numbers with 32 bits of precision in computing", - Example: "3.1128167e+37", - Output: "float32", + + Example: "3.1128167e+37", + + Output: "float32", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return float32Func(r), nil + }, }) AddFuncLookup("float32range", Info{ - Display: "Float32 Range", - Category: "number", + + Display: "Float32 Range", + + Category: "number", + Description: "Float32 value between given range", - Example: "914774.6", - Output: "float32", + + Example: "914774.6", + + Output: "float32", + Params: []Param{ + {Field: "min", Display: "Min", Type: "float", Description: "Minimum float32 value"}, + {Field: "max", Display: "Max", Type: "float", Description: "Maximum float32 value"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + min, err := info.GetFloat32(m, "min") + if err != nil { + return nil, err + } max, err := info.GetFloat32(m, "max") + if err != nil { + return nil, err + } return float32Range(r, min, max), nil + }, }) AddFuncLookup("float64", Info{ - Display: "Float64", - Category: "number", + + Display: "Float64", + + Category: "number", + Description: "Data type representing floating-point numbers with 64 bits of precision in computing", - Example: "1.644484108270445e+307", - Output: "float64", + + Example: "1.644484108270445e+307", + + Output: "float64", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return float64Func(r), nil + }, }) AddFuncLookup("float64range", Info{ - Display: "Float64 Range", - Category: "number", + + Display: "Float64 Range", + + Category: "number", + Description: "Float64 value between given range", - Example: "914774.5585333086", - Output: "float64", + + Example: "914774.5585333086", + + Output: "float64", + Params: []Param{ + {Field: "min", Display: "Min", Type: "float", Description: "Minimum float64 value"}, + {Field: "max", Display: "Max", Type: "float", Description: "Maximum float64 value"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + min, err := info.GetFloat64(m, "min") + if err != nil { + return nil, err + } max, err := info.GetFloat64(m, "max") + if err != nil { + return nil, err + } return float64Range(r, min, max), nil + }, }) AddFuncLookup("shuffleints", Info{ - Display: "Shuffle Ints", - Category: "number", + + Display: "Shuffle Ints", + + Category: "number", + Description: "Shuffles an array of ints", - Example: "1,2,3,4 => 3,1,4,2", - Output: "[]int", + + Example: "1,2,3,4 => 3,1,4,2", + + Output: "[]int", + Params: []Param{ + {Field: "ints", Display: "Integers", Type: "[]int", Description: "Delimited separated integers"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + ints, err := info.GetIntArray(m, "ints") + if err != nil { + return nil, err + } shuffleInts(r, ints) return ints, nil + }, }) AddFuncLookup("randomint", Info{ - Display: "Random Int", - Category: "number", + + Display: "Random Int", + + Category: "number", + Description: "Randomly selected value from a slice of int", - Example: "-1,2,-3,4 => -3", - Output: "int", + + Example: "-1,2,-3,4 => -3", + + Output: "int", + Params: []Param{ + {Field: "ints", Display: "Integers", Type: "[]int", Description: "Delimited separated integers"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + ints, err := info.GetIntArray(m, "ints") + if err != nil { + return nil, err + } return randomInt(r, ints), nil + }, }) AddFuncLookup("randomuint", Info{ - Display: "Random Uint", - Category: "number", + + Display: "Random Uint", + + Category: "number", + Description: "Randomly selected value from a slice of uint", - Example: "1,2,3,4 => 4", - Output: "uint", + + Example: "1,2,3,4 => 4", + + Output: "uint", + Params: []Param{ + {Field: "uints", Display: "Unsigned Integers", Type: "[]uint", Description: "Delimited separated unsigned integers"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + uints, err := info.GetUintArray(m, "uints") + if err != nil { + return nil, err + } return randomUint(r, uints), nil + }, }) AddFuncLookup("hexuint8", Info{ - Display: "HexUint8", - Category: "number", + + Display: "HexUint8", + + Category: "number", + Description: "Hexadecimal representation of an 8-bit unsigned integer", - Example: "0x87", - Output: "string", + + Example: "0x87", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return hexUint(r, 8), nil + }, }) AddFuncLookup("hexuint16", Info{ - Display: "HexUint16", - Category: "number", + + Display: "HexUint16", + + Category: "number", + Description: "Hexadecimal representation of an 16-bit unsigned integer", - Example: "0x8754", - Output: "string", + + Example: "0x8754", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return hexUint(r, 16), nil + }, }) AddFuncLookup("hexuint32", Info{ - Display: "HexUint32", - Category: "number", + + Display: "HexUint32", + + Category: "number", + Description: "Hexadecimal representation of an 32-bit unsigned integer", - Example: "0x87546957", - Output: "string", + + Example: "0x87546957", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return hexUint(r, 32), nil + }, }) AddFuncLookup("hexuint64", Info{ - Display: "HexUint64", - Category: "number", + + Display: "HexUint64", + + Category: "number", + Description: "Hexadecimal representation of an 64-bit unsigned integer", - Example: "0x875469578e51b5e5", - Output: "string", + + Example: "0x875469578e51b5e5", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return hexUint(r, 64), nil + }, }) AddFuncLookup("hexuint128", Info{ - Display: "HexUint128", - Category: "number", + + Display: "HexUint128", + + Category: "number", + Description: "Hexadecimal representation of an 128-bit unsigned integer", - Example: "0x875469578e51b5e56c95b64681d147a1", - Output: "string", + + Example: "0x875469578e51b5e56c95b64681d147a1", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return hexUint(r, 128), nil + }, }) AddFuncLookup("hexuint256", Info{ - Display: "HexUint256", - Category: "number", + + Display: "HexUint256", + + Category: "number", + Description: "Hexadecimal representation of an 256-bit unsigned integer", - Example: "0x875469578e51b5e56c95b64681d147a12cde48a4f417231b0c486abbc263e48d", - Output: "string", + + Example: "0x875469578e51b5e56c95b64681d147a12cde48a4f417231b0c486abbc263e48d", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return hexUint(r, 256), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/payment.go b/vendor/github.com/brianvoe/gofakeit/v6/payment.go index dc4b005..f4210bf 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/payment.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/payment.go @@ -11,432 +11,700 @@ import ( ) // CurrencyInfo is a struct of currency information + type CurrencyInfo struct { Short string `json:"short" xml:"short"` - Long string `json:"long" xml:"long"` + + Long string `json:"long" xml:"long"` } // Currency will generate a struct with random currency information + func Currency() *CurrencyInfo { return currency(globalFaker.Rand) } // Currency will generate a struct with random currency information + func (f *Faker) Currency() *CurrencyInfo { return currency(f.Rand) } func currency(r *rand.Rand) *CurrencyInfo { + index := r.Intn(len(data.Data["currency"]["short"])) + return &CurrencyInfo{ + Short: data.Data["currency"]["short"][index], - Long: data.Data["currency"]["long"][index], + + Long: data.Data["currency"]["long"][index], } + } // CurrencyShort will generate a random short currency value + func CurrencyShort() string { return currencyShort(globalFaker.Rand) } // CurrencyShort will generate a random short currency value + func (f *Faker) CurrencyShort() string { return currencyShort(f.Rand) } func currencyShort(r *rand.Rand) string { return getRandValue(r, []string{"currency", "short"}) } // CurrencyLong will generate a random long currency name + func CurrencyLong() string { return currencyLong(globalFaker.Rand) } // CurrencyLong will generate a random long currency name + func (f *Faker) CurrencyLong() string { return currencyLong(f.Rand) } func currencyLong(r *rand.Rand) string { return getRandValue(r, []string{"currency", "long"}) } // Price will take in a min and max value and return a formatted price + func Price(min, max float64) float64 { return price(globalFaker.Rand, min, max) } // Price will take in a min and max value and return a formatted price + func (f *Faker) Price(min, max float64) float64 { return price(f.Rand, min, max) } func price(r *rand.Rand, min, max float64) float64 { + return math.Floor(float64Range(r, min, max)*100) / 100 + } // CreditCardInfo is a struct containing credit variables + type CreditCardInfo struct { - Type string `json:"type" xml:"type"` + Type string `json:"type" xml:"type"` + Number string `json:"number" xml:"number"` - Exp string `json:"exp" xml:"exp"` - Cvv string `json:"cvv" xml:"cvv"` + + Exp string `json:"exp" xml:"exp"` + + Cvv string `json:"cvv" xml:"cvv"` } // CreditCard will generate a struct full of credit card information + func CreditCard() *CreditCardInfo { return creditCard(globalFaker.Rand) } // CreditCard will generate a struct full of credit card information + func (f *Faker) CreditCard() *CreditCardInfo { return creditCard(f.Rand) } func creditCard(r *rand.Rand) *CreditCardInfo { + ccType := randomString(r, data.CreditCardTypes) + return &CreditCardInfo{ - Type: data.CreditCards[randomString(r, data.CreditCardTypes)].Display, + + Type: data.CreditCards[randomString(r, data.CreditCardTypes)].Display, + Number: creditCardNumber(r, &CreditCardOptions{Types: []string{ccType}}), - Exp: creditCardExp(r), - Cvv: generate(r, strings.Repeat("#", int(data.CreditCards[randomString(r, data.CreditCardTypes)].Code.Size))), + + Exp: creditCardExp(r), + + Cvv: generate(r, strings.Repeat("#", int(data.CreditCards[randomString(r, data.CreditCardTypes)].Code.Size))), } + } // CreditCardType will generate a random credit card type string + func CreditCardType() string { return creditCardType(globalFaker.Rand) } // CreditCardType will generate a random credit card type string + func (f *Faker) CreditCardType() string { return creditCardType(f.Rand) } func creditCardType(r *rand.Rand) string { + return data.CreditCards[randomString(r, data.CreditCardTypes)].Display + } // CreditCardOptions is the options for credit card number + type CreditCardOptions struct { Types []string `json:"types"` - Bins []string `json:"bins"` // optional parameter of prepended numbers - Gaps bool `json:"gaps"` + + Bins []string `json:"bins"` // optional parameter of prepended numbers + + Gaps bool `json:"gaps"` } // CreditCardNumber will generate a random luhn credit card number + func CreditCardNumber(cco *CreditCardOptions) string { return creditCardNumber(globalFaker.Rand, cco) } // CreditCardNumber will generate a random luhn credit card number + func (f *Faker) CreditCardNumber(cco *CreditCardOptions) string { return creditCardNumber(f.Rand, cco) } func creditCardNumber(r *rand.Rand, cco *CreditCardOptions) string { + if cco == nil { + cco = &CreditCardOptions{} + } + if cco.Types == nil || len(cco.Types) == 0 { + cco.Types = data.CreditCardTypes + } + ccType := randomString(r, cco.Types) // Get Card info + var cardInfo data.CreditCardInfo + if info, ok := data.CreditCards[ccType]; ok { + cardInfo = info + } else { + ccType = randomString(r, data.CreditCardTypes) + cardInfo = data.CreditCards[ccType] + } // Get length and pattern + length := randomUint(r, cardInfo.Lengths) + numStr := "" + if len(cco.Bins) >= 1 { + numStr = randomString(r, cco.Bins) + } else { + numStr = strconv.FormatUint(uint64(randomUint(r, cardInfo.Patterns)), 10) + } + numStr += strings.Repeat("#", int(length)-len(numStr)) + numStr = numerify(r, numStr) + ui, _ := strconv.ParseUint(numStr, 10, 64) // Loop through until its a valid luhn + for { + valid := isLuhn(strconv.FormatUint(ui, 10)) + if valid { + break + } + ui++ + } + numStr = strconv.FormatUint(ui, 10) // Add gaps to number + if cco.Gaps { + for i, spot := range cardInfo.Gaps { + numStr = numStr[:(int(spot)+i)] + " " + numStr[(int(spot)+i):] + } + } return numStr + } // CreditCardExp will generate a random credit card expiration date string + // Exp date will always be a future date + func CreditCardExp() string { return creditCardExp(globalFaker.Rand) } // CreditCardExp will generate a random credit card expiration date string + // Exp date will always be a future date + func (f *Faker) CreditCardExp() string { return creditCardExp(f.Rand) } func creditCardExp(r *rand.Rand) string { + month := strconv.Itoa(randIntRange(r, 1, 12)) + if len(month) == 1 { + month = "0" + month + } var currentYear = time.Now().Year() - 2000 + return month + "/" + strconv.Itoa(randIntRange(r, currentYear+1, currentYear+10)) + } // CreditCardCvv will generate a random CVV number + // Its a string because you could have 017 as an exp date + func CreditCardCvv() string { return creditCardCvv(globalFaker.Rand) } // CreditCardCvv will generate a random CVV number + // Its a string because you could have 017 as an exp date + func (f *Faker) CreditCardCvv() string { return creditCardCvv(f.Rand) } func creditCardCvv(r *rand.Rand) string { return numerify(r, "###") } // isLuhn check is used for checking if credit card is a valid luhn card + func isLuhn(s string) bool { + var t = [...]int{0, 2, 4, 6, 8, 1, 3, 5, 7, 9} + odd := len(s) & 1 + var sum int + for i, c := range s { + if c < '0' || c > '9' { + return false + } + if i&1 == odd { + sum += t[c-'0'] + } else { + sum += int(c - '0') + } + } + return sum%10 == 0 + } // AchRouting will generate a 9 digit routing number + func AchRouting() string { return achRouting(globalFaker.Rand) } // AchRouting will generate a 9 digit routing number + func (f *Faker) AchRouting() string { return achRouting(f.Rand) } func achRouting(r *rand.Rand) string { return numerify(r, "#########") } // AchAccount will generate a 12 digit account number + func AchAccount() string { return achAccount(globalFaker.Rand) } // AchAccount will generate a 12 digit account number + func (f *Faker) AchAccount() string { return achAccount(f.Rand) } func achAccount(r *rand.Rand) string { return numerify(r, "############") } // BitcoinAddress will generate a random bitcoin address consisting of numbers, upper and lower characters + func BitcoinAddress() string { return bitcoinAddress(globalFaker.Rand) } // BitcoinAddress will generate a random bitcoin address consisting of numbers, upper and lower characters + func (f *Faker) BitcoinAddress() string { return bitcoinAddress(f.Rand) } func bitcoinAddress(r *rand.Rand) string { + return randomString(r, []string{"1", "3"}) + password(r, true, true, true, false, false, number(r, 25, 34)) + } // BitcoinPrivateKey will generate a random bitcoin private key base58 consisting of numbers, upper and lower characters + func BitcoinPrivateKey() string { return bitcoinPrivateKey(globalFaker.Rand) } // BitcoinPrivateKey will generate a random bitcoin private key base58 consisting of numbers, upper and lower characters + func (f *Faker) BitcoinPrivateKey() string { return bitcoinPrivateKey(f.Rand) } func bitcoinPrivateKey(r *rand.Rand) string { + var b strings.Builder + for i := 0; i < 49; i++ { + b.WriteString(randCharacter(r, base58)) + } + return "5" + randomString(r, []string{"H", "J", "K"}) + b.String() + } func addPaymentLookup() { + AddFuncLookup("currency", Info{ - Display: "Currency", - Category: "payment", + + Display: "Currency", + + Category: "payment", + Description: "Medium of exchange, often in the form of paper money or coins, used for trade and transactions", + Example: `{ + "short": "IQD", + "long": "Iraq Dinar" + }`, - Output: "map[string]string", + + Output: "map[string]string", + ContentType: "application/json", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return currency(r), nil + }, }) AddFuncLookup("currencyshort", Info{ - Display: "Currency Short", - Category: "payment", + + Display: "Currency Short", + + Category: "payment", + Description: "Short 3-letter word used to represent a specific currency", - Example: "USD", - Output: "string", + + Example: "USD", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return currencyShort(r), nil + }, }) AddFuncLookup("currencylong", Info{ - Display: "Currency Long", - Category: "payment", + + Display: "Currency Long", + + Category: "payment", + Description: "Complete name of a specific currency used for official identification in financial transactions", - Example: "United States Dollar", - Output: "string", + + Example: "United States Dollar", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return currencyLong(r), nil + }, }) AddFuncLookup("price", Info{ - Display: "Price", - Category: "payment", + + Display: "Price", + + Category: "payment", + Description: "The amount of money or value assigned to a product, service, or asset in a transaction", - Example: "92.26", - Output: "float64", + + Example: "92.26", + + Output: "float64", + Params: []Param{ + {Field: "min", Display: "Min", Type: "float", Default: "0", Description: "Minimum price value"}, + {Field: "max", Display: "Max", Type: "float", Default: "1000", Description: "Maximum price value"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + min, err := info.GetFloat64(m, "min") + if err != nil { + return nil, err + } max, err := info.GetFloat64(m, "max") + if err != nil { + return nil, err + } return price(r, min, max), nil + }, }) AddFuncLookup("creditcard", Info{ - Display: "Credit Card", - Category: "payment", + + Display: "Credit Card", + + Category: "payment", + Description: "Plastic card allowing users to make purchases on credit, with payment due at a later date", + Example: `{ + "type": "UnionPay", + "number": "4364599489953698", + "exp": "02/24", + "cvv": "300" + }`, - Output: "map[string]any", + + Output: "map[string]any", + ContentType: "application/json", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return creditCard(r), nil + }, }) AddFuncLookup("creditcardtype", Info{ - Display: "Credit Card Type", - Category: "payment", + + Display: "Credit Card Type", + + Category: "payment", + Description: "Classification of credit cards based on the issuing company", - Example: "Visa", - Output: "string", + + Example: "Visa", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return creditCardType(r), nil + }, }) AddFuncLookup("creditcardnumber", Info{ - Display: "Credit Card Number", - Category: "payment", + + Display: "Credit Card Number", + + Category: "payment", + Description: "Unique numerical identifier on a credit card used for making electronic payments and transactions", - Example: "4136459948995369", - Output: "string", + + Example: "4136459948995369", + + Output: "string", + Params: []Param{ + { + Field: "types", Display: "Types", Type: "[]string", Default: "all", - Options: []string{"visa", "mastercard", "american-express", "diners-club", "discover", "jcb", "unionpay", "maestro", "elo", "hiper", "hipercard"}, + + Options: []string{"visa", "mastercard", "american-express", "diners-club", "discover", "jcb", "unionpay", "maestro", "elo", "hiper", "hipercard"}, + Description: "A select number of types you want to use when generating a credit card number", }, + {Field: "bins", Display: "Bins", Type: "[]string", Optional: true, Description: "Optional list of prepended bin numbers to pick from"}, + {Field: "gaps", Display: "Gaps", Type: "bool", Default: "false", Description: "Whether or not to have gaps in number"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + types, err := info.GetStringArray(m, "types") + if err != nil { + return nil, err + } + if len(types) == 1 && types[0] == "all" { + types = []string{} + } bins, _ := info.GetStringArray(m, "bins") gaps, err := info.GetBool(m, "gaps") + if err != nil { + return nil, err + } options := CreditCardOptions{ + Types: types, - Gaps: gaps, + + Gaps: gaps, } if len(bins) >= 1 { + options.Bins = bins + } return creditCardNumber(r, &options), nil + }, }) AddFuncLookup("creditcardexp", Info{ - Display: "Credit Card Exp", - Category: "payment", + + Display: "Credit Card Exp", + + Category: "payment", + Description: "Date when a credit card becomes invalid and cannot be used for transactions", - Example: "01/21", - Output: "string", + + Example: "01/21", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return creditCardExp(r), nil + }, }) AddFuncLookup("creditcardcvv", Info{ - Display: "Credit Card CVV", - Category: "payment", + + Display: "Credit Card CVV", + + Category: "payment", + Description: "Three or four-digit security code on a credit card used for online and remote transactions", - Example: "513", - Output: "string", + + Example: "513", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return creditCardCvv(r), nil + }, }) AddFuncLookup("achrouting", Info{ - Display: "ACH Routing Number", - Category: "payment", + + Display: "ACH Routing Number", + + Category: "payment", + Description: "Unique nine-digit code used in the U.S. for identifying the bank and processing electronic transactions", - Example: "513715684", - Output: "string", + + Example: "513715684", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return achRouting(r), nil + }, }) AddFuncLookup("achaccount", Info{ - Display: "ACH Account Number", - Category: "payment", + + Display: "ACH Account Number", + + Category: "payment", + Description: "A bank account number used for Automated Clearing House transactions and electronic transfers", - Example: "491527954328", - Output: "string", + + Example: "491527954328", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return achAccount(r), nil + }, }) AddFuncLookup("bitcoinaddress", Info{ - Display: "Bitcoin Address", - Category: "payment", + + Display: "Bitcoin Address", + + Category: "payment", + Description: "Cryptographic identifier used to receive, store, and send Bitcoin cryptocurrency in a peer-to-peer network", - Example: "1lWLbxojXq6BqWX7X60VkcDIvYA", - Output: "string", + + Example: "1lWLbxojXq6BqWX7X60VkcDIvYA", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return bitcoinAddress(r), nil + }, }) AddFuncLookup("bitcoinprivatekey", Info{ - Display: "Bitcoin Private Key", - Category: "payment", + + Display: "Bitcoin Private Key", + + Category: "payment", + Description: "Secret, secure code that allows the owner to access and control their Bitcoin holdings", - Example: "5vrbXTADWJ6sQBSYd6lLkG97jljNc0X9VPBvbVqsIH9lWOLcoqg", - Output: "string", + + Example: "5vrbXTADWJ6sQBSYd6lLkG97jljNc0X9VPBvbVqsIH9lWOLcoqg", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return bitcoinPrivateKey(r), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/person.go b/vendor/github.com/brianvoe/gofakeit/v6/person.go index c1fe99f..aa7597a 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/person.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/person.go @@ -8,419 +8,682 @@ import ( ) // PersonInfo is a struct of person information + type PersonInfo struct { - FirstName string `json:"first_name" xml:"first_name"` - LastName string `json:"last_name" xml:"last_name"` - Gender string `json:"gender" xml:"gender"` - SSN string `json:"ssn" xml:"ssn"` - Image string `json:"image" xml:"image"` - Hobby string `json:"hobby" xml:"hobby"` - Job *JobInfo `json:"job" xml:"job"` - Address *AddressInfo `json:"address" xml:"address"` - Contact *ContactInfo `json:"contact" xml:"contact"` + FirstName string `json:"first_name" xml:"first_name"` + + LastName string `json:"last_name" xml:"last_name"` + + Gender string `json:"gender" xml:"gender"` + + SSN string `json:"ssn" xml:"ssn"` + + Image string `json:"image" xml:"image"` + + Hobby string `json:"hobby" xml:"hobby"` + + Job *JobInfo `json:"job" xml:"job"` + + Address *AddressInfo `json:"address" xml:"address"` + + Contact *ContactInfo `json:"contact" xml:"contact"` + CreditCard *CreditCardInfo `json:"credit_card" xml:"credit_card"` } // Person will generate a struct with person information + func Person() *PersonInfo { return person(globalFaker.Rand) } // Person will generate a struct with person information + func (f *Faker) Person() *PersonInfo { return person(f.Rand) } func person(r *rand.Rand) *PersonInfo { + return &PersonInfo{ - FirstName: firstName(r), - LastName: lastName(r), - Gender: gender(r), - SSN: ssn(r), - Image: imageURL(r, number(r, 100, 500), number(r, 100, 500)), - Hobby: hobby(r), - Job: job(r), - Address: address(r), - Contact: contact(r), + + FirstName: firstName(r), + + LastName: lastName(r), + + Gender: gender(r), + + SSN: ssn(r), + + Image: imageURL(r, number(r, 100, 500), number(r, 100, 500)), + + Hobby: hobby(r), + + Job: job(r), + + Address: address(r), + + Contact: contact(r), + CreditCard: creditCard(r), } + } // Name will generate a random First and Last Name + func Name() string { return name(globalFaker.Rand) } // Name will generate a random First and Last Name + func (f *Faker) Name() string { return name(f.Rand) } func name(r *rand.Rand) string { + return getRandValue(r, []string{"person", "first"}) + " " + getRandValue(r, []string{"person", "last"}) + } // FirstName will generate a random first name + func FirstName() string { return firstName(globalFaker.Rand) } // FirstName will generate a random first name + func (f *Faker) FirstName() string { return firstName(f.Rand) } func firstName(r *rand.Rand) string { return getRandValue(r, []string{"person", "first"}) } // MiddleName will generate a random middle name + func MiddleName() string { return middleName(globalFaker.Rand) } // MiddleName will generate a random middle name + func (f *Faker) MiddleName() string { return middleName(f.Rand) } func middleName(r *rand.Rand) string { return getRandValue(r, []string{"person", "middle"}) } // LastName will generate a random last name + func LastName() string { return lastName(globalFaker.Rand) } // LastName will generate a random last name + func (f *Faker) LastName() string { return lastName(f.Rand) } func lastName(r *rand.Rand) string { return getRandValue(r, []string{"person", "last"}) } // NamePrefix will generate a random name prefix + func NamePrefix() string { return namePrefix(globalFaker.Rand) } // NamePrefix will generate a random name prefix + func (f *Faker) NamePrefix() string { return namePrefix(f.Rand) } func namePrefix(r *rand.Rand) string { return getRandValue(r, []string{"person", "prefix"}) } // NameSuffix will generate a random name suffix + func NameSuffix() string { return nameSuffix(globalFaker.Rand) } // NameSuffix will generate a random name suffix + func (f *Faker) NameSuffix() string { return nameSuffix(f.Rand) } func nameSuffix(r *rand.Rand) string { return getRandValue(r, []string{"person", "suffix"}) } // SSN will generate a random Social Security Number + func SSN() string { return ssn(globalFaker.Rand) } // SSN will generate a random Social Security Number + func (f *Faker) SSN() string { return ssn(f.Rand) } func ssn(r *rand.Rand) string { return strconv.Itoa(randIntRange(r, 100000000, 999999999)) } // Gender will generate a random gender string + func Gender() string { return gender(globalFaker.Rand) } // Gender will generate a random gender string + func (f *Faker) Gender() string { return gender(f.Rand) } func gender(r *rand.Rand) string { + if boolFunc(r) { + return "male" + } return "female" + } // Hobby will generate a random hobby string + func Hobby() string { return hobby(globalFaker.Rand) } // Hobby will generate a random hobby string + func (f *Faker) Hobby() string { return hobby(f.Rand) } func hobby(r *rand.Rand) string { return getRandValue(r, []string{"person", "hobby"}) } // ContactInfo struct full of contact info + type ContactInfo struct { Phone string `json:"phone" xml:"phone"` + Email string `json:"email" xml:"email"` } // Contact will generate a struct with information randomly populated contact information + func Contact() *ContactInfo { return contact(globalFaker.Rand) } // Contact will generate a struct with information randomly populated contact information + func (f *Faker) Contact() *ContactInfo { return contact(f.Rand) } func contact(r *rand.Rand) *ContactInfo { + return &ContactInfo{ + Phone: phone(r), + Email: email(r), } + } // Phone will generate a random phone number string + func Phone() string { return phone(globalFaker.Rand) } // Phone will generate a random phone number string + func (f *Faker) Phone() string { return phone(f.Rand) } func phone(r *rand.Rand) string { return replaceWithNumbers(r, "##########") } // PhoneFormatted will generate a random phone number string + func PhoneFormatted() string { return phoneFormatted(globalFaker.Rand) } // PhoneFormatted will generate a random phone number string + func (f *Faker) PhoneFormatted() string { return phoneFormatted(f.Rand) } func phoneFormatted(r *rand.Rand) string { + return replaceWithNumbers(r, getRandValue(r, []string{"person", "phone"})) + } // Email will generate a random email string + func Email() string { return email(globalFaker.Rand) } // Email will generate a random email string + func (f *Faker) Email() string { return email(f.Rand) } func email(r *rand.Rand) string { + email := getRandValue(r, []string{"person", "first"}) + getRandValue(r, []string{"person", "last"}) + email += "@" + email += getRandValue(r, []string{"person", "last"}) + "." + getRandValue(r, []string{"internet", "domain_suffix"}) return strings.ToLower(email) + } // Teams takes in an array of people and team names and randomly places the people into teams as evenly as possible + func Teams(peopleArray []string, teamsArray []string) map[string][]string { + return teams(globalFaker.Rand, peopleArray, teamsArray) + } // Teams takes in an array of people and team names and randomly places the people into teams as evenly as possible + func (f *Faker) Teams(peopleArray []string, teamsArray []string) map[string][]string { + return teams(f.Rand, peopleArray, teamsArray) + } func teams(r *rand.Rand, people []string, teams []string) map[string][]string { + // Shuffle the people if more than 1 + if len(people) > 1 { + shuffleStrings(r, people) + } peopleIndex := 0 + teamsOutput := make(map[string][]string) + numPer := math.Ceil(float64(len(people)) / float64(len(teams))) + for _, team := range teams { + teamsOutput[team] = []string{} + for i := 0.00; i < numPer; i++ { + if peopleIndex < len(people) { + teamsOutput[team] = append(teamsOutput[team], people[peopleIndex]) + peopleIndex++ + } + } + } return teamsOutput + } func addPersonLookup() { + AddFuncLookup("person", Info{ - Display: "Person", - Category: "person", + + Display: "Person", + + Category: "person", + Description: "Personal data, like name and contact details, used for identification and communication", + Example: `{ + "first_name": "Markus", + "last_name": "Moen", + "gender": "male", + "ssn": "275413589", + "image": "https://picsum.photos/208/500", + "hobby": "Lacrosse", + "job": { + "company": "Intermap Technologies", + "title": "Developer", + "descriptor": "Direct", + "level": "Paradigm" + }, + "address": { + "address": "369 North Cornerbury, Miami, North Dakota 24259", + "street": "369 North Cornerbury", + "city": "Miami", + "state": "North Dakota", + "zip": "24259", + "country": "Ghana", + "latitude": -6.662595, + "longitude": 23.921575 + }, + "contact": { + "phone": "3023202027", + "email": "lamarkoelpin@heaney.biz" + }, + "credit_card": { + "type": "Maestro", + "number": "39800889982276", + "exp": "01/29", + "cvv": "932" + } + }`, - Output: "map[string]any", + + Output: "map[string]any", + ContentType: "application/json", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return person(r), nil + }, }) AddFuncLookup("name", Info{ - Display: "Name", - Category: "person", + + Display: "Name", + + Category: "person", + Description: "The given and family name of an individual", - Example: "Markus Moen", - Output: "string", + + Example: "Markus Moen", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return name(r), nil + }, }) AddFuncLookup("nameprefix", Info{ - Display: "Name Prefix", - Category: "person", + + Display: "Name Prefix", + + Category: "person", + Description: "A title or honorific added before a person's name", - Example: "Mr.", - Output: "string", + + Example: "Mr.", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return namePrefix(r), nil + }, }) AddFuncLookup("namesuffix", Info{ - Display: "Name Suffix", - Category: "person", + + Display: "Name Suffix", + + Category: "person", + Description: "A title or designation added after a person's name", - Example: "Jr.", - Output: "string", + + Example: "Jr.", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return nameSuffix(r), nil + }, }) AddFuncLookup("firstname", Info{ - Display: "First Name", - Category: "person", + + Display: "First Name", + + Category: "person", + Description: "The name given to a person at birth", - Example: "Markus", - Output: "string", + + Example: "Markus", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return firstName(r), nil + }, }) AddFuncLookup("middlename", Info{ - Display: "Middle Name", - Category: "person", + + Display: "Middle Name", + + Category: "person", + Description: "Name between a person's first name and last name", - Example: "Belinda", - Output: "string", + + Example: "Belinda", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return middleName(r), nil + }, }) AddFuncLookup("lastname", Info{ - Display: "Last Name", - Category: "person", + + Display: "Last Name", + + Category: "person", + Description: "The family name or surname of an individual", - Example: "Daniel", - Output: "string", + + Example: "Daniel", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return lastName(r), nil + }, }) AddFuncLookup("gender", Info{ - Display: "Gender", - Category: "person", + + Display: "Gender", + + Category: "person", + Description: "Classification based on social and cultural norms that identifies an individual", - Example: "male", - Output: "string", + + Example: "male", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return gender(r), nil + }, }) AddFuncLookup("ssn", Info{ - Display: "SSN", - Category: "person", + + Display: "SSN", + + Category: "person", + Description: "Unique nine-digit identifier used for government and financial purposes in the United States", - Example: "296446360", - Output: "string", + + Example: "296446360", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return ssn(r), nil + }, }) AddFuncLookup("hobby", Info{ - Display: "Hobby", - Category: "person", + + Display: "Hobby", + + Category: "person", + Description: "An activity pursued for leisure and pleasure", - Example: "Swimming", - Output: "string", + + Example: "Swimming", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return hobby(r), nil + }, }) AddFuncLookup("email", Info{ - Display: "Email", - Category: "person", + + Display: "Email", + + Category: "person", + Description: "Electronic mail used for sending digital messages and communication over the internet", - Example: "markusmoen@pagac.net", - Output: "string", + + Example: "markusmoen@pagac.net", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return email(r), nil + }, }) AddFuncLookup("phone", Info{ - Display: "Phone", - Category: "person", + + Display: "Phone", + + Category: "person", + Description: "Numerical sequence used to contact individuals via telephone or mobile devices", - Example: "6136459948", - Output: "string", + + Example: "6136459948", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return phone(r), nil + }, }) AddFuncLookup("phoneformatted", Info{ - Display: "Phone Formatted", - Category: "person", + + Display: "Phone Formatted", + + Category: "person", + Description: "Formatted phone number of a person", - Example: "136-459-9489", - Output: "string", + + Example: "136-459-9489", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return phoneFormatted(r), nil + }, }) AddFuncLookup("teams", Info{ - Display: "Teams", - Category: "person", + + Display: "Teams", + + Category: "person", + Description: "Randomly split people into teams", + Example: `{ + "Team 1": [ + "Justin", + "Connor", + "Jeff" + ], + "Team 2": [ + "Sharon", + "Fabian", + "Billy" + ], + "Team 3": [ + "Steve", + "Robert" + ] + }`, - Output: "map[string][]string", + + Output: "map[string][]string", + ContentType: "application/json", + Params: []Param{ + {Field: "people", Display: "Strings", Type: "[]string", Description: "Array of people"}, + {Field: "teams", Display: "Strings", Type: "[]string", Description: "Array of teams"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + people, err := info.GetStringArray(m, "people") + if err != nil { + return nil, err + } teamsArray, err := info.GetStringArray(m, "teams") + if err != nil { + return nil, err + } return teams(r, people, teamsArray), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/product.go b/vendor/github.com/brianvoe/gofakeit/v6/product.go index 7483ecb..f9140cd 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/product.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/product.go @@ -7,247 +7,409 @@ import ( ) type ProductInfo struct { - Name string `json:"name" xml:"name"` - Description string `json:"description" xml:"description"` - Categories []string `json:"categories" xml:"categories"` - Price float64 `json:"price" xml:"price"` - Features []string `json:"features" xml:"features"` - Color string `json:"color" xml:"color"` - Material string `json:"material" xml:"material"` - UPC string `json:"upc" xml:"upc"` + Name string `json:"name" xml:"name"` + + Description string `json:"description" xml:"description"` + + Categories []string `json:"categories" xml:"categories"` + + Price float64 `json:"price" xml:"price"` + + Features []string `json:"features" xml:"features"` + + Color string `json:"color" xml:"color"` + + Material string `json:"material" xml:"material"` + + UPC string `json:"upc" xml:"upc"` } // Product will generate a random set of product information + func Product() *ProductInfo { return product(globalFaker.Rand) } // Product will generate a random set of product information + func (f *Faker) Product() *ProductInfo { return product(f.Rand) } func product(r *rand.Rand) *ProductInfo { + // Categories + categories := []string{} + weightedCategory, _ := weighted(r, []any{1, 2, 3, 4}, []float32{1, 4, 3, 4}) for i := 0; i < weightedCategory.(int); i++ { + categories = append(categories, productCategory(r)) + } // Features + features := []string{} + for i := 0; i < number(r, 1, 5); i++ { + features = append(features, productFeature(r)) + } product := &ProductInfo{ - Name: productName(r), + + Name: productName(r), + Description: productDescription(r), - Categories: categories, - Price: price(r, 3.00, 100.00), - UPC: productUPC(r), - Features: features, - Color: safeColor(r), - Material: productMaterial(r), + + Categories: categories, + + Price: price(r, 3.00, 100.00), + + UPC: productUPC(r), + + Features: features, + + Color: safeColor(r), + + Material: productMaterial(r), } return product + } // ProductName will generate a random product name + func ProductName() string { return productName(globalFaker.Rand) } // ProductName will generate a random product name + func (f *Faker) ProductName() string { return productName(f.Rand) } func productName(r *rand.Rand) string { + name := getRandValue(r, []string{"product", "name"}) + switch number(r, 0, 9) { + case 1: + // Name + Adjective + Feature + return title(fmt.Sprintf("%s %s %s", name, getRandValue(r, []string{"product", "adjective"}), productFeature(r))) + case 2: + // Adjective + Material + Name + return title(fmt.Sprintf("%s %s %s", getRandValue(r, []string{"product", "adjective"}), productMaterial(r), name)) + case 3: + // Color + Name + Suffix + return title(fmt.Sprintf("%s %s %s", safeColor(r), name, getRandValue(r, []string{"product", "suffix"}))) + case 4: + // Feature + Name + Adjective + return title(fmt.Sprintf("%s %s %s", productFeature(r), name, getRandValue(r, []string{"product", "adjective"}))) + case 5: + // Material + Color + Name + return title(fmt.Sprintf("%s %s %s", productMaterial(r), safeColor(r), name)) + case 6: + // Name + Suffix + Material + return title(fmt.Sprintf("%s %s %s", name, getRandValue(r, []string{"product", "suffix"}), productMaterial(r))) + case 7: + // Adjective + Feature + Name + return title(fmt.Sprintf("%s %s %s", getRandValue(r, []string{"product", "adjective"}), productFeature(r), name)) + case 8: + // Color + Material + Name + return title(fmt.Sprintf("%s %s %s", safeColor(r), productMaterial(r), name)) + case 9: + // Suffix + Adjective + Name + return title(fmt.Sprintf("%s %s %s", getRandValue(r, []string{"product", "suffix"}), getRandValue(r, []string{"product", "adjective"}), name)) + } // case: 0 - Adjective + Name + Suffix + return title(fmt.Sprintf("%s %s %s", getRandValue(r, []string{"product", "adjective"}), name, getRandValue(r, []string{"product", "suffix"}))) + } // ProductDescription will generate a random product description + func ProductDescription() string { return productDescription(globalFaker.Rand) } // ProductDescription will generate a random product description + func (f *Faker) ProductDescription() string { return productDescription(f.Rand) } func productDescription(r *rand.Rand) string { + desc := []string{} + for i := 0; i < number(r, 1, 3); i++ { + desc = append(desc, sentence(r, number(r, 5, 15))) + } return strings.Join(desc, " ") + } // ProductCategory will generate a random product category + func ProductCategory() string { return productCategory(globalFaker.Rand) } // ProductCategory will generate a random product category + func (f *Faker) ProductCategory() string { return productCategory(f.Rand) } func productCategory(r *rand.Rand) string { + return getRandValue(r, []string{"product", "category"}) + } // ProductFeature will generate a random product feature + func ProductFeature() string { return productFeature(globalFaker.Rand) } // ProductFeature will generate a random product feature + func (f *Faker) ProductFeature() string { return productFeature(f.Rand) } func productFeature(r *rand.Rand) string { + return getRandValue(r, []string{"product", "feature"}) + } // ProductMaterial will generate a random product material + func ProductMaterial() string { return productMaterial(globalFaker.Rand) } // ProductMaterial will generate a random product material + func (f *Faker) ProductMaterial() string { return productMaterial(f.Rand) } func productMaterial(r *rand.Rand) string { + return getRandValue(r, []string{"product", "material"}) + } // ProductUPC will generate a random product UPC + func ProductUPC() string { return productUPC(globalFaker.Rand) } // ProductUPC will generate a random product UPC + func (f *Faker) ProductUPC() string { return productUPC(f.Rand) } func productUPC(r *rand.Rand) string { + // The first digit of a UPC is a fixed digit (usually 0) + upc := "0" // Generate the remaining 11 digits randomly + for i := 1; i < 12; i++ { + digit := number(r, 0, 9) + upc += fmt.Sprintf("%d", digit) + } return upc + } func addProductLookup() { + AddFuncLookup("product", Info{ - Display: "Product", - Category: "product", + + Display: "Product", + + Category: "product", + Description: "An item created for sale or use", + Example: `{ + "name": "olive copper monitor", + "description": "Backwards caused quarterly without week it hungry thing someone him regularly. Whomever this revolt hence from his timing as quantity us these yours.", + "categories": [ + "clothing", + "tools and hardware" + ], + "price": 7.61, + "features": [ + "ultra-lightweight" + ], + "color": "navy", + "material": "brass", + "upc": "012780949980" + }`, - Output: "map[string]any", + + Output: "map[string]any", + ContentType: "application/json", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return product(r), nil + }, }) AddFuncLookup("productname", Info{ - Display: "Product Name", - Category: "product", + + Display: "Product Name", + + Category: "product", + Description: "Distinctive title or label assigned to a product for identification and marketing", - Example: "olive copper monitor", - Output: "string", + + Example: "olive copper monitor", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return productName(r), nil + }, }) AddFuncLookup("productdescription", Info{ - Display: "Product Description", - Category: "product", + + Display: "Product Description", + + Category: "product", + Description: "Explanation detailing the features and characteristics of a product", - Example: "Backwards caused quarterly without week it hungry thing someone him regularly. Whomever this revolt hence from his timing as quantity us these yours.", - Output: "string", + + Example: "Backwards caused quarterly without week it hungry thing someone him regularly. Whomever this revolt hence from his timing as quantity us these yours.", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return productDescription(r), nil + }, }) AddFuncLookup("productcategory", Info{ - Display: "Product Category", - Category: "product", + + Display: "Product Category", + + Category: "product", + Description: "Classification grouping similar products based on shared characteristics or functions", - Example: "clothing", - Output: "string", + + Example: "clothing", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return productCategory(r), nil + }, }) AddFuncLookup("productfeature", Info{ - Display: "Product Feature", - Category: "product", + + Display: "Product Feature", + + Category: "product", + Description: "Specific characteristic of a product that distinguishes it from others products", - Example: "ultra-lightweight", - Output: "string", + + Example: "ultra-lightweight", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return productFeature(r), nil + }, }) AddFuncLookup("productmaterial", Info{ - Display: "Product Material", - Category: "product", + + Display: "Product Material", + + Category: "product", + Description: "The substance from which a product is made, influencing its appearance, durability, and properties", - Example: "brass", - Output: "string", + + Example: "brass", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return productMaterial(r), nil + }, }) AddFuncLookup("productupc", Info{ - Display: "Product UPC", - Category: "product", + + Display: "Product UPC", + + Category: "product", + Description: "Standardized barcode used for product identification and tracking in retail and commerce", - Example: "012780949980", - Output: "string", + + Example: "012780949980", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return productUPC(r), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/sql.go b/vendor/github.com/brianvoe/gofakeit/v6/sql.go index b9918b2..1ac24f1 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/sql.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/sql.go @@ -9,9 +9,12 @@ import ( ) type SQLOptions struct { - Table string `json:"table" xml:"table"` // Table name we are inserting into - Count int `json:"count" xml:"count"` // How many entries (tuples) we're generating + Table string `json:"table" xml:"table"` // Table name we are inserting into + + Count int `json:"count" xml:"count"` // How many entries (tuples) we're generating + Fields []Field `json:"fields" xml:"fields"` // The fields to be generated + } func SQL(so *SQLOptions) (string, error) { return sqlFunc(globalFaker.Rand, so) } @@ -19,139 +22,235 @@ func SQL(so *SQLOptions) (string, error) { return sqlFunc(globalFaker.Rand, so) func (f *Faker) SQL(so *SQLOptions) (string, error) { return sqlFunc(f.Rand, so) } func sqlFunc(r *rand.Rand, so *SQLOptions) (string, error) { + if so.Table == "" { + return "", errors.New("must provide table name to generate SQL") + } + if so.Fields == nil || len(so.Fields) <= 0 { + return "", errors.New(("must pass fields in order to generate SQL queries")) + } + if so.Count <= 0 { + return "", errors.New("must have entry count") + } var sb strings.Builder + sb.WriteString("INSERT INTO " + so.Table + " ") // Loop through each field and put together column names + var cols []string + for _, f := range so.Fields { + cols = append(cols, f.Name) + } + sb.WriteString("(" + strings.Join(cols, ", ") + ")") sb.WriteString(" VALUES ") + for i := 0; i < so.Count; i++ { + // Start opening value + sb.WriteString("(") // Now, we need to add all of our fields + var endStr string + for ii, field := range so.Fields { + // Set end of value string + endStr = ", " + if ii == len(so.Fields)-1 { + endStr = "" + } // If autoincrement, add based upon loop + if field.Function == "autoincrement" { + sb.WriteString(fmt.Sprintf("%d%s", i+1, endStr)) + continue + } // Get the function info for the field + funcInfo := GetFuncLookup(field.Function) + if funcInfo == nil { + return "", errors.New("invalid function, " + field.Function + " does not exist") + } // Generate the value + val, err := funcInfo.Generate(r, &field.Params, funcInfo) + if err != nil { + return "", err + } // Convert the output value to the proper SQL type + convertType := sqlConvertType(funcInfo.Output, val) // If its the last field, we need to close the value + sb.WriteString(convertType + endStr) + } // If its the last value, we need to close the value + if i == so.Count-1 { + sb.WriteString(");") + } else { + sb.WriteString("),") + } + } return sb.String(), nil + } // sqlConvertType will take in a type and value and convert it to the proper SQL type + func sqlConvertType(t string, val any) string { + switch t { + case "string": + return `'` + fmt.Sprintf("%v", val) + `'` + case "[]byte": + return `'` + fmt.Sprintf("%s", val) + `'` + default: + return fmt.Sprintf("%v", val) + } + } func addDatabaseSQLLookup() { + AddFuncLookup("sql", Info{ - Display: "SQL", - Category: "database", + + Display: "SQL", + + Category: "database", + Description: "Command in SQL used to add new data records into a database table", + Example: `INSERT INTO people + (id, first_name, price, age, created_at) + VALUES + (1, 'Markus', 804.92, 21, '1937-01-30 07:58:01'), + (2, 'Santino', 235.13, 40, '1964-07-07 22:25:40');`, - Output: "string", + + Output: "string", + ContentType: "application/sql", + Params: []Param{ + {Field: "table", Display: "Table", Type: "string", Description: "Name of the table to insert into"}, + {Field: "count", Display: "Count", Type: "int", Default: "100", Description: "Number of inserts to generate"}, + {Field: "fields", Display: "Fields", Type: "[]Field", Description: "Fields containing key name and function to run in json format"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + so := SQLOptions{} table, err := info.GetString(m, "table") + if err != nil { + return nil, err + } + so.Table = table count, err := info.GetInt(m, "count") + if err != nil { + return nil, err + } + so.Count = count fieldsStr, err := info.GetStringArray(m, "fields") + if err != nil { + return nil, err + } // Check to make sure fields has length + if len(fieldsStr) > 0 { + so.Fields = make([]Field, len(fieldsStr)) for i, f := range fieldsStr { + // Unmarshal fields string into fields array + err = json.Unmarshal([]byte(f), &so.Fields[i]) + if err != nil { + return nil, err + } + } + } return sqlFunc(r, &so) + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/struct.go b/vendor/github.com/brianvoe/gofakeit/v6/struct.go index c587ca1..326866e 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/struct.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/struct.go @@ -10,574 +10,983 @@ import ( ) // Struct fills in exported fields of a struct with random data + // based on the value of `fake` tag of exported fields + // or with the result of a call to the Fake() method + // if the field type implements `Fakeable`. + // Use `fake:"skip"` to explicitly skip an element. + // All built-in types are supported, with templating support + // for string types. + func Struct(v any) error { return structFunc(globalFaker, v) } // Struct fills in exported fields of a struct with random data + // based on the value of `fake` tag of exported fields. + // Use `fake:"skip"` to explicitly skip an element. + // All built-in types are supported, with templating support + // for string types. + func (f *Faker) Struct(v any) error { return structFunc(f, v) } func structFunc(f *Faker, v any) error { + return r(f, reflect.TypeOf(v), reflect.ValueOf(v), "", 0) + } func r(f *Faker, t reflect.Type, v reflect.Value, tag string, size int) error { + // Handle special types if t.PkgPath() == "encoding/json" { + // encoding/json has two special types: + // - RawMessage + // - Number switch t.Name() { + case "RawMessage": + return rJsonRawMessage(f, t, v, tag, size) + case "Number": + return rJsonNumber(f, t, v, tag, size) + default: + return errors.New("unknown encoding/json type: " + t.Name()) + } + } // Handle generic types + switch t.Kind() { + case reflect.Ptr: + return rPointer(f, t, v, tag, size) + case reflect.Struct: + return rStruct(f, t, v, tag) + case reflect.String: + return rString(f, t, v, tag) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return rUint(f, t, v, tag) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return rInt(f, t, v, tag) + case reflect.Float32, reflect.Float64: + return rFloat(f, t, v, tag) + case reflect.Bool: + return rBool(f, t, v, tag) + case reflect.Array, reflect.Slice: + return rSlice(f, t, v, tag, size) + case reflect.Map: + return rMap(f, t, v, tag, size) + } return nil + } func rCustom(f *Faker, t reflect.Type, v reflect.Value, tag string) error { + // If tag is empty return error + if tag == "" { + return errors.New("tag is empty") + } fName, fParams := parseNameAndParamsFromTag(tag) + info := GetFuncLookup(fName) // Check to see if it's a replaceable lookup function + if info == nil { + return fmt.Errorf("function %q not found", tag) + } // Parse map params + mapParams := parseMapParams(info, fParams) // Call function + fValue, err := info.Generate(f.Rand, mapParams, info) + if err != nil { + return err + } // Create new element of expected type + field := reflect.New(reflect.TypeOf(fValue)) + field.Elem().Set(reflect.ValueOf(fValue)) // Check if element is pointer if so + // grab the underlying value + fieldElem := field.Elem() + if fieldElem.Kind() == reflect.Ptr { + fieldElem = fieldElem.Elem() + } // Check if field kind is the same as the expected type + if fieldElem.Kind() != v.Kind() { + // return error saying the field and kinds that do not match + return errors.New("field kind " + fieldElem.Kind().String() + " does not match expected kind " + v.Kind().String()) + } // Set the value + v.Set(fieldElem.Convert(v.Type())) // If a function is called to set the struct + // stop from going through sub fields + return nil + } func rStruct(f *Faker, t reflect.Type, v reflect.Value, tag string) error { + // Check if tag exists, if so run custom function + if t.Name() != "" && tag != "" { + return rCustom(f, t, v, tag) + } // Check if struct is fakeable + if isFakeable(t) { + value, err := callFake(f, v, reflect.Struct) + if err != nil { + return err + } v.Set(reflect.ValueOf(value)) + return nil + } // Loop through all the fields of the struct + n := t.NumField() + for i := 0; i < n; i++ { + elementT := t.Field(i) + elementV := v.Field(i) + fakeTag, ok := elementT.Tag.Lookup("fake") // Check whether or not to skip this field + if ok && fakeTag == "skip" || fakeTag == "-" { + // Do nothing, skip it + continue + } // Check to make sure you can set it or that it's an embedded(anonymous) field + if !elementV.CanSet() && !elementT.Anonymous { + continue + } // Check if reflect type is of values we can specifically set + elemStr := elementT.Type.String() + switch elemStr { + case "time.Time", "*time.Time": + // Check if element is a pointer + elemV := elementV + if elemStr == "*time.Time" { + elemV = reflect.New(elementT.Type.Elem()).Elem() + } // Run rTime on the element + err := rTime(f, elementT, elemV, fakeTag) + if err != nil { + return err + } if elemStr == "*time.Time" { + elementV.Set(elemV.Addr()) + } continue + } // Check if fakesize is set + size := -1 // Set to -1 to indicate fakesize was not set + fs, ok := elementT.Tag.Lookup("fakesize") + if ok { + var err error // Check if size has params separated by , + if strings.Contains(fs, ",") { + sizeSplit := strings.SplitN(fs, ",", 2) + if len(sizeSplit) == 2 { + var sizeMin int + var sizeMax int sizeMin, err = strconv.Atoi(sizeSplit[0]) + if err != nil { + return err + } + sizeMax, err = strconv.Atoi(sizeSplit[1]) + if err != nil { + return err + } size = f.Rand.Intn(sizeMax-sizeMin+1) + sizeMin + } + } else { + size, err = strconv.Atoi(fs) + if err != nil { + return err + } + } + } // Recursively call r() to fill in the struct + err := r(f, elementT.Type, elementV, fakeTag, size) + if err != nil { + return err + } + } return nil + } func rPointer(f *Faker, t reflect.Type, v reflect.Value, tag string, size int) error { + elemT := t.Elem() + if v.IsNil() { + nv := reflect.New(elemT).Elem() + err := r(f, elemT, nv, tag, size) + if err != nil { + return err + } v.Set(nv.Addr()) + } else { + err := r(f, elemT, v.Elem(), tag, size) + if err != nil { + return err + } + } return nil + } func rSlice(f *Faker, t reflect.Type, v reflect.Value, tag string, size int) error { + // If you cant even set it dont even try + if !v.CanSet() { + return errors.New("cannot set slice") + } // Check if tag exists, if so run custom function + if t.Name() != "" && tag != "" { + // Check to see if custom function works if not continue to normal loop of values + err := rCustom(f, t, v, tag) + if err == nil { + return nil + } + } else if isFakeable(t) { + value, err := callFake(f, v, reflect.Slice) + if err != nil { + return err + } v.Set(reflect.ValueOf(value)) + return nil + } // Grab original size to use if needed for sub arrays + ogSize := size // If the value has a len and is less than the size + // use that instead of the requested size + elemLen := v.Len() + if elemLen == 0 && size == -1 { + size = number(f.Rand, 1, 10) + } else if elemLen != 0 && (size == -1 || elemLen < size) { + size = elemLen + } // Get the element type + elemT := t.Elem() // Loop through the elements length and set based upon the index + for i := 0; i < size; i++ { + nv := reflect.New(elemT) + err := r(f, elemT, nv.Elem(), tag, ogSize) + if err != nil { + return err + } // If values are already set fill them up, otherwise append + if elemLen != 0 { + v.Index(i).Set(reflect.Indirect(nv)) + } else { + v.Set(reflect.Append(reflect.Indirect(v), reflect.Indirect(nv))) + } + } return nil + } func rMap(f *Faker, t reflect.Type, v reflect.Value, tag string, size int) error { + // If you cant even set it dont even try + if !v.CanSet() { + return errors.New("cannot set slice") + } // Check if tag exists, if so run custom function + if tag != "" { + return rCustom(f, t, v, tag) + } else if size > 0 { + // NOOP + } else if isFakeable(t) { + value, err := callFake(f, v, reflect.Map) + if err != nil { + return err + } v.Set(reflect.ValueOf(value)) + return nil + } // Set a size + newSize := size + if newSize == -1 { + newSize = number(f.Rand, 1, 10) + } // Create new map based upon map key value type + mapType := reflect.MapOf(t.Key(), t.Elem()) + newMap := reflect.MakeMap(mapType) for i := 0; i < newSize; i++ { + // Create new key + mapIndex := reflect.New(t.Key()) + err := r(f, t.Key(), mapIndex.Elem(), "", -1) + if err != nil { + return err + } // Create new value + mapValue := reflect.New(t.Elem()) + err = r(f, t.Elem(), mapValue.Elem(), "", -1) + if err != nil { + return err + } newMap.SetMapIndex(mapIndex.Elem(), mapValue.Elem()) + } // Set newMap into struct field + if t.Kind() == reflect.Ptr { + v.Set(newMap.Elem()) + } else { + v.Set(newMap) + } return nil + } func rString(f *Faker, t reflect.Type, v reflect.Value, tag string) error { + if tag != "" { + v.SetString(generate(f.Rand, tag)) + } else if isFakeable(t) { + value, err := callFake(f, v, reflect.String) + if err != nil { + return err + } valueStr, ok := value.(string) + if !ok { + return errors.New("call to Fake method did not return a string") + } + v.SetString(valueStr) + } else { + v.SetString(generate(f.Rand, strings.Repeat("?", number(f.Rand, 4, 10)))) + } return nil + } func rInt(f *Faker, t reflect.Type, v reflect.Value, tag string) error { + if tag != "" { + i, err := strconv.ParseInt(generate(f.Rand, tag), 10, 64) + if err != nil { + return err + } v.SetInt(i) + } else if isFakeable(t) { + value, err := callFake(f, v, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64) + if err != nil { + return err + } switch i := value.(type) { + case int: + v.SetInt(int64(i)) + case int8: + v.SetInt(int64(i)) + case int16: + v.SetInt(int64(i)) + case int32: + v.SetInt(int64(i)) + case int64: + v.SetInt(int64(i)) + default: + return errors.New("call to Fake method did not return an integer") + } + } else { + // If no tag or error converting to int, set with random value + switch t.Kind() { + case reflect.Int: + v.SetInt(int64Func(f.Rand)) + case reflect.Int8: + v.SetInt(int64(int8Func(f.Rand))) + case reflect.Int16: + v.SetInt(int64(int16Func(f.Rand))) + case reflect.Int32: + v.SetInt(int64(int32Func(f.Rand))) + case reflect.Int64: + v.SetInt(int64Func(f.Rand)) + } + } return nil + } func rUint(f *Faker, t reflect.Type, v reflect.Value, tag string) error { + if tag != "" { + u, err := strconv.ParseUint(generate(f.Rand, tag), 10, 64) + if err != nil { + return err + } v.SetUint(u) + } else if isFakeable(t) { + value, err := callFake(f, v, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64) + if err != nil { + return err + } switch i := value.(type) { + case uint: + v.SetUint(uint64(i)) + case uint8: + v.SetUint(uint64(i)) + case uint16: + v.SetUint(uint64(i)) + case uint32: + v.SetUint(uint64(i)) + case uint64: + v.SetUint(uint64(i)) + default: + return errors.New("call to Fake method did not return an unsigned integer") + } + } else { + // If no tag or error converting to uint, set with random value + switch t.Kind() { + case reflect.Uint: + v.SetUint(uint64Func(f.Rand)) + case reflect.Uint8: + v.SetUint(uint64(uint8Func(f.Rand))) + case reflect.Uint16: + v.SetUint(uint64(uint16Func(f.Rand))) + case reflect.Uint32: + v.SetUint(uint64(uint32Func(f.Rand))) + case reflect.Uint64: + v.SetUint(uint64Func(f.Rand)) + } + } return nil + } func rFloat(f *Faker, t reflect.Type, v reflect.Value, tag string) error { + if tag != "" { + f, err := strconv.ParseFloat(generate(f.Rand, tag), 64) + if err != nil { + return err + } v.SetFloat(f) + } else if isFakeable(t) { + value, err := callFake(f, v, reflect.Float32, reflect.Float64) + if err != nil { + return err + } switch i := value.(type) { + case float32: + v.SetFloat(float64(i)) + case float64: + v.SetFloat(float64(i)) + default: + return errors.New("call to Fake method did not return a float") + } + } else { + // If no tag or error converting to float, set with random value + switch t.Kind() { + case reflect.Float64: + v.SetFloat(float64Func(f.Rand)) + case reflect.Float32: + v.SetFloat(float64(float32Func(f.Rand))) + } + } return nil + } func rBool(f *Faker, t reflect.Type, v reflect.Value, tag string) error { + if tag != "" { + b, err := strconv.ParseBool(generate(f.Rand, tag)) + if err != nil { + return err + } v.SetBool(b) + } else if isFakeable(t) { + value, err := callFake(f, v, reflect.Bool) + if err != nil { + return err + } switch i := value.(type) { + case bool: + v.SetBool(bool(i)) + default: + return errors.New("call to Fake method did not return a boolean") + } + } else { + // If no tag or error converting to boolean, set with random value + v.SetBool(boolFunc(f.Rand)) + } return nil + } // rTime will set a time.Time field the best it can from either the default date tag or from the generate tag + func rTime(f *Faker, t reflect.StructField, v reflect.Value, tag string) error { + if tag != "" { + // Generate time + timeOutput := generate(f.Rand, tag) // Check to see if timeOutput has monotonic clock reading + // if so, remove it. This is because time.Parse() does not + // support parsing the monotonic clock reading + if strings.Contains(timeOutput, " m=") { + timeOutput = strings.Split(timeOutput, " m=")[0] + } // Check to see if they are passing in a format to parse the time + timeFormat, timeFormatOK := t.Tag.Lookup("format") + if timeFormatOK { + timeFormat = javaDateFormatToGolangDateFormat(timeFormat) + } else { + // If tag == "{date}" use time.RFC3339 + // They are attempting to use the default date lookup + if tag == "{date}" { + timeFormat = time.RFC3339 + } else { + // Default format of time.Now().String() + timeFormat = "2006-01-02 15:04:05.999999999 -0700 MST" + } + } // If output is larger than format cut the output + // This helps us avoid errors from time.Parse + if len(timeOutput) > len(timeFormat) { + timeOutput = timeOutput[:len(timeFormat)] + } // Attempt to parse the time + timeStruct, err := time.Parse(timeFormat, timeOutput) + if err != nil { + return err + } v.Set(reflect.ValueOf(timeStruct)) + return nil + } v.Set(reflect.ValueOf(date(f.Rand))) + return nil + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/template.go b/vendor/github.com/brianvoe/gofakeit/v6/template.go index 37ca879..e8d4b74 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/template.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/template.go @@ -12,432 +12,756 @@ import ( ) // TemplateOptions defines values needed for template document generation + type TemplateOptions struct { Funcs template.FuncMap `fake:"-"` - Data any `json:"data" xml:"data" fake:"-"` + + Data any `json:"data" xml:"data" fake:"-"` } // Template generates an document based on the the supplied template + func Template(template string, co *TemplateOptions) (string, error) { + if co == nil { + co = &TemplateOptions{} + globalFaker.Struct(co) + } + return templateFunc(template, templateFuncMap(globalFaker.Rand, &co.Funcs), co) + } // Template generates an document based on the the supplied template + func (f *Faker) Template(template string, co *TemplateOptions) (string, error) { + if co == nil { + co = &TemplateOptions{} + f.Struct(co) + } + return templateFunc(template, templateFuncMap(f.Rand, &co.Funcs), co) + } // MarkdownOptions defines values needed for markdown document generation + type MarkdownOptions struct { } // Template for Markdown + const templateMarkdown = ` + {{$repo := Gamertag}} + {{$language := RandomString (SliceString "go" "python" "javascript")}} + {{$username := Gamertag}} + {{$weightedSlice := SliceAny "github.com" "gitlab.com" "bitbucket.org"}} + {{$weightedWeights := SliceF32 5 1 1}} + {{$domain := Weighted $weightedSlice $weightedWeights}} + {{$action := RandomString (SliceString "process" "run" "execute" "perform" "handle")}} + {{$usage := RandomString (SliceString "whimsical story" "quirky message" "playful alert" "funny request" "lighthearted command")}} + {{$result := RandomString (SliceString "success" "error" "unknown" "completed" "failed" "finished" "in progress" "terminated")}} + + # {{$repo}} + + *Author: {{FirstName}} {{LastName}}* + + {{Paragraph 2 5 7 "\n\n"}} + + ## Table of Contents + - [Installation](#installation) + - [Usage](#usage) + - [License](#license) + + ## Installation + {{if eq $language "go"}}'''go + go get {{$domain}}/{{$username}}/{{$repo}} + '''{{else if eq $language "python"}}'''bash + pip install {{$repo}} + '''{{else if eq $language "javascript"}}'''js + npm install {{$repo}} + '''{{end}} + + ## Usage + {{if eq $language "go"}}'''go + result := {{$repo}}.{{$action}}("{{ToLower $usage}}") + fmt.Println("{{ToLower $repo}} result:", "{{ToLower $result}}") + '''{{else if eq $language "python"}}'''python + result = {{ToLower $repo}}.{{$action}}("{{ToLower $usage}}") + print("{{ToLower $repo}} result:", "{{ToLower $result}}") + '''{{else if eq $language "javascript"}}'''javascript + const result = {{ToLower $repo}}.{{$action}}("{{ToLower $usage}}"); + console.log("{{ToLower $repo}} result:", "{{ToLower $result}}"); + '''{{end}} + + ## License + {{RandomString (SliceString "MIT" "Apache 2.0" "GPL-3.0" "BSD-3-Clause" "ISC")}} + ` // Markdown will return a single random Markdown template document + func Markdown(co *MarkdownOptions) (string, error) { + if co == nil { + co = &MarkdownOptions{} + globalFaker.Struct(co) + } + return templateFunc(templateMarkdown, templateFuncMap(globalFaker.Rand, nil), co) + } // Markdown will return a single random Markdown template document + func (f *Faker) Markdown(co *MarkdownOptions) (string, error) { + if co == nil { + co = &MarkdownOptions{} + f.Struct(co) + } + return templateFunc(templateMarkdown, templateFuncMap(f.Rand, nil), co) + } // EmailOptions defines values needed for email document generation + type EmailOptions struct { } // Template for email text + const templateEmail = ` + Subject: {{RandomString (SliceString "Greetings" "Hello" "Hi")}} from {{FirstName}}! + + Dear {{LastName}}, + + {{RandomString (SliceString "Greetings!" "Hello there!" "Hi, how are you?")}} {{RandomString (SliceString "How's everything going?" "I hope your day is going well." "Sending positive vibes your way.")}} + + {{RandomString (SliceString "I trust this email finds you well." "I hope you're doing great." "Hoping this message reaches you in good spirits.")}} {{RandomString (SliceString "Wishing you a fantastic day!" "May your week be filled with joy." "Sending good vibes your way.")}} + + {{Paragraph 3 5 10 "\n\n"}} + + {{RandomString (SliceString "I would appreciate your thoughts on" "I'm eager to hear your feedback on" "I'm curious to know what you think about")}} it. If you have a moment, please feel free to check out the project on {{RandomString (SliceString "GitHub" "GitLab" "Bitbucket")}} + + {{RandomString (SliceString "Your insights would be invaluable." "I'm eager to hear what you think." "Feel free to share your opinions with me.")}} {{RandomString (SliceString "Looking forward to your feedback!" "Your perspective is highly valued." "Your thoughts matter to me.")}} + + {{RandomString (SliceString "Thank you for your consideration!" "I appreciate your attention to this matter." "Your support means a lot to me.")}} {{RandomString (SliceString "Wishing you a wonderful day!" "Thanks in advance for your time." "Your feedback is greatly appreciated.")}} + + {{RandomString (SliceString "Warm regards" "Best wishes" "Kind regards" "Sincerely" "With gratitude")}} + {{FirstName}} {{LastName}} + {{Email}} + {{PhoneFormatted}} + ` // EmailText will return a single random text email template document + func EmailText(co *EmailOptions) (string, error) { + if co == nil { + co = &EmailOptions{} + globalFaker.Struct(co) + } + return templateFunc(templateEmail, templateFuncMap(globalFaker.Rand, nil), co) + } // EmailText will return a single random text email template document + func (f *Faker) EmailText(co *EmailOptions) (string, error) { + if co == nil { + co = &EmailOptions{} + f.Struct(co) + } + return templateFunc(templateEmail, templateFuncMap(f.Rand, nil), co) + } // functions that wont work with template engine + var templateExclusion = []string{ + "RandomMapKey", + "SQL", + "Template", } // Build the template.FuncMap for the template engine + func templateFuncMap(r *rand.Rand, fm *template.FuncMap) *template.FuncMap { // create a new function map + funcMap := template.FuncMap{} // build the function map from a faker using their rand + f := &Faker{Rand: r} v := reflect.ValueOf(f) // loop through the methods + for i := 0; i < v.NumMethod(); i++ { + // check if the method is in the exclusion list + if stringInSlice(v.Type().Method(i).Name, templateExclusion) { + continue + } // Check if method has return values + // If not don't add to function map + if v.Type().Method(i).Type.NumOut() == 0 { + continue + } // add the method to the function map + funcMap[v.Type().Method(i).Name] = v.Method(i).Interface() + } // make string upper case + funcMap["ToUpper"] = strings.ToUpper // make string lower case + funcMap["ToLower"] = strings.ToLower // make string title case + funcMap["IntRange"] = func(start, end int) []int { + n := end - start + 1 + result := make([]int, n) + for i := 0; i < n; i++ { + result[i] = start + i + } + return result + } // enable passing any type to return a string + funcMap["ToInt"] = func(args any) int { + switch v := args.(type) { + case string: + i, err := strconv.Atoi(v) + if err != nil { + return 0 + } return i + case float64: + return int(v) + case float32: + return int(v) + case int: + return v // Anything else return 0 + default: + return 0 + } + } // enable passing any type to return a float64 + funcMap["ToFloat"] = func(args any) float64 { + switch v := args.(type) { + case string: + i, err := strconv.ParseFloat(v, 64) + if err != nil { + return 0 + } return i + case float64: + return v + case float32: + return float64(v) + case int: + return float64(v) // Anything else return 0 + default: + return 0 + } + } // ensable passing any type to return a string + funcMap["ToString"] = func(args any) string { + switch v := args.(type) { + case string: + return v + case float64: + return strconv.FormatFloat(v, 'f', -1, 64) + case float32: + return strconv.FormatFloat(float64(v), 'f', -1, 32) + case int: + return strconv.Itoa(v) // Anything else return empty string + default: + return "" + } + } // function to convert string to date time + funcMap["ToDate"] = func(dateString string) time.Time { + date, err := time.Parse("2006-01-02", dateString) + if err != nil { + return time.Now() + } + return date + } // enable passing slice of interface to functions + funcMap["SliceAny"] = func(args ...any) []any { + return args + } // enable passing slice of string to functions + funcMap["SliceString"] = func(args ...string) []string { + return args + } // enable passing slice of uint to functions + funcMap["SliceUInt"] = func(args ...uint) []uint { + return args + } // enable passing slice of int to functions + funcMap["SliceInt"] = func(args ...int) []int { + return args + } // enable passing slice of int to functions + funcMap["SliceF32"] = func(args ...float32) []float32 { + return args + } // Add passed in function map to the function map + if fm != nil { + for k, v := range *fm { + funcMap[k] = v + } + } return &funcMap + } // function to build the function map for the template engine from the global faker + func templateFunc(temp string, funcs *template.FuncMap, data any) (string, error) { + if temp == "" { + return "", fmt.Errorf("template parameter is empty") + } // Create a new template and parse + template_gen, err := template.New("CodeRun").Funcs(*funcs).Parse(temp) + if err != nil { + return "", err + } b := &bytes.Buffer{} + err = template_gen.Execute(b, data) + if err != nil { + return "", err + } // Return the result + return strings.ReplaceAll(b.String(), "\\n", "\n"), nil } // addTemplateLookup will add the template functions to the global lookup + func addTemplateLookup() { + AddFuncLookup("template", Info{ - Display: "Template", - Category: "template", + + Display: "Template", + + Category: "template", + Description: "Generates document from template", + Example: `{{Firstname}} {{Lastname}} + + // output + Markus Moen`, - Output: "string", + + Output: "string", + ContentType: "text/plain", + Params: []Param{ + {Field: "template", Display: "Template", Type: "string", Description: "Golang template to generate the document from"}, + {Field: "data", Display: "Custom Data", Type: "string", Default: "", Optional: true, Description: "Custom data to pass to the template"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + tpl, err := info.GetString(m, "template") + if err != nil { + return nil, err + } data, err := info.GetAny(m, "data") + if err != nil { + return nil, err + } templateOut, err := templateFunc(tpl, templateFuncMap(r, nil), &TemplateOptions{Data: data}) + if err != nil { + return nil, err + } return templateOut, nil + }, }) AddFuncLookup("markdown", Info{ - Display: "Random markdown document", - Category: "template", + + Display: "Random markdown document", + + Category: "template", + Description: "Lightweight markup language used for formatting plain text", + Example: `# PurpleSheep5 + + *Author: Amie Feil* + + Quarterly without week it hungry thing someone. Him regularly today whomever this revolt hence. From his timing as quantity us these. Yours live these frantic not may another. How this ours his them those whose. + + Them batch its Iraqi most that few. Abroad cheese this whereas next how there. Gorgeous genetics time choir fiction therefore yourselves. Am those infrequently heap software quarterly rather. Punctuation yellow where several his orchard to. + + ## Table of Contents + - [Installation](#installation) + - [Usage](#usage) + - [License](#license) + + ## Installation + '''bash + pip install PurpleSheep5 + ''' + + ## Usage + '''python + result = purplesheep5.process("funny request") + print("purplesheep5 result:", "in progress") + ''' + + ## License + MIT`, + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + template_result, err := templateFunc(templateMarkdown, templateFuncMap(r, nil), &MarkdownOptions{}) + return string(template_result), err + }, }) AddFuncLookup("email_text", Info{ - Display: "Random text email Document", - Category: "template", + + Display: "Random text email Document", + + Category: "template", + Description: "Written content of an email message, including the sender's message to the recipient", + Example: `Subject: Greetings from Marcel! + + Dear Pagac, + + Hello there! Sending positive vibes your way. + + I hope you're doing great. May your week be filled with joy. + + Virtually woman where team late quarterly without week it hungry. Thing someone him regularly today whomever this revolt hence from. His timing as quantity us these yours live these frantic. Not may another how this ours his them those whose. Them batch its Iraqi most that few abroad cheese this. + + Whereas next how there gorgeous genetics time choir fiction therefore. Yourselves am those infrequently heap software quarterly rather punctuation yellow. Where several his orchard to frequently hence victorious boxers each. Does auspicious yourselves first soup tomorrow this that must conclude. Anyway some yearly who cough laugh himself both yet rarely. + + Me dolphin intensely block would leap plane us first then. Down them eager would hundred super throughout animal yet themselves. Been group flock shake part purchase up usually it her. None it hers boat what their there Turkmen moreover one. Lebanese to brace these shower in it everybody should whatever. + + I'm curious to know what you think about it. If you have a moment, please feel free to check out the project on Bitbucket + + I'm eager to hear what you think. Looking forward to your feedback! + + Thank you for your consideration! Thanks in advance for your time. + + Kind regards + Milford Johnston + jamelhaag@king.org + (507)096-3058`, + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + template_result, err := templateFunc(templateEmail, templateFuncMap(r, nil), &EmailOptions{}) + return string(template_result), err + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/time.go b/vendor/github.com/brianvoe/gofakeit/v6/time.go index ecd0c1c..716c7df 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/time.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/time.go @@ -8,492 +8,776 @@ import ( ) // Date will generate a random time.Time struct + func Date() time.Time { return date(globalFaker.Rand) } // Date will generate a random time.Time struct + func (f *Faker) Date() time.Time { return date(f.Rand) } func date(r *rand.Rand) time.Time { + return time.Date(year(r), time.Month(month(r)), day(r), hour(r), minute(r), second(r), nanoSecond(r), time.UTC) + } // FutureDate will generate a random past time.Time struct + func PastDate() time.Time { return pastDate(globalFaker.Rand) } // FutureDate will generate a random past time.Time struct + func (f *Faker) PastDate() time.Time { return pastDate(f.Rand) } func pastDate(r *rand.Rand) time.Time { + return time.Now().Add(time.Hour * -time.Duration(number(r, 1, 12))) + } // FutureDate will generate a random future time.Time struct + func FutureDate() time.Time { return futureDate(globalFaker.Rand) } // FutureDate will generate a random future time.Time struct + func (f *Faker) FutureDate() time.Time { return futureDate(f.Rand) } func futureDate(r *rand.Rand) time.Time { + return time.Now().Add(time.Hour * time.Duration(number(r, 1, 12))) + } // DateRange will generate a random time.Time struct between a start and end date + func DateRange(start, end time.Time) time.Time { return dateRange(globalFaker.Rand, start, end) } // DateRange will generate a random time.Time struct between a start and end date + func (f *Faker) DateRange(start, end time.Time) time.Time { return dateRange(f.Rand, start, end) } func dateRange(r *rand.Rand, start time.Time, end time.Time) time.Time { + return time.Unix(0, int64(number(r, int(start.UnixNano()), int(end.UnixNano())))).UTC() + } // NanoSecond will generate a random nano second + func NanoSecond() int { return nanoSecond(globalFaker.Rand) } // NanoSecond will generate a random nano second + func (f *Faker) NanoSecond() int { return nanoSecond(f.Rand) } func nanoSecond(r *rand.Rand) int { return number(r, 0, 999999999) } // Second will generate a random second + func Second() int { return second(globalFaker.Rand) } // Second will generate a random second + func (f *Faker) Second() int { return second(f.Rand) } func second(r *rand.Rand) int { return number(r, 0, 59) } // Minute will generate a random minute + func Minute() int { return minute(globalFaker.Rand) } // Minute will generate a random minute + func (f *Faker) Minute() int { return minute(f.Rand) } func minute(r *rand.Rand) int { return number(r, 0, 59) } // Hour will generate a random hour - in military time + func Hour() int { return hour(globalFaker.Rand) } // Hour will generate a random hour - in military time + func (f *Faker) Hour() int { return hour(f.Rand) } func hour(r *rand.Rand) int { return number(r, 0, 23) } // Day will generate a random day between 1 - 31 + func Day() int { return day(globalFaker.Rand) } // Day will generate a random day between 1 - 31 + func (f *Faker) Day() int { return day(f.Rand) } func day(r *rand.Rand) int { return number(r, 1, 31) } // WeekDay will generate a random weekday string (Monday-Sunday) + func WeekDay() string { return weekDay(globalFaker.Rand) } // WeekDay will generate a random weekday string (Monday-Sunday) + func (f *Faker) WeekDay() string { return weekDay(f.Rand) } func weekDay(r *rand.Rand) string { return time.Weekday(number(r, 0, 6)).String() } // Month will generate a random month int + func Month() int { return month(globalFaker.Rand) } // Month will generate a random month int + func (f *Faker) Month() int { return month(f.Rand) } func month(r *rand.Rand) int { return number(r, 1, 12) } // MonthString will generate a random month string + func MonthString() string { return monthString(globalFaker.Rand) } // MonthString will generate a random month string + func (f *Faker) MonthString() string { return monthString(f.Rand) } func monthString(r *rand.Rand) string { return time.Month(number(r, 1, 12)).String() } // Year will generate a random year between 1900 - current year + func Year() int { return year(globalFaker.Rand) } // Year will generate a random year between 1900 - current year + func (f *Faker) Year() int { return year(f.Rand) } func year(r *rand.Rand) int { return number(r, 1900, time.Now().Year()) } // TimeZone will select a random timezone string + func TimeZone() string { return timeZone(globalFaker.Rand) } // TimeZone will select a random timezone string + func (f *Faker) TimeZone() string { return timeZone(f.Rand) } func timeZone(r *rand.Rand) string { return getRandValue(r, []string{"timezone", "text"}) } // TimeZoneFull will select a random full timezone string + func TimeZoneFull() string { return timeZoneFull(globalFaker.Rand) } // TimeZoneFull will select a random full timezone string + func (f *Faker) TimeZoneFull() string { return timeZoneFull(f.Rand) } func timeZoneFull(r *rand.Rand) string { return getRandValue(r, []string{"timezone", "full"}) } // TimeZoneRegion will select a random region style timezone string, e.g. "America/Chicago" + func TimeZoneRegion() string { return timeZoneRegion(globalFaker.Rand) } // TimeZoneRegion will select a random region style timezone string, e.g. "America/Chicago" + func (f *Faker) TimeZoneRegion() string { return timeZoneRegion(f.Rand) } func timeZoneRegion(r *rand.Rand) string { return getRandValue(r, []string{"timezone", "region"}) } // TimeZoneAbv will select a random timezone abbreviation string + func TimeZoneAbv() string { return timeZoneAbv(globalFaker.Rand) } // TimeZoneAbv will select a random timezone abbreviation string + func (f *Faker) TimeZoneAbv() string { return timeZoneAbv(f.Rand) } func timeZoneAbv(r *rand.Rand) string { return getRandValue(r, []string{"timezone", "abr"}) } // TimeZoneOffset will select a random timezone offset + func TimeZoneOffset() float32 { return timeZoneOffset(globalFaker.Rand) } // TimeZoneOffset will select a random timezone offset + func (f *Faker) TimeZoneOffset() float32 { return timeZoneOffset(f.Rand) } func timeZoneOffset(r *rand.Rand) float32 { + value, _ := strconv.ParseFloat(getRandValue(r, []string{"timezone", "offset"}), 32) + return float32(value) + } // javaDateFormatToGolangDateFormat converts java date format into go date format + func javaDateFormatToGolangDateFormat(format string) string { + format = strings.Replace(format, "ddd", "_2", -1) + format = strings.Replace(format, "dd", "02", -1) + format = strings.Replace(format, "d", "2", -1) format = strings.Replace(format, "HH", "15", -1) format = strings.Replace(format, "hh", "03", -1) + format = strings.Replace(format, "h", "3", -1) format = strings.Replace(format, "mm", "04", -1) + format = strings.Replace(format, "m", "4", -1) format = strings.Replace(format, "ss", "05", -1) + format = strings.Replace(format, "s", "5", -1) format = strings.Replace(format, "yyyy", "2006", -1) + format = strings.Replace(format, "yy", "06", -1) + format = strings.Replace(format, "y", "06", -1) format = strings.Replace(format, "SSS", "000", -1) format = strings.Replace(format, "a", "pm", -1) + format = strings.Replace(format, "aa", "PM", -1) format = strings.Replace(format, "MMMM", "January", -1) + format = strings.Replace(format, "MMM", "Jan", -1) + format = strings.Replace(format, "MM", "01", -1) + format = strings.Replace(format, "M", "1", -1) format = strings.Replace(format, "ZZ", "-0700", -1) if !strings.Contains(format, "Z07") { + format = strings.Replace(format, "Z", "-07", -1) + } format = strings.Replace(format, "zz:zz", "Z07:00", -1) + format = strings.Replace(format, "zzzz", "Z0700", -1) + format = strings.Replace(format, "z", "MST", -1) format = strings.Replace(format, "EEEE", "Monday", -1) + format = strings.Replace(format, "E", "Mon", -1) return format + } func addDateTimeLookup() { + AddFuncLookup("date", Info{ - Display: "Date", - Category: "time", + + Display: "Date", + + Category: "time", + Description: "Representation of a specific day, month, and year, often used for chronological reference", - Example: "2006-01-02T15:04:05Z07:00", - Output: "string", + + Example: "2006-01-02T15:04:05Z07:00", + + Output: "string", + Params: []Param{ + { - Field: "format", - Display: "Format", - Type: "string", - Default: "RFC3339", - Options: []string{"ANSIC", "UnixDate", "RubyDate", "RFC822", "RFC822Z", "RFC850", "RFC1123", "RFC1123Z", "RFC3339", "RFC3339Nano"}, + + Field: "format", + + Display: "Format", + + Type: "string", + + Default: "RFC3339", + + Options: []string{"ANSIC", "UnixDate", "RubyDate", "RFC822", "RFC822Z", "RFC850", "RFC1123", "RFC1123Z", "RFC3339", "RFC3339Nano"}, + Description: "Date time string format output. You may also use golang time format or java time format", }, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + format, err := info.GetString(m, "format") + if err != nil { + return nil, err + } switch format { + case "ANSIC": + return Date().Format(time.ANSIC), nil + case "UnixDate": + return Date().Format(time.UnixDate), nil + case "RubyDate": + return Date().Format(time.RubyDate), nil + case "RFC822": + return Date().Format(time.RFC822), nil + case "RFC822Z": + return Date().Format(time.RFC822Z), nil + case "RFC850": + return Date().Format(time.RFC850), nil + case "RFC1123": + return Date().Format(time.RFC1123), nil + case "RFC1123Z": + return Date().Format(time.RFC1123Z), nil + case "RFC3339": + return Date().Format(time.RFC3339), nil + case "RFC3339Nano": + return Date().Format(time.RFC3339Nano), nil + default: + if format == "" { + return Date().Format(time.RFC3339), nil + } return Date().Format(javaDateFormatToGolangDateFormat(format)), nil + } + }, }) AddFuncLookup("daterange", Info{ - Display: "DateRange", - Category: "time", + + Display: "DateRange", + + Category: "time", + Description: "Random date between two ranges", - Example: "2006-01-02T15:04:05Z07:00", - Output: "string", + + Example: "2006-01-02T15:04:05Z07:00", + + Output: "string", + Params: []Param{ + { - Field: "startdate", - Display: "Start Date", - Type: "string", - Default: "1970-01-01", + + Field: "startdate", + + Display: "Start Date", + + Type: "string", + + Default: "1970-01-01", + Description: "Start date time string", }, + { - Field: "enddate", - Display: "End Date", - Type: "string", - Default: time.Now().Format("2006-01-02"), + + Field: "enddate", + + Display: "End Date", + + Type: "string", + + Default: time.Now().Format("2006-01-02"), + Description: "End date time string", }, + { - Field: "format", - Display: "Format", - Type: "string", - Default: "yyyy-MM-dd", + + Field: "format", + + Display: "Format", + + Type: "string", + + Default: "yyyy-MM-dd", + Description: "Date time string format", }, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + format, err := info.GetString(m, "format") + if err != nil { + return nil, err + } + format = javaDateFormatToGolangDateFormat(format) startdate, err := info.GetString(m, "startdate") + if err != nil { + return nil, err + } + startDateTime, err := time.Parse(format, startdate) + if err != nil { + return nil, err + } enddate, err := info.GetString(m, "enddate") + if err != nil { + return nil, err + } + endDateTime, err := time.Parse(format, enddate) + if err != nil { + return nil, err + } return DateRange(startDateTime, endDateTime).Format(format), nil + }, }) AddFuncLookup("pasttime", Info{ - Display: "PastTime", - Category: "time", + + Display: "PastTime", + + Category: "time", + Description: "Date that has occurred before the current moment in time", - Example: "2007-01-24 13:00:35.820738079 +0000 UTC", - Output: "string", + + Example: "2007-01-24 13:00:35.820738079 +0000 UTC", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return pastDate(r), nil + }, }) AddFuncLookup("futuretime", Info{ - Display: "FutureTime", - Category: "time", + + Display: "FutureTime", + + Category: "time", + Description: "Date that has occurred after the current moment in time", - Example: "2107-01-24 13:00:35.820738079 +0000 UTC", - Output: "string", + + Example: "2107-01-24 13:00:35.820738079 +0000 UTC", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return futureDate(r), nil + }, }) AddFuncLookup("nanosecond", Info{ - Display: "Nanosecond", - Category: "time", + + Display: "Nanosecond", + + Category: "time", + Description: "Unit of time equal to One billionth (10^-9) of a second", - Example: "196446360", - Output: "int", + + Example: "196446360", + + Output: "int", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return nanoSecond(r), nil + }, }) AddFuncLookup("second", Info{ - Display: "Second", - Category: "time", + + Display: "Second", + + Category: "time", + Description: "Unit of time equal to 1/60th of a minute", - Example: "43", - Output: "int", + + Example: "43", + + Output: "int", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return second(r), nil + }, }) AddFuncLookup("minute", Info{ - Display: "Minute", - Category: "time", + + Display: "Minute", + + Category: "time", + Description: "Unit of time equal to 60 seconds", - Example: "34", - Output: "int", + + Example: "34", + + Output: "int", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return minute(r), nil + }, }) AddFuncLookup("hour", Info{ - Display: "Hour", - Category: "time", + + Display: "Hour", + + Category: "time", + Description: "Unit of time equal to 60 minutes", - Example: "8", - Output: "int", + + Example: "8", + + Output: "int", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return hour(r), nil + }, }) AddFuncLookup("day", Info{ - Display: "Day", - Category: "time", + + Display: "Day", + + Category: "time", + Description: "24-hour period equivalent to one rotation of Earth on its axis", - Example: "12", - Output: "int", + + Example: "12", + + Output: "int", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return day(r), nil + }, }) AddFuncLookup("weekday", Info{ - Display: "Weekday", - Category: "time", + + Display: "Weekday", + + Category: "time", + Description: "Day of the week excluding the weekend", - Example: "Friday", - Output: "string", + + Example: "Friday", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return weekDay(r), nil + }, }) AddFuncLookup("month", Info{ - Display: "Month", - Category: "time", + + Display: "Month", + + Category: "time", + Description: "Division of the year, typically 30 or 31 days long", - Example: "1", - Output: "string", + + Example: "1", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return month(r), nil + }, }) AddFuncLookup("monthstring", Info{ - Display: "Month String", - Category: "time", + + Display: "Month String", + + Category: "time", + Description: "String Representation of a month name", - Example: "September", - Output: "string", + + Example: "September", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return monthString(r), nil + }, }) AddFuncLookup("year", Info{ - Display: "Year", - Category: "time", + + Display: "Year", + + Category: "time", + Description: "Period of 365 days, the time Earth takes to orbit the Sun", - Example: "1900", - Output: "int", + + Example: "1900", + + Output: "int", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return year(r), nil + }, }) AddFuncLookup("timezone", Info{ - Display: "Timezone", - Category: "time", + + Display: "Timezone", + + Category: "time", + Description: "Region where the same standard time is used, based on longitudinal divisions of the Earth", - Example: "Kaliningrad Standard Time", - Output: "string", + + Example: "Kaliningrad Standard Time", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return timeZone(r), nil + }, }) AddFuncLookup("timezoneabv", Info{ - Display: "Timezone Abbreviation", - Category: "time", + + Display: "Timezone Abbreviation", + + Category: "time", + Description: "Abbreviated 3-letter word of a timezone", - Example: "KST", - Output: "string", + + Example: "KST", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return timeZoneAbv(r), nil + }, }) AddFuncLookup("timezonefull", Info{ - Display: "Timezone Full", - Category: "time", + + Display: "Timezone Full", + + Category: "time", + Description: "Full name of a timezone", - Example: "(UTC+03:00) Kaliningrad, Minsk", - Output: "string", + + Example: "(UTC+03:00) Kaliningrad, Minsk", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return timeZoneFull(r), nil + }, }) AddFuncLookup("timezoneoffset", Info{ - Display: "Timezone Offset", - Category: "time", + + Display: "Timezone Offset", + + Category: "time", + Description: "The difference in hours from Coordinated Universal Time (UTC) for a specific region", - Example: "3", - Output: "float32", + + Example: "3", + + Output: "float32", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return timeZoneOffset(r), nil + }, }) AddFuncLookup("timezoneregion", Info{ - Display: "Timezone Region", - Category: "time", + + Display: "Timezone Region", + + Category: "time", + Description: "Geographic area sharing the same standard time", - Example: "America/Alaska", - Output: "string", + + Example: "America/Alaska", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return timeZoneRegion(r), nil + }, }) diff --git a/vendor/github.com/brianvoe/gofakeit/v6/weighted.go b/vendor/github.com/brianvoe/gofakeit/v6/weighted.go index c04fa6b..f8d979a 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/weighted.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/weighted.go @@ -6,102 +6,169 @@ import ( ) // Weighted will take in an array of options and weights and return a random selection based upon its indexed weight + func Weighted(options []any, weights []float32) (any, error) { + return weighted(globalFaker.Rand, options, weights) + } // Weighted will take in an array of options and weights and return a random selection based upon its indexed weight + func (f *Faker) Weighted(options []any, weights []float32) (any, error) { + return weighted(f.Rand, options, weights) + } // Weighted will take in an array of options and weights and return a random selection based upon its indexed weight + func weighted(r *rand.Rand, options []any, weights []float32) (any, error) { + ol := len(options) + wl := len(weights) // If options length is 1 just return it back + if ol == 1 { + return options[0], nil + } // Make sure they are passing in options + if ol == 0 { + return nil, errors.New("didnt pass options") + } // Make sure they are passing in weights + if wl == 0 { + return nil, errors.New("didnt pass weights") + } // Make sure they are passing in the same length + if ol != wl { + return nil, errors.New("options and weights need to be the same length") + } // Compute the discrete cumulative density from the sum of the weights + cdf := make([]float32, wl) + var sumOfWeights float32 = 0.0 + for i, weight := range weights { + if i > 0 { + cdf[i] = cdf[i-1] + weight + sumOfWeights += weight + continue + } cdf[i] = weight + sumOfWeights += weight + } // Get rand value from a multple of sumOfWeights + randSumOfWeights := r.Float32() * sumOfWeights var l int = 0 + var h int = wl - 1 + for l <= h { + m := l + (h-l)/2 + if randSumOfWeights <= cdf[m] { + if m == 0 || (m > 0 && randSumOfWeights > cdf[m-1]) { + return options[m], nil + } + h = m - 1 + } else { + l = m + 1 + } + } return nil, errors.New("end of function") + } func addWeightedLookup() { + AddFuncLookup("weighted", Info{ - Display: "Weighted", - Category: "misc", + + Display: "Weighted", + + Category: "misc", + Description: "Randomly select a given option based upon an equal amount of weights", - Example: "[hello, 2, 6.9],[1, 2, 3] => 6.9", - Output: "any", + + Example: "[hello, 2, 6.9],[1, 2, 3] => 6.9", + + Output: "any", + Params: []Param{ + {Field: "options", Display: "Options", Type: "[]string", Description: "Array of any values"}, + {Field: "weights", Display: "Weights", Type: "[]float", Description: "Array of weights"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + options, err := info.GetStringArray(m, "options") + if err != nil { + return nil, err + } weights, err := info.GetFloat32Array(m, "weights") + if err != nil { + return nil, err + } optionsInterface := make([]any, len(options)) + for i, o := range options { + optionsInterface[i] = o + } return weighted(r, optionsInterface, weights) + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/word_comment.go b/vendor/github.com/brianvoe/gofakeit/v6/word_comment.go index 3f5d3e4..3c8ce0d 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/word_comment.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/word_comment.go @@ -6,68 +6,113 @@ import ( ) // Comment will generate a random statement or remark expressing an opinion, observation, or reaction + func Comment() string { return comment(globalFaker.Rand) } // Comment will generate a random statement or remark expressing an opinion, observation, or reaction + func (f *Faker) Comment() string { return comment(f.Rand) } func comment(r *rand.Rand) string { + structures := [][]string{ + {"interjection", "adjective", "noun", "verb", "adverb"}, + {"noun", "verb", "preposition", "determiner", "adjective", "noun"}, + {"noun", "verb", "adverb"}, + {"adjective", "noun", "verb"}, + {"noun", "verb", "preposition", "noun"}, } // Randomly select a structure + structure := structures[number(r, 0, len(structures)-1)] // Build the sentence + var commentParts []string + for _, wordType := range structure { + switch wordType { + case "noun": + commentParts = append(commentParts, noun(r)) + case "verb": + commentParts = append(commentParts, verb(r)) + case "adjective": + commentParts = append(commentParts, adjective(r)) + case "adverb": + commentParts = append(commentParts, adverb(r)) + case "interjection": + commentParts = append(commentParts, interjection(r)) + case "preposition": + commentParts = append(commentParts, preposition(r)) + case "determiner": + commentParts = append(commentParts, nounDeterminer(r)) + default: + // Should never hit + panic("Invalid word type") + } + } // Combine the words into a sentence + sentence := strings.Join(commentParts, " ") // Capitalize the first letter + sentence = title(sentence) // Add a period to the end of the sentence + sentence = sentence + "." return sentence + } func addWordCommentLookup() { + AddFuncLookup("comment", Info{ - Display: "Comment", - Category: "word", + + Display: "Comment", + + Category: "word", + Description: "Statement or remark expressing an opinion, observation, or reaction", - Example: "wow", - Output: "string", + + Example: "wow", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return interjection(r), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/word_general.go b/vendor/github.com/brianvoe/gofakeit/v6/word_general.go index d2a84f9..d5a5344 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/word_general.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/word_general.go @@ -8,31 +8,48 @@ import ( ) // Word will generate a random word + func Word() string { return word(globalFaker.Rand) } // Word will generate a random word + func (f *Faker) Word() string { return word(f.Rand) } func word(r *rand.Rand) string { + word := getRandValue(r, []string{"word", randomString(r, data.WordKeys)}) // Word may return a couple of words, if so we will split on space and return a random word + if strings.Contains(word, " ") { + return randomString(r, strings.Split(word, " ")) + } return word + } func addWordGeneralLookup() { + AddFuncLookup("word", Info{ - Display: "Word", - Category: "word", + + Display: "Word", + + Category: "word", + Description: "Basic unit of language representing a concept or thing, consisting of letters and having meaning", - Example: "man", - Output: "string", + + Example: "man", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return word(r), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/word_grammar.go b/vendor/github.com/brianvoe/gofakeit/v6/word_grammar.go index 77722d7..ab23a54 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/word_grammar.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/word_grammar.go @@ -6,30 +6,48 @@ import ( ) // SentenceSimple will generate a random simple sentence + func SentenceSimple() string { return sentenceSimple(globalFaker.Rand) } // SentenceSimple will generate a random simple sentence + func (f *Faker) SentenceSimple() string { return sentenceSimple(f.Rand) } func sentenceSimple(r *rand.Rand) string { + // simple sentence consists of a noun phrase and a verb phrase + str := phraseNoun(r) + " " + phraseVerb(r) + "." // capitalize the first letter + strR := []rune(str) + strR[0] = unicode.ToUpper(strR[0]) + return string(strR) + } func addWordGrammerLookup() { + AddFuncLookup("sentencesimple", Info{ - Display: "Simple Sentence", - Category: "word", + + Display: "Simple Sentence", + + Category: "word", + Description: "Group of words that expresses a complete thought", - Example: "A tribe fly the lemony kitchen.", - Output: "string", + + Example: "A tribe fly the lemony kitchen.", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return sentenceSimple(r), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/word_phrase.go b/vendor/github.com/brianvoe/gofakeit/v6/word_phrase.go index 1432f17..dd7f9ee 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/word_phrase.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/word_phrase.go @@ -6,158 +6,248 @@ import ( ) // Phrase will return a random phrase + func Phrase() string { return phrase(globalFaker.Rand) } // Phrase will return a random phrase + func (f *Faker) Phrase() string { return phrase(f.Rand) } func phrase(r *rand.Rand) string { return getRandValue(r, []string{"sentence", "phrase"}) } // PhraseNoun will return a random noun phrase + func PhraseNoun() string { return phraseNoun(globalFaker.Rand) } // PhraseNoun will return a random noun phrase + func (f *Faker) PhraseNoun() string { return phraseNoun(f.Rand) } func phraseNoun(r *rand.Rand) string { + str := "" // You may also want to add an adjective to describe the noun + if boolFunc(r) { + str = adjectiveDescriptive(r) + " " + noun(r) + } else { + str = noun(r) + } // Add determiner from weighted list + prob, _ := weighted(r, []any{1, 2, 3}, []float32{2, 1.5, 1}) + if prob == 1 { + str = getArticle(str) + " " + str + } else if prob == 2 { + str = "the " + str + } return str + } // PhraseVerb will return a random preposition phrase + func PhraseVerb() string { return phraseVerb(globalFaker.Rand) } // PhraseVerb will return a random preposition phrase + func (f *Faker) PhraseVerb() string { return phraseVerb(f.Rand) } func phraseVerb(r *rand.Rand) string { + // Put together a string builder + sb := []string{} // You may have an adverb phrase + if boolFunc(r) { + sb = append(sb, phraseAdverb(r)) + } // Lets add the primary verb + sb = append(sb, verbAction(r)) // You may have a noun phrase + if boolFunc(r) { + sb = append(sb, phraseNoun(r)) + } // You may have an adverb phrase + if boolFunc(r) { + sb = append(sb, phraseAdverb(r)) // You may also have a preposition phrase + if boolFunc(r) { + sb = append(sb, phrasePreposition(r)) + } // You may also hae an adverb phrase + if boolFunc(r) { + sb = append(sb, phraseAdverb(r)) + } + } return strings.Join(sb, " ") + } // PhraseAdverb will return a random adverb phrase + func PhraseAdverb() string { return phraseAdverb(globalFaker.Rand) } // PhraseAdverb will return a random adverb phrase + func (f *Faker) PhraseAdverb() string { return phraseAdverb(f.Rand) } func phraseAdverb(r *rand.Rand) string { + if boolFunc(r) { + return adverbDegree(r) + " " + adverbManner(r) + } return adverbManner(r) + } // PhrasePreposition will return a random preposition phrase + func PhrasePreposition() string { return phrasePreposition(globalFaker.Rand) } // PhrasePreposition will return a random preposition phrase + func (f *Faker) PhrasePreposition() string { return phrasePreposition(f.Rand) } func phrasePreposition(r *rand.Rand) string { + return prepositionSimple(r) + " " + phraseNoun(r) + } func addWordPhraseLookup() { + AddFuncLookup("phrase", Info{ - Display: "Phrase", - Category: "word", + + Display: "Phrase", + + Category: "word", + Description: "A small group of words standing together", - Example: "time will tell", - Output: "string", + + Example: "time will tell", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return phrase(r), nil + }, }) AddFuncLookup("phrasenoun", Info{ - Display: "Noun Phrase", - Category: "word", + + Display: "Noun Phrase", + + Category: "word", + Description: "Phrase with a noun as its head, functions within sentence like a noun", - Example: "a tribe", - Output: "string", + + Example: "a tribe", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return phraseNoun(r), nil + }, }) AddFuncLookup("phraseverb", Info{ - Display: "Verb Phrase", - Category: "word", + + Display: "Verb Phrase", + + Category: "word", + Description: "Phrase that Consists of a verb and its modifiers, expressing an action or state", - Example: "a tribe", - Output: "string", + + Example: "a tribe", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return phraseVerb(r), nil + }, }) AddFuncLookup("phraseadverb", Info{ - Display: "Adverb Phrase", - Category: "word", + + Display: "Adverb Phrase", + + Category: "word", + Description: "Phrase that modifies a verb, adjective, or another adverb, providing additional information.", - Example: "fully gladly", - Output: "string", + + Example: "fully gladly", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return phraseAdverb(r), nil + }, }) AddFuncLookup("phrasepreposition", Info{ - Display: "Preposition Phrase", - Category: "word", + + Display: "Preposition Phrase", + + Category: "word", + Description: "Phrase starting with a preposition, showing relation between elements in a sentence.", - Example: "out the black thing", - Output: "string", + + Example: "out the black thing", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return phrasePreposition(r), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/word_sentence.go b/vendor/github.com/brianvoe/gofakeit/v6/word_sentence.go index de8d41e..e2e0ff6 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/word_sentence.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/word_sentence.go @@ -10,204 +10,336 @@ import ( type paragrapOptions struct { paragraphCount int - sentenceCount int - wordCount int - separator string + + sentenceCount int + + wordCount int + + separator string } const bytesPerWordEstimation = 6 type sentenceGenerator func(r *rand.Rand, wordCount int) string + type wordGenerator func(r *rand.Rand) string // Sentence will generate a random sentence + func Sentence(wordCount int) string { return sentence(globalFaker.Rand, wordCount) } // Sentence will generate a random sentence + func (f *Faker) Sentence(wordCount int) string { return sentence(f.Rand, wordCount) } func sentence(r *rand.Rand, wordCount int) string { + return sentenceGen(r, wordCount, word) + } // Paragraph will generate a random paragraphGenerator + func Paragraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string { + return paragraph(globalFaker.Rand, paragraphCount, sentenceCount, wordCount, separator) + } // Paragraph will generate a random paragraphGenerator + func (f *Faker) Paragraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string { + return paragraph(f.Rand, paragraphCount, sentenceCount, wordCount, separator) + } func paragraph(r *rand.Rand, paragraphCount int, sentenceCount int, wordCount int, separator string) string { + return paragraphGen(r, paragrapOptions{paragraphCount, sentenceCount, wordCount, separator}, sentence) + } func sentenceGen(r *rand.Rand, wordCount int, word wordGenerator) string { + if wordCount <= 0 { + return "" + } wordSeparator := ' ' + sentence := bytes.Buffer{} + sentence.Grow(wordCount * bytesPerWordEstimation) for i := 0; i < wordCount; i++ { + word := word(r) + if i == 0 { + runes := []rune(word) + runes[0] = unicode.ToTitle(runes[0]) + word = string(runes) + } + sentence.WriteString(word) + if i < wordCount-1 { + sentence.WriteRune(wordSeparator) + } + } + sentence.WriteRune('.') + return sentence.String() + } func paragraphGen(r *rand.Rand, opts paragrapOptions, sentecer sentenceGenerator) string { + if opts.paragraphCount <= 0 || opts.sentenceCount <= 0 || opts.wordCount <= 0 { + return "" + } //to avoid making Go 1.10 dependency, we cannot use strings.Builder + paragraphs := bytes.Buffer{} + //we presume the length + paragraphs.Grow(opts.paragraphCount * opts.sentenceCount * opts.wordCount * bytesPerWordEstimation) + wordSeparator := ' ' for i := 0; i < opts.paragraphCount; i++ { + for e := 0; e < opts.sentenceCount; e++ { + paragraphs.WriteString(sentecer(r, opts.wordCount)) + if e < opts.sentenceCount-1 { + paragraphs.WriteRune(wordSeparator) + } + } if i < opts.paragraphCount-1 { + paragraphs.WriteString(opts.separator) + } + } return paragraphs.String() + } // Question will return a random question + func Question() string { + return question(globalFaker.Rand) + } // Question will return a random question + func (f *Faker) Question() string { + return question(f.Rand) + } func question(r *rand.Rand) string { + return strings.Replace(hipsterSentence(r, number(r, 3, 10)), ".", "?", 1) + } // Quote will return a random quote from a random person + func Quote() string { return quote(globalFaker.Rand) } // Quote will return a random quote from a random person + func (f *Faker) Quote() string { return quote(f.Rand) } func quote(r *rand.Rand) string { + return `"` + hipsterSentence(r, number(r, 3, 10)) + `" - ` + firstName(r) + " " + lastName(r) + } func addWordSentenceLookup() { + AddFuncLookup("sentence", Info{ - Display: "Sentence", - Category: "word", + + Display: "Sentence", + + Category: "word", + Description: "Set of words expressing a statement, question, exclamation, or command", - Example: "Interpret context record river mind.", - Output: "string", + + Example: "Interpret context record river mind.", + + Output: "string", + Params: []Param{ + {Field: "wordcount", Display: "Word Count", Type: "int", Default: "5", Description: "Number of words in a sentence"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + wordCount, err := info.GetInt(m, "wordcount") + if err != nil { + return nil, err + } + if wordCount <= 0 || wordCount > 50 { + return nil, errors.New("invalid word count, must be greater than 0, less than 50") + } return sentence(r, wordCount), nil + }, }) AddFuncLookup("paragraph", Info{ - Display: "Paragraph", - Category: "word", + + Display: "Paragraph", + + Category: "word", + Description: "Distinct section of writing covering a single theme, composed of multiple sentences", - Example: "Interpret context record river mind press self should compare property outcome divide. Combine approach sustain consult discover explanation direct address church husband seek army. Begin own act welfare replace press suspect stay link place manchester specialist. Arrive price satisfy sign force application hair train provide basis right pay. Close mark teacher strengthen information attempt head touch aim iron tv take.", - Output: "string", + + Example: "Interpret context record river mind press self should compare property outcome divide. Combine approach sustain consult discover explanation direct address church husband seek army. Begin own act welfare replace press suspect stay link place manchester specialist. Arrive price satisfy sign force application hair train provide basis right pay. Close mark teacher strengthen information attempt head touch aim iron tv take.", + + Output: "string", + Params: []Param{ + {Field: "paragraphcount", Display: "Paragraph Count", Type: "int", Default: "2", Description: "Number of paragraphs"}, + {Field: "sentencecount", Display: "Sentence Count", Type: "int", Default: "2", Description: "Number of sentences in a paragraph"}, + {Field: "wordcount", Display: "Word Count", Type: "int", Default: "5", Description: "Number of words in a sentence"}, + {Field: "paragraphseparator", Display: "Paragraph Separator", Type: "string", Default: "
", Description: "String value to add between paragraphs"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + paragraphCount, err := info.GetInt(m, "paragraphcount") + if err != nil { + return nil, err + } + if paragraphCount <= 0 || paragraphCount > 20 { + return nil, errors.New("invalid paragraph count, must be greater than 0, less than 20") + } sentenceCount, err := info.GetInt(m, "sentencecount") + if err != nil { + return nil, err + } + if sentenceCount <= 0 || sentenceCount > 20 { + return nil, errors.New("invalid sentence count, must be greater than 0, less than 20") + } wordCount, err := info.GetInt(m, "wordcount") + if err != nil { + return nil, err + } + if wordCount <= 0 || wordCount > 50 { + return nil, errors.New("invalid word count, must be greater than 0, less than 50") + } paragraphSeparator, err := info.GetString(m, "paragraphseparator") + if err != nil { + return nil, err + } return paragraph(r, paragraphCount, sentenceCount, wordCount, paragraphSeparator), nil + }, }) AddFuncLookup("question", Info{ - Display: "Question", - Category: "word", + + Display: "Question", + + Category: "word", + Description: "Statement formulated to inquire or seek clarification", - Example: "Roof chia echo?", - Output: "string", + + Example: "Roof chia echo?", + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return question(r), nil + }, }) AddFuncLookup("quote", Info{ - Display: "Quote", - Category: "word", + + Display: "Quote", + + Category: "word", + Description: "Direct repetition of someone else's words", - Example: `"Roof chia echo." - Lura Lockman`, - Output: "string", + + Example: `"Roof chia echo." - Lura Lockman`, + + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return quote(r), nil + }, }) + } diff --git a/vendor/github.com/brianvoe/gofakeit/v6/xml.go b/vendor/github.com/brianvoe/gofakeit/v6/xml.go index b922d0d..cdf811b 100644 --- a/vendor/github.com/brianvoe/gofakeit/v6/xml.go +++ b/vendor/github.com/brianvoe/gofakeit/v6/xml.go @@ -10,342 +10,566 @@ import ( ) // XMLOptions defines values needed for json generation + type XMLOptions struct { - Type string `json:"type" xml:"type" fake:"{randomstring:[array,single]}"` // single or array - RootElement string `json:"root_element" xml:"root_element"` - RecordElement string `json:"record_element" xml:"record_element"` - RowCount int `json:"row_count" xml:"row_count" fake:"{number:1,10}"` - Indent bool `json:"indent" xml:"indent"` - Fields []Field `json:"fields" xml:"fields" fake:"{fields}"` + Type string `json:"type" xml:"type" fake:"{randomstring:[array,single]}"` // single or array + + RootElement string `json:"root_element" xml:"root_element"` + + RecordElement string `json:"record_element" xml:"record_element"` + + RowCount int `json:"row_count" xml:"row_count" fake:"{number:1,10}"` + + Indent bool `json:"indent" xml:"indent"` + + Fields []Field `json:"fields" xml:"fields" fake:"{fields}"` } type xmlArray struct { XMLName xml.Name - Array []xmlMap + + Array []xmlMap } type xmlMap struct { - XMLName xml.Name + XMLName xml.Name + KeyOrder []string - Map map[string]any `xml:",chardata"` + + Map map[string]any `xml:",chardata"` } type xmlEntry struct { XMLName xml.Name - Value any `xml:",chardata"` + + Value any `xml:",chardata"` } func (m xmlMap) MarshalXML(e *xml.Encoder, start xml.StartElement) error { + if len(m.Map) == 0 { + return nil + } start.Name = m.XMLName err := e.EncodeToken(start) + if err != nil { + return err + } err = xmlMapLoop(e, &m) + if err != nil { + return err + } return e.EncodeToken(start.End()) + } func xmlMapLoop(e *xml.Encoder, m *xmlMap) error { + var err error // Check if xmlmap has key order if not create it + // Get key order by order of fields array + if m.KeyOrder == nil { + m.KeyOrder = make([]string, len(m.Map)) + for k := range m.Map { + m.KeyOrder = append(m.KeyOrder, k) + } + } for _, key := range m.KeyOrder { + v := reflect.ValueOf(m.Map[key]) // Always get underlyning Value of value + if v.Kind() == reflect.Ptr { + v = reflect.Indirect(v) + } switch v.Kind() { + case reflect.Bool, + reflect.String, + reflect.Int, reflect.Int8, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint32, reflect.Uint64, + reflect.Float32, reflect.Float64: + err = e.Encode(xmlEntry{XMLName: xml.Name{Local: key}, Value: m.Map[key]}) + if err != nil { + return err + } + case reflect.Slice: + e.EncodeToken(xml.StartElement{Name: xml.Name{Local: key}}) + for i := 0; i < v.Len(); i++ { + err = e.Encode(xmlEntry{XMLName: xml.Name{Local: "value"}, Value: v.Index(i).String()}) + if err != nil { + return err + } + } + e.EncodeToken(xml.EndElement{Name: xml.Name{Local: key}}) + case reflect.Map: + err = e.Encode(xmlMap{ + XMLName: xml.Name{Local: key}, - Map: m.Map[key].(map[string]any), + + Map: m.Map[key].(map[string]any), }) + if err != nil { + return err + } + case reflect.Struct: + // Convert struct to map[string]any + // So we can rewrap element + var inInterface map[string]any + inrec, _ := json.Marshal(m.Map[key]) + json.Unmarshal(inrec, &inInterface) err = e.Encode(xmlMap{ + XMLName: xml.Name{Local: key}, - Map: inInterface, + + Map: inInterface, }) + if err != nil { + return err + } + default: + err = e.Encode(m.Map[key]) + if err != nil { + return err + } + } + } return nil + } // XML generates an object or an array of objects in json format + // A nil XMLOptions returns a randomly structured XML. + func XML(xo *XMLOptions) ([]byte, error) { return xmlFunc(globalFaker, xo) } // XML generates an object or an array of objects in json format + // A nil XMLOptions returns a randomly structured XML. + func (f *Faker) XML(xo *XMLOptions) ([]byte, error) { return xmlFunc(f, xo) } func xmlFunc(f *Faker, xo *XMLOptions) ([]byte, error) { + if xo == nil { + // We didn't get a XMLOptions, so create a new random one + err := f.Struct(&xo) + if err != nil { + return nil, err + } + } // Check to make sure they passed in a type + if xo.Type != "single" && xo.Type != "array" { + return nil, errors.New("invalid type, must be array or object") + } // Check fields length + if xo.Fields == nil || len(xo.Fields) <= 0 { + return nil, errors.New("must pass fields in order to build json object(s)") + } // Check root element string + if xo.RootElement == "" { + xo.RecordElement = "xml" + } // Check record element string + if xo.RecordElement == "" { + xo.RecordElement = "record" + } // Get key order by order of fields array + keyOrder := make([]string, len(xo.Fields)) + for _, f := range xo.Fields { + keyOrder = append(keyOrder, f.Name) + } if xo.Type == "single" { + v := xmlMap{ - XMLName: xml.Name{Local: xo.RootElement}, + + XMLName: xml.Name{Local: xo.RootElement}, + KeyOrder: keyOrder, - Map: make(map[string]any), + + Map: make(map[string]any), } // Loop through fields and add to them to map[string]any + for _, field := range xo.Fields { + // Get function info + funcInfo := GetFuncLookup(field.Function) + if funcInfo == nil { + return nil, errors.New("invalid function, " + field.Function + " does not exist") + } value, err := funcInfo.Generate(f.Rand, &field.Params, funcInfo) + if err != nil { + return nil, err + } v.Map[field.Name] = value + } // Marshal into bytes + var b bytes.Buffer + x := xml.NewEncoder(&b) + if xo.Indent { + x.Indent("", " ") + } + err := x.Encode(v) + if err != nil { + return nil, err + } return b.Bytes(), nil + } if xo.Type == "array" { + // Make sure you set a row count + if xo.RowCount <= 0 { + return nil, errors.New("must have row count") + } xa := xmlArray{ + XMLName: xml.Name{Local: xo.RootElement}, - Array: make([]xmlMap, xo.RowCount), + + Array: make([]xmlMap, xo.RowCount), } for i := 1; i <= int(xo.RowCount); i++ { + v := xmlMap{ - XMLName: xml.Name{Local: xo.RecordElement}, + + XMLName: xml.Name{Local: xo.RecordElement}, + KeyOrder: keyOrder, - Map: make(map[string]any), + + Map: make(map[string]any), } // Loop through fields and add to them to map[string]any + for _, field := range xo.Fields { + if field.Function == "autoincrement" { + v.Map[field.Name] = i + continue + } // Get function info + funcInfo := GetFuncLookup(field.Function) + if funcInfo == nil { + return nil, errors.New("invalid function, " + field.Function + " does not exist") + } value, err := funcInfo.Generate(f.Rand, &field.Params, funcInfo) + if err != nil { + return nil, err + } v.Map[field.Name] = value + } xa.Array = append(xa.Array, v) + } // Marshal into bytes + var b bytes.Buffer + x := xml.NewEncoder(&b) + if xo.Indent { + x.Indent("", " ") + } + err := x.Encode(xa) + if err != nil { + return nil, err + } return b.Bytes(), nil + } return nil, errors.New("invalid type, must be array or object") + } func addFileXMLLookup() { + AddFuncLookup("xml", Info{ - Display: "XML", - Category: "file", + + Display: "XML", + + Category: "file", + Description: "Generates an single or an array of elements in xml format", + Example: ` + + Markus + Moen + Dc0VYXjkWABx + + + Osborne + Hilll + XPJ9OVNbs5lm + + `, - Output: "[]byte", + + Output: "[]byte", + ContentType: "application/xml", + Params: []Param{ + {Field: "type", Display: "Type", Type: "string", Default: "single", Options: []string{"single", "array"}, Description: "Type of XML, single or array"}, + {Field: "rootelement", Display: "Root Element", Type: "string", Default: "xml", Description: "Root element wrapper name"}, + {Field: "recordelement", Display: "Record Element", Type: "string", Default: "record", Description: "Record element for each record row"}, + {Field: "rowcount", Display: "Row Count", Type: "int", Default: "100", Description: "Number of rows in JSON array"}, + {Field: "indent", Display: "Indent", Type: "bool", Default: "false", Description: "Whether or not to add indents and newlines"}, + {Field: "fields", Display: "Fields", Type: "[]Field", Description: "Fields containing key name and function to run in json format"}, }, + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + xo := XMLOptions{} typ, err := info.GetString(m, "type") + if err != nil { + return nil, err + } + xo.Type = typ rootElement, err := info.GetString(m, "rootelement") + if err != nil { + return nil, err + } + xo.RootElement = rootElement recordElement, err := info.GetString(m, "recordelement") + if err != nil { + return nil, err + } + xo.RecordElement = recordElement rowcount, err := info.GetInt(m, "rowcount") + if err != nil { + return nil, err + } + xo.RowCount = rowcount fieldsStr, err := info.GetStringArray(m, "fields") + if err != nil { + return nil, err + } indent, err := info.GetBool(m, "indent") + if err != nil { + return nil, err + } + xo.Indent = indent // Check to make sure fields has length + if len(fieldsStr) > 0 { + xo.Fields = make([]Field, len(fieldsStr)) for i, f := range fieldsStr { + // Unmarshal fields string into fields array + err = json.Unmarshal([]byte(f), &xo.Fields[i]) + if err != nil { + return nil, errors.New("unable to decode json string") + } + } + } f := &Faker{Rand: r} + return xmlFunc(f, &xo) + }, }) + } diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash.go b/vendor/github.com/cespare/xxhash/v2/xxhash.go index a9e0d45..eebfabc 100644 --- a/vendor/github.com/cespare/xxhash/v2/xxhash.go +++ b/vendor/github.com/cespare/xxhash/v2/xxhash.go @@ -1,5 +1,7 @@ // Package xxhash implements the 64-bit variant of xxHash (XXH64) as described + // at http://cyan4973.github.io/xxHash/. + package xxhash import ( @@ -10,219 +12,372 @@ import ( const ( prime1 uint64 = 11400714785074694791 + prime2 uint64 = 14029467366897019727 + prime3 uint64 = 1609587929392839161 + prime4 uint64 = 9650029242287828579 + prime5 uint64 = 2870177450012600261 ) // Store the primes in an array as well. + // + // The consts are used when possible in Go code to avoid MOVs but we need a + // contiguous array of the assembly code. + var primes = [...]uint64{prime1, prime2, prime3, prime4, prime5} // Digest implements hash.Hash64. + type Digest struct { - v1 uint64 - v2 uint64 - v3 uint64 - v4 uint64 + v1 uint64 + + v2 uint64 + + v3 uint64 + + v4 uint64 + total uint64 - mem [32]byte - n int // how much of mem is used + + mem [32]byte + + n int // how much of mem is used + } // New creates a new Digest that computes the 64-bit xxHash algorithm. + func New() *Digest { + var d Digest + d.Reset() + return &d + } // Reset clears the Digest's state so that it can be reused. + func (d *Digest) Reset() { + d.v1 = primes[0] + prime2 + d.v2 = prime2 + d.v3 = 0 + d.v4 = -primes[0] + d.total = 0 + d.n = 0 + } // Size always returns 8 bytes. + func (d *Digest) Size() int { return 8 } // BlockSize always returns 32 bytes. + func (d *Digest) BlockSize() int { return 32 } // Write adds more data to d. It always returns len(b), nil. + func (d *Digest) Write(b []byte) (n int, err error) { + n = len(b) + d.total += uint64(n) memleft := d.mem[d.n&(len(d.mem)-1):] if d.n+n < 32 { + // This new data doesn't even fill the current block. + copy(memleft, b) + d.n += n + return + } if d.n > 0 { + // Finish off the partial block. + c := copy(memleft, b) + d.v1 = round(d.v1, u64(d.mem[0:8])) + d.v2 = round(d.v2, u64(d.mem[8:16])) + d.v3 = round(d.v3, u64(d.mem[16:24])) + d.v4 = round(d.v4, u64(d.mem[24:32])) + b = b[c:] + d.n = 0 + } if len(b) >= 32 { + // One or more full blocks left. + nw := writeBlocks(d, b) + b = b[nw:] + } // Store any remaining partial block. + copy(d.mem[:], b) + d.n = len(b) return + } // Sum appends the current hash to b and returns the resulting slice. + func (d *Digest) Sum(b []byte) []byte { + s := d.Sum64() + return append( + b, + byte(s>>56), + byte(s>>48), + byte(s>>40), + byte(s>>32), + byte(s>>24), + byte(s>>16), + byte(s>>8), + byte(s), ) + } // Sum64 returns the current hash. + func (d *Digest) Sum64() uint64 { + var h uint64 if d.total >= 32 { + v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4 + h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) + h = mergeRound(h, v1) + h = mergeRound(h, v2) + h = mergeRound(h, v3) + h = mergeRound(h, v4) + } else { + h = d.v3 + prime5 + } h += d.total b := d.mem[:d.n&(len(d.mem)-1)] + for ; len(b) >= 8; b = b[8:] { + k1 := round(0, u64(b[:8])) + h ^= k1 + h = rol27(h)*prime1 + prime4 + } + if len(b) >= 4 { + h ^= uint64(u32(b[:4])) * prime1 + h = rol23(h)*prime2 + prime3 + b = b[4:] + } + for ; len(b) > 0; b = b[1:] { + h ^= uint64(b[0]) * prime5 + h = rol11(h) * prime1 + } h ^= h >> 33 + h *= prime2 + h ^= h >> 29 + h *= prime3 + h ^= h >> 32 return h + } const ( - magic = "xxh\x06" + magic = "xxh\x06" + marshaledSize = len(magic) + 8*5 + 32 ) // MarshalBinary implements the encoding.BinaryMarshaler interface. + func (d *Digest) MarshalBinary() ([]byte, error) { + b := make([]byte, 0, marshaledSize) + b = append(b, magic...) + b = appendUint64(b, d.v1) + b = appendUint64(b, d.v2) + b = appendUint64(b, d.v3) + b = appendUint64(b, d.v4) + b = appendUint64(b, d.total) + b = append(b, d.mem[:d.n]...) + b = b[:len(b)+len(d.mem)-d.n] + return b, nil + } // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. + func (d *Digest) UnmarshalBinary(b []byte) error { + if len(b) < len(magic) || string(b[:len(magic)]) != magic { + return errors.New("xxhash: invalid hash state identifier") + } + if len(b) != marshaledSize { + return errors.New("xxhash: invalid hash state size") + } + b = b[len(magic):] + b, d.v1 = consumeUint64(b) + b, d.v2 = consumeUint64(b) + b, d.v3 = consumeUint64(b) + b, d.v4 = consumeUint64(b) + b, d.total = consumeUint64(b) + copy(d.mem[:], b) + d.n = int(d.total % uint64(len(d.mem))) + return nil + } func appendUint64(b []byte, x uint64) []byte { + var a [8]byte + binary.LittleEndian.PutUint64(a[:], x) + return append(b, a[:]...) + } func consumeUint64(b []byte) ([]byte, uint64) { + x := u64(b) + return b[8:], x + } func u64(b []byte) uint64 { return binary.LittleEndian.Uint64(b) } + func u32(b []byte) uint32 { return binary.LittleEndian.Uint32(b) } func round(acc, input uint64) uint64 { + acc += input * prime2 + acc = rol31(acc) + acc *= prime1 + return acc + } func mergeRound(acc, val uint64) uint64 { + val = round(0, val) + acc ^= val + acc = acc*prime1 + prime4 + return acc + } -func rol1(x uint64) uint64 { return bits.RotateLeft64(x, 1) } -func rol7(x uint64) uint64 { return bits.RotateLeft64(x, 7) } +func rol1(x uint64) uint64 { return bits.RotateLeft64(x, 1) } + +func rol7(x uint64) uint64 { return bits.RotateLeft64(x, 7) } + func rol11(x uint64) uint64 { return bits.RotateLeft64(x, 11) } + func rol12(x uint64) uint64 { return bits.RotateLeft64(x, 12) } + func rol18(x uint64) uint64 { return bits.RotateLeft64(x, 18) } + func rol23(x uint64) uint64 { return bits.RotateLeft64(x, 23) } + func rol27(x uint64) uint64 { return bits.RotateLeft64(x, 27) } + func rol31(x uint64) uint64 { return bits.RotateLeft64(x, 31) } diff --git a/vendor/github.com/davecgh/go-spew/spew/bypass.go b/vendor/github.com/davecgh/go-spew/spew/bypass.go index 70ddeaa..0fb4cac 100644 --- a/vendor/github.com/davecgh/go-spew/spew/bypass.go +++ b/vendor/github.com/davecgh/go-spew/spew/bypass.go @@ -1,23 +1,41 @@ // Copyright (c) 2015-2016 Dave Collins + // + // Permission to use, copy, modify, and distribute this software for any + // purpose with or without fee is hereby granted, provided that the above + // copyright notice and this permission notice appear in all copies. + // + // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // NOTE: Due to the following build constraints, this file will only be compiled + // when the code is not running on Google App Engine, compiled by GopherJS, and + // "-tags safe" is not added to the go build command line. The "disableunsafe" + // tag is deprecated and thus should not be used. + // Go versions prior to 1.4 are disabled because they use a different layout + // for interfaces which make the implementation of unsafeReflectValue more complex. + //go:build !js && !appengine && !safe && !disableunsafe && go1.4 // +build !js,!appengine,!safe,!disableunsafe,go1.4 @@ -29,118 +47,199 @@ import ( ) const ( + // UnsafeDisabled is a build-time constant which specifies whether or + // not access to the unsafe package is available. + UnsafeDisabled = false // ptrSize is the size of a pointer on the current arch. + ptrSize = unsafe.Sizeof((*byte)(nil)) ) type flag uintptr var ( + // flagRO indicates whether the value field of a reflect.Value + // is read-only. + flagRO flag // flagAddr indicates whether the address of the reflect.Value's + // value may be taken. + flagAddr flag ) // flagKindMask holds the bits that make up the kind + // part of the flags field. In all the supported versions, + // it is in the lower 5 bits. + const flagKindMask = flag(0x1f) // Different versions of Go have used different + // bit layouts for the flags type. This table + // records the known combinations. + var okFlags = []struct { ro, addr flag }{{ + // From Go 1.4 to 1.5 - ro: 1 << 5, + + ro: 1 << 5, + addr: 1 << 7, }, { + // Up to Go tip. - ro: 1<<5 | 1<<6, + + ro: 1<<5 | 1<<6, + addr: 1 << 8, }} var flagValOffset = func() uintptr { + field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") + if !ok { + panic("reflect.Value has no flag field") + } + return field.Offset + }() // flagField returns a pointer to the flag field of a reflect.Value. + func flagField(v *reflect.Value) *flag { + return (*flag)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + flagValOffset)) + } // unsafeReflectValue converts the passed reflect.Value into a one that bypasses + // the typical safety restrictions preventing access to unaddressable and + // unexported data. It works by digging the raw pointer to the underlying + // value out of the protected value and generating a new unprotected (unsafe) + // reflect.Value to it. + // + // This allows us to check for implementations of the Stringer and error + // interfaces to be used for pretty printing ordinarily unaddressable and + // inaccessible values such as unexported struct fields. + func unsafeReflectValue(v reflect.Value) reflect.Value { + if !v.IsValid() || (v.CanInterface() && v.CanAddr()) { + return v + } + flagFieldPtr := flagField(&v) + *flagFieldPtr &^= flagRO + *flagFieldPtr |= flagAddr + return v + } // Sanity checks against future reflect package changes + // to the type or semantics of the Value.flag field. + func init() { + field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") + if !ok { + panic("reflect.Value has no flag field") + } + if field.Type.Kind() != reflect.TypeOf(flag(0)).Kind() { + panic("reflect.Value flag field has changed kind") + } + type t0 int + var t struct { A t0 + // t0 will have flagEmbedRO set. + t0 + // a will have flagStickyRO set + a t0 } + vA := reflect.ValueOf(t).FieldByName("A") + va := reflect.ValueOf(t).FieldByName("a") + vt0 := reflect.ValueOf(t).FieldByName("t0") // Infer flagRO from the difference between the flags + // for the (otherwise identical) fields in t. + flagPublic := *flagField(&vA) + flagWithRO := *flagField(&va) | *flagField(&vt0) + flagRO = flagPublic ^ flagWithRO // Infer flagAddr from the difference between a value + // taken from a pointer and not. + vPtrA := reflect.ValueOf(&t).Elem().FieldByName("A") + flagNoPtr := *flagField(&vA) + flagPtr := *flagField(&vPtrA) + flagAddr = flagNoPtr ^ flagPtr // Check that the inferred flags tally with one of the known versions. + for _, f := range okFlags { + if flagRO == f.ro && flagAddr == f.addr { + return + } + } + panic("reflect.Value read-only flag has changed semantics") + } diff --git a/vendor/github.com/davecgh/go-spew/spew/common.go b/vendor/github.com/davecgh/go-spew/spew/common.go index 1be8ce9..1d5cd92 100644 --- a/vendor/github.com/davecgh/go-spew/spew/common.go +++ b/vendor/github.com/davecgh/go-spew/spew/common.go @@ -1,17 +1,31 @@ /* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ package spew @@ -26,316 +40,573 @@ import ( ) // Some constants in the form of bytes to avoid string overhead. This mirrors + // the technique used in the fmt package. + var ( - panicBytes = []byte("(PANIC=") - plusBytes = []byte("+") - iBytes = []byte("i") - trueBytes = []byte("true") - falseBytes = []byte("false") - interfaceBytes = []byte("(interface {})") - commaNewlineBytes = []byte(",\n") - newlineBytes = []byte("\n") - openBraceBytes = []byte("{") + panicBytes = []byte("(PANIC=") + + plusBytes = []byte("+") + + iBytes = []byte("i") + + trueBytes = []byte("true") + + falseBytes = []byte("false") + + interfaceBytes = []byte("(interface {})") + + commaNewlineBytes = []byte(",\n") + + newlineBytes = []byte("\n") + + openBraceBytes = []byte("{") + openBraceNewlineBytes = []byte("{\n") - closeBraceBytes = []byte("}") - asteriskBytes = []byte("*") - colonBytes = []byte(":") - colonSpaceBytes = []byte(": ") - openParenBytes = []byte("(") - closeParenBytes = []byte(")") - spaceBytes = []byte(" ") - pointerChainBytes = []byte("->") - nilAngleBytes = []byte("") - maxNewlineBytes = []byte("\n") - maxShortBytes = []byte("") - circularBytes = []byte("") - circularShortBytes = []byte("") - invalidAngleBytes = []byte("") - openBracketBytes = []byte("[") - closeBracketBytes = []byte("]") - percentBytes = []byte("%") - precisionBytes = []byte(".") - openAngleBytes = []byte("<") - closeAngleBytes = []byte(">") - openMapBytes = []byte("map[") - closeMapBytes = []byte("]") - lenEqualsBytes = []byte("len=") - capEqualsBytes = []byte("cap=") + + closeBraceBytes = []byte("}") + + asteriskBytes = []byte("*") + + colonBytes = []byte(":") + + colonSpaceBytes = []byte(": ") + + openParenBytes = []byte("(") + + closeParenBytes = []byte(")") + + spaceBytes = []byte(" ") + + pointerChainBytes = []byte("->") + + nilAngleBytes = []byte("") + + maxNewlineBytes = []byte("\n") + + maxShortBytes = []byte("") + + circularBytes = []byte("") + + circularShortBytes = []byte("") + + invalidAngleBytes = []byte("") + + openBracketBytes = []byte("[") + + closeBracketBytes = []byte("]") + + percentBytes = []byte("%") + + precisionBytes = []byte(".") + + openAngleBytes = []byte("<") + + closeAngleBytes = []byte(">") + + openMapBytes = []byte("map[") + + closeMapBytes = []byte("]") + + lenEqualsBytes = []byte("len=") + + capEqualsBytes = []byte("cap=") ) // hexDigits is used to map a decimal value to a hex digit. + var hexDigits = "0123456789abcdef" // catchPanic handles any panics that might occur during the handleMethods + // calls. + func catchPanic(w io.Writer, v reflect.Value) { + if err := recover(); err != nil { + w.Write(panicBytes) + fmt.Fprintf(w, "%v", err) + w.Write(closeParenBytes) + } + } // handleMethods attempts to call the Error and String methods on the underlying + // type the passed reflect.Value represents and outputes the result to Writer w. + // + // It handles panics in any called methods by catching and displaying the error + // as the formatted value. + func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) { + // We need an interface to check if the type implements the error or + // Stringer interface. However, the reflect package won't give us an + // interface on certain things like unexported struct fields in order + // to enforce visibility rules. We use unsafe, when it's available, + // to bypass these restrictions since this package does not mutate the + // values. + if !v.CanInterface() { + if UnsafeDisabled { + return false + } v = unsafeReflectValue(v) + } // Choose whether or not to do error and Stringer interface lookups against + // the base type or a pointer to the base type depending on settings. + // Technically calling one of these methods with a pointer receiver can + // mutate the value, however, types which choose to satisify an error or + // Stringer interface with a pointer receiver should not be mutating their + // state inside these interface methods. + if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() { + v = unsafeReflectValue(v) + } + if v.CanAddr() { + v = v.Addr() + } // Is it an error or Stringer? + switch iface := v.Interface().(type) { + case error: + defer catchPanic(w, v) + if cs.ContinueOnMethod { + w.Write(openParenBytes) + w.Write([]byte(iface.Error())) + w.Write(closeParenBytes) + w.Write(spaceBytes) + return false + } w.Write([]byte(iface.Error())) + return true case fmt.Stringer: + defer catchPanic(w, v) + if cs.ContinueOnMethod { + w.Write(openParenBytes) + w.Write([]byte(iface.String())) + w.Write(closeParenBytes) + w.Write(spaceBytes) + return false + } + w.Write([]byte(iface.String())) + return true + } + return false + } // printBool outputs a boolean value as true or false to Writer w. + func printBool(w io.Writer, val bool) { + if val { + w.Write(trueBytes) + } else { + w.Write(falseBytes) + } + } // printInt outputs a signed integer value to Writer w. + func printInt(w io.Writer, val int64, base int) { + w.Write([]byte(strconv.FormatInt(val, base))) + } // printUint outputs an unsigned integer value to Writer w. + func printUint(w io.Writer, val uint64, base int) { + w.Write([]byte(strconv.FormatUint(val, base))) + } // printFloat outputs a floating point value using the specified precision, + // which is expected to be 32 or 64bit, to Writer w. + func printFloat(w io.Writer, val float64, precision int) { + w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision))) + } // printComplex outputs a complex value using the specified float precision + // for the real and imaginary parts to Writer w. + func printComplex(w io.Writer, c complex128, floatPrecision int) { + r := real(c) + w.Write(openParenBytes) + w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision))) + i := imag(c) + if i >= 0 { + w.Write(plusBytes) + } + w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision))) + w.Write(iBytes) + w.Write(closeParenBytes) + } // printHexPtr outputs a uintptr formatted as hexadecimal with a leading '0x' + // prefix to Writer w. + func printHexPtr(w io.Writer, p uintptr) { + // Null pointer. + num := uint64(p) + if num == 0 { + w.Write(nilAngleBytes) + return + } // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix + buf := make([]byte, 18) // It's simpler to construct the hex string right to left. + base := uint64(16) + i := len(buf) - 1 + for num >= base { + buf[i] = hexDigits[num%base] + num /= base + i-- + } + buf[i] = hexDigits[num] // Add '0x' prefix. + i-- + buf[i] = 'x' + i-- + buf[i] = '0' // Strip unused leading bytes. + buf = buf[i:] + w.Write(buf) + } // valuesSorter implements sort.Interface to allow a slice of reflect.Value + // elements to be sorted. + type valuesSorter struct { - values []reflect.Value + values []reflect.Value + strings []string // either nil or same len and values - cs *ConfigState + + cs *ConfigState } // newValuesSorter initializes a valuesSorter instance, which holds a set of + // surrogate keys on which the data should be sorted. It uses flags in + // ConfigState to decide if and how to populate those surrogate keys. + func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface { + vs := &valuesSorter{values: values, cs: cs} + if canSortSimply(vs.values[0].Kind()) { + return vs + } + if !cs.DisableMethods { + vs.strings = make([]string, len(values)) + for i := range vs.values { + b := bytes.Buffer{} + if !handleMethods(cs, &b, vs.values[i]) { + vs.strings = nil + break + } + vs.strings[i] = b.String() + } + } + if vs.strings == nil && cs.SpewKeys { + vs.strings = make([]string, len(values)) + for i := range vs.values { + vs.strings[i] = Sprintf("%#v", vs.values[i].Interface()) + } + } + return vs + } // canSortSimply tests whether a reflect.Kind is a primitive that can be sorted + // directly, or whether it should be considered for sorting by surrogate keys + // (if the ConfigState allows it). + func canSortSimply(kind reflect.Kind) bool { + // This switch parallels valueSortLess, except for the default case. + switch kind { + case reflect.Bool: + return true + case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + return true + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + return true + case reflect.Float32, reflect.Float64: + return true + case reflect.String: + return true + case reflect.Uintptr: + return true + case reflect.Array: + return true + } + return false + } // Len returns the number of values in the slice. It is part of the + // sort.Interface implementation. + func (s *valuesSorter) Len() int { + return len(s.values) + } // Swap swaps the values at the passed indices. It is part of the + // sort.Interface implementation. + func (s *valuesSorter) Swap(i, j int) { + s.values[i], s.values[j] = s.values[j], s.values[i] + if s.strings != nil { + s.strings[i], s.strings[j] = s.strings[j], s.strings[i] + } + } // valueSortLess returns whether the first value should sort before the second + // value. It is used by valueSorter.Less as part of the sort.Interface + // implementation. + func valueSortLess(a, b reflect.Value) bool { + switch a.Kind() { + case reflect.Bool: + return !a.Bool() && b.Bool() + case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + return a.Int() < b.Int() + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + return a.Uint() < b.Uint() + case reflect.Float32, reflect.Float64: + return a.Float() < b.Float() + case reflect.String: + return a.String() < b.String() + case reflect.Uintptr: + return a.Uint() < b.Uint() + case reflect.Array: + // Compare the contents of both arrays. + l := a.Len() + for i := 0; i < l; i++ { + av := a.Index(i) + bv := b.Index(i) + if av.Interface() == bv.Interface() { + continue + } + return valueSortLess(av, bv) + } + } + return a.String() < b.String() + } // Less returns whether the value at index i should sort before the + // value at index j. It is part of the sort.Interface implementation. + func (s *valuesSorter) Less(i, j int) bool { + if s.strings == nil { + return valueSortLess(s.values[i], s.values[j]) + } + return s.strings[i] < s.strings[j] + } // sortValues is a sort function that handles both native types and any type that + // can be converted to error or Stringer. Other inputs are sorted according to + // their Value.String() value to ensure display stability. + func sortValues(values []reflect.Value, cs *ConfigState) { + if len(values) == 0 { + return + } + sort.Sort(newValuesSorter(values, cs)) + } diff --git a/vendor/github.com/davecgh/go-spew/spew/config.go b/vendor/github.com/davecgh/go-spew/spew/config.go index 161895f..4657790 100644 --- a/vendor/github.com/davecgh/go-spew/spew/config.go +++ b/vendor/github.com/davecgh/go-spew/spew/config.go @@ -1,17 +1,31 @@ /* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ package spew @@ -24,283 +38,512 @@ import ( ) // ConfigState houses the configuration options used by spew to format and + // display values. There is a global instance, Config, that is used to control + // all top-level Formatter and Dump functionality. Each ConfigState instance + // provides methods equivalent to the top-level functions. + // + // The zero value for ConfigState provides no indentation. You would typically + // want to set it to a space or a tab. + // + // Alternatively, you can use NewDefaultConfig to get a ConfigState instance + // with default settings. See the documentation of NewDefaultConfig for default + // values. + type ConfigState struct { + // Indent specifies the string to use for each indentation level. The + // global config instance that all top-level functions use set this to a + // single space by default. If you would like more indentation, you might + // set this to a tab with "\t" or perhaps two spaces with " ". + Indent string // MaxDepth controls the maximum number of levels to descend into nested + // data structures. The default, 0, means there is no limit. + // + // NOTE: Circular data structures are properly detected, so it is not + // necessary to set this value unless you specifically want to limit deeply + // nested data structures. + MaxDepth int // DisableMethods specifies whether or not error and Stringer interfaces are + // invoked for types that implement them. + DisableMethods bool // DisablePointerMethods specifies whether or not to check for and invoke + // error and Stringer interfaces on types which only accept a pointer + // receiver when the current type is not a pointer. + // + // NOTE: This might be an unsafe action since calling one of these methods + // with a pointer receiver could technically mutate the value, however, + // in practice, types which choose to satisify an error or Stringer + // interface with a pointer receiver should not be mutating their state + // inside these interface methods. As a result, this option relies on + // access to the unsafe package, so it will not have any effect when + // running in environments without access to the unsafe package such as + // Google App Engine or with the "safe" build tag specified. + DisablePointerMethods bool // DisablePointerAddresses specifies whether to disable the printing of + // pointer addresses. This is useful when diffing data structures in tests. + DisablePointerAddresses bool // DisableCapacities specifies whether to disable the printing of capacities + // for arrays, slices, maps and channels. This is useful when diffing + // data structures in tests. + DisableCapacities bool // ContinueOnMethod specifies whether or not recursion should continue once + // a custom error or Stringer interface is invoked. The default, false, + // means it will print the results of invoking the custom error or Stringer + // interface and return immediately instead of continuing to recurse into + // the internals of the data type. + // + // NOTE: This flag does not have any effect if method invocation is disabled + // via the DisableMethods or DisablePointerMethods options. + ContinueOnMethod bool // SortKeys specifies map keys should be sorted before being printed. Use + // this to have a more deterministic, diffable output. Note that only + // native types (bool, int, uint, floats, uintptr and string) and types + // that support the error or Stringer interfaces (if methods are + // enabled) are supported, with other types sorted according to the + // reflect.Value.String() output which guarantees display stability. + SortKeys bool // SpewKeys specifies that, as a last resort attempt, map keys should + // be spewed to strings and sorted by those strings. This is only + // considered if SortKeys is true. + SpewKeys bool } // Config is the active configuration of the top-level functions. + // The configuration can be changed by modifying the contents of spew.Config. + var Config = ConfigState{Indent: " "} // Errorf is a wrapper for fmt.Errorf that treats each argument as if it were + // passed with a Formatter interface returned by c.NewFormatter. It returns + // the formatted string as a value that satisfies error. See NewFormatter + // for formatting details. + // + // This function is shorthand for the following syntax: + // + // fmt.Errorf(format, c.NewFormatter(a), c.NewFormatter(b)) + func (c *ConfigState) Errorf(format string, a ...interface{}) (err error) { + return fmt.Errorf(format, c.convertArgs(a)...) + } // Fprint is a wrapper for fmt.Fprint that treats each argument as if it were + // passed with a Formatter interface returned by c.NewFormatter. It returns + // the number of bytes written and any write error encountered. See + // NewFormatter for formatting details. + // + // This function is shorthand for the following syntax: + // + // fmt.Fprint(w, c.NewFormatter(a), c.NewFormatter(b)) + func (c *ConfigState) Fprint(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprint(w, c.convertArgs(a)...) + } // Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were + // passed with a Formatter interface returned by c.NewFormatter. It returns + // the number of bytes written and any write error encountered. See + // NewFormatter for formatting details. + // + // This function is shorthand for the following syntax: + // + // fmt.Fprintf(w, format, c.NewFormatter(a), c.NewFormatter(b)) + func (c *ConfigState) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { + return fmt.Fprintf(w, format, c.convertArgs(a)...) + } // Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it + // passed with a Formatter interface returned by c.NewFormatter. See + // NewFormatter for formatting details. + // + // This function is shorthand for the following syntax: + // + // fmt.Fprintln(w, c.NewFormatter(a), c.NewFormatter(b)) + func (c *ConfigState) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprintln(w, c.convertArgs(a)...) + } // Print is a wrapper for fmt.Print that treats each argument as if it were + // passed with a Formatter interface returned by c.NewFormatter. It returns + // the number of bytes written and any write error encountered. See + // NewFormatter for formatting details. + // + // This function is shorthand for the following syntax: + // + // fmt.Print(c.NewFormatter(a), c.NewFormatter(b)) + func (c *ConfigState) Print(a ...interface{}) (n int, err error) { + return fmt.Print(c.convertArgs(a)...) + } // Printf is a wrapper for fmt.Printf that treats each argument as if it were + // passed with a Formatter interface returned by c.NewFormatter. It returns + // the number of bytes written and any write error encountered. See + // NewFormatter for formatting details. + // + // This function is shorthand for the following syntax: + // + // fmt.Printf(format, c.NewFormatter(a), c.NewFormatter(b)) + func (c *ConfigState) Printf(format string, a ...interface{}) (n int, err error) { + return fmt.Printf(format, c.convertArgs(a)...) + } // Println is a wrapper for fmt.Println that treats each argument as if it were + // passed with a Formatter interface returned by c.NewFormatter. It returns + // the number of bytes written and any write error encountered. See + // NewFormatter for formatting details. + // + // This function is shorthand for the following syntax: + // + // fmt.Println(c.NewFormatter(a), c.NewFormatter(b)) + func (c *ConfigState) Println(a ...interface{}) (n int, err error) { + return fmt.Println(c.convertArgs(a)...) + } // Sprint is a wrapper for fmt.Sprint that treats each argument as if it were + // passed with a Formatter interface returned by c.NewFormatter. It returns + // the resulting string. See NewFormatter for formatting details. + // + // This function is shorthand for the following syntax: + // + // fmt.Sprint(c.NewFormatter(a), c.NewFormatter(b)) + func (c *ConfigState) Sprint(a ...interface{}) string { + return fmt.Sprint(c.convertArgs(a)...) + } // Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were + // passed with a Formatter interface returned by c.NewFormatter. It returns + // the resulting string. See NewFormatter for formatting details. + // + // This function is shorthand for the following syntax: + // + // fmt.Sprintf(format, c.NewFormatter(a), c.NewFormatter(b)) + func (c *ConfigState) Sprintf(format string, a ...interface{}) string { + return fmt.Sprintf(format, c.convertArgs(a)...) + } // Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it + // were passed with a Formatter interface returned by c.NewFormatter. It + // returns the resulting string. See NewFormatter for formatting details. + // + // This function is shorthand for the following syntax: + // + // fmt.Sprintln(c.NewFormatter(a), c.NewFormatter(b)) + func (c *ConfigState) Sprintln(a ...interface{}) string { + return fmt.Sprintln(c.convertArgs(a)...) + } /* + NewFormatter returns a custom formatter that satisfies the fmt.Formatter + interface. As a result, it integrates cleanly with standard fmt package + printing functions. The formatter is useful for inline printing of smaller data + types similar to the standard %v format specifier. + + The custom formatter only responds to the %v (most compact), %+v (adds pointer + addresses), %#v (adds types), and %#+v (adds types and pointer addresses) verb + combinations. Any other verbs such as %x and %q will be sent to the the + standard fmt package for formatting. In addition, the custom formatter ignores + the width and precision arguments (however they will still work on the format + specifiers not handled by the custom formatter). + + Typically this function shouldn't be called directly. It is much easier to make + use of the custom formatter by calling one of the convenience functions such as + c.Printf, c.Println, or c.Printf. + */ + func (c *ConfigState) NewFormatter(v interface{}) fmt.Formatter { + return newFormatter(c, v) + } // Fdump formats and displays the passed arguments to io.Writer w. It formats + // exactly the same as Dump. + func (c *ConfigState) Fdump(w io.Writer, a ...interface{}) { + fdump(c, w, a...) + } /* + Dump displays the passed parameters to standard out with newlines, customizable + indentation, and additional debug information such as complete types and all + pointer addresses used to indirect to the final value. It provides the + following features over the built-in printing facilities provided by the fmt + package: + + - Pointers are dereferenced and followed + - Circular data structures are detected and handled properly + - Custom Stringer/error interfaces are optionally invoked, including + on unexported types + - Custom types which only implement the Stringer/error interfaces via + a pointer receiver are optionally invoked when passing non-pointer + variables + - Byte arrays and slices are dumped like the hexdump -C command which + includes offsets, byte values in hex, and ASCII output + + The configuration options are controlled by modifying the public members + of c. See ConfigState for options documentation. + + See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to + get the formatted result as a string. + */ + func (c *ConfigState) Dump(a ...interface{}) { + fdump(c, os.Stdout, a...) + } // Sdump returns a string with the passed arguments formatted exactly the same + // as Dump. + func (c *ConfigState) Sdump(a ...interface{}) string { + var buf bytes.Buffer + fdump(c, &buf, a...) + return buf.String() + } // convertArgs accepts a slice of arguments and returns a slice of the same + // length with each argument converted to a spew Formatter interface using + // the ConfigState associated with s. + func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{}) { + formatters = make([]interface{}, len(args)) + for index, arg := range args { + formatters[index] = newFormatter(c, arg) + } + return formatters + } // NewDefaultConfig returns a ConfigState with the following default settings. + // + // Indent: " " + // MaxDepth: 0 + // DisableMethods: false + // DisablePointerMethods: false + // ContinueOnMethod: false + // SortKeys: false + func NewDefaultConfig() *ConfigState { + return &ConfigState{Indent: " "} + } diff --git a/vendor/github.com/davecgh/go-spew/spew/dump.go b/vendor/github.com/davecgh/go-spew/spew/dump.go index 8323041..a104708 100644 --- a/vendor/github.com/davecgh/go-spew/spew/dump.go +++ b/vendor/github.com/davecgh/go-spew/spew/dump.go @@ -1,17 +1,31 @@ /* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ package spew @@ -29,481 +43,854 @@ import ( ) var ( + // uint8Type is a reflect.Type representing a uint8. It is used to + // convert cgo types to uint8 slices for hexdumping. + uint8Type = reflect.TypeOf(uint8(0)) // cCharRE is a regular expression that matches a cgo char. + // It is used to detect character arrays to hexdump them. + cCharRE = regexp.MustCompile(`^.*\._Ctype_char$`) // cUnsignedCharRE is a regular expression that matches a cgo unsigned + // char. It is used to detect unsigned character arrays to hexdump + // them. + cUnsignedCharRE = regexp.MustCompile(`^.*\._Ctype_unsignedchar$`) // cUint8tCharRE is a regular expression that matches a cgo uint8_t. + // It is used to detect uint8_t arrays to hexdump them. + cUint8tCharRE = regexp.MustCompile(`^.*\._Ctype_uint8_t$`) ) // dumpState contains information about the state of a dump operation. + type dumpState struct { - w io.Writer - depth int - pointers map[uintptr]int - ignoreNextType bool + w io.Writer + + depth int + + pointers map[uintptr]int + + ignoreNextType bool + ignoreNextIndent bool - cs *ConfigState + + cs *ConfigState } // indent performs indentation according to the depth level and cs.Indent + // option. + func (d *dumpState) indent() { + if d.ignoreNextIndent { + d.ignoreNextIndent = false + return + } + d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth)) + } // unpackValue returns values inside of non-nil interfaces when possible. + // This is useful for data types like structs, arrays, slices, and maps which + // can contain varying types packed inside an interface. + func (d *dumpState) unpackValue(v reflect.Value) reflect.Value { + if v.Kind() == reflect.Interface && !v.IsNil() { + v = v.Elem() + } + return v + } // dumpPtr handles formatting of pointers by indirecting them as necessary. + func (d *dumpState) dumpPtr(v reflect.Value) { + // Remove pointers at or below the current depth from map used to detect + // circular refs. + for k, depth := range d.pointers { + if depth >= d.depth { + delete(d.pointers, k) + } + } // Keep list of all dereferenced pointers to show later. + pointerChain := make([]uintptr, 0) // Figure out how many levels of indirection there are by dereferencing + // pointers and unpacking interfaces down the chain while detecting circular + // references. + nilFound := false + cycleFound := false + indirects := 0 + ve := v + for ve.Kind() == reflect.Ptr { + if ve.IsNil() { + nilFound = true + break + } + indirects++ + addr := ve.Pointer() + pointerChain = append(pointerChain, addr) + if pd, ok := d.pointers[addr]; ok && pd < d.depth { + cycleFound = true + indirects-- + break + } + d.pointers[addr] = d.depth ve = ve.Elem() + if ve.Kind() == reflect.Interface { + if ve.IsNil() { + nilFound = true + break + } + ve = ve.Elem() + } + } // Display type information. + d.w.Write(openParenBytes) + d.w.Write(bytes.Repeat(asteriskBytes, indirects)) + d.w.Write([]byte(ve.Type().String())) + d.w.Write(closeParenBytes) // Display pointer information. + if !d.cs.DisablePointerAddresses && len(pointerChain) > 0 { + d.w.Write(openParenBytes) + for i, addr := range pointerChain { + if i > 0 { + d.w.Write(pointerChainBytes) + } + printHexPtr(d.w, addr) + } + d.w.Write(closeParenBytes) + } // Display dereferenced value. + d.w.Write(openParenBytes) + switch { + case nilFound: + d.w.Write(nilAngleBytes) case cycleFound: + d.w.Write(circularBytes) default: + d.ignoreNextType = true + d.dump(ve) + } + d.w.Write(closeParenBytes) + } // dumpSlice handles formatting of arrays and slices. Byte (uint8 under + // reflection) arrays and slices are dumped in hexdump -C fashion. + func (d *dumpState) dumpSlice(v reflect.Value) { + // Determine whether this type should be hex dumped or not. Also, + // for types which should be hexdumped, try to use the underlying data + // first, then fall back to trying to convert them to a uint8 slice. + var buf []uint8 + doConvert := false + doHexDump := false + numEntries := v.Len() + if numEntries > 0 { + vt := v.Index(0).Type() + vts := vt.String() + switch { + // C types that need to be converted. + case cCharRE.MatchString(vts): + fallthrough + case cUnsignedCharRE.MatchString(vts): + fallthrough + case cUint8tCharRE.MatchString(vts): + doConvert = true // Try to use existing uint8 slices and fall back to converting + // and copying if that fails. + case vt.Kind() == reflect.Uint8: + // We need an addressable interface to convert the type + // to a byte slice. However, the reflect package won't + // give us an interface on certain things like + // unexported struct fields in order to enforce + // visibility rules. We use unsafe, when available, to + // bypass these restrictions since this package does not + // mutate the values. + vs := v + if !vs.CanInterface() || !vs.CanAddr() { + vs = unsafeReflectValue(vs) + } + if !UnsafeDisabled { + vs = vs.Slice(0, numEntries) // Use the existing uint8 slice if it can be + // type asserted. + iface := vs.Interface() + if slice, ok := iface.([]uint8); ok { + buf = slice + doHexDump = true + break + } + } // The underlying data needs to be converted if it can't + // be type asserted to a uint8 slice. + doConvert = true + } // Copy and convert the underlying type if needed. + if doConvert && vt.ConvertibleTo(uint8Type) { + // Convert and copy each element into a uint8 byte + // slice. + buf = make([]uint8, numEntries) + for i := 0; i < numEntries; i++ { + vv := v.Index(i) + buf[i] = uint8(vv.Convert(uint8Type).Uint()) + } + doHexDump = true + } + } // Hexdump the entire slice as needed. + if doHexDump { + indent := strings.Repeat(d.cs.Indent, d.depth) + str := indent + hex.Dump(buf) + str = strings.Replace(str, "\n", "\n"+indent, -1) + str = strings.TrimRight(str, d.cs.Indent) + d.w.Write([]byte(str)) + return + } // Recursively call dump for each item. + for i := 0; i < numEntries; i++ { + d.dump(d.unpackValue(v.Index(i))) + if i < (numEntries - 1) { + d.w.Write(commaNewlineBytes) + } else { + d.w.Write(newlineBytes) + } + } + } // dump is the main workhorse for dumping a value. It uses the passed reflect + // value to figure out what kind of object we are dealing with and formats it + // appropriately. It is a recursive function, however circular data structures + // are detected and handled properly. + func (d *dumpState) dump(v reflect.Value) { + // Handle invalid reflect values immediately. + kind := v.Kind() + if kind == reflect.Invalid { + d.w.Write(invalidAngleBytes) + return + } // Handle pointers specially. + if kind == reflect.Ptr { + d.indent() + d.dumpPtr(v) + return + } // Print type information unless already handled elsewhere. + if !d.ignoreNextType { + d.indent() + d.w.Write(openParenBytes) + d.w.Write([]byte(v.Type().String())) + d.w.Write(closeParenBytes) + d.w.Write(spaceBytes) + } + d.ignoreNextType = false // Display length and capacity if the built-in len and cap functions + // work with the value's kind and the len/cap itself is non-zero. + valueLen, valueCap := 0, 0 + switch v.Kind() { + case reflect.Array, reflect.Slice, reflect.Chan: + valueLen, valueCap = v.Len(), v.Cap() + case reflect.Map, reflect.String: + valueLen = v.Len() + } + if valueLen != 0 || !d.cs.DisableCapacities && valueCap != 0 { + d.w.Write(openParenBytes) + if valueLen != 0 { + d.w.Write(lenEqualsBytes) + printInt(d.w, int64(valueLen), 10) + } + if !d.cs.DisableCapacities && valueCap != 0 { + if valueLen != 0 { + d.w.Write(spaceBytes) + } + d.w.Write(capEqualsBytes) + printInt(d.w, int64(valueCap), 10) + } + d.w.Write(closeParenBytes) + d.w.Write(spaceBytes) + } // Call Stringer/error interfaces if they exist and the handle methods flag + // is enabled + if !d.cs.DisableMethods { + if (kind != reflect.Invalid) && (kind != reflect.Interface) { + if handled := handleMethods(d.cs, d.w, v); handled { + return + } + } + } switch kind { + case reflect.Invalid: + // Do nothing. We should never get here since invalid has already + // been handled above. case reflect.Bool: + printBool(d.w, v.Bool()) case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + printInt(d.w, v.Int(), 10) case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + printUint(d.w, v.Uint(), 10) case reflect.Float32: + printFloat(d.w, v.Float(), 32) case reflect.Float64: + printFloat(d.w, v.Float(), 64) case reflect.Complex64: + printComplex(d.w, v.Complex(), 32) case reflect.Complex128: + printComplex(d.w, v.Complex(), 64) case reflect.Slice: + if v.IsNil() { + d.w.Write(nilAngleBytes) + break + } + fallthrough case reflect.Array: + d.w.Write(openBraceNewlineBytes) + d.depth++ + if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { + d.indent() + d.w.Write(maxNewlineBytes) + } else { + d.dumpSlice(v) + } + d.depth-- + d.indent() + d.w.Write(closeBraceBytes) case reflect.String: + d.w.Write([]byte(strconv.Quote(v.String()))) case reflect.Interface: + // The only time we should get here is for nil interfaces due to + // unpackValue calls. + if v.IsNil() { + d.w.Write(nilAngleBytes) + } case reflect.Ptr: + // Do nothing. We should never get here since pointers have already + // been handled above. case reflect.Map: + // nil maps should be indicated as different than empty maps + if v.IsNil() { + d.w.Write(nilAngleBytes) + break + } d.w.Write(openBraceNewlineBytes) + d.depth++ + if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { + d.indent() + d.w.Write(maxNewlineBytes) + } else { + numEntries := v.Len() + keys := v.MapKeys() + if d.cs.SortKeys { + sortValues(keys, d.cs) + } + for i, key := range keys { + d.dump(d.unpackValue(key)) + d.w.Write(colonSpaceBytes) + d.ignoreNextIndent = true + d.dump(d.unpackValue(v.MapIndex(key))) + if i < (numEntries - 1) { + d.w.Write(commaNewlineBytes) + } else { + d.w.Write(newlineBytes) + } + } + } + d.depth-- + d.indent() + d.w.Write(closeBraceBytes) case reflect.Struct: + d.w.Write(openBraceNewlineBytes) + d.depth++ + if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { + d.indent() + d.w.Write(maxNewlineBytes) + } else { + vt := v.Type() + numFields := v.NumField() + for i := 0; i < numFields; i++ { + d.indent() + vtf := vt.Field(i) + d.w.Write([]byte(vtf.Name)) + d.w.Write(colonSpaceBytes) + d.ignoreNextIndent = true + d.dump(d.unpackValue(v.Field(i))) + if i < (numFields - 1) { + d.w.Write(commaNewlineBytes) + } else { + d.w.Write(newlineBytes) + } + } + } + d.depth-- + d.indent() + d.w.Write(closeBraceBytes) case reflect.Uintptr: + printHexPtr(d.w, uintptr(v.Uint())) case reflect.UnsafePointer, reflect.Chan, reflect.Func: + printHexPtr(d.w, v.Pointer()) // There were not any other types at the time this code was written, but + // fall back to letting the default fmt package handle it in case any new + // types are added. + default: + if v.CanInterface() { + fmt.Fprintf(d.w, "%v", v.Interface()) + } else { + fmt.Fprintf(d.w, "%v", v.String()) + } + } + } // fdump is a helper function to consolidate the logic from the various public + // methods which take varying writers and config states. + func fdump(cs *ConfigState, w io.Writer, a ...interface{}) { + for _, arg := range a { + if arg == nil { + w.Write(interfaceBytes) + w.Write(spaceBytes) + w.Write(nilAngleBytes) + w.Write(newlineBytes) + continue + } d := dumpState{w: w, cs: cs} + d.pointers = make(map[uintptr]int) + d.dump(reflect.ValueOf(arg)) + d.w.Write(newlineBytes) + } + } // Fdump formats and displays the passed arguments to io.Writer w. It formats + // exactly the same as Dump. + func Fdump(w io.Writer, a ...interface{}) { + fdump(&Config, w, a...) + } // Sdump returns a string with the passed arguments formatted exactly the same + // as Dump. + func Sdump(a ...interface{}) string { + var buf bytes.Buffer + fdump(&Config, &buf, a...) + return buf.String() + } /* + Dump displays the passed parameters to standard out with newlines, customizable + indentation, and additional debug information such as complete types and all + pointer addresses used to indirect to the final value. It provides the + following features over the built-in printing facilities provided by the fmt + package: + + - Pointers are dereferenced and followed + - Circular data structures are detected and handled properly + - Custom Stringer/error interfaces are optionally invoked, including + on unexported types + - Custom types which only implement the Stringer/error interfaces via + a pointer receiver are optionally invoked when passing non-pointer + variables + - Byte arrays and slices are dumped like the hexdump -C command which + includes offsets, byte values in hex, and ASCII output + + The configuration options are controlled by an exported package global, + spew.Config. See ConfigState for options documentation. + + See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to + get the formatted result as a string. + */ + func Dump(a ...interface{}) { + fdump(&Config, os.Stdout, a...) + } diff --git a/vendor/github.com/davecgh/go-spew/spew/format.go b/vendor/github.com/davecgh/go-spew/spew/format.go index b04edb7..983dd68 100644 --- a/vendor/github.com/davecgh/go-spew/spew/format.go +++ b/vendor/github.com/davecgh/go-spew/spew/format.go @@ -1,17 +1,31 @@ /* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ package spew @@ -25,395 +39,683 @@ import ( ) // supportedFlags is a list of all the character flags supported by fmt package. + const supportedFlags = "0-+# " // formatState implements the fmt.Formatter interface and contains information + // about the state of a formatting operation. The NewFormatter function can + // be used to get a new Formatter which can be used directly as arguments + // in standard fmt package printing calls. + type formatState struct { - value interface{} - fs fmt.State - depth int - pointers map[uintptr]int + value interface{} + + fs fmt.State + + depth int + + pointers map[uintptr]int + ignoreNextType bool - cs *ConfigState + + cs *ConfigState } // buildDefaultFormat recreates the original format string without precision + // and width information to pass in to fmt.Sprintf in the case of an + // unrecognized type. Unless new types are added to the language, this + // function won't ever be called. + func (f *formatState) buildDefaultFormat() (format string) { + buf := bytes.NewBuffer(percentBytes) for _, flag := range supportedFlags { + if f.fs.Flag(int(flag)) { + buf.WriteRune(flag) + } + } buf.WriteRune('v') format = buf.String() + return format + } // constructOrigFormat recreates the original format string including precision + // and width information to pass along to the standard fmt package. This allows + // automatic deferral of all format strings this package doesn't support. + func (f *formatState) constructOrigFormat(verb rune) (format string) { + buf := bytes.NewBuffer(percentBytes) for _, flag := range supportedFlags { + if f.fs.Flag(int(flag)) { + buf.WriteRune(flag) + } + } if width, ok := f.fs.Width(); ok { + buf.WriteString(strconv.Itoa(width)) + } if precision, ok := f.fs.Precision(); ok { + buf.Write(precisionBytes) + buf.WriteString(strconv.Itoa(precision)) + } buf.WriteRune(verb) format = buf.String() + return format + } // unpackValue returns values inside of non-nil interfaces when possible and + // ensures that types for values which have been unpacked from an interface + // are displayed when the show types flag is also set. + // This is useful for data types like structs, arrays, slices, and maps which + // can contain varying types packed inside an interface. + func (f *formatState) unpackValue(v reflect.Value) reflect.Value { + if v.Kind() == reflect.Interface { + f.ignoreNextType = false + if !v.IsNil() { + v = v.Elem() + } + } + return v + } // formatPtr handles formatting of pointers by indirecting them as necessary. + func (f *formatState) formatPtr(v reflect.Value) { + // Display nil if top level pointer is nil. + showTypes := f.fs.Flag('#') + if v.IsNil() && (!showTypes || f.ignoreNextType) { + f.fs.Write(nilAngleBytes) + return + } // Remove pointers at or below the current depth from map used to detect + // circular refs. + for k, depth := range f.pointers { + if depth >= f.depth { + delete(f.pointers, k) + } + } // Keep list of all dereferenced pointers to possibly show later. + pointerChain := make([]uintptr, 0) // Figure out how many levels of indirection there are by derferencing + // pointers and unpacking interfaces down the chain while detecting circular + // references. + nilFound := false + cycleFound := false + indirects := 0 + ve := v + for ve.Kind() == reflect.Ptr { + if ve.IsNil() { + nilFound = true + break + } + indirects++ + addr := ve.Pointer() + pointerChain = append(pointerChain, addr) + if pd, ok := f.pointers[addr]; ok && pd < f.depth { + cycleFound = true + indirects-- + break + } + f.pointers[addr] = f.depth ve = ve.Elem() + if ve.Kind() == reflect.Interface { + if ve.IsNil() { + nilFound = true + break + } + ve = ve.Elem() + } + } // Display type or indirection level depending on flags. + if showTypes && !f.ignoreNextType { + f.fs.Write(openParenBytes) + f.fs.Write(bytes.Repeat(asteriskBytes, indirects)) + f.fs.Write([]byte(ve.Type().String())) + f.fs.Write(closeParenBytes) + } else { + if nilFound || cycleFound { + indirects += strings.Count(ve.Type().String(), "*") + } + f.fs.Write(openAngleBytes) + f.fs.Write([]byte(strings.Repeat("*", indirects))) + f.fs.Write(closeAngleBytes) + } // Display pointer information depending on flags. + if f.fs.Flag('+') && (len(pointerChain) > 0) { + f.fs.Write(openParenBytes) + for i, addr := range pointerChain { + if i > 0 { + f.fs.Write(pointerChainBytes) + } + printHexPtr(f.fs, addr) + } + f.fs.Write(closeParenBytes) + } // Display dereferenced value. + switch { + case nilFound: + f.fs.Write(nilAngleBytes) case cycleFound: + f.fs.Write(circularShortBytes) default: + f.ignoreNextType = true + f.format(ve) + } + } // format is the main workhorse for providing the Formatter interface. It + // uses the passed reflect value to figure out what kind of object we are + // dealing with and formats it appropriately. It is a recursive function, + // however circular data structures are detected and handled properly. + func (f *formatState) format(v reflect.Value) { + // Handle invalid reflect values immediately. + kind := v.Kind() + if kind == reflect.Invalid { + f.fs.Write(invalidAngleBytes) + return + } // Handle pointers specially. + if kind == reflect.Ptr { + f.formatPtr(v) + return + } // Print type information unless already handled elsewhere. + if !f.ignoreNextType && f.fs.Flag('#') { + f.fs.Write(openParenBytes) + f.fs.Write([]byte(v.Type().String())) + f.fs.Write(closeParenBytes) + } + f.ignoreNextType = false // Call Stringer/error interfaces if they exist and the handle methods + // flag is enabled. + if !f.cs.DisableMethods { + if (kind != reflect.Invalid) && (kind != reflect.Interface) { + if handled := handleMethods(f.cs, f.fs, v); handled { + return + } + } + } switch kind { + case reflect.Invalid: + // Do nothing. We should never get here since invalid has already + // been handled above. case reflect.Bool: + printBool(f.fs, v.Bool()) case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + printInt(f.fs, v.Int(), 10) case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + printUint(f.fs, v.Uint(), 10) case reflect.Float32: + printFloat(f.fs, v.Float(), 32) case reflect.Float64: + printFloat(f.fs, v.Float(), 64) case reflect.Complex64: + printComplex(f.fs, v.Complex(), 32) case reflect.Complex128: + printComplex(f.fs, v.Complex(), 64) case reflect.Slice: + if v.IsNil() { + f.fs.Write(nilAngleBytes) + break + } + fallthrough case reflect.Array: + f.fs.Write(openBracketBytes) + f.depth++ + if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { + f.fs.Write(maxShortBytes) + } else { + numEntries := v.Len() + for i := 0; i < numEntries; i++ { + if i > 0 { + f.fs.Write(spaceBytes) + } + f.ignoreNextType = true + f.format(f.unpackValue(v.Index(i))) + } + } + f.depth-- + f.fs.Write(closeBracketBytes) case reflect.String: + f.fs.Write([]byte(v.String())) case reflect.Interface: + // The only time we should get here is for nil interfaces due to + // unpackValue calls. + if v.IsNil() { + f.fs.Write(nilAngleBytes) + } case reflect.Ptr: + // Do nothing. We should never get here since pointers have already + // been handled above. case reflect.Map: + // nil maps should be indicated as different than empty maps + if v.IsNil() { + f.fs.Write(nilAngleBytes) + break + } f.fs.Write(openMapBytes) + f.depth++ + if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { + f.fs.Write(maxShortBytes) + } else { + keys := v.MapKeys() + if f.cs.SortKeys { + sortValues(keys, f.cs) + } + for i, key := range keys { + if i > 0 { + f.fs.Write(spaceBytes) + } + f.ignoreNextType = true + f.format(f.unpackValue(key)) + f.fs.Write(colonBytes) + f.ignoreNextType = true + f.format(f.unpackValue(v.MapIndex(key))) + } + } + f.depth-- + f.fs.Write(closeMapBytes) case reflect.Struct: + numFields := v.NumField() + f.fs.Write(openBraceBytes) + f.depth++ + if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { + f.fs.Write(maxShortBytes) + } else { + vt := v.Type() + for i := 0; i < numFields; i++ { + if i > 0 { + f.fs.Write(spaceBytes) + } + vtf := vt.Field(i) + if f.fs.Flag('+') || f.fs.Flag('#') { + f.fs.Write([]byte(vtf.Name)) + f.fs.Write(colonBytes) + } + f.format(f.unpackValue(v.Field(i))) + } + } + f.depth-- + f.fs.Write(closeBraceBytes) case reflect.Uintptr: + printHexPtr(f.fs, uintptr(v.Uint())) case reflect.UnsafePointer, reflect.Chan, reflect.Func: + printHexPtr(f.fs, v.Pointer()) // There were not any other types at the time this code was written, but + // fall back to letting the default fmt package handle it if any get added. + default: + format := f.buildDefaultFormat() + if v.CanInterface() { + fmt.Fprintf(f.fs, format, v.Interface()) + } else { + fmt.Fprintf(f.fs, format, v.String()) + } + } + } // Format satisfies the fmt.Formatter interface. See NewFormatter for usage + // details. + func (f *formatState) Format(fs fmt.State, verb rune) { + f.fs = fs // Use standard formatting for verbs that are not v. + if verb != 'v' { + format := f.constructOrigFormat(verb) + fmt.Fprintf(fs, format, f.value) + return + } if f.value == nil { + if fs.Flag('#') { + fs.Write(interfaceBytes) + } + fs.Write(nilAngleBytes) + return + } f.format(reflect.ValueOf(f.value)) + } // newFormatter is a helper function to consolidate the logic from the various + // public methods which take varying config states. + func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter { + fs := &formatState{value: v, cs: cs} + fs.pointers = make(map[uintptr]int) + return fs + } /* + NewFormatter returns a custom formatter that satisfies the fmt.Formatter + interface. As a result, it integrates cleanly with standard fmt package + printing functions. The formatter is useful for inline printing of smaller data + types similar to the standard %v format specifier. + + The custom formatter only responds to the %v (most compact), %+v (adds pointer + addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb + combinations. Any other verbs such as %x and %q will be sent to the the + standard fmt package for formatting. In addition, the custom formatter ignores + the width and precision arguments (however they will still work on the format + specifiers not handled by the custom formatter). + + Typically this function shouldn't be called directly. It is much easier to make + use of the custom formatter by calling one of the convenience functions such as + Printf, Println, or Fprintf. + */ + func NewFormatter(v interface{}) fmt.Formatter { + return newFormatter(&Config, v) + } diff --git a/vendor/github.com/davecgh/go-spew/spew/spew.go b/vendor/github.com/davecgh/go-spew/spew/spew.go index 32c0e33..1c6e12f 100644 --- a/vendor/github.com/davecgh/go-spew/spew/spew.go +++ b/vendor/github.com/davecgh/go-spew/spew/spew.go @@ -1,17 +1,31 @@ /* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ package spew @@ -22,127 +36,231 @@ import ( ) // Errorf is a wrapper for fmt.Errorf that treats each argument as if it were + // passed with a default Formatter interface returned by NewFormatter. It + // returns the formatted string as a value that satisfies error. See + // NewFormatter for formatting details. + // + // This function is shorthand for the following syntax: + // + // fmt.Errorf(format, spew.NewFormatter(a), spew.NewFormatter(b)) + func Errorf(format string, a ...interface{}) (err error) { + return fmt.Errorf(format, convertArgs(a)...) + } // Fprint is a wrapper for fmt.Fprint that treats each argument as if it were + // passed with a default Formatter interface returned by NewFormatter. It + // returns the number of bytes written and any write error encountered. See + // NewFormatter for formatting details. + // + // This function is shorthand for the following syntax: + // + // fmt.Fprint(w, spew.NewFormatter(a), spew.NewFormatter(b)) + func Fprint(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprint(w, convertArgs(a)...) + } // Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were + // passed with a default Formatter interface returned by NewFormatter. It + // returns the number of bytes written and any write error encountered. See + // NewFormatter for formatting details. + // + // This function is shorthand for the following syntax: + // + // fmt.Fprintf(w, format, spew.NewFormatter(a), spew.NewFormatter(b)) + func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { + return fmt.Fprintf(w, format, convertArgs(a)...) + } // Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it + // passed with a default Formatter interface returned by NewFormatter. See + // NewFormatter for formatting details. + // + // This function is shorthand for the following syntax: + // + // fmt.Fprintln(w, spew.NewFormatter(a), spew.NewFormatter(b)) + func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprintln(w, convertArgs(a)...) + } // Print is a wrapper for fmt.Print that treats each argument as if it were + // passed with a default Formatter interface returned by NewFormatter. It + // returns the number of bytes written and any write error encountered. See + // NewFormatter for formatting details. + // + // This function is shorthand for the following syntax: + // + // fmt.Print(spew.NewFormatter(a), spew.NewFormatter(b)) + func Print(a ...interface{}) (n int, err error) { + return fmt.Print(convertArgs(a)...) + } // Printf is a wrapper for fmt.Printf that treats each argument as if it were + // passed with a default Formatter interface returned by NewFormatter. It + // returns the number of bytes written and any write error encountered. See + // NewFormatter for formatting details. + // + // This function is shorthand for the following syntax: + // + // fmt.Printf(format, spew.NewFormatter(a), spew.NewFormatter(b)) + func Printf(format string, a ...interface{}) (n int, err error) { + return fmt.Printf(format, convertArgs(a)...) + } // Println is a wrapper for fmt.Println that treats each argument as if it were + // passed with a default Formatter interface returned by NewFormatter. It + // returns the number of bytes written and any write error encountered. See + // NewFormatter for formatting details. + // + // This function is shorthand for the following syntax: + // + // fmt.Println(spew.NewFormatter(a), spew.NewFormatter(b)) + func Println(a ...interface{}) (n int, err error) { + return fmt.Println(convertArgs(a)...) + } // Sprint is a wrapper for fmt.Sprint that treats each argument as if it were + // passed with a default Formatter interface returned by NewFormatter. It + // returns the resulting string. See NewFormatter for formatting details. + // + // This function is shorthand for the following syntax: + // + // fmt.Sprint(spew.NewFormatter(a), spew.NewFormatter(b)) + func Sprint(a ...interface{}) string { + return fmt.Sprint(convertArgs(a)...) + } // Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were + // passed with a default Formatter interface returned by NewFormatter. It + // returns the resulting string. See NewFormatter for formatting details. + // + // This function is shorthand for the following syntax: + // + // fmt.Sprintf(format, spew.NewFormatter(a), spew.NewFormatter(b)) + func Sprintf(format string, a ...interface{}) string { + return fmt.Sprintf(format, convertArgs(a)...) + } // Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it + // were passed with a default Formatter interface returned by NewFormatter. It + // returns the resulting string. See NewFormatter for formatting details. + // + // This function is shorthand for the following syntax: + // + // fmt.Sprintln(spew.NewFormatter(a), spew.NewFormatter(b)) + func Sprintln(a ...interface{}) string { + return fmt.Sprintln(convertArgs(a)...) + } // convertArgs accepts a slice of arguments and returns a slice of the same + // length with each argument converted to a default spew Formatter interface. + func convertArgs(args []interface{}) (formatters []interface{}) { + formatters = make([]interface{}, len(args)) + for index, arg := range args { + formatters[index] = NewFormatter(arg) + } + return formatters + } diff --git a/vendor/github.com/fatih/structs/field.go b/vendor/github.com/fatih/structs/field.go index 23270e0..45f11ec 100644 --- a/vendor/github.com/fatih/structs/field.go +++ b/vendor/github.com/fatih/structs/field.go @@ -8,134 +8,219 @@ import ( var ( errNotExported = errors.New("field is not exported") + errNotSettable = errors.New("field is not settable") ) // Field represents a single struct field that encapsulates high level + // functions around the field. + type Field struct { - value reflect.Value - field reflect.StructField + value reflect.Value + + field reflect.StructField + defaultTag string } // Tag returns the value associated with key in the tag string. If there is no + // such key in the tag, Tag returns the empty string. + func (f *Field) Tag(key string) string { + return f.field.Tag.Get(key) + } // Value returns the underlying value of the field. It panics if the field + // is not exported. + func (f *Field) Value() interface{} { + return f.value.Interface() + } // IsEmbedded returns true if the given field is an anonymous field (embedded) + func (f *Field) IsEmbedded() bool { + return f.field.Anonymous + } // IsExported returns true if the given field is exported. + func (f *Field) IsExported() bool { + return f.field.PkgPath == "" + } // IsZero returns true if the given field is not initialized (has a zero value). + // It panics if the field is not exported. + func (f *Field) IsZero() bool { + zero := reflect.Zero(f.value.Type()).Interface() + current := f.Value() return reflect.DeepEqual(current, zero) + } // Name returns the name of the given field + func (f *Field) Name() string { + return f.field.Name + } // Kind returns the fields kind, such as "string", "map", "bool", etc .. + func (f *Field) Kind() reflect.Kind { + return f.value.Kind() + } // Set sets the field to given value v. It returns an error if the field is not + // settable (not addressable or not exported) or if the given value's type + // doesn't match the fields type. + func (f *Field) Set(val interface{}) error { + // we can't set unexported fields, so be sure this field is exported + if !f.IsExported() { + return errNotExported + } // do we get here? not sure... + if !f.value.CanSet() { + return errNotSettable + } given := reflect.ValueOf(val) if f.value.Kind() != given.Kind() { + return fmt.Errorf("wrong kind. got: %s want: %s", given.Kind(), f.value.Kind()) + } f.value.Set(given) + return nil + } // Zero sets the field to its zero value. It returns an error if the field is not + // settable (not addressable or not exported). + func (f *Field) Zero() error { + zero := reflect.Zero(f.value.Type()).Interface() + return f.Set(zero) + } // Fields returns a slice of Fields. This is particular handy to get the fields + // of a nested struct . A struct tag with the content of "-" ignores the + // checking of that particular field. Example: + // + // // Field is ignored by this package. + // Field *http.Request `structs:"-"` + // + // It panics if field is not exported or if field's kind is not struct + func (f *Field) Fields() []*Field { + return getFields(f.value, f.defaultTag) + } // Field returns the field from a nested struct. It panics if the nested struct + // is not exported or if the field was not found. + func (f *Field) Field(name string) *Field { + field, ok := f.FieldOk(name) + if !ok { + panic("field not found") + } return field + } // FieldOk returns the field from a nested struct. The boolean returns whether + // the field was found (true) or not (false). + func (f *Field) FieldOk(name string) (*Field, bool) { + value := &f.value + // value must be settable so we need to make sure it holds the address of the + // variable and not a copy, so we can pass the pointer to strctVal instead of a + // copy (which is not assigned to any variable, hence not settable). + // see "https://blog.golang.org/laws-of-reflection#TOC_8." + if f.value.Kind() != reflect.Ptr { + a := f.value.Addr() + value = &a + } + v := strctVal(value.Interface()) + t := v.Type() field, ok := t.FieldByName(name) + if !ok { + return nil, false + } return &Field{ + field: field, + value: v.FieldByName(name), }, true + } diff --git a/vendor/github.com/fatih/structs/structs.go b/vendor/github.com/fatih/structs/structs.go index 7970aa0..aa2a2fc 100644 --- a/vendor/github.com/fatih/structs/structs.go +++ b/vendor/github.com/fatih/structs/structs.go @@ -1,4 +1,5 @@ // Package structs contains various utilities functions to work with structs. + package structs import ( @@ -7,243 +8,420 @@ import ( ) var ( + // DefaultTagName is the default tag name for struct fields which provides + // a more granular to tweak certain structs. Lookup the necessary functions + // for more info. + DefaultTagName = "structs" // struct's field default tag name + ) // Struct encapsulates a struct type to provide several high level functions + // around the struct. + type Struct struct { - raw interface{} - value reflect.Value + raw interface{} + + value reflect.Value + TagName string } // New returns a new *Struct with the struct s. It panics if the s's kind is + // not struct. + func New(s interface{}) *Struct { + return &Struct{ - raw: s, - value: strctVal(s), + + raw: s, + + value: strctVal(s), + TagName: DefaultTagName, } + } // Map converts the given struct to a map[string]interface{}, where the keys + // of the map are the field names and the values of the map the associated + // values of the fields. The default key string is the struct field name but + // can be changed in the struct field's tag value. The "structs" key in the + // struct's field tag value is the key name. Example: + // + // // Field appears in map as key "myName". + // Name string `structs:"myName"` + // + // A tag value with the content of "-" ignores that particular field. Example: + // + // // Field is ignored by this package. + // Field bool `structs:"-"` + // + // A tag value with the content of "string" uses the stringer to get the value. Example: + // + // // The value will be output of Animal's String() func. + // // Map will panic if Animal does not implement String(). + // Field *Animal `structs:"field,string"` + // + // A tag value with the option of "flatten" used in a struct field is to flatten its fields + // in the output map. Example: + // + // // The FieldStruct's fields will be flattened into the output map. + // FieldStruct time.Time `structs:",flatten"` + // + // A tag value with the option of "omitnested" stops iterating further if the type + // is a struct. Example: + // + // // Field is not processed further by this package. + // Field time.Time `structs:"myName,omitnested"` + // Field *http.Request `structs:",omitnested"` + // + // A tag value with the option of "omitempty" ignores that particular field if + // the field value is empty. Example: + // + // // Field appears in map as key "myName", but the field is + // // skipped if empty. + // Field string `structs:"myName,omitempty"` + // + // // Field appears in map as key "Field" (the default), but + // // the field is skipped if empty. + // Field string `structs:",omitempty"` + // + // Note that only exported fields of a struct can be accessed, non exported + // fields will be neglected. + func (s *Struct) Map() map[string]interface{} { + out := make(map[string]interface{}) + s.FillMap(out) + return out + } // FillMap is the same as Map. Instead of returning the output, it fills the + // given map. + func (s *Struct) FillMap(out map[string]interface{}) { + if out == nil { + return + } fields := s.structFields() for _, field := range fields { + name := field.Name + val := s.value.FieldByName(name) + isSubStruct := false + var finalVal interface{} tagName, tagOpts := parseTag(field.Tag.Get(s.TagName)) + if tagName != "" { + name = tagName + } // if the value is a zero value and the field is marked as omitempty do + // not include + if tagOpts.Has("omitempty") { + zero := reflect.Zero(val.Type()).Interface() + current := val.Interface() if reflect.DeepEqual(current, zero) { + continue + } + } if !tagOpts.Has("omitnested") { + finalVal = s.nested(val) v := reflect.ValueOf(val.Interface()) + if v.Kind() == reflect.Ptr { + v = v.Elem() + } switch v.Kind() { + case reflect.Map, reflect.Struct: + isSubStruct = true + } + } else { + finalVal = val.Interface() + } if tagOpts.Has("string") { + s, ok := val.Interface().(fmt.Stringer) + if ok { + out[name] = s.String() + } + continue + } if isSubStruct && (tagOpts.Has("flatten")) { + for k := range finalVal.(map[string]interface{}) { + out[k] = finalVal.(map[string]interface{})[k] + } + } else { + out[name] = finalVal + } + } + } // Values converts the given s struct's field values to a []interface{}. A + // struct tag with the content of "-" ignores the that particular field. + // Example: + // + // // Field is ignored by this package. + // Field int `structs:"-"` + // + // A value with the option of "omitnested" stops iterating further if the type + // is a struct. Example: + // + // // Fields is not processed further by this package. + // Field time.Time `structs:",omitnested"` + // Field *http.Request `structs:",omitnested"` + // + // A tag value with the option of "omitempty" ignores that particular field and + // is not added to the values if the field value is empty. Example: + // + // // Field is skipped if empty + // Field string `structs:",omitempty"` + // + // Note that only exported fields of a struct can be accessed, non exported + // fields will be neglected. + func (s *Struct) Values() []interface{} { + fields := s.structFields() var t []interface{} for _, field := range fields { + val := s.value.FieldByName(field.Name) _, tagOpts := parseTag(field.Tag.Get(s.TagName)) // if the value is a zero value and the field is marked as omitempty do + // not include + if tagOpts.Has("omitempty") { + zero := reflect.Zero(val.Type()).Interface() + current := val.Interface() if reflect.DeepEqual(current, zero) { + continue + } + } if tagOpts.Has("string") { + s, ok := val.Interface().(fmt.Stringer) + if ok { + t = append(t, s.String()) + } + continue + } if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") { + // look out for embedded structs, and convert them to a + // []interface{} to be added to the final values slice + t = append(t, Values(val.Interface())...) + } else { + t = append(t, val.Interface()) + } + } return t + } // Fields returns a slice of Fields. A struct tag with the content of "-" + // ignores the checking of that particular field. Example: + // + // // Field is ignored by this package. + // Field bool `structs:"-"` + // + // It panics if s's kind is not struct. + func (s *Struct) Fields() []*Field { + return getFields(s.value, s.TagName) + } // Names returns a slice of field names. A struct tag with the content of "-" + // ignores the checking of that particular field. Example: + // + // // Field is ignored by this package. + // Field bool `structs:"-"` + // + // It panics if s's kind is not struct. + func (s *Struct) Names() []string { + fields := getFields(s.value, s.TagName) names := make([]string, len(fields)) for i, field := range fields { + names[i] = field.Name() + } return names + } func getFields(v reflect.Value, tagName string) []*Field { + if v.Kind() == reflect.Ptr { + v = v.Elem() + } t := v.Type() @@ -251,14 +429,19 @@ func getFields(v reflect.Value, tagName string) []*Field { var fields []*Field for i := 0; i < t.NumField(); i++ { + field := t.Field(i) if tag := field.Tag.Get(tagName); tag == "-" { + continue + } f := &Field{ + field: field, + value: v.FieldByName(field.Name), } @@ -267,317 +450,522 @@ func getFields(v reflect.Value, tagName string) []*Field { } return fields + } // Field returns a new Field struct that provides several high level functions + // around a single struct field entity. It panics if the field is not found. + func (s *Struct) Field(name string) *Field { + f, ok := s.FieldOk(name) + if !ok { + panic("field not found") + } return f + } // FieldOk returns a new Field struct that provides several high level functions + // around a single struct field entity. The boolean returns true if the field + // was found. + func (s *Struct) FieldOk(name string) (*Field, bool) { + t := s.value.Type() field, ok := t.FieldByName(name) + if !ok { + return nil, false + } return &Field{ - field: field, - value: s.value.FieldByName(name), + + field: field, + + value: s.value.FieldByName(name), + defaultTag: s.TagName, }, true + } // IsZero returns true if all fields in a struct is a zero value (not + // initialized) A struct tag with the content of "-" ignores the checking of + // that particular field. Example: + // + // // Field is ignored by this package. + // Field bool `structs:"-"` + // + // A value with the option of "omitnested" stops iterating further if the type + // is a struct. Example: + // + // // Field is not processed further by this package. + // Field time.Time `structs:"myName,omitnested"` + // Field *http.Request `structs:",omitnested"` + // + // Note that only exported fields of a struct can be accessed, non exported + // fields will be neglected. It panics if s's kind is not struct. + func (s *Struct) IsZero() bool { + fields := s.structFields() for _, field := range fields { + val := s.value.FieldByName(field.Name) _, tagOpts := parseTag(field.Tag.Get(s.TagName)) if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") { + ok := IsZero(val.Interface()) + if !ok { + return false + } continue + } // zero value of the given field, such as "" for string, 0 for int + zero := reflect.Zero(val.Type()).Interface() // current value of the given field + current := val.Interface() if !reflect.DeepEqual(current, zero) { + return false + } + } return true + } // HasZero returns true if a field in a struct is not initialized (zero value). + // A struct tag with the content of "-" ignores the checking of that particular + // field. Example: + // + // // Field is ignored by this package. + // Field bool `structs:"-"` + // + // A value with the option of "omitnested" stops iterating further if the type + // is a struct. Example: + // + // // Field is not processed further by this package. + // Field time.Time `structs:"myName,omitnested"` + // Field *http.Request `structs:",omitnested"` + // + // Note that only exported fields of a struct can be accessed, non exported + // fields will be neglected. It panics if s's kind is not struct. + func (s *Struct) HasZero() bool { + fields := s.structFields() for _, field := range fields { + val := s.value.FieldByName(field.Name) _, tagOpts := parseTag(field.Tag.Get(s.TagName)) if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") { + ok := HasZero(val.Interface()) + if ok { + return true + } continue + } // zero value of the given field, such as "" for string, 0 for int + zero := reflect.Zero(val.Type()).Interface() // current value of the given field + current := val.Interface() if reflect.DeepEqual(current, zero) { + return true + } + } return false + } // Name returns the structs's type name within its package. For more info refer + // to Name() function. + func (s *Struct) Name() string { + return s.value.Type().Name() + } // structFields returns the exported struct fields for a given s struct. This + // is a convenient helper method to avoid duplicate code in some of the + // functions. + func (s *Struct) structFields() []reflect.StructField { + t := s.value.Type() var f []reflect.StructField for i := 0; i < t.NumField(); i++ { + field := t.Field(i) + // we can't access the value of unexported fields + if field.PkgPath != "" { + continue + } // don't check if it's omitted + if tag := field.Tag.Get(s.TagName); tag == "-" { + continue + } f = append(f, field) + } return f + } func strctVal(s interface{}) reflect.Value { + v := reflect.ValueOf(s) // if pointer get the underlying element≤ + for v.Kind() == reflect.Ptr { + v = v.Elem() + } if v.Kind() != reflect.Struct { + panic("not struct") + } return v + } // Map converts the given struct to a map[string]interface{}. For more info + // refer to Struct types Map() method. It panics if s's kind is not struct. + func Map(s interface{}) map[string]interface{} { + return New(s).Map() + } // FillMap is the same as Map. Instead of returning the output, it fills the + // given map. + func FillMap(s interface{}, out map[string]interface{}) { + New(s).FillMap(out) + } // Values converts the given struct to a []interface{}. For more info refer to + // Struct types Values() method. It panics if s's kind is not struct. + func Values(s interface{}) []interface{} { + return New(s).Values() + } // Fields returns a slice of *Field. For more info refer to Struct types + // Fields() method. It panics if s's kind is not struct. + func Fields(s interface{}) []*Field { + return New(s).Fields() + } // Names returns a slice of field names. For more info refer to Struct types + // Names() method. It panics if s's kind is not struct. + func Names(s interface{}) []string { + return New(s).Names() + } // IsZero returns true if all fields is equal to a zero value. For more info + // refer to Struct types IsZero() method. It panics if s's kind is not struct. + func IsZero(s interface{}) bool { + return New(s).IsZero() + } // HasZero returns true if any field is equal to a zero value. For more info + // refer to Struct types HasZero() method. It panics if s's kind is not struct. + func HasZero(s interface{}) bool { + return New(s).HasZero() + } // IsStruct returns true if the given variable is a struct or a pointer to + // struct. + func IsStruct(s interface{}) bool { + v := reflect.ValueOf(s) + if v.Kind() == reflect.Ptr { + v = v.Elem() + } // uninitialized zero value of a struct + if v.Kind() == reflect.Invalid { + return false + } return v.Kind() == reflect.Struct + } // Name returns the structs's type name within its package. It returns an + // empty string for unnamed types. It panics if s's kind is not struct. + func Name(s interface{}) string { + return New(s).Name() + } // nested retrieves recursively all types for the given value and returns the + // nested value. + func (s *Struct) nested(val reflect.Value) interface{} { + var finalVal interface{} v := reflect.ValueOf(val.Interface()) + if v.Kind() == reflect.Ptr { + v = v.Elem() + } switch v.Kind() { + case reflect.Struct: + n := New(val.Interface()) + n.TagName = s.TagName + m := n.Map() // do not add the converted value if there are no exported fields, ie: + // time.Time + if len(m) == 0 { + finalVal = val.Interface() + } else { + finalVal = m + } + case reflect.Map: + // get the element type of the map + mapElem := val.Type() + switch val.Type().Kind() { + case reflect.Ptr, reflect.Array, reflect.Map, + reflect.Slice, reflect.Chan: + mapElem = val.Type().Elem() + if mapElem.Kind() == reflect.Ptr { + mapElem = mapElem.Elem() + } + } // only iterate over struct types, ie: map[string]StructType, + // map[string][]StructType, + if mapElem.Kind() == reflect.Struct || + (mapElem.Kind() == reflect.Slice && + mapElem.Elem().Kind() == reflect.Struct) { + m := make(map[string]interface{}, val.Len()) + for _, k := range val.MapKeys() { + m[k.String()] = s.nested(val.MapIndex(k)) + } + finalVal = m + break + } // TODO(arslan): should this be optional? + finalVal = val.Interface() + case reflect.Slice, reflect.Array: + if val.Type().Kind() == reflect.Interface { + finalVal = val.Interface() + break + } // TODO(arslan): should this be optional? + // do not iterate of non struct types, just pass the value. Ie: []int, + // []string, co... We only iterate further if it's a struct. + // i.e []foo or []*foo + if val.Type().Elem().Kind() != reflect.Struct && + !(val.Type().Elem().Kind() == reflect.Ptr && + val.Type().Elem().Elem().Kind() == reflect.Struct) { + finalVal = val.Interface() + break + } slices := make([]interface{}, val.Len()) + for x := 0; x < val.Len(); x++ { + slices[x] = s.nested(val.Index(x)) + } + finalVal = slices + default: + finalVal = val.Interface() + } return finalVal + } diff --git a/vendor/github.com/fsnotify/fsnotify/backend_fen.go b/vendor/github.com/fsnotify/fsnotify/backend_fen.go index 28497f1..241b951 100644 --- a/vendor/github.com/fsnotify/fsnotify/backend_fen.go +++ b/vendor/github.com/fsnotify/fsnotify/backend_fen.go @@ -2,6 +2,7 @@ // +build solaris // Note: the documentation on the Watcher type and methods is generated from + // mkdoc.zsh package fsnotify @@ -17,624 +18,1140 @@ import ( ) // Watcher watches a set of paths, delivering events on a channel. + // + // A watcher should not be copied (e.g. pass it by pointer, rather than by + // value). + // + // # Linux notes + // + // When a file is removed a Remove event won't be emitted until all file + // descriptors are closed, and deletes will always emit a Chmod. For example: + // + // fp := os.Open("file") + // os.Remove("file") // Triggers Chmod + // fp.Close() // Triggers Remove + // + // This is the event that inotify sends, so not much can be changed about this. + // + // The fs.inotify.max_user_watches sysctl variable specifies the upper limit + // for the number of watches per user, and fs.inotify.max_user_instances + // specifies the maximum number of inotify instances per user. Every Watcher you + // create is an "instance", and every path you add is a "watch". + // + // These are also exposed in /proc as /proc/sys/fs/inotify/max_user_watches and + // /proc/sys/fs/inotify/max_user_instances + // + // To increase them you can use sysctl or write the value to the /proc file: + // + // # Default values on Linux 5.18 + // sysctl fs.inotify.max_user_watches=124983 + // sysctl fs.inotify.max_user_instances=128 + // + // To make the changes persist on reboot edit /etc/sysctl.conf or + // /usr/lib/sysctl.d/50-default.conf (details differ per Linux distro; check + // your distro's documentation): + // + // fs.inotify.max_user_watches=124983 + // fs.inotify.max_user_instances=128 + // + // Reaching the limit will result in a "no space left on device" or "too many open + // files" error. + // + // # kqueue notes (macOS, BSD) + // + // kqueue requires opening a file descriptor for every file that's being watched; + // so if you're watching a directory with five files then that's six file + // descriptors. You will run in to your system's "max open files" limit faster on + // these platforms. + // + // The sysctl variables kern.maxfiles and kern.maxfilesperproc can be used to + // control the maximum number of open files, as well as /etc/login.conf on BSD + // systems. + // + // # Windows notes + // + // Paths can be added as "C:\path\to\dir", but forward slashes + // ("C:/path/to/dir") will also work. + // + // When a watched directory is removed it will always send an event for the + // directory itself, but may not send events for all files in that directory. + // Sometimes it will send events for all times, sometimes it will send no + // events, and often only for some files. + // + // The default ReadDirectoryChangesW() buffer size is 64K, which is the largest + // value that is guaranteed to work with SMB filesystems. If you have many + // events in quick succession this may not be enough, and you will have to use + // [WithBufferSize] to increase the value. + type Watcher struct { + // Events sends the filesystem change events. + // + // fsnotify can send the following events; a "path" here can refer to a + // file, directory, symbolic link, or special file like a FIFO. + // + // fsnotify.Create A new path was created; this may be followed by one + // or more Write events if data also gets written to a + // file. + // + // fsnotify.Remove A path was removed. + // + // fsnotify.Rename A path was renamed. A rename is always sent with the + // old path as Event.Name, and a Create event will be + // sent with the new name. Renames are only sent for + // paths that are currently watched; e.g. moving an + // unmonitored file into a monitored directory will + // show up as just a Create. Similarly, renaming a file + // to outside a monitored directory will show up as + // only a Rename. + // + // fsnotify.Write A file or named pipe was written to. A Truncate will + // also trigger a Write. A single "write action" + // initiated by the user may show up as one or multiple + // writes, depending on when the system syncs things to + // disk. For example when compiling a large Go program + // you may get hundreds of Write events, and you may + // want to wait until you've stopped receiving them + // (see the dedup example in cmd/fsnotify). + // + // Some systems may send Write event for directories + // when the directory content changes. + // + // fsnotify.Chmod Attributes were changed. On Linux this is also sent + // when a file is removed (or more accurately, when a + // link to an inode is removed). On kqueue it's sent + // when a file is truncated. On Windows it's never + // sent. + Events chan Event // Errors sends any errors. + // + // ErrEventOverflow is used to indicate there are too many events: + // + // - inotify: There are too many queued events (fs.inotify.max_queued_events sysctl) + // - windows: The buffer size is too small; WithBufferSize() can be used to increase it. + // - kqueue, fen: Not used. + Errors chan error - mu sync.Mutex - port *unix.EventPort - done chan struct{} // Channel for sending a "quit message" to the reader goroutine - dirs map[string]struct{} // Explicitly watched directories + mu sync.Mutex + + port *unix.EventPort + + done chan struct{} // Channel for sending a "quit message" to the reader goroutine + + dirs map[string]struct{} // Explicitly watched directories + watches map[string]struct{} // Explicitly watched non-directories + } // NewWatcher creates a new Watcher. + func NewWatcher() (*Watcher, error) { + return NewBufferedWatcher(0) + } // NewBufferedWatcher creates a new Watcher with a buffered Watcher.Events + // channel. + // + // The main use case for this is situations with a very large number of events + // where the kernel buffer size can't be increased (e.g. due to lack of + // permissions). An unbuffered Watcher will perform better for almost all use + // cases, and whenever possible you will be better off increasing the kernel + // buffers instead of adding a large userspace buffer. + func NewBufferedWatcher(sz uint) (*Watcher, error) { + w := &Watcher{ - Events: make(chan Event, sz), - Errors: make(chan error), - dirs: make(map[string]struct{}), + + Events: make(chan Event, sz), + + Errors: make(chan error), + + dirs: make(map[string]struct{}), + watches: make(map[string]struct{}), - done: make(chan struct{}), + + done: make(chan struct{}), } var err error + w.port, err = unix.NewEventPort() + if err != nil { + return nil, fmt.Errorf("fsnotify.NewWatcher: %w", err) + } go w.readEvents() + return w, nil + } // sendEvent attempts to send an event to the user, returning true if the event + // was put in the channel successfully and false if the watcher has been closed. + func (w *Watcher) sendEvent(name string, op Op) (sent bool) { + select { + case w.Events <- Event{Name: name, Op: op}: + return true + case <-w.done: + return false + } + } // sendError attempts to send an error to the user, returning true if the error + // was put in the channel successfully and false if the watcher has been closed. + func (w *Watcher) sendError(err error) (sent bool) { + select { + case w.Errors <- err: + return true + case <-w.done: + return false + } + } func (w *Watcher) isClosed() bool { + select { + case <-w.done: + return true + default: + return false + } + } // Close removes all watches and closes the Events channel. + func (w *Watcher) Close() error { + // Take the lock used by associateFile to prevent lingering events from + // being processed after the close + w.mu.Lock() + defer w.mu.Unlock() + if w.isClosed() { + return nil + } + close(w.done) + return w.port.Close() + } // Add starts monitoring the path for changes. + // + // A path can only be watched once; watching it more than once is a no-op and will + // not return an error. Paths that do not yet exist on the filesystem cannot be + // watched. + // + // A watch will be automatically removed if the watched path is deleted or + // renamed. The exception is the Windows backend, which doesn't remove the + // watcher on renames. + // + // Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special + // filesystems (/proc, /sys, etc.) generally don't work. + // + // Returns [ErrClosed] if [Watcher.Close] was called. + // + // See [Watcher.AddWith] for a version that allows adding options. + // + // # Watching directories + // + // All files in a directory are monitored, including new files that are created + // after the watcher is started. Subdirectories are not watched (i.e. it's + // non-recursive). + // + // # Watching files + // + // Watching individual files (rather than directories) is generally not + // recommended as many programs (especially editors) update files atomically: it + // will write to a temporary file which is then moved to to destination, + // overwriting the original (or some variant thereof). The watcher on the + // original file is now lost, as that no longer exists. + // + // The upshot of this is that a power failure or crash won't leave a + // half-written file. + // + // Watch the parent directory and use Event.Name to filter out files you're not + // interested in. There is an example of this in cmd/fsnotify/file.go. + func (w *Watcher) Add(name string) error { return w.AddWith(name) } // AddWith is like [Watcher.Add], but allows adding options. When using Add() + // the defaults described below are used. + // + // Possible options are: + // + // - [WithBufferSize] sets the buffer size for the Windows backend; no-op on + // other platforms. The default is 64K (65536 bytes). + func (w *Watcher) AddWith(name string, opts ...addOpt) error { + if w.isClosed() { + return ErrClosed + } + if w.port.PathIsWatched(name) { + return nil + } _ = getOptions(opts...) // Currently we resolve symlinks that were explicitly requested to be + // watched. Otherwise we would use LStat here. + stat, err := os.Stat(name) + if err != nil { + return err + } // Associate all files in the directory. + if stat.IsDir() { + err := w.handleDirectory(name, stat, true, w.associateFile) + if err != nil { + return err + } w.mu.Lock() + w.dirs[name] = struct{}{} + w.mu.Unlock() + return nil + } err = w.associateFile(name, stat, true) + if err != nil { + return err + } w.mu.Lock() + w.watches[name] = struct{}{} + w.mu.Unlock() + return nil + } // Remove stops monitoring the path for changes. + // + // Directories are always removed non-recursively. For example, if you added + // /tmp/dir and /tmp/dir/subdir then you will need to remove both. + // + // Removing a path that has not yet been added returns [ErrNonExistentWatch]. + // + // Returns nil if [Watcher.Close] was called. + func (w *Watcher) Remove(name string) error { + if w.isClosed() { + return nil + } + if !w.port.PathIsWatched(name) { + return fmt.Errorf("%w: %s", ErrNonExistentWatch, name) + } // The user has expressed an intent. Immediately remove this name from + // whichever watch list it might be in. If it's not in there the delete + // doesn't cause harm. + w.mu.Lock() + delete(w.watches, name) + delete(w.dirs, name) + w.mu.Unlock() stat, err := os.Stat(name) + if err != nil { + return err + } // Remove associations for every file in the directory. + if stat.IsDir() { + err := w.handleDirectory(name, stat, false, w.dissociateFile) + if err != nil { + return err + } + return nil + } err = w.port.DissociatePath(name) + if err != nil { + return err + } return nil + } // readEvents contains the main loop that runs in a goroutine watching for events. + func (w *Watcher) readEvents() { + // If this function returns, the watcher has been closed and we can close + // these channels + defer func() { + close(w.Errors) + close(w.Events) + }() pevents := make([]unix.PortEvent, 8) + for { + count, err := w.port.Get(pevents, 1, nil) + if err != nil && err != unix.ETIME { + // Interrupted system call (count should be 0) ignore and continue + if errors.Is(err, unix.EINTR) && count == 0 { + continue + } + // Get failed because we called w.Close() + if errors.Is(err, unix.EBADF) && w.isClosed() { + return + } + // There was an error not caused by calling w.Close() + if !w.sendError(err) { + return + } + } p := pevents[:count] + for _, pevent := range p { + if pevent.Source != unix.PORT_SOURCE_FILE { + // Event from unexpected source received; should never happen. + if !w.sendError(errors.New("Event from unexpected source received")) { + return + } + continue + } err = w.handleEvent(&pevent) + if err != nil { + if !w.sendError(err) { + return + } + } + } + } + } func (w *Watcher) handleDirectory(path string, stat os.FileInfo, follow bool, handler func(string, os.FileInfo, bool) error) error { + files, err := os.ReadDir(path) + if err != nil { + return err + } // Handle all children of the directory. + for _, entry := range files { + finfo, err := entry.Info() + if err != nil { + return err + } + err = handler(filepath.Join(path, finfo.Name()), finfo, false) + if err != nil { + return err + } + } // And finally handle the directory itself. + return handler(path, stat, follow) + } // handleEvent might need to emit more than one fsnotify event if the events + // bitmap matches more than one event type (e.g. the file was both modified and + // had the attributes changed between when the association was created and the + // when event was returned) + func (w *Watcher) handleEvent(event *unix.PortEvent) error { + var ( - events = event.Events - path = event.Path - fmode = event.Cookie.(os.FileMode) + events = event.Events + + path = event.Path + + fmode = event.Cookie.(os.FileMode) + reRegister = true ) w.mu.Lock() + _, watchedDir := w.dirs[path] + _, watchedPath := w.watches[path] + w.mu.Unlock() + isWatched := watchedDir || watchedPath if events&unix.FILE_DELETE != 0 { + if !w.sendEvent(path, Remove) { + return nil + } + reRegister = false + } + if events&unix.FILE_RENAME_FROM != 0 { + if !w.sendEvent(path, Rename) { + return nil + } + // Don't keep watching the new file name + reRegister = false + } + if events&unix.FILE_RENAME_TO != 0 { + // We don't report a Rename event for this case, because Rename events + // are interpreted as referring to the _old_ name of the file, and in + // this case the event would refer to the new name of the file. This + // type of rename event is not supported by fsnotify. // inotify reports a Remove event in this case, so we simulate this + // here. + if !w.sendEvent(path, Remove) { + return nil + } + // Don't keep watching the file that was removed + reRegister = false + } // The file is gone, nothing left to do. + if !reRegister { + if watchedDir { + w.mu.Lock() + delete(w.dirs, path) + w.mu.Unlock() + } + if watchedPath { + w.mu.Lock() + delete(w.watches, path) + w.mu.Unlock() + } + return nil + } // If we didn't get a deletion the file still exists and we're going to have + // to watch it again. Let's Stat it now so that we can compare permissions + // and have what we need to continue watching the file stat, err := os.Lstat(path) + if err != nil { + // This is unexpected, but we should still emit an event. This happens + // most often on "rm -r" of a subdirectory inside a watched directory We + // get a modify event of something happening inside, but by the time we + // get here, the sudirectory is already gone. Clearly we were watching + // this path but now it is gone. Let's tell the user that it was + // removed. + if !w.sendEvent(path, Remove) { + return nil + } + // Suppress extra write events on removed directories; they are not + // informative and can be confusing. + return nil + } // resolve symlinks that were explicitly watched as we would have at Add() + // time. this helps suppress spurious Chmod events on watched symlinks + if isWatched { + stat, err = os.Stat(path) + if err != nil { + // The symlink still exists, but the target is gone. Report the + // Remove similar to above. + if !w.sendEvent(path, Remove) { + return nil + } + // Don't return the error + } + } if events&unix.FILE_MODIFIED != 0 { + if fmode.IsDir() { + if watchedDir { + if err := w.updateDirectory(path); err != nil { + return err + } + } else { + if !w.sendEvent(path, Write) { + return nil + } + } + } else { + if !w.sendEvent(path, Write) { + return nil + } + } + } + if events&unix.FILE_ATTRIB != 0 && stat != nil { + // Only send Chmod if perms changed + if stat.Mode().Perm() != fmode.Perm() { + if !w.sendEvent(path, Chmod) { + return nil + } + } + } if stat != nil { + // If we get here, it means we've hit an event above that requires us to + // continue watching the file or directory + return w.associateFile(path, stat, isWatched) + } + return nil + } func (w *Watcher) updateDirectory(path string) error { + // The directory was modified, so we must find unwatched entities and watch + // them. If something was removed from the directory, nothing will happen, + // as everything else should still be watched. + files, err := os.ReadDir(path) + if err != nil { + return err + } for _, entry := range files { + path := filepath.Join(path, entry.Name()) + if w.port.PathIsWatched(path) { + continue + } finfo, err := entry.Info() + if err != nil { + return err + } + err = w.associateFile(path, finfo, false) + if err != nil { + if !w.sendError(err) { + return nil + } + } + if !w.sendEvent(path, Create) { + return nil + } + } + return nil + } func (w *Watcher) associateFile(path string, stat os.FileInfo, follow bool) error { + if w.isClosed() { + return ErrClosed + } + // This is primarily protecting the call to AssociatePath but it is + // important and intentional that the call to PathIsWatched is also + // protected by this mutex. Without this mutex, AssociatePath has been seen + // to error out that the path is already associated. + w.mu.Lock() + defer w.mu.Unlock() if w.port.PathIsWatched(path) { + // Remove the old association in favor of this one If we get ENOENT, + // then while the x/sys/unix wrapper still thought that this path was + // associated, the underlying event port did not. This call will have + // cleared up that discrepancy. The most likely cause is that the event + // has fired but we haven't processed it yet. + err := w.port.DissociatePath(path) + if err != nil && err != unix.ENOENT { + return err + } + } + // FILE_NOFOLLOW means we watch symlinks themselves rather than their + // targets. + events := unix.FILE_MODIFIED | unix.FILE_ATTRIB | unix.FILE_NOFOLLOW + if follow { + // We *DO* follow symlinks for explicitly watched entries. + events = unix.FILE_MODIFIED | unix.FILE_ATTRIB + } + return w.port.AssociatePath(path, stat, + events, + stat.Mode()) + } func (w *Watcher) dissociateFile(path string, stat os.FileInfo, unused bool) error { + if !w.port.PathIsWatched(path) { + return nil + } + return w.port.DissociatePath(path) + } // WatchList returns all paths explicitly added with [Watcher.Add] (and are not + // yet removed). + // + // Returns nil if [Watcher.Close] was called. + func (w *Watcher) WatchList() []string { + if w.isClosed() { + return nil + } w.mu.Lock() + defer w.mu.Unlock() entries := make([]string, 0, len(w.watches)+len(w.dirs)) + for pathname := range w.dirs { + entries = append(entries, pathname) + } + for pathname := range w.watches { + entries = append(entries, pathname) + } return entries + } diff --git a/vendor/github.com/fsnotify/fsnotify/backend_inotify.go b/vendor/github.com/fsnotify/fsnotify/backend_inotify.go index 921c1c1..e2aa073 100644 --- a/vendor/github.com/fsnotify/fsnotify/backend_inotify.go +++ b/vendor/github.com/fsnotify/fsnotify/backend_inotify.go @@ -2,6 +2,7 @@ // +build linux,!appengine // Note: the documentation on the Watcher type and methods is generated from + // mkdoc.zsh package fsnotify @@ -20,575 +21,1026 @@ import ( ) // Watcher watches a set of paths, delivering events on a channel. + // + // A watcher should not be copied (e.g. pass it by pointer, rather than by + // value). + // + // # Linux notes + // + // When a file is removed a Remove event won't be emitted until all file + // descriptors are closed, and deletes will always emit a Chmod. For example: + // + // fp := os.Open("file") + // os.Remove("file") // Triggers Chmod + // fp.Close() // Triggers Remove + // + // This is the event that inotify sends, so not much can be changed about this. + // + // The fs.inotify.max_user_watches sysctl variable specifies the upper limit + // for the number of watches per user, and fs.inotify.max_user_instances + // specifies the maximum number of inotify instances per user. Every Watcher you + // create is an "instance", and every path you add is a "watch". + // + // These are also exposed in /proc as /proc/sys/fs/inotify/max_user_watches and + // /proc/sys/fs/inotify/max_user_instances + // + // To increase them you can use sysctl or write the value to the /proc file: + // + // # Default values on Linux 5.18 + // sysctl fs.inotify.max_user_watches=124983 + // sysctl fs.inotify.max_user_instances=128 + // + // To make the changes persist on reboot edit /etc/sysctl.conf or + // /usr/lib/sysctl.d/50-default.conf (details differ per Linux distro; check + // your distro's documentation): + // + // fs.inotify.max_user_watches=124983 + // fs.inotify.max_user_instances=128 + // + // Reaching the limit will result in a "no space left on device" or "too many open + // files" error. + // + // # kqueue notes (macOS, BSD) + // + // kqueue requires opening a file descriptor for every file that's being watched; + // so if you're watching a directory with five files then that's six file + // descriptors. You will run in to your system's "max open files" limit faster on + // these platforms. + // + // The sysctl variables kern.maxfiles and kern.maxfilesperproc can be used to + // control the maximum number of open files, as well as /etc/login.conf on BSD + // systems. + // + // # Windows notes + // + // Paths can be added as "C:\path\to\dir", but forward slashes + // ("C:/path/to/dir") will also work. + // + // When a watched directory is removed it will always send an event for the + // directory itself, but may not send events for all files in that directory. + // Sometimes it will send events for all times, sometimes it will send no + // events, and often only for some files. + // + // The default ReadDirectoryChangesW() buffer size is 64K, which is the largest + // value that is guaranteed to work with SMB filesystems. If you have many + // events in quick succession this may not be enough, and you will have to use + // [WithBufferSize] to increase the value. + type Watcher struct { + // Events sends the filesystem change events. + // + // fsnotify can send the following events; a "path" here can refer to a + // file, directory, symbolic link, or special file like a FIFO. + // + // fsnotify.Create A new path was created; this may be followed by one + // or more Write events if data also gets written to a + // file. + // + // fsnotify.Remove A path was removed. + // + // fsnotify.Rename A path was renamed. A rename is always sent with the + // old path as Event.Name, and a Create event will be + // sent with the new name. Renames are only sent for + // paths that are currently watched; e.g. moving an + // unmonitored file into a monitored directory will + // show up as just a Create. Similarly, renaming a file + // to outside a monitored directory will show up as + // only a Rename. + // + // fsnotify.Write A file or named pipe was written to. A Truncate will + // also trigger a Write. A single "write action" + // initiated by the user may show up as one or multiple + // writes, depending on when the system syncs things to + // disk. For example when compiling a large Go program + // you may get hundreds of Write events, and you may + // want to wait until you've stopped receiving them + // (see the dedup example in cmd/fsnotify). + // + // Some systems may send Write event for directories + // when the directory content changes. + // + // fsnotify.Chmod Attributes were changed. On Linux this is also sent + // when a file is removed (or more accurately, when a + // link to an inode is removed). On kqueue it's sent + // when a file is truncated. On Windows it's never + // sent. + Events chan Event // Errors sends any errors. + // + // ErrEventOverflow is used to indicate there are too many events: + // + // - inotify: There are too many queued events (fs.inotify.max_queued_events sysctl) + // - windows: The buffer size is too small; WithBufferSize() can be used to increase it. + // - kqueue, fen: Not used. + Errors chan error // Store fd here as os.File.Read() will no longer return on close after + // calling Fd(). See: https://github.com/golang/go/issues/26439 - fd int + + fd int + inotifyFile *os.File - watches *watches - done chan struct{} // Channel for sending a "quit message" to the reader goroutine - closeMu sync.Mutex - doneResp chan struct{} // Channel to respond to Close + + watches *watches + + done chan struct{} // Channel for sending a "quit message" to the reader goroutine + + closeMu sync.Mutex + + doneResp chan struct{} // Channel to respond to Close + } type ( watches struct { - mu sync.RWMutex - wd map[uint32]*watch // wd → watch + mu sync.RWMutex + + wd map[uint32]*watch // wd → watch + path map[string]uint32 // pathname → wd + } + watch struct { - wd uint32 // Watch descriptor (as returned by the inotify_add_watch() syscall) + wd uint32 // Watch descriptor (as returned by the inotify_add_watch() syscall) + flags uint32 // inotify flags of this watch (see inotify(7) for the list of valid flags) - path string // Watch path. + + path string // Watch path. + } ) func newWatches() *watches { + return &watches{ - wd: make(map[uint32]*watch), + + wd: make(map[uint32]*watch), + path: make(map[string]uint32), } + } func (w *watches) len() int { + w.mu.RLock() + defer w.mu.RUnlock() + return len(w.wd) + } func (w *watches) add(ww *watch) { + w.mu.Lock() + defer w.mu.Unlock() + w.wd[ww.wd] = ww + w.path[ww.path] = ww.wd + } func (w *watches) remove(wd uint32) { + w.mu.Lock() + defer w.mu.Unlock() + delete(w.path, w.wd[wd].path) + delete(w.wd, wd) + } func (w *watches) removePath(path string) (uint32, bool) { + w.mu.Lock() + defer w.mu.Unlock() wd, ok := w.path[path] + if !ok { + return 0, false + } delete(w.path, path) + delete(w.wd, wd) return wd, true + } func (w *watches) byPath(path string) *watch { + w.mu.RLock() + defer w.mu.RUnlock() + return w.wd[w.path[path]] + } func (w *watches) byWd(wd uint32) *watch { + w.mu.RLock() + defer w.mu.RUnlock() + return w.wd[wd] + } func (w *watches) updatePath(path string, f func(*watch) (*watch, error)) error { + w.mu.Lock() + defer w.mu.Unlock() var existing *watch + wd, ok := w.path[path] + if ok { + existing = w.wd[wd] + } upd, err := f(existing) + if err != nil { + return err + } + if upd != nil { + w.wd[upd.wd] = upd + w.path[upd.path] = upd.wd if upd.wd != wd { + delete(w.wd, wd) + } + } return nil + } // NewWatcher creates a new Watcher. + func NewWatcher() (*Watcher, error) { + return NewBufferedWatcher(0) + } // NewBufferedWatcher creates a new Watcher with a buffered Watcher.Events + // channel. + // + // The main use case for this is situations with a very large number of events + // where the kernel buffer size can't be increased (e.g. due to lack of + // permissions). An unbuffered Watcher will perform better for almost all use + // cases, and whenever possible you will be better off increasing the kernel + // buffers instead of adding a large userspace buffer. + func NewBufferedWatcher(sz uint) (*Watcher, error) { + // Need to set nonblocking mode for SetDeadline to work, otherwise blocking + // I/O operations won't terminate on close. + fd, errno := unix.InotifyInit1(unix.IN_CLOEXEC | unix.IN_NONBLOCK) + if fd == -1 { + return nil, errno + } w := &Watcher{ - fd: fd, + + fd: fd, + inotifyFile: os.NewFile(uintptr(fd), ""), - watches: newWatches(), - Events: make(chan Event, sz), - Errors: make(chan error), - done: make(chan struct{}), - doneResp: make(chan struct{}), + + watches: newWatches(), + + Events: make(chan Event, sz), + + Errors: make(chan error), + + done: make(chan struct{}), + + doneResp: make(chan struct{}), } go w.readEvents() + return w, nil + } // Returns true if the event was sent, or false if watcher is closed. + func (w *Watcher) sendEvent(e Event) bool { + select { + case w.Events <- e: + return true + case <-w.done: + return false + } + } // Returns true if the error was sent, or false if watcher is closed. + func (w *Watcher) sendError(err error) bool { + select { + case w.Errors <- err: + return true + case <-w.done: + return false + } + } func (w *Watcher) isClosed() bool { + select { + case <-w.done: + return true + default: + return false + } + } // Close removes all watches and closes the Events channel. + func (w *Watcher) Close() error { + w.closeMu.Lock() + if w.isClosed() { + w.closeMu.Unlock() + return nil + } + close(w.done) + w.closeMu.Unlock() // Causes any blocking reads to return with an error, provided the file + // still supports deadline operations. + err := w.inotifyFile.Close() + if err != nil { + return err + } // Wait for goroutine to close + <-w.doneResp return nil + } // Add starts monitoring the path for changes. + // + // A path can only be watched once; watching it more than once is a no-op and will + // not return an error. Paths that do not yet exist on the filesystem cannot be + // watched. + // + // A watch will be automatically removed if the watched path is deleted or + // renamed. The exception is the Windows backend, which doesn't remove the + // watcher on renames. + // + // Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special + // filesystems (/proc, /sys, etc.) generally don't work. + // + // Returns [ErrClosed] if [Watcher.Close] was called. + // + // See [Watcher.AddWith] for a version that allows adding options. + // + // # Watching directories + // + // All files in a directory are monitored, including new files that are created + // after the watcher is started. Subdirectories are not watched (i.e. it's + // non-recursive). + // + // # Watching files + // + // Watching individual files (rather than directories) is generally not + // recommended as many programs (especially editors) update files atomically: it + // will write to a temporary file which is then moved to to destination, + // overwriting the original (or some variant thereof). The watcher on the + // original file is now lost, as that no longer exists. + // + // The upshot of this is that a power failure or crash won't leave a + // half-written file. + // + // Watch the parent directory and use Event.Name to filter out files you're not + // interested in. There is an example of this in cmd/fsnotify/file.go. + func (w *Watcher) Add(name string) error { return w.AddWith(name) } // AddWith is like [Watcher.Add], but allows adding options. When using Add() + // the defaults described below are used. + // + // Possible options are: + // + // - [WithBufferSize] sets the buffer size for the Windows backend; no-op on + // other platforms. The default is 64K (65536 bytes). + func (w *Watcher) AddWith(name string, opts ...addOpt) error { + if w.isClosed() { + return ErrClosed + } name = filepath.Clean(name) + _ = getOptions(opts...) var flags uint32 = unix.IN_MOVED_TO | unix.IN_MOVED_FROM | + unix.IN_CREATE | unix.IN_ATTRIB | unix.IN_MODIFY | + unix.IN_MOVE_SELF | unix.IN_DELETE | unix.IN_DELETE_SELF return w.watches.updatePath(name, func(existing *watch) (*watch, error) { + if existing != nil { + flags |= existing.flags | unix.IN_MASK_ADD + } wd, err := unix.InotifyAddWatch(w.fd, name, flags) + if wd == -1 { + return nil, err + } if existing == nil { + return &watch{ - wd: uint32(wd), - path: name, + + wd: uint32(wd), + + path: name, + flags: flags, }, nil + } existing.wd = uint32(wd) + existing.flags = flags + return existing, nil + }) + } // Remove stops monitoring the path for changes. + // + // Directories are always removed non-recursively. For example, if you added + // /tmp/dir and /tmp/dir/subdir then you will need to remove both. + // + // Removing a path that has not yet been added returns [ErrNonExistentWatch]. + // + // Returns nil if [Watcher.Close] was called. + func (w *Watcher) Remove(name string) error { + if w.isClosed() { + return nil + } + return w.remove(filepath.Clean(name)) + } func (w *Watcher) remove(name string) error { + wd, ok := w.watches.removePath(name) + if !ok { + return fmt.Errorf("%w: %s", ErrNonExistentWatch, name) + } success, errno := unix.InotifyRmWatch(w.fd, wd) + if success == -1 { + // TODO: Perhaps it's not helpful to return an error here in every case; + // The only two possible errors are: + // + // - EBADF, which happens when w.fd is not a valid file descriptor + // of any kind. + // - EINVAL, which is when fd is not an inotify descriptor or wd + // is not a valid watch descriptor. Watch descriptors are + // invalidated when they are removed explicitly or implicitly; + // explicitly by inotify_rm_watch, implicitly when the file they + // are watching is deleted. + return errno + } + return nil + } // WatchList returns all paths explicitly added with [Watcher.Add] (and are not + // yet removed). + // + // Returns nil if [Watcher.Close] was called. + func (w *Watcher) WatchList() []string { + if w.isClosed() { + return nil + } entries := make([]string, 0, w.watches.len()) + w.watches.mu.RLock() + for pathname := range w.watches.path { + entries = append(entries, pathname) + } + w.watches.mu.RUnlock() return entries + } // readEvents reads from the inotify file descriptor, converts the + // received events into Event objects and sends them via the Events channel + func (w *Watcher) readEvents() { + defer func() { + close(w.doneResp) + close(w.Errors) + close(w.Events) + }() var ( - buf [unix.SizeofInotifyEvent * 4096]byte // Buffer for a maximum of 4096 raw events - errno error // Syscall errno + buf [unix.SizeofInotifyEvent * 4096]byte // Buffer for a maximum of 4096 raw events + + errno error // Syscall errno + ) + for { + // See if we have been closed. + if w.isClosed() { + return + } n, err := w.inotifyFile.Read(buf[:]) + switch { + case errors.Unwrap(err) == os.ErrClosed: + return + case err != nil: + if !w.sendError(err) { + return + } + continue + } if n < unix.SizeofInotifyEvent { + var err error + if n == 0 { + err = io.EOF // If EOF is received. This should really never happen. + } else if n < 0 { + err = errno // If an error occurred while reading. + } else { + err = errors.New("notify: short read in readEvents()") // Read was too short. + } + if !w.sendError(err) { + return + } + continue + } var offset uint32 + // We don't know how many events we just read into the buffer + // While the offset points to at least one whole event... + for offset <= uint32(n-unix.SizeofInotifyEvent) { + var ( + // Point "raw" to the event in the buffer - raw = (*unix.InotifyEvent)(unsafe.Pointer(&buf[offset])) - mask = uint32(raw.Mask) + + raw = (*unix.InotifyEvent)(unsafe.Pointer(&buf[offset])) + + mask = uint32(raw.Mask) + nameLen = uint32(raw.Len) ) if mask&unix.IN_Q_OVERFLOW != 0 { + if !w.sendError(ErrEventOverflow) { + return + } + } // If the event happened to the watched directory or the watched file, the kernel + // doesn't append the filename to the event, but we would like to always fill the + // the "Name" field with a valid filename. We retrieve the path of the watch from + // the "paths" map. + watch := w.watches.byWd(uint32(raw.Wd)) // inotify will automatically remove the watch on deletes; just need + // to clean our state here. + if watch != nil && mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF { + w.watches.remove(watch.wd) + } + // We can't really update the state when a watched path is moved; + // only IN_MOVE_SELF is sent and not IN_MOVED_{FROM,TO}. So remove + // the watch. + if watch != nil && mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF { + err := w.remove(watch.path) + if err != nil && !errors.Is(err, ErrNonExistentWatch) { + if !w.sendError(err) { + return + } + } + } var name string + if watch != nil { + name = watch.path + } + if nameLen > 0 { + // Point "bytes" at the first byte of the filename + bytes := (*[unix.PathMax]byte)(unsafe.Pointer(&buf[offset+unix.SizeofInotifyEvent]))[:nameLen:nameLen] + // The filename is padded with NULL bytes. TrimRight() gets rid of those. + name += "/" + strings.TrimRight(string(bytes[0:nameLen]), "\000") + } event := w.newEvent(name, mask) // Send the events that are not ignored on the events channel + if mask&unix.IN_IGNORED == 0 { + if !w.sendEvent(event) { + return + } + } // Move to the next event in the buffer + offset += unix.SizeofInotifyEvent + nameLen + } + } + } // newEvent returns an platform-independent Event based on an inotify mask. + func (w *Watcher) newEvent(name string, mask uint32) Event { + e := Event{Name: name} + if mask&unix.IN_CREATE == unix.IN_CREATE || mask&unix.IN_MOVED_TO == unix.IN_MOVED_TO { + e.Op |= Create + } + if mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF || mask&unix.IN_DELETE == unix.IN_DELETE { + e.Op |= Remove + } + if mask&unix.IN_MODIFY == unix.IN_MODIFY { + e.Op |= Write + } + if mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF || mask&unix.IN_MOVED_FROM == unix.IN_MOVED_FROM { + e.Op |= Rename + } + if mask&unix.IN_ATTRIB == unix.IN_ATTRIB { + e.Op |= Chmod + } + return e + } diff --git a/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go b/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go index 063a091..9c3a331 100644 --- a/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go +++ b/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go @@ -2,6 +2,7 @@ // +build freebsd openbsd netbsd dragonfly darwin // Note: the documentation on the Watcher type and methods is generated from + // mkdoc.zsh package fsnotify @@ -17,766 +18,1366 @@ import ( ) // Watcher watches a set of paths, delivering events on a channel. + // + // A watcher should not be copied (e.g. pass it by pointer, rather than by + // value). + // + // # Linux notes + // + // When a file is removed a Remove event won't be emitted until all file + // descriptors are closed, and deletes will always emit a Chmod. For example: + // + // fp := os.Open("file") + // os.Remove("file") // Triggers Chmod + // fp.Close() // Triggers Remove + // + // This is the event that inotify sends, so not much can be changed about this. + // + // The fs.inotify.max_user_watches sysctl variable specifies the upper limit + // for the number of watches per user, and fs.inotify.max_user_instances + // specifies the maximum number of inotify instances per user. Every Watcher you + // create is an "instance", and every path you add is a "watch". + // + // These are also exposed in /proc as /proc/sys/fs/inotify/max_user_watches and + // /proc/sys/fs/inotify/max_user_instances + // + // To increase them you can use sysctl or write the value to the /proc file: + // + // # Default values on Linux 5.18 + // sysctl fs.inotify.max_user_watches=124983 + // sysctl fs.inotify.max_user_instances=128 + // + // To make the changes persist on reboot edit /etc/sysctl.conf or + // /usr/lib/sysctl.d/50-default.conf (details differ per Linux distro; check + // your distro's documentation): + // + // fs.inotify.max_user_watches=124983 + // fs.inotify.max_user_instances=128 + // + // Reaching the limit will result in a "no space left on device" or "too many open + // files" error. + // + // # kqueue notes (macOS, BSD) + // + // kqueue requires opening a file descriptor for every file that's being watched; + // so if you're watching a directory with five files then that's six file + // descriptors. You will run in to your system's "max open files" limit faster on + // these platforms. + // + // The sysctl variables kern.maxfiles and kern.maxfilesperproc can be used to + // control the maximum number of open files, as well as /etc/login.conf on BSD + // systems. + // + // # Windows notes + // + // Paths can be added as "C:\path\to\dir", but forward slashes + // ("C:/path/to/dir") will also work. + // + // When a watched directory is removed it will always send an event for the + // directory itself, but may not send events for all files in that directory. + // Sometimes it will send events for all times, sometimes it will send no + // events, and often only for some files. + // + // The default ReadDirectoryChangesW() buffer size is 64K, which is the largest + // value that is guaranteed to work with SMB filesystems. If you have many + // events in quick succession this may not be enough, and you will have to use + // [WithBufferSize] to increase the value. + type Watcher struct { + // Events sends the filesystem change events. + // + // fsnotify can send the following events; a "path" here can refer to a + // file, directory, symbolic link, or special file like a FIFO. + // + // fsnotify.Create A new path was created; this may be followed by one + // or more Write events if data also gets written to a + // file. + // + // fsnotify.Remove A path was removed. + // + // fsnotify.Rename A path was renamed. A rename is always sent with the + // old path as Event.Name, and a Create event will be + // sent with the new name. Renames are only sent for + // paths that are currently watched; e.g. moving an + // unmonitored file into a monitored directory will + // show up as just a Create. Similarly, renaming a file + // to outside a monitored directory will show up as + // only a Rename. + // + // fsnotify.Write A file or named pipe was written to. A Truncate will + // also trigger a Write. A single "write action" + // initiated by the user may show up as one or multiple + // writes, depending on when the system syncs things to + // disk. For example when compiling a large Go program + // you may get hundreds of Write events, and you may + // want to wait until you've stopped receiving them + // (see the dedup example in cmd/fsnotify). + // + // Some systems may send Write event for directories + // when the directory content changes. + // + // fsnotify.Chmod Attributes were changed. On Linux this is also sent + // when a file is removed (or more accurately, when a + // link to an inode is removed). On kqueue it's sent + // when a file is truncated. On Windows it's never + // sent. + Events chan Event // Errors sends any errors. + // + // ErrEventOverflow is used to indicate there are too many events: + // + // - inotify: There are too many queued events (fs.inotify.max_queued_events sysctl) + // - windows: The buffer size is too small; WithBufferSize() can be used to increase it. + // - kqueue, fen: Not used. + Errors chan error - done chan struct{} - kq int // File descriptor (as returned by the kqueue() syscall). - closepipe [2]int // Pipe used for closing. - mu sync.Mutex // Protects access to watcher data - watches map[string]int // Watched file descriptors (key: path). + done chan struct{} + + kq int // File descriptor (as returned by the kqueue() syscall). + + closepipe [2]int // Pipe used for closing. + + mu sync.Mutex // Protects access to watcher data + + watches map[string]int // Watched file descriptors (key: path). + watchesByDir map[string]map[int]struct{} // Watched file descriptors indexed by the parent directory (key: dirname(path)). - userWatches map[string]struct{} // Watches added with Watcher.Add() - dirFlags map[string]uint32 // Watched directories to fflags used in kqueue. - paths map[int]pathInfo // File descriptors to path names for processing kqueue events. - fileExists map[string]struct{} // Keep track of if we know this file exists (to stop duplicate create events). - isClosed bool // Set to true when Close() is first called + + userWatches map[string]struct{} // Watches added with Watcher.Add() + + dirFlags map[string]uint32 // Watched directories to fflags used in kqueue. + + paths map[int]pathInfo // File descriptors to path names for processing kqueue events. + + fileExists map[string]struct{} // Keep track of if we know this file exists (to stop duplicate create events). + + isClosed bool // Set to true when Close() is first called + } type pathInfo struct { - name string + name string + isDir bool } // NewWatcher creates a new Watcher. + func NewWatcher() (*Watcher, error) { + return NewBufferedWatcher(0) + } // NewBufferedWatcher creates a new Watcher with a buffered Watcher.Events + // channel. + // + // The main use case for this is situations with a very large number of events + // where the kernel buffer size can't be increased (e.g. due to lack of + // permissions). An unbuffered Watcher will perform better for almost all use + // cases, and whenever possible you will be better off increasing the kernel + // buffers instead of adding a large userspace buffer. + func NewBufferedWatcher(sz uint) (*Watcher, error) { + kq, closepipe, err := newKqueue() + if err != nil { + return nil, err + } w := &Watcher{ - kq: kq, - closepipe: closepipe, - watches: make(map[string]int), + + kq: kq, + + closepipe: closepipe, + + watches: make(map[string]int), + watchesByDir: make(map[string]map[int]struct{}), - dirFlags: make(map[string]uint32), - paths: make(map[int]pathInfo), - fileExists: make(map[string]struct{}), - userWatches: make(map[string]struct{}), - Events: make(chan Event, sz), - Errors: make(chan error), - done: make(chan struct{}), + + dirFlags: make(map[string]uint32), + + paths: make(map[int]pathInfo), + + fileExists: make(map[string]struct{}), + + userWatches: make(map[string]struct{}), + + Events: make(chan Event, sz), + + Errors: make(chan error), + + done: make(chan struct{}), } go w.readEvents() + return w, nil + } // newKqueue creates a new kernel event queue and returns a descriptor. + // + // This registers a new event on closepipe, which will trigger an event when + // it's closed. This way we can use kevent() without timeout/polling; without + // the closepipe, it would block forever and we wouldn't be able to stop it at + // all. + func newKqueue() (kq int, closepipe [2]int, err error) { + kq, err = unix.Kqueue() + if kq == -1 { + return kq, closepipe, err + } // Register the close pipe. + err = unix.Pipe(closepipe[:]) + if err != nil { + unix.Close(kq) + return kq, closepipe, err + } // Register changes to listen on the closepipe. + changes := make([]unix.Kevent_t, 1) + // SetKevent converts int to the platform-specific types. + unix.SetKevent(&changes[0], closepipe[0], unix.EVFILT_READ, + unix.EV_ADD|unix.EV_ENABLE|unix.EV_ONESHOT) ok, err := unix.Kevent(kq, changes, nil, nil) + if ok == -1 { + unix.Close(kq) + unix.Close(closepipe[0]) + unix.Close(closepipe[1]) + return kq, closepipe, err + } + return kq, closepipe, nil + } // Returns true if the event was sent, or false if watcher is closed. + func (w *Watcher) sendEvent(e Event) bool { + select { + case w.Events <- e: + return true + case <-w.done: + return false + } + } // Returns true if the error was sent, or false if watcher is closed. + func (w *Watcher) sendError(err error) bool { + select { + case w.Errors <- err: + return true + case <-w.done: + return false + } + } // Close removes all watches and closes the Events channel. + func (w *Watcher) Close() error { + w.mu.Lock() + if w.isClosed { + w.mu.Unlock() + return nil + } + w.isClosed = true // copy paths to remove while locked + pathsToRemove := make([]string, 0, len(w.watches)) + for name := range w.watches { + pathsToRemove = append(pathsToRemove, name) + } + w.mu.Unlock() // Unlock before calling Remove, which also locks + for _, name := range pathsToRemove { + w.Remove(name) + } // Send "quit" message to the reader goroutine. + unix.Close(w.closepipe[1]) + close(w.done) return nil + } // Add starts monitoring the path for changes. + // + // A path can only be watched once; watching it more than once is a no-op and will + // not return an error. Paths that do not yet exist on the filesystem cannot be + // watched. + // + // A watch will be automatically removed if the watched path is deleted or + // renamed. The exception is the Windows backend, which doesn't remove the + // watcher on renames. + // + // Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special + // filesystems (/proc, /sys, etc.) generally don't work. + // + // Returns [ErrClosed] if [Watcher.Close] was called. + // + // See [Watcher.AddWith] for a version that allows adding options. + // + // # Watching directories + // + // All files in a directory are monitored, including new files that are created + // after the watcher is started. Subdirectories are not watched (i.e. it's + // non-recursive). + // + // # Watching files + // + // Watching individual files (rather than directories) is generally not + // recommended as many programs (especially editors) update files atomically: it + // will write to a temporary file which is then moved to to destination, + // overwriting the original (or some variant thereof). The watcher on the + // original file is now lost, as that no longer exists. + // + // The upshot of this is that a power failure or crash won't leave a + // half-written file. + // + // Watch the parent directory and use Event.Name to filter out files you're not + // interested in. There is an example of this in cmd/fsnotify/file.go. + func (w *Watcher) Add(name string) error { return w.AddWith(name) } // AddWith is like [Watcher.Add], but allows adding options. When using Add() + // the defaults described below are used. + // + // Possible options are: + // + // - [WithBufferSize] sets the buffer size for the Windows backend; no-op on + // other platforms. The default is 64K (65536 bytes). + func (w *Watcher) AddWith(name string, opts ...addOpt) error { + _ = getOptions(opts...) w.mu.Lock() + w.userWatches[name] = struct{}{} + w.mu.Unlock() + _, err := w.addWatch(name, noteAllEvents) + return err + } // Remove stops monitoring the path for changes. + // + // Directories are always removed non-recursively. For example, if you added + // /tmp/dir and /tmp/dir/subdir then you will need to remove both. + // + // Removing a path that has not yet been added returns [ErrNonExistentWatch]. + // + // Returns nil if [Watcher.Close] was called. + func (w *Watcher) Remove(name string) error { + return w.remove(name, true) + } func (w *Watcher) remove(name string, unwatchFiles bool) error { + name = filepath.Clean(name) + w.mu.Lock() + if w.isClosed { + w.mu.Unlock() + return nil + } + watchfd, ok := w.watches[name] + w.mu.Unlock() + if !ok { + return fmt.Errorf("%w: %s", ErrNonExistentWatch, name) + } err := w.register([]int{watchfd}, unix.EV_DELETE, 0) + if err != nil { + return err + } unix.Close(watchfd) w.mu.Lock() + isDir := w.paths[watchfd].isDir + delete(w.watches, name) + delete(w.userWatches, name) parentName := filepath.Dir(name) + delete(w.watchesByDir[parentName], watchfd) if len(w.watchesByDir[parentName]) == 0 { + delete(w.watchesByDir, parentName) + } delete(w.paths, watchfd) + delete(w.dirFlags, name) + delete(w.fileExists, name) + w.mu.Unlock() // Find all watched paths that are in this directory that are not external. + if unwatchFiles && isDir { + var pathsToRemove []string + w.mu.Lock() + for fd := range w.watchesByDir[name] { + path := w.paths[fd] + if _, ok := w.userWatches[path.name]; !ok { + pathsToRemove = append(pathsToRemove, path.name) + } + } + w.mu.Unlock() + for _, name := range pathsToRemove { + // Since these are internal, not much sense in propagating error to + // the user, as that will just confuse them with an error about a + // path they did not explicitly watch themselves. + w.Remove(name) + } + } + return nil + } // WatchList returns all paths explicitly added with [Watcher.Add] (and are not + // yet removed). + // + // Returns nil if [Watcher.Close] was called. + func (w *Watcher) WatchList() []string { + w.mu.Lock() + defer w.mu.Unlock() + if w.isClosed { + return nil + } entries := make([]string, 0, len(w.userWatches)) + for pathname := range w.userWatches { + entries = append(entries, pathname) + } return entries + } // Watch all events (except NOTE_EXTEND, NOTE_LINK, NOTE_REVOKE) + const noteAllEvents = unix.NOTE_DELETE | unix.NOTE_WRITE | unix.NOTE_ATTRIB | unix.NOTE_RENAME // addWatch adds name to the watched file set; the flags are interpreted as + // described in kevent(2). + // + // Returns the real path to the file which was added, with symlinks resolved. + func (w *Watcher) addWatch(name string, flags uint32) (string, error) { + var isDir bool + name = filepath.Clean(name) w.mu.Lock() + if w.isClosed { + w.mu.Unlock() + return "", ErrClosed + } + watchfd, alreadyWatching := w.watches[name] + // We already have a watch, but we can still override flags. + if alreadyWatching { + isDir = w.paths[watchfd].isDir + } + w.mu.Unlock() if !alreadyWatching { + fi, err := os.Lstat(name) + if err != nil { + return "", err + } // Don't watch sockets or named pipes + if (fi.Mode()&os.ModeSocket == os.ModeSocket) || (fi.Mode()&os.ModeNamedPipe == os.ModeNamedPipe) { + return "", nil + } // Follow Symlinks. + if fi.Mode()&os.ModeSymlink == os.ModeSymlink { + link, err := os.Readlink(name) + if err != nil { + // Return nil because Linux can add unresolvable symlinks to the + // watch list without problems, so maintain consistency with + // that. There will be no file events for broken symlinks. + // TODO: more specific check; returns os.PathError; ENOENT? + return "", nil + } w.mu.Lock() + _, alreadyWatching = w.watches[link] + w.mu.Unlock() if alreadyWatching { + // Add to watches so we don't get spurious Create events later + // on when we diff the directories. + w.watches[name] = 0 + w.fileExists[name] = struct{}{} + return link, nil + } name = link + fi, err = os.Lstat(name) + if err != nil { + return "", nil + } + } // Retry on EINTR; open() can return EINTR in practice on macOS. + // See #354, and Go issues 11180 and 39237. + for { + watchfd, err = unix.Open(name, openMode, 0) + if err == nil { + break + } + if errors.Is(err, unix.EINTR) { + continue + } return "", err + } isDir = fi.IsDir() + } err := w.register([]int{watchfd}, unix.EV_ADD|unix.EV_CLEAR|unix.EV_ENABLE, flags) + if err != nil { + unix.Close(watchfd) + return "", err + } if !alreadyWatching { + w.mu.Lock() + parentName := filepath.Dir(name) + w.watches[name] = watchfd watchesByDir, ok := w.watchesByDir[parentName] + if !ok { + watchesByDir = make(map[int]struct{}, 1) + w.watchesByDir[parentName] = watchesByDir + } + watchesByDir[watchfd] = struct{}{} + w.paths[watchfd] = pathInfo{name: name, isDir: isDir} + w.mu.Unlock() + } if isDir { + // Watch the directory if it has not been watched before, or if it was + // watched before, but perhaps only a NOTE_DELETE (watchDirectoryFiles) + w.mu.Lock() watchDir := (flags&unix.NOTE_WRITE) == unix.NOTE_WRITE && + (!alreadyWatching || (w.dirFlags[name]&unix.NOTE_WRITE) != unix.NOTE_WRITE) + // Store flags so this watch can be updated later + w.dirFlags[name] = flags + w.mu.Unlock() if watchDir { + if err := w.watchDirectoryFiles(name); err != nil { + return "", err + } + } + } + return name, nil + } // readEvents reads from kqueue and converts the received kevents into + // Event values that it sends down the Events channel. + func (w *Watcher) readEvents() { + defer func() { + close(w.Events) + close(w.Errors) + _ = unix.Close(w.kq) + unix.Close(w.closepipe[0]) + }() eventBuffer := make([]unix.Kevent_t, 10) + for closed := false; !closed; { + kevents, err := w.read(eventBuffer) + // EINTR is okay, the syscall was interrupted before timeout expired. + if err != nil && err != unix.EINTR { + if !w.sendError(fmt.Errorf("fsnotify.readEvents: %w", err)) { + closed = true + } + continue + } // Flush the events we received to the Events channel + for _, kevent := range kevents { + var ( watchfd = int(kevent.Ident) - mask = uint32(kevent.Fflags) + + mask = uint32(kevent.Fflags) ) // Shut down the loop when the pipe is closed, but only after all + // other events have been processed. + if watchfd == w.closepipe[0] { + closed = true + continue + } w.mu.Lock() + path := w.paths[watchfd] + w.mu.Unlock() event := w.newEvent(path.name, mask) if event.Has(Rename) || event.Has(Remove) { + w.remove(event.Name, false) + w.mu.Lock() + delete(w.fileExists, event.Name) + w.mu.Unlock() + } if path.isDir && event.Has(Write) && !event.Has(Remove) { + w.sendDirectoryChangeEvents(event.Name) + } else { + if !w.sendEvent(event) { + closed = true + continue + } + } if event.Has(Remove) { + // Look for a file that may have overwritten this; for example, + // mv f1 f2 will delete f2, then create f2. + if path.isDir { + fileDir := filepath.Clean(event.Name) + w.mu.Lock() + _, found := w.watches[fileDir] + w.mu.Unlock() + if found { + err := w.sendDirectoryChangeEvents(fileDir) + if err != nil { + if !w.sendError(err) { + closed = true + } + } + } + } else { + filePath := filepath.Clean(event.Name) + if fi, err := os.Lstat(filePath); err == nil { + err := w.sendFileCreatedEventIfNew(filePath, fi) + if err != nil { + if !w.sendError(err) { + closed = true + } + } + } + } + } + } + } + } // newEvent returns an platform-independent Event based on kqueue Fflags. + func (w *Watcher) newEvent(name string, mask uint32) Event { + e := Event{Name: name} + if mask&unix.NOTE_DELETE == unix.NOTE_DELETE { + e.Op |= Remove + } + if mask&unix.NOTE_WRITE == unix.NOTE_WRITE { + e.Op |= Write + } + if mask&unix.NOTE_RENAME == unix.NOTE_RENAME { + e.Op |= Rename + } + if mask&unix.NOTE_ATTRIB == unix.NOTE_ATTRIB { + e.Op |= Chmod + } + // No point sending a write and delete event at the same time: if it's gone, + // then it's gone. + if e.Op.Has(Write) && e.Op.Has(Remove) { + e.Op &^= Write + } + return e + } // watchDirectoryFiles to mimic inotify when adding a watch on a directory + func (w *Watcher) watchDirectoryFiles(dirPath string) error { + // Get all files + files, err := os.ReadDir(dirPath) + if err != nil { + return err + } for _, f := range files { + path := filepath.Join(dirPath, f.Name()) fi, err := f.Info() + if err != nil { + return fmt.Errorf("%q: %w", path, err) + } cleanPath, err := w.internalWatch(path, fi) + if err != nil { + // No permission to read the file; that's not a problem: just skip. + // But do add it to w.fileExists to prevent it from being picked up + // as a "new" file later (it still shows up in the directory + // listing). + switch { + case errors.Is(err, unix.EACCES) || errors.Is(err, unix.EPERM): + cleanPath = filepath.Clean(path) + default: + return fmt.Errorf("%q: %w", path, err) + } + } w.mu.Lock() + w.fileExists[cleanPath] = struct{}{} + w.mu.Unlock() + } return nil + } // Search the directory for new files and send an event for them. + // + // This functionality is to have the BSD watcher match the inotify, which sends + // a create event for files created in a watched directory. + func (w *Watcher) sendDirectoryChangeEvents(dir string) error { + files, err := os.ReadDir(dir) + if err != nil { + // Directory no longer exists: we can ignore this safely. kqueue will + // still give us the correct events. + if errors.Is(err, os.ErrNotExist) { + return nil + } + return fmt.Errorf("fsnotify.sendDirectoryChangeEvents: %w", err) + } for _, f := range files { + fi, err := f.Info() + if err != nil { + return fmt.Errorf("fsnotify.sendDirectoryChangeEvents: %w", err) + } err = w.sendFileCreatedEventIfNew(filepath.Join(dir, fi.Name()), fi) + if err != nil { + // Don't need to send an error if this file isn't readable. + if errors.Is(err, unix.EACCES) || errors.Is(err, unix.EPERM) { + return nil + } + return fmt.Errorf("fsnotify.sendDirectoryChangeEvents: %w", err) + } + } + return nil + } // sendFileCreatedEvent sends a create event if the file isn't already being tracked. + func (w *Watcher) sendFileCreatedEventIfNew(filePath string, fi os.FileInfo) (err error) { + w.mu.Lock() + _, doesExist := w.fileExists[filePath] + w.mu.Unlock() + if !doesExist { + if !w.sendEvent(Event{Name: filePath, Op: Create}) { + return + } + } // like watchDirectoryFiles (but without doing another ReadDir) + filePath, err = w.internalWatch(filePath, fi) + if err != nil { + return err + } w.mu.Lock() + w.fileExists[filePath] = struct{}{} + w.mu.Unlock() return nil + } func (w *Watcher) internalWatch(name string, fi os.FileInfo) (string, error) { + if fi.IsDir() { + // mimic Linux providing delete events for subdirectories, but preserve + // the flags used if currently watching subdirectory + w.mu.Lock() + flags := w.dirFlags[name] + w.mu.Unlock() flags |= unix.NOTE_DELETE | unix.NOTE_RENAME + return w.addWatch(name, flags) + } // watch file to mimic Linux inotify + return w.addWatch(name, noteAllEvents) + } // Register events with the queue. + func (w *Watcher) register(fds []int, flags int, fflags uint32) error { + changes := make([]unix.Kevent_t, len(fds)) + for i, fd := range fds { + // SetKevent converts int to the platform-specific types. + unix.SetKevent(&changes[i], fd, unix.EVFILT_VNODE, flags) + changes[i].Fflags = fflags + } // Register the events. + success, err := unix.Kevent(w.kq, changes, nil, nil) + if success == -1 { + return err + } + return nil + } // read retrieves pending events, or waits until an event occurs. + func (w *Watcher) read(events []unix.Kevent_t) ([]unix.Kevent_t, error) { + n, err := unix.Kevent(w.kq, nil, events, nil) + if err != nil { + return nil, err + } + return events[0:n], nil + } diff --git a/vendor/github.com/fsnotify/fsnotify/backend_windows.go b/vendor/github.com/fsnotify/fsnotify/backend_windows.go index 9bc91e5..2f913bd 100644 --- a/vendor/github.com/fsnotify/fsnotify/backend_windows.go +++ b/vendor/github.com/fsnotify/fsnotify/backend_windows.go @@ -2,10 +2,15 @@ // +build windows // Windows backend based on ReadDirectoryChangesW() + // + // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-readdirectorychangesw + // + // Note: the documentation on the Watcher type and methods is generated from + // mkdoc.zsh package fsnotify @@ -25,361 +30,661 @@ import ( ) // Watcher watches a set of paths, delivering events on a channel. + // + // A watcher should not be copied (e.g. pass it by pointer, rather than by + // value). + // + // # Linux notes + // + // When a file is removed a Remove event won't be emitted until all file + // descriptors are closed, and deletes will always emit a Chmod. For example: + // + // fp := os.Open("file") + // os.Remove("file") // Triggers Chmod + // fp.Close() // Triggers Remove + // + // This is the event that inotify sends, so not much can be changed about this. + // + // The fs.inotify.max_user_watches sysctl variable specifies the upper limit + // for the number of watches per user, and fs.inotify.max_user_instances + // specifies the maximum number of inotify instances per user. Every Watcher you + // create is an "instance", and every path you add is a "watch". + // + // These are also exposed in /proc as /proc/sys/fs/inotify/max_user_watches and + // /proc/sys/fs/inotify/max_user_instances + // + // To increase them you can use sysctl or write the value to the /proc file: + // + // # Default values on Linux 5.18 + // sysctl fs.inotify.max_user_watches=124983 + // sysctl fs.inotify.max_user_instances=128 + // + // To make the changes persist on reboot edit /etc/sysctl.conf or + // /usr/lib/sysctl.d/50-default.conf (details differ per Linux distro; check + // your distro's documentation): + // + // fs.inotify.max_user_watches=124983 + // fs.inotify.max_user_instances=128 + // + // Reaching the limit will result in a "no space left on device" or "too many open + // files" error. + // + // # kqueue notes (macOS, BSD) + // + // kqueue requires opening a file descriptor for every file that's being watched; + // so if you're watching a directory with five files then that's six file + // descriptors. You will run in to your system's "max open files" limit faster on + // these platforms. + // + // The sysctl variables kern.maxfiles and kern.maxfilesperproc can be used to + // control the maximum number of open files, as well as /etc/login.conf on BSD + // systems. + // + // # Windows notes + // + // Paths can be added as "C:\path\to\dir", but forward slashes + // ("C:/path/to/dir") will also work. + // + // When a watched directory is removed it will always send an event for the + // directory itself, but may not send events for all files in that directory. + // Sometimes it will send events for all times, sometimes it will send no + // events, and often only for some files. + // + // The default ReadDirectoryChangesW() buffer size is 64K, which is the largest + // value that is guaranteed to work with SMB filesystems. If you have many + // events in quick succession this may not be enough, and you will have to use + // [WithBufferSize] to increase the value. + type Watcher struct { + // Events sends the filesystem change events. + // + // fsnotify can send the following events; a "path" here can refer to a + // file, directory, symbolic link, or special file like a FIFO. + // + // fsnotify.Create A new path was created; this may be followed by one + // or more Write events if data also gets written to a + // file. + // + // fsnotify.Remove A path was removed. + // + // fsnotify.Rename A path was renamed. A rename is always sent with the + // old path as Event.Name, and a Create event will be + // sent with the new name. Renames are only sent for + // paths that are currently watched; e.g. moving an + // unmonitored file into a monitored directory will + // show up as just a Create. Similarly, renaming a file + // to outside a monitored directory will show up as + // only a Rename. + // + // fsnotify.Write A file or named pipe was written to. A Truncate will + // also trigger a Write. A single "write action" + // initiated by the user may show up as one or multiple + // writes, depending on when the system syncs things to + // disk. For example when compiling a large Go program + // you may get hundreds of Write events, and you may + // want to wait until you've stopped receiving them + // (see the dedup example in cmd/fsnotify). + // + // Some systems may send Write event for directories + // when the directory content changes. + // + // fsnotify.Chmod Attributes were changed. On Linux this is also sent + // when a file is removed (or more accurately, when a + // link to an inode is removed). On kqueue it's sent + // when a file is truncated. On Windows it's never + // sent. + Events chan Event // Errors sends any errors. + // + // ErrEventOverflow is used to indicate there are too many events: + // + // - inotify: There are too many queued events (fs.inotify.max_queued_events sysctl) + // - windows: The buffer size is too small; WithBufferSize() can be used to increase it. + // - kqueue, fen: Not used. + Errors chan error - port windows.Handle // Handle to completion port - input chan *input // Inputs to the reader are sent on this channel - quit chan chan<- error + port windows.Handle // Handle to completion port + + input chan *input // Inputs to the reader are sent on this channel + + quit chan chan<- error + + mu sync.Mutex // Protects access to watches, closed + + watches watchMap // Map of watches (key: i-number) + + closed bool // Set to true when Close() is first called - mu sync.Mutex // Protects access to watches, closed - watches watchMap // Map of watches (key: i-number) - closed bool // Set to true when Close() is first called } // NewWatcher creates a new Watcher. + func NewWatcher() (*Watcher, error) { + return NewBufferedWatcher(50) + } // NewBufferedWatcher creates a new Watcher with a buffered Watcher.Events + // channel. + // + // The main use case for this is situations with a very large number of events + // where the kernel buffer size can't be increased (e.g. due to lack of + // permissions). An unbuffered Watcher will perform better for almost all use + // cases, and whenever possible you will be better off increasing the kernel + // buffers instead of adding a large userspace buffer. + func NewBufferedWatcher(sz uint) (*Watcher, error) { + port, err := windows.CreateIoCompletionPort(windows.InvalidHandle, 0, 0, 0) + if err != nil { + return nil, os.NewSyscallError("CreateIoCompletionPort", err) + } + w := &Watcher{ - port: port, + + port: port, + watches: make(watchMap), - input: make(chan *input, 1), - Events: make(chan Event, sz), - Errors: make(chan error), - quit: make(chan chan<- error, 1), + + input: make(chan *input, 1), + + Events: make(chan Event, sz), + + Errors: make(chan error), + + quit: make(chan chan<- error, 1), } + go w.readEvents() + return w, nil + } func (w *Watcher) isClosed() bool { + w.mu.Lock() + defer w.mu.Unlock() + return w.closed + } func (w *Watcher) sendEvent(name string, mask uint64) bool { + if mask == 0 { + return false + } event := w.newEvent(name, uint32(mask)) + select { + case ch := <-w.quit: + w.quit <- ch + case w.Events <- event: + } + return true + } // Returns true if the error was sent, or false if watcher is closed. + func (w *Watcher) sendError(err error) bool { + select { + case w.Errors <- err: + return true + case <-w.quit: + } + return false + } // Close removes all watches and closes the Events channel. + func (w *Watcher) Close() error { + if w.isClosed() { + return nil + } w.mu.Lock() + w.closed = true + w.mu.Unlock() // Send "quit" message to the reader goroutine + ch := make(chan error) + w.quit <- ch + if err := w.wakeupReader(); err != nil { + return err + } + return <-ch + } // Add starts monitoring the path for changes. + // + // A path can only be watched once; watching it more than once is a no-op and will + // not return an error. Paths that do not yet exist on the filesystem cannot be + // watched. + // + // A watch will be automatically removed if the watched path is deleted or + // renamed. The exception is the Windows backend, which doesn't remove the + // watcher on renames. + // + // Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special + // filesystems (/proc, /sys, etc.) generally don't work. + // + // Returns [ErrClosed] if [Watcher.Close] was called. + // + // See [Watcher.AddWith] for a version that allows adding options. + // + // # Watching directories + // + // All files in a directory are monitored, including new files that are created + // after the watcher is started. Subdirectories are not watched (i.e. it's + // non-recursive). + // + // # Watching files + // + // Watching individual files (rather than directories) is generally not + // recommended as many programs (especially editors) update files atomically: it + // will write to a temporary file which is then moved to to destination, + // overwriting the original (or some variant thereof). The watcher on the + // original file is now lost, as that no longer exists. + // + // The upshot of this is that a power failure or crash won't leave a + // half-written file. + // + // Watch the parent directory and use Event.Name to filter out files you're not + // interested in. There is an example of this in cmd/fsnotify/file.go. + func (w *Watcher) Add(name string) error { return w.AddWith(name) } // AddWith is like [Watcher.Add], but allows adding options. When using Add() + // the defaults described below are used. + // + // Possible options are: + // + // - [WithBufferSize] sets the buffer size for the Windows backend; no-op on + // other platforms. The default is 64K (65536 bytes). + func (w *Watcher) AddWith(name string, opts ...addOpt) error { + if w.isClosed() { + return ErrClosed + } with := getOptions(opts...) + if with.bufsize < 4096 { + return fmt.Errorf("fsnotify.WithBufferSize: buffer size cannot be smaller than 4096 bytes") + } in := &input{ - op: opAddWatch, - path: filepath.Clean(name), - flags: sysFSALLEVENTS, - reply: make(chan error), + + op: opAddWatch, + + path: filepath.Clean(name), + + flags: sysFSALLEVENTS, + + reply: make(chan error), + bufsize: with.bufsize, } + w.input <- in + if err := w.wakeupReader(); err != nil { + return err + } + return <-in.reply + } // Remove stops monitoring the path for changes. + // + // Directories are always removed non-recursively. For example, if you added + // /tmp/dir and /tmp/dir/subdir then you will need to remove both. + // + // Removing a path that has not yet been added returns [ErrNonExistentWatch]. + // + // Returns nil if [Watcher.Close] was called. + func (w *Watcher) Remove(name string) error { + if w.isClosed() { + return nil + } in := &input{ - op: opRemoveWatch, - path: filepath.Clean(name), + + op: opRemoveWatch, + + path: filepath.Clean(name), + reply: make(chan error), } + w.input <- in + if err := w.wakeupReader(); err != nil { + return err + } + return <-in.reply + } // WatchList returns all paths explicitly added with [Watcher.Add] (and are not + // yet removed). + // + // Returns nil if [Watcher.Close] was called. + func (w *Watcher) WatchList() []string { + if w.isClosed() { + return nil + } w.mu.Lock() + defer w.mu.Unlock() entries := make([]string, 0, len(w.watches)) + for _, entry := range w.watches { + for _, watchEntry := range entry { + entries = append(entries, watchEntry.path) + } + } return entries + } // These options are from the old golang.org/x/exp/winfsnotify, where you could + // add various options to the watch. This has long since been removed. + // + // The "sys" in the name is misleading as they're not part of any "system". + // + // This should all be removed at some point, and just use windows.FILE_NOTIFY_* + const ( - sysFSALLEVENTS = 0xfff - sysFSCREATE = 0x100 - sysFSDELETE = 0x200 + sysFSALLEVENTS = 0xfff + + sysFSCREATE = 0x100 + + sysFSDELETE = 0x200 + sysFSDELETESELF = 0x400 - sysFSMODIFY = 0x2 - sysFSMOVE = 0xc0 - sysFSMOVEDFROM = 0x40 - sysFSMOVEDTO = 0x80 - sysFSMOVESELF = 0x800 - sysFSIGNORED = 0x8000 + + sysFSMODIFY = 0x2 + + sysFSMOVE = 0xc0 + + sysFSMOVEDFROM = 0x40 + + sysFSMOVEDTO = 0x80 + + sysFSMOVESELF = 0x800 + + sysFSIGNORED = 0x8000 ) func (w *Watcher) newEvent(name string, mask uint32) Event { + e := Event{Name: name} + if mask&sysFSCREATE == sysFSCREATE || mask&sysFSMOVEDTO == sysFSMOVEDTO { + e.Op |= Create + } + if mask&sysFSDELETE == sysFSDELETE || mask&sysFSDELETESELF == sysFSDELETESELF { + e.Op |= Remove + } + if mask&sysFSMODIFY == sysFSMODIFY { + e.Op |= Write + } + if mask&sysFSMOVE == sysFSMOVE || mask&sysFSMOVESELF == sysFSMOVESELF || mask&sysFSMOVEDFROM == sysFSMOVEDFROM { + e.Op |= Rename + } + return e + } const ( opAddWatch = iota + opRemoveWatch ) @@ -388,440 +693,786 @@ const ( ) type input struct { - op int - path string - flags uint32 + op int + + path string + + flags uint32 + bufsize int - reply chan error + + reply chan error } type inode struct { handle windows.Handle + volume uint32 - index uint64 + + index uint64 } type watch struct { - ov windows.Overlapped - ino *inode // i-number - recurse bool // Recursive watch? - path string // Directory path - mask uint64 // Directory itself is being watched with these notify flags - names map[string]uint64 // Map of names being watched and their notify flags - rename string // Remembers the old name while renaming a file - buf []byte // buffer, allocated later + ov windows.Overlapped + + ino *inode // i-number + + recurse bool // Recursive watch? + + path string // Directory path + + mask uint64 // Directory itself is being watched with these notify flags + + names map[string]uint64 // Map of names being watched and their notify flags + + rename string // Remembers the old name while renaming a file + + buf []byte // buffer, allocated later + } type ( indexMap map[uint64]*watch + watchMap map[uint32]indexMap ) func (w *Watcher) wakeupReader() error { + err := windows.PostQueuedCompletionStatus(w.port, 0, 0, nil) + if err != nil { + return os.NewSyscallError("PostQueuedCompletionStatus", err) + } + return nil + } func (w *Watcher) getDir(pathname string) (dir string, err error) { + attr, err := windows.GetFileAttributes(windows.StringToUTF16Ptr(pathname)) + if err != nil { + return "", os.NewSyscallError("GetFileAttributes", err) + } + if attr&windows.FILE_ATTRIBUTE_DIRECTORY != 0 { + dir = pathname + } else { + dir, _ = filepath.Split(pathname) + dir = filepath.Clean(dir) + } + return + } func (w *Watcher) getIno(path string) (ino *inode, err error) { + h, err := windows.CreateFile(windows.StringToUTF16Ptr(path), + windows.FILE_LIST_DIRECTORY, + windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, + nil, windows.OPEN_EXISTING, + windows.FILE_FLAG_BACKUP_SEMANTICS|windows.FILE_FLAG_OVERLAPPED, 0) + if err != nil { + return nil, os.NewSyscallError("CreateFile", err) + } var fi windows.ByHandleFileInformation + err = windows.GetFileInformationByHandle(h, &fi) + if err != nil { + windows.CloseHandle(h) + return nil, os.NewSyscallError("GetFileInformationByHandle", err) + } + ino = &inode{ + handle: h, + volume: fi.VolumeSerialNumber, - index: uint64(fi.FileIndexHigh)<<32 | uint64(fi.FileIndexLow), + + index: uint64(fi.FileIndexHigh)<<32 | uint64(fi.FileIndexLow), } + return ino, nil + } // Must run within the I/O thread. + func (m watchMap) get(ino *inode) *watch { + if i := m[ino.volume]; i != nil { + return i[ino.index] + } + return nil + } // Must run within the I/O thread. + func (m watchMap) set(ino *inode, watch *watch) { + i := m[ino.volume] + if i == nil { + i = make(indexMap) + m[ino.volume] = i + } + i[ino.index] = watch + } // Must run within the I/O thread. + func (w *Watcher) addWatch(pathname string, flags uint64, bufsize int) error { + //pathname, recurse := recursivePath(pathname) + recurse := false dir, err := w.getDir(pathname) + if err != nil { + return err + } ino, err := w.getIno(dir) + if err != nil { + return err + } + w.mu.Lock() + watchEntry := w.watches.get(ino) + w.mu.Unlock() + if watchEntry == nil { + _, err := windows.CreateIoCompletionPort(ino.handle, w.port, 0, 0) + if err != nil { + windows.CloseHandle(ino.handle) + return os.NewSyscallError("CreateIoCompletionPort", err) + } + watchEntry = &watch{ - ino: ino, - path: dir, - names: make(map[string]uint64), + + ino: ino, + + path: dir, + + names: make(map[string]uint64), + recurse: recurse, - buf: make([]byte, bufsize), + + buf: make([]byte, bufsize), } + w.mu.Lock() + w.watches.set(ino, watchEntry) + w.mu.Unlock() + flags |= provisional + } else { + windows.CloseHandle(ino.handle) + } + if pathname == dir { + watchEntry.mask |= flags + } else { + watchEntry.names[filepath.Base(pathname)] |= flags + } err = w.startRead(watchEntry) + if err != nil { + return err + } if pathname == dir { + watchEntry.mask &= ^provisional + } else { + watchEntry.names[filepath.Base(pathname)] &= ^provisional + } + return nil + } // Must run within the I/O thread. + func (w *Watcher) remWatch(pathname string) error { + pathname, recurse := recursivePath(pathname) dir, err := w.getDir(pathname) + if err != nil { + return err + } + ino, err := w.getIno(dir) + if err != nil { + return err + } w.mu.Lock() + watch := w.watches.get(ino) + w.mu.Unlock() if recurse && !watch.recurse { + return fmt.Errorf("can't use \\... with non-recursive watch %q", pathname) + } err = windows.CloseHandle(ino.handle) + if err != nil { + w.sendError(os.NewSyscallError("CloseHandle", err)) + } + if watch == nil { + return fmt.Errorf("%w: %s", ErrNonExistentWatch, pathname) + } + if pathname == dir { + w.sendEvent(watch.path, watch.mask&sysFSIGNORED) + watch.mask = 0 + } else { + name := filepath.Base(pathname) + w.sendEvent(filepath.Join(watch.path, name), watch.names[name]&sysFSIGNORED) + delete(watch.names, name) + } return w.startRead(watch) + } // Must run within the I/O thread. + func (w *Watcher) deleteWatch(watch *watch) { + for name, mask := range watch.names { + if mask&provisional == 0 { + w.sendEvent(filepath.Join(watch.path, name), mask&sysFSIGNORED) + } + delete(watch.names, name) + } + if watch.mask != 0 { + if watch.mask&provisional == 0 { + w.sendEvent(watch.path, watch.mask&sysFSIGNORED) + } + watch.mask = 0 + } + } // Must run within the I/O thread. + func (w *Watcher) startRead(watch *watch) error { + err := windows.CancelIo(watch.ino.handle) + if err != nil { + w.sendError(os.NewSyscallError("CancelIo", err)) + w.deleteWatch(watch) + } + mask := w.toWindowsFlags(watch.mask) + for _, m := range watch.names { + mask |= w.toWindowsFlags(m) + } + if mask == 0 { + err := windows.CloseHandle(watch.ino.handle) + if err != nil { + w.sendError(os.NewSyscallError("CloseHandle", err)) + } + w.mu.Lock() + delete(w.watches[watch.ino.volume], watch.ino.index) + w.mu.Unlock() + return nil + } // We need to pass the array, rather than the slice. + hdr := (*reflect.SliceHeader)(unsafe.Pointer(&watch.buf)) + rdErr := windows.ReadDirectoryChanges(watch.ino.handle, + (*byte)(unsafe.Pointer(hdr.Data)), uint32(hdr.Len), + watch.recurse, mask, nil, &watch.ov, 0) + if rdErr != nil { + err := os.NewSyscallError("ReadDirectoryChanges", rdErr) + if rdErr == windows.ERROR_ACCESS_DENIED && watch.mask&provisional == 0 { + // Watched directory was probably removed + w.sendEvent(watch.path, watch.mask&sysFSDELETESELF) + err = nil + } + w.deleteWatch(watch) + w.startRead(watch) + return err + } + return nil + } // readEvents reads from the I/O completion port, converts the + // received events into Event objects and sends them via the Events channel. + // Entry point to the I/O thread. + func (w *Watcher) readEvents() { + var ( - n uint32 + n uint32 + key uintptr - ov *windows.Overlapped + + ov *windows.Overlapped ) + runtime.LockOSThread() for { + // This error is handled after the watch == nil check below. + qErr := windows.GetQueuedCompletionStatus(w.port, &n, &key, &ov, windows.INFINITE) watch := (*watch)(unsafe.Pointer(ov)) + if watch == nil { + select { + case ch := <-w.quit: + w.mu.Lock() + var indexes []indexMap + for _, index := range w.watches { + indexes = append(indexes, index) + } + w.mu.Unlock() + for _, index := range indexes { + for _, watch := range index { + w.deleteWatch(watch) + w.startRead(watch) + } + } err := windows.CloseHandle(w.port) + if err != nil { + err = os.NewSyscallError("CloseHandle", err) + } + close(w.Events) + close(w.Errors) + ch <- err + return + case in := <-w.input: + switch in.op { + case opAddWatch: + in.reply <- w.addWatch(in.path, uint64(in.flags), in.bufsize) + case opRemoveWatch: + in.reply <- w.remWatch(in.path) + } + default: + } + continue + } switch qErr { + case nil: + // No error + case windows.ERROR_MORE_DATA: + if watch == nil { + w.sendError(errors.New("ERROR_MORE_DATA has unexpectedly null lpOverlapped buffer")) + } else { + // The i/o succeeded but the buffer is full. + // In theory we should be building up a full packet. + // In practice we can get away with just carrying on. + n = uint32(unsafe.Sizeof(watch.buf)) + } + case windows.ERROR_ACCESS_DENIED: + // Watched directory was probably removed + w.sendEvent(watch.path, watch.mask&sysFSDELETESELF) + w.deleteWatch(watch) + w.startRead(watch) + continue + case windows.ERROR_OPERATION_ABORTED: + // CancelIo was called on this handle + continue + default: + w.sendError(os.NewSyscallError("GetQueuedCompletionPort", qErr)) + continue + } var offset uint32 + for { + if n == 0 { + w.sendError(ErrEventOverflow) + break + } // Point "raw" to the event in the buffer + raw := (*windows.FileNotifyInformation)(unsafe.Pointer(&watch.buf[offset])) // Create a buf that is the size of the path name + size := int(raw.FileNameLength / 2) + var buf []uint16 + // TODO: Use unsafe.Slice in Go 1.17; https://stackoverflow.com/questions/51187973 + sh := (*reflect.SliceHeader)(unsafe.Pointer(&buf)) + sh.Data = uintptr(unsafe.Pointer(&raw.FileName)) + sh.Len = size + sh.Cap = size + name := windows.UTF16ToString(buf) + fullname := filepath.Join(watch.path, name) var mask uint64 + switch raw.Action { + case windows.FILE_ACTION_REMOVED: + mask = sysFSDELETESELF + case windows.FILE_ACTION_MODIFIED: + mask = sysFSMODIFY + case windows.FILE_ACTION_RENAMED_OLD_NAME: + watch.rename = name + case windows.FILE_ACTION_RENAMED_NEW_NAME: + // Update saved path of all sub-watches. + old := filepath.Join(watch.path, watch.rename) + w.mu.Lock() + for _, watchMap := range w.watches { + for _, ww := range watchMap { + if strings.HasPrefix(ww.path, old) { + ww.path = filepath.Join(fullname, strings.TrimPrefix(ww.path, old)) + } + } + } + w.mu.Unlock() if watch.names[watch.rename] != 0 { + watch.names[name] |= watch.names[watch.rename] + delete(watch.names, watch.rename) + mask = sysFSMOVESELF + } + } sendNameEvent := func() { + w.sendEvent(fullname, watch.names[name]&mask) + } + if raw.Action != windows.FILE_ACTION_RENAMED_NEW_NAME { + sendNameEvent() + } + if raw.Action == windows.FILE_ACTION_REMOVED { + w.sendEvent(fullname, watch.names[name]&sysFSIGNORED) + delete(watch.names, name) + } w.sendEvent(fullname, watch.mask&w.toFSnotifyFlags(raw.Action)) + if raw.Action == windows.FILE_ACTION_RENAMED_NEW_NAME { + fullname = filepath.Join(watch.path, watch.rename) + sendNameEvent() + } // Move to the next event in the buffer + if raw.NextEntryOffset == 0 { + break + } + offset += raw.NextEntryOffset // Error! + if offset >= n { + //lint:ignore ST1005 Windows should be capitalized + w.sendError(errors.New( + "Windows system assumed buffer larger than it is, events have likely been missed")) + break + } + } if err := w.startRead(watch); err != nil { + w.sendError(err) + } + } + } func (w *Watcher) toWindowsFlags(mask uint64) uint32 { + var m uint32 + if mask&sysFSMODIFY != 0 { + m |= windows.FILE_NOTIFY_CHANGE_LAST_WRITE + } + if mask&(sysFSMOVE|sysFSCREATE|sysFSDELETE) != 0 { + m |= windows.FILE_NOTIFY_CHANGE_FILE_NAME | windows.FILE_NOTIFY_CHANGE_DIR_NAME + } + return m + } func (w *Watcher) toFSnotifyFlags(action uint32) uint64 { + switch action { + case windows.FILE_ACTION_ADDED: + return sysFSCREATE + case windows.FILE_ACTION_REMOVED: + return sysFSDELETE + case windows.FILE_ACTION_MODIFIED: + return sysFSMODIFY + case windows.FILE_ACTION_RENAMED_OLD_NAME: + return sysFSMOVEDFROM + case windows.FILE_ACTION_RENAMED_NEW_NAME: + return sysFSMOVEDTO + } + return 0 + } diff --git a/vendor/github.com/fsnotify/fsnotify/fsnotify.go b/vendor/github.com/fsnotify/fsnotify/fsnotify.go index 24c99cc..0e70065 100644 --- a/vendor/github.com/fsnotify/fsnotify/fsnotify.go +++ b/vendor/github.com/fsnotify/fsnotify/fsnotify.go @@ -1,12 +1,21 @@ // Package fsnotify provides a cross-platform interface for file system + // notifications. + // + // Currently supported systems: + // + // Linux 2.6.32+ via inotify + // BSD, macOS via kqueue + // Windows via ReadDirectoryChangesW + // illumos via FEN + package fsnotify import ( @@ -17,130 +26,215 @@ import ( ) // Event represents a file system notification. + type Event struct { + // Path to the file or directory. + // + // Paths are relative to the input; for example with Add("dir") the Name + // will be set to "dir/file" if you create that file, but if you use + // Add("/path/to/dir") it will be "/path/to/dir/file". + Name string // File operation that triggered the event. + // + // This is a bitmask and some systems may send multiple operations at once. + // Use the Event.Has() method instead of comparing with ==. + Op Op } // Op describes a set of file operations. + type Op uint32 // The operations fsnotify can trigger; see the documentation on [Watcher] for a + // full description, and check them with [Event.Has]. + const ( + // A new pathname was created. + Create Op = 1 << iota // The pathname was written to; this does *not* mean the write has finished, + // and a write can be followed by more writes. + Write // The path was removed; any watches on it will be removed. Some "remove" + // operations may trigger a Rename if the file is actually moved (for + // example "remove to trash" is often a rename). + Remove // The path was renamed to something else; any watched on it will be + // removed. + Rename // File attributes were changed. + // + // It's generally not recommended to take action on this event, as it may + // get triggered very frequently by some software. For example, Spotlight + // indexing on macOS, anti-virus software, backup software, etc. + Chmod ) // Common errors that can be reported. + var ( ErrNonExistentWatch = errors.New("fsnotify: can't remove non-existent watch") - ErrEventOverflow = errors.New("fsnotify: queue or buffer overflow") - ErrClosed = errors.New("fsnotify: watcher already closed") + + ErrEventOverflow = errors.New("fsnotify: queue or buffer overflow") + + ErrClosed = errors.New("fsnotify: watcher already closed") ) func (o Op) String() string { + var b strings.Builder + if o.Has(Create) { + b.WriteString("|CREATE") + } + if o.Has(Remove) { + b.WriteString("|REMOVE") + } + if o.Has(Write) { + b.WriteString("|WRITE") + } + if o.Has(Rename) { + b.WriteString("|RENAME") + } + if o.Has(Chmod) { + b.WriteString("|CHMOD") + } + if b.Len() == 0 { + return "[no events]" + } + return b.String()[1:] + } // Has reports if this operation has the given operation. + func (o Op) Has(h Op) bool { return o&h != 0 } // Has reports if this event has the given operation. + func (e Event) Has(op Op) bool { return e.Op.Has(op) } // String returns a string representation of the event with their path. + func (e Event) String() string { + return fmt.Sprintf("%-13s %q", e.Op.String(), e.Name) + } type ( - addOpt func(opt *withOpts) + addOpt func(opt *withOpts) + withOpts struct { bufsize int } ) var defaultOpts = withOpts{ + bufsize: 65536, // 64K + } func getOptions(opts ...addOpt) withOpts { + with := defaultOpts + for _, o := range opts { + o(&with) + } + return with + } // WithBufferSize sets the [ReadDirectoryChangesW] buffer size. + // + // This only has effect on Windows systems, and is a no-op for other backends. + // + // The default value is 64K (65536 bytes) which is the highest value that works + // on all filesystems and should be enough for most applications, but if you + // have a large burst of events it may not be enough. You can increase it if + // you're hitting "queue or buffer overflow" errors ([ErrEventOverflow]). + // + // [ReadDirectoryChangesW]: https://learn.microsoft.com/en-gb/windows/win32/api/winbase/nf-winbase-readdirectorychangesw + func WithBufferSize(bytes int) addOpt { + return func(opt *withOpts) { opt.bufsize = bytes } + } // Check if this path is recursive (ends with "/..." or "\..."), and return the + // path with the /... stripped. + func recursivePath(path string) (string, bool) { + if filepath.Base(path) == "..." { + return filepath.Dir(path), true + } + return path, false + } diff --git a/vendor/github.com/ghodss/yaml/fields.go b/vendor/github.com/ghodss/yaml/fields.go index 5e36e56..ab95067 100644 --- a/vendor/github.com/ghodss/yaml/fields.go +++ b/vendor/github.com/ghodss/yaml/fields.go @@ -1,6 +1,9 @@ // Copyright 2013 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. + package yaml import ( @@ -16,76 +19,133 @@ import ( ) // 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 last pointer so it can be set to nil. + func indirect(v reflect.Value, decodingNull bool) (json.Unmarshaler, encoding.TextUnmarshaler, reflect.Value) { + // If v is a named type and is addressable, + // start with its address, so that if the type has pointer methods, + // we find them. + if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() { + v = v.Addr() + } + for { + // Load value from interface, but only if the result will be + // usefully addressable. + if v.Kind() == reflect.Interface && !v.IsNil() { + e := v.Elem() + if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) { + v = e + continue + } + } if v.Kind() != reflect.Ptr { + break + } if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() { + break + } + if v.IsNil() { + if v.CanSet() { + v.Set(reflect.New(v.Type().Elem())) + } else { + v = reflect.New(v.Type().Elem()) + } + } + if v.Type().NumMethod() > 0 { + if u, ok := v.Interface().(json.Unmarshaler); ok { + return u, nil, reflect.Value{} + } + if u, ok := v.Interface().(encoding.TextUnmarshaler); ok { + return nil, u, reflect.Value{} + } + } + v = v.Elem() + } + return nil, nil, v + } // A field represents a single field found in a struct. + type field struct { - name string - nameBytes []byte // []byte(name) + name string + + nameBytes []byte // []byte(name) + equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent - tag bool - index []int - typ reflect.Type + tag bool + + index []int + + typ reflect.Type + omitEmpty bool - quoted bool + + quoted bool } func fillField(f field) field { + f.nameBytes = []byte(f.name) + f.equalFold = foldFunc(f.nameBytes) + return f + } // byName sorts field by name, breaking ties with depth, + // then breaking ties with "name came from json tag", then + // breaking ties with index sequence. + type byName []field func (x byName) Len() int { return len(x) } @@ -93,19 +153,31 @@ func (x byName) Len() int { return len(x) } func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } func (x byName) Less(i, j int) bool { + if x[i].name != x[j].name { + return x[i].name < x[j].name + } + if len(x[i].index) != len(x[j].index) { + return len(x[i].index) < len(x[j].index) + } + if x[i].tag != x[j].tag { + return x[i].tag + } + return byIndex(x).Less(i, j) + } // byIndex sorts field by index sequence. + type byIndex []field func (x byIndex) Len() int { return len(x) } @@ -113,390 +185,712 @@ func (x byIndex) Len() int { return len(x) } func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } func (x byIndex) Less(i, j int) bool { + for k, xik := range x[i].index { + if k >= len(x[j].index) { + return false + } + if xik != x[j].index[k] { + return xik < x[j].index[k] + } + } + return len(x[i].index) < len(x[j].index) + } // 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. + func typeFields(t reflect.Type) []field { + // Anonymous fields to explore at the current level and the next. + current := []field{} + next := []field{{typ: t}} // Count of queued names for current level and the next. + count := map[reflect.Type]int{} + nextCount := map[reflect.Type]int{} // Types already visited at an earlier level. + visited := map[reflect.Type]bool{} // Fields found. + var fields []field for len(next) > 0 { + current, next = next, current[:0] + count, nextCount = nextCount, map[reflect.Type]int{} for _, f := range current { + if visited[f.typ] { + continue + } + visited[f.typ] = true // Scan f.typ for fields to include. + for i := 0; i < f.typ.NumField(); i++ { + sf := f.typ.Field(i) + if sf.PkgPath != "" { // unexported + continue + } + tag := sf.Tag.Get("json") + if tag == "-" { + continue + } + name, opts := parseTag(tag) + if !isValidTag(name) { + name = "" + } + index := make([]int, len(f.index)+1) + copy(index, f.index) + index[len(f.index)] = i ft := sf.Type + if ft.Name() == "" && ft.Kind() == reflect.Ptr { + // Follow pointer. + ft = ft.Elem() + } // Record found field and index sequence. + if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct { + tagged := name != "" + if name == "" { + name = sf.Name + } + fields = append(fields, fillField(field{ - name: name, - tag: tagged, - index: index, - typ: ft, + + name: name, + + tag: tagged, + + index: index, + + typ: ft, + omitEmpty: opts.Contains("omitempty"), - quoted: opts.Contains("string"), + + quoted: opts.Contains("string"), })) + if count[f.typ] > 1 { + // If there were multiple instances, add a second, + // so that the annihilation code will see a duplicate. + // It only cares about the distinction between 1 or 2, + // so don't bother generating any more copies. + fields = append(fields, fields[len(fields)-1]) + } + continue + } // Record new anonymous struct to explore in next round. + nextCount[ft]++ + if nextCount[ft] == 1 { + next = append(next, fillField(field{name: ft.Name(), index: index, typ: ft})) + } + } + } + } sort.Sort(byName(fields)) // Delete all fields that are hidden by the Go rules for embedded fields, + // except that fields with JSON tags are promoted. // The fields are sorted in primary order of name, secondary order + // of field index length. Loop over names; for each name, delete + // hidden fields by choosing the one dominant field that survives. + out := fields[:0] + for advance, i := 0, 0; i < len(fields); i += advance { + // One iteration per name. + // Find the sequence of fields with the name of this first field. + fi := fields[i] + name := fi.name + for advance = 1; i+advance < len(fields); advance++ { + fj := fields[i+advance] + if fj.name != name { + break + } + } + if advance == 1 { // Only one field with this name + out = append(out, fi) + continue + } + dominant, ok := dominantField(fields[i : i+advance]) + if ok { + out = append(out, dominant) + } + } fields = out + sort.Sort(byIndex(fields)) return fields + } // 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 dominantField(fields []field) (field, bool) { + // The fields are sorted in increasing index-length order. The winner + // must therefore be one with the shortest index length. Drop all + // longer entries, which is easy: just truncate the slice. + length := len(fields[0].index) + tagged := -1 // Index of first tagged field. + for i, f := range fields { + if len(f.index) > length { + fields = fields[:i] + break + } + if f.tag { + if tagged >= 0 { + // Multiple tagged fields at the same level: conflict. + // Return no field. + return field{}, false + } + tagged = i + } + } + if tagged >= 0 { + return fields[tagged], true + } + // All remaining fields have the same length. If there's more than one, + // we have a conflict (two fields named "X" at the same level) and we + // return no field. + if len(fields) > 1 { + return field{}, false + } + return fields[0], true + } var fieldCache struct { sync.RWMutex + m map[reflect.Type][]field } // cachedTypeFields is like typeFields but uses a cache to avoid repeated work. + func cachedTypeFields(t reflect.Type) []field { + fieldCache.RLock() + f := fieldCache.m[t] + fieldCache.RUnlock() + if f != nil { + return f + } // Compute fields without lock. + // Might duplicate effort but won't hold other computations back. + f = typeFields(t) + if f == nil { + f = []field{} + } fieldCache.Lock() + if fieldCache.m == nil { + fieldCache.m = map[reflect.Type][]field{} + } + fieldCache.m[t] = f + fieldCache.Unlock() + return f + } func isValidTag(s string) bool { + if s == "" { + return false + } + for _, c := range s { + switch { + case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c): + // Backslash and quote chars are reserved, but + // otherwise any punctuation chars are allowed + // in a tag name. + default: + if !unicode.IsLetter(c) && !unicode.IsDigit(c) { + return false + } + } + } + return true + } const ( - caseMask = ^byte(0x20) // Mask to ignore case in ASCII. - kelvin = '\u212a' + caseMask = ^byte(0x20) // Mask to ignore case in ASCII. + + kelvin = '\u212a' + smallLongEss = '\u017f' ) // foldFunc returns one of four different case folding equivalence + // functions, from most general (and slow) to fastest: + // + // 1) bytes.EqualFold, if the key s contains any non-ASCII UTF-8 + // 2) equalFoldRight, if s contains special folding ASCII ('k', 'K', 's', 'S') + // 3) asciiEqualFold, no special, but includes non-letters (including _) + // 4) simpleLetterEqualFold, no specials, no non-letters. + // + // The letters S and K are special because they map to 3 runes, not just 2: + // - S maps to s and to U+017F 'ſ' Latin small letter long s + // - k maps to K and to U+212A 'K' Kelvin sign + // + // See http://play.golang.org/p/tTxjOc0OGo + // + // The returned function is specialized for matching against s and + // should only be given s. It's not curried for performance reasons. + func foldFunc(s []byte) func(s, t []byte) bool { + nonLetter := false + special := false // special letter + for _, b := range s { + if b >= utf8.RuneSelf { + return bytes.EqualFold + } + upper := b & caseMask + if upper < 'A' || upper > 'Z' { + nonLetter = true + } else if upper == 'K' || upper == 'S' { + // See above for why these letters are special. + special = true + } + } + if special { + return equalFoldRight + } + if nonLetter { + return asciiEqualFold + } + return simpleLetterEqualFold + } // equalFoldRight is a specialization of bytes.EqualFold when s is + // known to be all ASCII (including punctuation), but contains an 's', + // 'S', 'k', or 'K', requiring a Unicode fold on the bytes in t. + // See comments on foldFunc. + func equalFoldRight(s, t []byte) bool { + for _, sb := range s { + if len(t) == 0 { + return false + } + tb := t[0] + if tb < utf8.RuneSelf { + if sb != tb { + sbUpper := sb & caseMask + if 'A' <= sbUpper && sbUpper <= 'Z' { + if sbUpper != tb&caseMask { + return false + } + } else { + return false + } + } + t = t[1:] + continue + } + // sb is ASCII and t is not. t must be either kelvin + // sign or long s; sb must be s, S, k, or K. + tr, size := utf8.DecodeRune(t) + switch sb { + case 's', 'S': + if tr != smallLongEss { + return false + } + case 'k', 'K': + if tr != kelvin { + return false + } + default: + return false + } + t = t[size:] } + if len(t) > 0 { + return false + } + return true + } // asciiEqualFold is a specialization of bytes.EqualFold for use when + // s is all ASCII (but may contain non-letters) and contains no + // special-folding letters. + // See comments on foldFunc. + func asciiEqualFold(s, t []byte) bool { + if len(s) != len(t) { + return false + } + for i, sb := range s { + tb := t[i] + if sb == tb { + continue + } + if ('a' <= sb && sb <= 'z') || ('A' <= sb && sb <= 'Z') { + if sb&caseMask != tb&caseMask { + return false + } + } else { + return false + } + } + return true + } // simpleLetterEqualFold is a specialization of bytes.EqualFold for + // use when s is all ASCII letters (no underscores, etc) and also + // doesn't contain 'k', 'K', 's', or 'S'. + // See comments on foldFunc. + func simpleLetterEqualFold(s, t []byte) bool { + if len(s) != len(t) { + return false + } + for i, b := range s { + if b&caseMask != t[i]&caseMask { + return false + } + } + return true + } // 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. + type tagOptions string // parseTag splits a struct field's json tag into its name and + // comma-separated options. + func parseTag(tag string) (string, tagOptions) { + if idx := strings.Index(tag, ","); idx != -1 { + return tag[:idx], tagOptions(tag[idx+1:]) + } + return tag, tagOptions("") + } // Contains reports whether a comma-separated list of options + // contains a particular substr flag. substr must be surrounded by a + // string boundary or commas. + func (o tagOptions) Contains(optionName string) bool { + if len(o) == 0 { + return false + } + s := string(o) + for s != "" { + var next string + i := strings.Index(s, ",") + if i >= 0 { + s, next = s[:i], s[i+1:] + } + if s == optionName { + return true + } + s = next + } + return false + } diff --git a/vendor/github.com/ghodss/yaml/yaml.go b/vendor/github.com/ghodss/yaml/yaml.go index 70edc4b..a0e23ac 100644 --- a/vendor/github.com/ghodss/yaml/yaml.go +++ b/vendor/github.com/ghodss/yaml/yaml.go @@ -11,267 +11,495 @@ import ( ) // Marshals the object into JSON then converts JSON to YAML and returns the + // YAML. + func Marshal(o interface{}) ([]byte, error) { + j, err := json.Marshal(o) + if err != nil { + return nil, fmt.Errorf("error marshaling into JSON: %v", err) + } y, err := JSONToYAML(j) + if err != nil { + return nil, fmt.Errorf("error converting JSON to YAML: %v", err) + } return y, nil + } // Converts YAML to JSON then uses JSON to unmarshal into an object. + func Unmarshal(y []byte, o interface{}) error { + vo := reflect.ValueOf(o) + j, err := yamlToJSON(y, &vo) + if err != nil { + return fmt.Errorf("error converting YAML to JSON: %v", err) + } err = json.Unmarshal(j, o) + if err != nil { + return fmt.Errorf("error unmarshaling JSON: %v", err) + } return nil + } // Convert JSON to YAML. + func JSONToYAML(j []byte) ([]byte, error) { + // Convert the JSON to an object. + var jsonObj interface{} + // We are using yaml.Unmarshal here (instead of json.Unmarshal) because the + // Go JSON library doesn't try to pick the right number type (int, float, + // etc.) when unmarshalling to interface{}, it just picks float64 + // universally. go-yaml does go through the effort of picking the right + // number type, so we can preserve number type throughout this process. + err := yaml.Unmarshal(j, &jsonObj) + if err != nil { + return nil, err + } // Marshal this object into YAML. + return yaml.Marshal(jsonObj) + } // Convert YAML to JSON. Since JSON is a subset of YAML, passing JSON through + // this method should be a no-op. + // + // Things YAML can do that are not supported by JSON: + // - In YAML you can have binary and null keys in your maps. These are invalid + // in JSON. (int and float keys are converted to strings.) + // - Binary data in YAML with the !!binary tag is not supported. If you want to + // use binary data with this library, encode the data as base64 as usual but do + // not use the !!binary tag in your YAML. This will ensure the original base64 + // encoded data makes it all the way through to the JSON. + func YAMLToJSON(y []byte) ([]byte, error) { + return yamlToJSON(y, nil) + } func yamlToJSON(y []byte, jsonTarget *reflect.Value) ([]byte, error) { + // Convert the YAML to an object. + var yamlObj interface{} + err := yaml.Unmarshal(y, &yamlObj) + if err != nil { + return nil, err + } // YAML objects are not completely compatible with JSON objects (e.g. you + // can have non-string keys in YAML). So, convert the YAML-compatible object + // to a JSON-compatible object, failing with an error if irrecoverable + // incompatibilties happen along the way. + jsonObj, err := convertToJSONableObject(yamlObj, jsonTarget) + if err != nil { + return nil, err + } // Convert this object to JSON and return the data. + return json.Marshal(jsonObj) + } func convertToJSONableObject(yamlObj interface{}, jsonTarget *reflect.Value) (interface{}, error) { + var err error // Resolve jsonTarget to a concrete value (i.e. not a pointer or an + // interface). We pass decodingNull as false because we're not actually + // decoding into the value, we're just checking if the ultimate target is a + // string. + if jsonTarget != nil { + ju, tu, pv := indirect(*jsonTarget, false) + // We have a JSON or Text Umarshaler at this level, so we can't be trying + // to decode into a string. + if ju != nil || tu != nil { + jsonTarget = nil + } else { + jsonTarget = &pv + } + } // If yamlObj is a number or a boolean, check if jsonTarget is a string - + // if so, coerce. Else return normal. + // If yamlObj is a map or array, find the field that each key is + // unmarshaling to, and when you recurse pass the reflect.Value for that + // field back into this function. + switch typedYAMLObj := yamlObj.(type) { + case map[interface{}]interface{}: + // JSON does not support arbitrary keys in a map, so we must convert + // these keys to strings. + // + // From my reading of go-yaml v2 (specifically the resolve function), + // keys can only have the types string, int, int64, float64, binary + // (unsupported), or null (unsupported). + strMap := make(map[string]interface{}) + for k, v := range typedYAMLObj { + // Resolve the key to a string first. + var keyString string + switch typedKey := k.(type) { + case string: + keyString = typedKey + case int: + keyString = strconv.Itoa(typedKey) + case int64: + // go-yaml will only return an int64 as a key if the system + // architecture is 32-bit and the key's value is between 32-bit + // and 64-bit. Otherwise the key type will simply be int. + keyString = strconv.FormatInt(typedKey, 10) + case float64: + // Stolen from go-yaml to use the same conversion to string as + // the go-yaml library uses to convert float to string when + // Marshaling. + s := strconv.FormatFloat(typedKey, 'g', -1, 32) + switch s { + case "+Inf": + s = ".inf" + case "-Inf": + s = "-.inf" + case "NaN": + s = ".nan" + } + keyString = s + case bool: + if typedKey { + keyString = "true" + } else { + keyString = "false" + } + default: + return nil, fmt.Errorf("Unsupported map key of type: %s, key: %+#v, value: %+#v", + reflect.TypeOf(k), k, v) + } // jsonTarget should be a struct or a map. If it's a struct, find + // the field it's going to map to and pass its reflect.Value. If + // it's a map, find the element type of the map and pass the + // reflect.Value created from that type. If it's neither, just pass + // nil - JSON conversion will error for us if it's a real issue. + if jsonTarget != nil { + t := *jsonTarget + if t.Kind() == reflect.Struct { + keyBytes := []byte(keyString) + // Find the field that the JSON library would use. + var f *field + fields := cachedTypeFields(t.Type()) + for i := range fields { + ff := &fields[i] + if bytes.Equal(ff.nameBytes, keyBytes) { + f = ff + break + } + // Do case-insensitive comparison. + if f == nil && ff.equalFold(ff.nameBytes, keyBytes) { + f = ff + } + } + if f != nil { + // Find the reflect.Value of the most preferential + // struct field. + jtf := t.Field(f.index[0]) + strMap[keyString], err = convertToJSONableObject(v, &jtf) + if err != nil { + return nil, err + } + continue + } + } else if t.Kind() == reflect.Map { + // Create a zero value of the map's element type to use as + // the JSON target. + jtv := reflect.Zero(t.Type().Elem()) + strMap[keyString], err = convertToJSONableObject(v, &jtv) + if err != nil { + return nil, err + } + continue + } + } + strMap[keyString], err = convertToJSONableObject(v, nil) + if err != nil { + return nil, err + } + } + return strMap, nil + case []interface{}: + // We need to recurse into arrays in case there are any + // map[interface{}]interface{}'s inside and to convert any + // numbers to strings. // If jsonTarget is a slice (which it really should be), find the + // thing it's going to map to. If it's not a slice, just pass nil + // - JSON conversion will error for us if it's a real issue. + var jsonSliceElemValue *reflect.Value + if jsonTarget != nil { + t := *jsonTarget + if t.Kind() == reflect.Slice { + // By default slices point to nil, but we need a reflect.Value + // pointing to a value of the slice type, so we create one here. + ev := reflect.Indirect(reflect.New(t.Type().Elem())) + jsonSliceElemValue = &ev + } + } // Make and use a new array. + arr := make([]interface{}, len(typedYAMLObj)) + for i, v := range typedYAMLObj { + arr[i], err = convertToJSONableObject(v, jsonSliceElemValue) + if err != nil { + return nil, err + } + } + return arr, nil + default: + // If the target type is a string and the YAML type is a number, + // convert the YAML type to a string. + if jsonTarget != nil && (*jsonTarget).Kind() == reflect.String { + // Based on my reading of go-yaml, it may return int, int64, + // float64, or uint64. + var s string + switch typedVal := typedYAMLObj.(type) { + case int: + s = strconv.FormatInt(int64(typedVal), 10) + case int64: + s = strconv.FormatInt(typedVal, 10) + case float64: + s = strconv.FormatFloat(typedVal, 'g', -1, 32) + case uint64: + s = strconv.FormatUint(typedVal, 10) + case bool: + if typedVal { + s = "true" + } else { + s = "false" + } + } + if len(s) > 0 { + yamlObj = interface{}(s) + } + } + return yamlObj, nil + } return nil, nil + } diff --git a/vendor/github.com/go-gorp/gorp/v3/db.go b/vendor/github.com/go-gorp/gorp/v3/db.go index 249ad6f..21f24ee 100644 --- a/vendor/github.com/go-gorp/gorp/v3/db.go +++ b/vendor/github.com/go-gorp/gorp/v3/db.go @@ -1,5 +1,7 @@ // Copyright 2012 James Cooper. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package gorp @@ -19,862 +21,1519 @@ import ( ) // DbMap is the root gorp mapping object. Create one of these for each + // database schema you wish to map. Each DbMap contains a list of + // mapped tables. + // + // Example: + // + // dialect := gorp.MySQLDialect{"InnoDB", "UTF8"} + // dbmap := &gorp.DbMap{Db: db, Dialect: dialect} + type DbMap struct { ctx context.Context // Db handle to use with this map + Db *sql.DB // Dialect implementation to use with this map + Dialect Dialect TypeConverter TypeConverter // ExpandSlices when enabled will convert slice arguments in mappers into flat + // values. It will modify the query, adding more placeholders, and the mapper, + // adding each item of the slice as a new unique entry in the mapper. For + // example, given the scenario bellow: + // + // dbmap.Select(&output, "SELECT 1 FROM example WHERE id IN (:IDs)", map[string]interface{}{ + // "IDs": []int64{1, 2, 3}, + // }) + // + // The executed query would be: + // + // SELECT 1 FROM example WHERE id IN (:IDs0,:IDs1,:IDs2) + // + // With the mapper: + // + // map[string]interface{}{ + // "IDs": []int64{1, 2, 3}, + // "IDs0": int64(1), + // "IDs1": int64(2), + // "IDs2": int64(3), + // } + // + // It is also flexible for custom slice types. The value just need to + // implement stringer or numberer interfaces. + // + // type CustomValue string + // + // const ( + // CustomValueHey CustomValue = "hey" + // CustomValueOh CustomValue = "oh" + // ) + // + // type CustomValues []CustomValue + // + // func (c CustomValues) ToStringSlice() []string { + // values := make([]string, len(c)) + // for i := range c { + // values[i] = string(c[i]) + // } + // return values + // } + // + // func query() { + // // ... + // result, err := dbmap.Select(&output, "SELECT 1 FROM example WHERE value IN (:Values)", map[string]interface{}{ + // "Values": CustomValues([]CustomValue{CustomValueHey}), + // }) + // // ... + // } + ExpandSliceArgs bool - tables []*TableMap + tables []*TableMap + tablesDynamic map[string]*TableMap // tables that use same go-struct and different db table names - logger GorpLogger - logPrefix string + + logger GorpLogger + + logPrefix string } func (m *DbMap) dynamicTableAdd(tableName string, tbl *TableMap) { + if m.tablesDynamic == nil { + m.tablesDynamic = make(map[string]*TableMap) + } + m.tablesDynamic[tableName] = tbl + } func (m *DbMap) dynamicTableFind(tableName string) (*TableMap, bool) { + if m.tablesDynamic == nil { + return nil, false + } + tbl, found := m.tablesDynamic[tableName] + return tbl, found + } func (m *DbMap) dynamicTableMap() map[string]*TableMap { + if m.tablesDynamic == nil { + m.tablesDynamic = make(map[string]*TableMap) + } + return m.tablesDynamic + } func (m *DbMap) WithContext(ctx context.Context) SqlExecutor { + copy := &DbMap{} + *copy = *m + copy.ctx = ctx + return copy + } func (m *DbMap) CreateIndex() error { + var err error + dialect := reflect.TypeOf(m.Dialect) + for _, table := range m.tables { + for _, index := range table.indexes { + err = m.createIndexImpl(dialect, table, index) + if err != nil { + break + } + } + } for _, table := range m.dynamicTableMap() { + for _, index := range table.indexes { + err = m.createIndexImpl(dialect, table, index) + if err != nil { + break + } + } + } return err + } func (m *DbMap) createIndexImpl(dialect reflect.Type, + table *TableMap, + index *IndexMap) error { + s := bytes.Buffer{} + s.WriteString("create") + if index.Unique { + s.WriteString(" unique") + } + s.WriteString(" index") + s.WriteString(fmt.Sprintf(" %s on %s", index.IndexName, table.TableName)) + if dname := dialect.Name(); dname == "PostgresDialect" && index.IndexType != "" { + s.WriteString(fmt.Sprintf(" %s %s", m.Dialect.CreateIndexSuffix(), index.IndexType)) + } + s.WriteString(" (") + for x, col := range index.columns { + if x > 0 { + s.WriteString(", ") + } + s.WriteString(m.Dialect.QuoteField(col)) + } + s.WriteString(")") if dname := dialect.Name(); dname == "MySQLDialect" && index.IndexType != "" { + s.WriteString(fmt.Sprintf(" %s %s", m.Dialect.CreateIndexSuffix(), index.IndexType)) + } + s.WriteString(";") + _, err := m.Exec(s.String()) + return err + } func (t *TableMap) DropIndex(name string) error { var err error + dialect := reflect.TypeOf(t.dbmap.Dialect) + for _, idx := range t.indexes { + if idx.IndexName == name { + s := bytes.Buffer{} + s.WriteString(fmt.Sprintf("DROP INDEX %s", idx.IndexName)) if dname := dialect.Name(); dname == "MySQLDialect" { + s.WriteString(fmt.Sprintf(" %s %s", t.dbmap.Dialect.DropIndexSuffix(), t.TableName)) + } + s.WriteString(";") + _, e := t.dbmap.Exec(s.String()) + if e != nil { + err = e + } + break + } + } + t.ResetSql() + return err + } // AddTable registers the given interface type with gorp. The table name + // will be given the name of the TypeOf(i). You must call this function, + // or AddTableWithName, for any struct type you wish to persist with + // the given DbMap. + // + // This operation is idempotent. If i's type is already mapped, the + // existing *TableMap is returned + func (m *DbMap) AddTable(i interface{}) *TableMap { + return m.AddTableWithName(i, "") + } // AddTableWithName has the same behavior as AddTable, but sets + // table.TableName to name. + func (m *DbMap) AddTableWithName(i interface{}, name string) *TableMap { + return m.AddTableWithNameAndSchema(i, "", name) + } // AddTableWithNameAndSchema has the same behavior as AddTable, but sets + // table.TableName to name. + func (m *DbMap) AddTableWithNameAndSchema(i interface{}, schema string, name string) *TableMap { + t := reflect.TypeOf(i) + if name == "" { + name = t.Name() + } // check if we have a table for this type already + // if so, update the name and return the existing pointer + for i := range m.tables { + table := m.tables[i] + if table.gotype == t { + table.TableName = name + return table + } + } tmap := &TableMap{gotype: t, TableName: name, SchemaName: schema, dbmap: m} + var primaryKey []*ColumnMap + tmap.Columns, primaryKey = m.readStructColumns(t) + m.tables = append(m.tables, tmap) + if len(primaryKey) > 0 { + tmap.keys = append(tmap.keys, primaryKey...) + } return tmap + } // AddTableDynamic registers the given interface type with gorp. + // The table name will be dynamically determined at runtime by + // using the GetTableName method on DynamicTable interface + func (m *DbMap) AddTableDynamic(inp DynamicTable, schema string) *TableMap { val := reflect.ValueOf(inp) + elm := val.Elem() + t := elm.Type() + name := inp.TableName() + if name == "" { + panic("Missing table name in DynamicTable instance") + } // Check if there is another dynamic table with the same name + if _, found := m.dynamicTableFind(name); found { + panic(fmt.Sprintf("A table with the same name %v already exists", name)) + } tmap := &TableMap{gotype: t, TableName: name, SchemaName: schema, dbmap: m} + var primaryKey []*ColumnMap + tmap.Columns, primaryKey = m.readStructColumns(t) + if len(primaryKey) > 0 { + tmap.keys = append(tmap.keys, primaryKey...) + } m.dynamicTableAdd(name, tmap) return tmap + } func (m *DbMap) readStructColumns(t reflect.Type) (cols []*ColumnMap, primaryKey []*ColumnMap) { + primaryKey = make([]*ColumnMap, 0) + n := t.NumField() + for i := 0; i < n; i++ { + f := t.Field(i) + if f.Anonymous && f.Type.Kind() == reflect.Struct { + // Recursively add nested fields in embedded structs. + subcols, subpk := m.readStructColumns(f.Type) + // Don't append nested fields that have the same field + // name as an already-mapped field. + for _, subcol := range subcols { + shouldAppend := true + for _, col := range cols { + if !subcol.Transient && subcol.fieldName == col.fieldName { + shouldAppend = false + break + } + } + if shouldAppend { + cols = append(cols, subcol) + } + } + if subpk != nil { + primaryKey = append(primaryKey, subpk...) + } + } else { + // Tag = Name { ',' Option } + // Option = OptionKey [ ':' OptionValue ] + cArguments := strings.Split(f.Tag.Get("db"), ",") + columnName := cArguments[0] + var maxSize int + var defaultValue string + var isAuto bool + var isPK bool + var isNotNull bool + for _, argString := range cArguments[1:] { + argString = strings.TrimSpace(argString) + arg := strings.SplitN(argString, ":", 2) // check mandatory/unexpected option values + switch arg[0] { + case "size", "default": + // options requiring value + if len(arg) == 1 { + panic(fmt.Sprintf("missing option value for option %v on field %v", arg[0], f.Name)) + } + default: + // options where value is invalid (currently all other options) + if len(arg) == 2 { + panic(fmt.Sprintf("unexpected option value for option %v on field %v", arg[0], f.Name)) + } + } switch arg[0] { + case "size": + maxSize, _ = strconv.Atoi(arg[1]) + case "default": + defaultValue = arg[1] + case "primarykey": + isPK = true + case "autoincrement": + isAuto = true + case "notnull": + isNotNull = true + default: + panic(fmt.Sprintf("Unrecognized tag option for field %v: %v", f.Name, arg)) + } + } + if columnName == "" { + columnName = f.Name + } gotype := f.Type + valueType := gotype + if valueType.Kind() == reflect.Ptr { + valueType = valueType.Elem() + } + value := reflect.New(valueType).Interface() + if m.TypeConverter != nil { + // Make a new pointer to a value of type gotype and + // pass it to the TypeConverter's FromDb method to see + // if a different type should be used for the column + // type during table creation. + scanner, useHolder := m.TypeConverter.FromDb(value) + if useHolder { + value = scanner.Holder + gotype = reflect.TypeOf(value) + } + } + if typer, ok := value.(SqlTyper); ok { + gotype = reflect.TypeOf(typer.SqlType()) + } else if typer, ok := value.(legacySqlTyper); ok { + log.Printf("Deprecation Warning: update your SqlType methods to return a driver.Value") + gotype = reflect.TypeOf(typer.SqlType()) + } else if valuer, ok := value.(driver.Valuer); ok { + // Only check for driver.Valuer if SqlTyper wasn't + // found. + v, err := valuer.Value() + if err == nil && v != nil { + gotype = reflect.TypeOf(v) + } + } + cm := &ColumnMap{ - ColumnName: columnName, + + ColumnName: columnName, + DefaultValue: defaultValue, - Transient: columnName == "-", - fieldName: f.Name, - gotype: gotype, - isPK: isPK, - isAutoIncr: isAuto, - isNotNull: isNotNull, - MaxSize: maxSize, + + Transient: columnName == "-", + + fieldName: f.Name, + + gotype: gotype, + + isPK: isPK, + + isAutoIncr: isAuto, + + isNotNull: isNotNull, + + MaxSize: maxSize, } + if isPK { + primaryKey = append(primaryKey, cm) + } + // Check for nested fields of the same field name and + // override them. + shouldAppend := true + for index, col := range cols { + if !col.Transient && col.fieldName == cm.fieldName { + cols[index] = cm + shouldAppend = false + break + } + } + if shouldAppend { + cols = append(cols, cm) + } + } } + return + } // CreateTables iterates through TableMaps registered to this DbMap and + // executes "create table" statements against the database for each. + // + // This is particularly useful in unit tests where you want to create + // and destroy the schema automatically. + func (m *DbMap) CreateTables() error { + return m.createTables(false) + } // CreateTablesIfNotExists is similar to CreateTables, but starts + // each statement with "create table if not exists" so that existing + // tables do not raise errors + func (m *DbMap) CreateTablesIfNotExists() error { + return m.createTables(true) + } func (m *DbMap) createTables(ifNotExists bool) error { + var err error + for i := range m.tables { + table := m.tables[i] + sql := table.SqlForCreate(ifNotExists) + _, err = m.Exec(sql) + if err != nil { + return err + } + } for _, tbl := range m.dynamicTableMap() { + sql := tbl.SqlForCreate(ifNotExists) + _, err = m.Exec(sql) + if err != nil { + return err + } + } return err + } // DropTable drops an individual table. + // Returns an error when the table does not exist. + func (m *DbMap) DropTable(table interface{}) error { + t := reflect.TypeOf(table) tableName := "" + if dyn, ok := table.(DynamicTable); ok { + tableName = dyn.TableName() + } return m.dropTable(t, tableName, false) + } // DropTableIfExists drops an individual table when the table exists. + func (m *DbMap) DropTableIfExists(table interface{}) error { + t := reflect.TypeOf(table) tableName := "" + if dyn, ok := table.(DynamicTable); ok { + tableName = dyn.TableName() + } return m.dropTable(t, tableName, true) + } // DropTables iterates through TableMaps registered to this DbMap and + // executes "drop table" statements against the database for each. + func (m *DbMap) DropTables() error { + return m.dropTables(false) + } // DropTablesIfExists is the same as DropTables, but uses the "if exists" clause to + // avoid errors for tables that do not exist. + func (m *DbMap) DropTablesIfExists() error { + return m.dropTables(true) + } // Goes through all the registered tables, dropping them one by one. + // If an error is encountered, then it is returned and the rest of + // the tables are not dropped. + func (m *DbMap) dropTables(addIfExists bool) (err error) { + for _, table := range m.tables { + err = m.dropTableImpl(table, addIfExists) + if err != nil { + return err + } + } for _, table := range m.dynamicTableMap() { + err = m.dropTableImpl(table, addIfExists) + if err != nil { + return err + } + } return err + } // Implementation of dropping a single table. + func (m *DbMap) dropTable(t reflect.Type, name string, addIfExists bool) error { + table := tableOrNil(m, t, name) + if table == nil { + return fmt.Errorf("table %s was not registered", table.TableName) + } return m.dropTableImpl(table, addIfExists) + } func (m *DbMap) dropTableImpl(table *TableMap, ifExists bool) (err error) { + tableDrop := "drop table" + if ifExists { + tableDrop = m.Dialect.IfTableExists(tableDrop, table.SchemaName, table.TableName) + } + _, err = m.Exec(fmt.Sprintf("%s %s;", tableDrop, m.Dialect.QuotedTableForQuery(table.SchemaName, table.TableName))) + return err + } // TruncateTables iterates through TableMaps registered to this DbMap and + // executes "truncate table" statements against the database for each, or in the case of + // sqlite, a "delete from" with no "where" clause, which uses the truncate optimization + // (http://www.sqlite.org/lang_delete.html) + func (m *DbMap) TruncateTables() error { + var err error + for i := range m.tables { + table := m.tables[i] + _, e := m.Exec(fmt.Sprintf("%s %s;", m.Dialect.TruncateClause(), m.Dialect.QuotedTableForQuery(table.SchemaName, table.TableName))) + if e != nil { + err = e + } + } for _, table := range m.dynamicTableMap() { + _, e := m.Exec(fmt.Sprintf("%s %s;", m.Dialect.TruncateClause(), m.Dialect.QuotedTableForQuery(table.SchemaName, table.TableName))) + if e != nil { + err = e + } + } return err + } // Insert runs a SQL INSERT statement for each element in list. List + // items must be pointers. + // + // Any interface whose TableMap has an auto-increment primary key will + // have its last insert id bound to the PK field on the struct. + // + // The hook functions PreInsert() and/or PostInsert() will be executed + // before/after the INSERT statement if the interface defines them. + // + // Panics if any interface in the list has not been registered with AddTable + func (m *DbMap) Insert(list ...interface{}) error { + return insert(m, m, list...) + } // Update runs a SQL UPDATE statement for each element in list. List + // items must be pointers. + // + // The hook functions PreUpdate() and/or PostUpdate() will be executed + // before/after the UPDATE statement if the interface defines them. + // + // Returns the number of rows updated. + // + // Returns an error if SetKeys has not been called on the TableMap + // Panics if any interface in the list has not been registered with AddTable + func (m *DbMap) Update(list ...interface{}) (int64, error) { + return update(m, m, nil, list...) + } // UpdateColumns runs a SQL UPDATE statement for each element in list. List + // items must be pointers. + // + // Only the columns accepted by filter are included in the UPDATE. + // + // The hook functions PreUpdate() and/or PostUpdate() will be executed + // before/after the UPDATE statement if the interface defines them. + // + // Returns the number of rows updated. + // + // Returns an error if SetKeys has not been called on the TableMap + // Panics if any interface in the list has not been registered with AddTable + func (m *DbMap) UpdateColumns(filter ColumnFilter, list ...interface{}) (int64, error) { + return update(m, m, filter, list...) + } // Delete runs a SQL DELETE statement for each element in list. List + // items must be pointers. + // + // The hook functions PreDelete() and/or PostDelete() will be executed + // before/after the DELETE statement if the interface defines them. + // + // Returns the number of rows deleted. + // + // Returns an error if SetKeys has not been called on the TableMap + // Panics if any interface in the list has not been registered with AddTable + func (m *DbMap) Delete(list ...interface{}) (int64, error) { + return delete(m, m, list...) + } // Get runs a SQL SELECT to fetch a single row from the table based on the + // primary key(s) + // + // i should be an empty value for the struct to load. keys should be + // the primary key value(s) for the row to load. If multiple keys + // exist on the table, the order should match the column order + // specified in SetKeys() when the table mapping was defined. + // + // The hook function PostGet() will be executed after the SELECT + // statement if the interface defines them. + // + // Returns a pointer to a struct that matches or nil if no row is found. + // + // Returns an error if SetKeys has not been called on the TableMap + // Panics if any interface in the list has not been registered with AddTable + func (m *DbMap) Get(i interface{}, keys ...interface{}) (interface{}, error) { + return get(m, m, i, keys...) + } // Select runs an arbitrary SQL query, binding the columns in the result + // to fields on the struct specified by i. args represent the bind + // parameters for the SQL statement. + // + // Column names on the SELECT statement should be aliased to the field names + // on the struct i. Returns an error if one or more columns in the result + // do not match. It is OK if fields on i are not part of the SQL + // statement. + // + // The hook function PostGet() will be executed after the SELECT + // statement if the interface defines them. + // + // Values are returned in one of two ways: + // 1. If i is a struct or a pointer to a struct, returns a slice of pointers to + // matching rows of type i. + // 2. If i is a pointer to a slice, the results will be appended to that slice + // and nil returned. + // + // i does NOT need to be registered with AddTable() + func (m *DbMap) Select(i interface{}, query string, args ...interface{}) ([]interface{}, error) { + if m.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } return hookedselect(m, m, i, query, args...) + } // Exec runs an arbitrary SQL statement. args represent the bind parameters. + // This is equivalent to running: Exec() using database/sql + func (m *DbMap) Exec(query string, args ...interface{}) (sql.Result, error) { + if m.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } if m.logger != nil { + now := time.Now() + defer m.trace(now, query, args...) + } + return maybeExpandNamedQueryAndExec(m, query, args...) + } // SelectInt is a convenience wrapper around the gorp.SelectInt function + func (m *DbMap) SelectInt(query string, args ...interface{}) (int64, error) { + if m.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } return SelectInt(m, query, args...) + } // SelectNullInt is a convenience wrapper around the gorp.SelectNullInt function + func (m *DbMap) SelectNullInt(query string, args ...interface{}) (sql.NullInt64, error) { + if m.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } return SelectNullInt(m, query, args...) + } // SelectFloat is a convenience wrapper around the gorp.SelectFloat function + func (m *DbMap) SelectFloat(query string, args ...interface{}) (float64, error) { + if m.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } return SelectFloat(m, query, args...) + } // SelectNullFloat is a convenience wrapper around the gorp.SelectNullFloat function + func (m *DbMap) SelectNullFloat(query string, args ...interface{}) (sql.NullFloat64, error) { + if m.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } return SelectNullFloat(m, query, args...) + } // SelectStr is a convenience wrapper around the gorp.SelectStr function + func (m *DbMap) SelectStr(query string, args ...interface{}) (string, error) { + if m.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } return SelectStr(m, query, args...) + } // SelectNullStr is a convenience wrapper around the gorp.SelectNullStr function + func (m *DbMap) SelectNullStr(query string, args ...interface{}) (sql.NullString, error) { + if m.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } return SelectNullStr(m, query, args...) + } // SelectOne is a convenience wrapper around the gorp.SelectOne function + func (m *DbMap) SelectOne(holder interface{}, query string, args ...interface{}) error { + if m.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } return SelectOne(m, m, holder, query, args...) + } // Begin starts a gorp Transaction + func (m *DbMap) Begin() (*Transaction, error) { + if m.logger != nil { + now := time.Now() + defer m.trace(now, "begin;") + } + tx, err := begin(m) + if err != nil { + return nil, err + } + return &Transaction{ - dbmap: m, - tx: tx, + + dbmap: m, + + tx: tx, + closed: false, }, nil + } // TableFor returns the *TableMap corresponding to the given Go Type + // If no table is mapped to that type an error is returned. + // If checkPK is true and the mapped table has no registered PKs, an error is returned. + func (m *DbMap) TableFor(t reflect.Type, checkPK bool) (*TableMap, error) { + table := tableOrNil(m, t, "") + if table == nil { + return nil, fmt.Errorf("no table found for type: %v", t.Name()) + } if checkPK && len(table.keys) < 1 { + e := fmt.Sprintf("gorp: no keys defined for table: %s", + table.TableName) + return nil, errors.New(e) + } return table, nil + } // DynamicTableFor returns the *TableMap for the dynamic table corresponding + // to the input tablename + // If no table is mapped to that tablename an error is returned. + // If checkPK is true and the mapped table has no registered PKs, an error is returned. + func (m *DbMap) DynamicTableFor(tableName string, checkPK bool) (*TableMap, error) { + table, found := m.dynamicTableFind(tableName) + if !found { + return nil, fmt.Errorf("gorp: no table found for name: %v", tableName) + } if checkPK && len(table.keys) < 1 { + e := fmt.Sprintf("gorp: no keys defined for table: %s", + table.TableName) + return nil, errors.New(e) + } return table, nil + } // Prepare creates a prepared statement for later queries or executions. + // Multiple queries or executions may be run concurrently from the returned statement. + // This is equivalent to running: Prepare() using database/sql + func (m *DbMap) Prepare(query string) (*sql.Stmt, error) { + if m.logger != nil { + now := time.Now() + defer m.trace(now, query, nil) + } + return prepare(m, query) + } func tableOrNil(m *DbMap, t reflect.Type, name string) *TableMap { + if name != "" { + // Search by table name (dynamic tables) + if table, found := m.dynamicTableFind(name); found { + return table + } + return nil + } for i := range m.tables { + table := m.tables[i] + if table.gotype == t { + return table + } + } + return nil + } func (m *DbMap) tableForPointer(ptr interface{}, checkPK bool) (*TableMap, reflect.Value, error) { + ptrv := reflect.ValueOf(ptr) + if ptrv.Kind() != reflect.Ptr { + e := fmt.Sprintf("gorp: passed non-pointer: %v (kind=%v)", ptr, + ptrv.Kind()) + return nil, reflect.Value{}, errors.New(e) + } + elem := ptrv.Elem() + ifc := elem.Interface() + var t *TableMap + var err error + tableName := "" + if dyn, isDyn := ptr.(DynamicTable); isDyn { + tableName = dyn.TableName() + t, err = m.DynamicTableFor(tableName, checkPK) + } else { + etype := reflect.TypeOf(ifc) + t, err = m.TableFor(etype, checkPK) + } if err != nil { + return nil, reflect.Value{}, err + } return t, elem, nil + } func (m *DbMap) QueryRow(query string, args ...interface{}) *sql.Row { + if m.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } if m.logger != nil { + now := time.Now() + defer m.trace(now, query, args...) + } + return queryRow(m, query, args...) + } func (m *DbMap) Query(q string, args ...interface{}) (*sql.Rows, error) { + if m.ExpandSliceArgs { + expandSliceArgs(&q, args...) + } if m.logger != nil { + now := time.Now() + defer m.trace(now, q, args...) + } + return query(m, q, args...) + } func (m *DbMap) trace(started time.Time, query string, args ...interface{}) { + if m.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } if m.logger != nil { + var margs = argsString(args...) + m.logger.Printf("%s%s [%s] (%v)", m.logPrefix, query, margs, (time.Now().Sub(started))) + } + } type stringer interface { @@ -886,99 +1545,185 @@ type numberer interface { } func expandSliceArgs(query *string, args ...interface{}) { + for _, arg := range args { + mapper, ok := arg.(map[string]interface{}) + if !ok { + continue + } for key, value := range mapper { + var replacements []string // add flexibility for any custom type to be convert to one of the + // acceptable formats. + if v, ok := value.(stringer); ok { + value = v.ToStringSlice() + } + if v, ok := value.(numberer); ok { + value = v.ToInt64Slice() + } switch v := value.(type) { + case []string: + for id, replace := range v { + mapper[fmt.Sprintf("%s%d", key, id)] = replace + replacements = append(replacements, fmt.Sprintf(":%s%d", key, id)) + } + case []uint: + for id, replace := range v { + mapper[fmt.Sprintf("%s%d", key, id)] = replace + replacements = append(replacements, fmt.Sprintf(":%s%d", key, id)) + } + case []uint8: + for id, replace := range v { + mapper[fmt.Sprintf("%s%d", key, id)] = replace + replacements = append(replacements, fmt.Sprintf(":%s%d", key, id)) + } + case []uint16: + for id, replace := range v { + mapper[fmt.Sprintf("%s%d", key, id)] = replace + replacements = append(replacements, fmt.Sprintf(":%s%d", key, id)) + } + case []uint32: + for id, replace := range v { + mapper[fmt.Sprintf("%s%d", key, id)] = replace + replacements = append(replacements, fmt.Sprintf(":%s%d", key, id)) + } + case []uint64: + for id, replace := range v { + mapper[fmt.Sprintf("%s%d", key, id)] = replace + replacements = append(replacements, fmt.Sprintf(":%s%d", key, id)) + } + case []int: + for id, replace := range v { + mapper[fmt.Sprintf("%s%d", key, id)] = replace + replacements = append(replacements, fmt.Sprintf(":%s%d", key, id)) + } + case []int8: + for id, replace := range v { + mapper[fmt.Sprintf("%s%d", key, id)] = replace + replacements = append(replacements, fmt.Sprintf(":%s%d", key, id)) + } + case []int16: + for id, replace := range v { + mapper[fmt.Sprintf("%s%d", key, id)] = replace + replacements = append(replacements, fmt.Sprintf(":%s%d", key, id)) + } + case []int32: + for id, replace := range v { + mapper[fmt.Sprintf("%s%d", key, id)] = replace + replacements = append(replacements, fmt.Sprintf(":%s%d", key, id)) + } + case []int64: + for id, replace := range v { + mapper[fmt.Sprintf("%s%d", key, id)] = replace + replacements = append(replacements, fmt.Sprintf(":%s%d", key, id)) + } + case []float32: + for id, replace := range v { + mapper[fmt.Sprintf("%s%d", key, id)] = replace + replacements = append(replacements, fmt.Sprintf(":%s%d", key, id)) + } + case []float64: + for id, replace := range v { + mapper[fmt.Sprintf("%s%d", key, id)] = replace + replacements = append(replacements, fmt.Sprintf(":%s%d", key, id)) + } + default: + continue + } if len(replacements) == 0 { + continue + } *query = strings.Replace(*query, fmt.Sprintf(":%s", key), strings.Join(replacements, ","), -1) + } + } + } diff --git a/vendor/github.com/go-gorp/gorp/v3/dialect_mysql.go b/vendor/github.com/go-gorp/gorp/v3/dialect_mysql.go index d068ebe..071f6ea 100644 --- a/vendor/github.com/go-gorp/gorp/v3/dialect_mysql.go +++ b/vendor/github.com/go-gorp/gorp/v3/dialect_mysql.go @@ -1,5 +1,7 @@ // Copyright 2012 James Cooper. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package gorp @@ -12,158 +14,262 @@ import ( ) // Implementation of Dialect for MySQL databases. + type MySQLDialect struct { // Engine is the storage engine to use "InnoDB" vs "MyISAM" for example + Engine string // Encoding is the character encoding to use for created tables + Encoding string } func (d MySQLDialect) QuerySuffix() string { return ";" } func (d MySQLDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string { + switch val.Kind() { + case reflect.Ptr: + return d.ToSqlType(val.Elem(), maxsize, isAutoIncr) + case reflect.Bool: + return "boolean" + case reflect.Int8: + return "tinyint" + case reflect.Uint8: + return "tinyint unsigned" + case reflect.Int16: + return "smallint" + case reflect.Uint16: + return "smallint unsigned" + case reflect.Int, reflect.Int32: + return "int" + case reflect.Uint, reflect.Uint32: + return "int unsigned" + case reflect.Int64: + return "bigint" + case reflect.Uint64: + return "bigint unsigned" + case reflect.Float64, reflect.Float32: + return "double" + case reflect.Slice: + if val.Elem().Kind() == reflect.Uint8 { + return "mediumblob" + } + } switch val.Name() { + case "NullInt64": + return "bigint" + case "NullFloat64": + return "double" + case "NullBool": + return "tinyint" + case "Time": + return "datetime" + } if maxsize < 1 { + maxsize = 255 + } /* == About varchar(N) == + * N is number of characters. + * A varchar column can store up to 65535 bytes. + * Remember that 1 character is 3 bytes in utf-8 charset. + * Also remember that each row can store up to 65535 bytes, + * and you have some overheads, so it's not possible for a + * varchar column to have 65535/3 characters really. + * So it would be better to use 'text' type in stead of + * large varchar type. + */ + if maxsize < 256 { + return fmt.Sprintf("varchar(%d)", maxsize) + } else { + return "text" + } + } // Returns auto_increment + func (d MySQLDialect) AutoIncrStr() string { + return "auto_increment" + } func (d MySQLDialect) AutoIncrBindValue() string { + return "null" + } func (d MySQLDialect) AutoIncrInsertSuffix(col *ColumnMap) string { + return "" + } // Returns engine=%s charset=%s based on values stored on struct + func (d MySQLDialect) CreateTableSuffix() string { + if d.Engine == "" || d.Encoding == "" { + msg := "gorp - undefined" if d.Engine == "" { + msg += " MySQLDialect.Engine" + } + if d.Engine == "" && d.Encoding == "" { + msg += "," + } + if d.Encoding == "" { + msg += " MySQLDialect.Encoding" + } + msg += ". Check that your MySQLDialect was correctly initialized when declared." + panic(msg) + } return fmt.Sprintf(" engine=%s charset=%s", d.Engine, d.Encoding) + } func (d MySQLDialect) CreateIndexSuffix() string { + return "using" + } func (d MySQLDialect) DropIndexSuffix() string { + return "on" + } func (d MySQLDialect) TruncateClause() string { + return "truncate" + } func (d MySQLDialect) SleepClause(s time.Duration) string { + return fmt.Sprintf("sleep(%f)", s.Seconds()) + } // Returns "?" + func (d MySQLDialect) BindVar(i int) string { + return "?" + } func (d MySQLDialect) InsertAutoIncr(exec SqlExecutor, insertSql string, params ...interface{}) (int64, error) { + return standardInsertAutoIncr(exec, insertSql, params...) + } func (d MySQLDialect) QuoteField(f string) string { + return "`" + f + "`" + } func (d MySQLDialect) QuotedTableForQuery(schema string, table string) string { + if strings.TrimSpace(schema) == "" { + return d.QuoteField(table) + } return schema + "." + d.QuoteField(table) + } func (d MySQLDialect) IfSchemaNotExists(command, schema string) string { + return fmt.Sprintf("%s if not exists", command) + } func (d MySQLDialect) IfTableExists(command, schema, table string) string { + return fmt.Sprintf("%s if exists", command) + } func (d MySQLDialect) IfTableNotExists(command, schema, table string) string { + return fmt.Sprintf("%s if not exists", command) + } diff --git a/vendor/github.com/go-gorp/gorp/v3/dialect_oracle.go b/vendor/github.com/go-gorp/gorp/v3/dialect_oracle.go index 01a99b8..6753622 100644 --- a/vendor/github.com/go-gorp/gorp/v3/dialect_oracle.go +++ b/vendor/github.com/go-gorp/gorp/v3/dialect_oracle.go @@ -1,5 +1,7 @@ // Copyright 2012 James Cooper. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package gorp @@ -11,6 +13,7 @@ import ( ) // Implementation of Dialect for Oracle databases. + type OracleDialect struct{} func (d OracleDialect) QuerySuffix() string { return "" } @@ -20,120 +23,205 @@ func (d OracleDialect) CreateIndexSuffix() string { return "" } func (d OracleDialect) DropIndexSuffix() string { return "" } func (d OracleDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string { + switch val.Kind() { + case reflect.Ptr: + return d.ToSqlType(val.Elem(), maxsize, isAutoIncr) + case reflect.Bool: + return "boolean" + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32: + if isAutoIncr { + return "serial" + } + return "integer" + case reflect.Int64, reflect.Uint64: + if isAutoIncr { + return "bigserial" + } + return "bigint" + case reflect.Float64: + return "double precision" + case reflect.Float32: + return "real" + case reflect.Slice: + if val.Elem().Kind() == reflect.Uint8 { + return "bytea" + } + } switch val.Name() { + case "NullInt64": + return "bigint" + case "NullFloat64": + return "double precision" + case "NullBool": + return "boolean" + case "NullTime", "Time": + return "timestamp with time zone" + } if maxsize > 0 { + return fmt.Sprintf("varchar(%d)", maxsize) + } else { + return "text" + } } // Returns empty string + func (d OracleDialect) AutoIncrStr() string { + return "" + } func (d OracleDialect) AutoIncrBindValue() string { + return "NULL" + } func (d OracleDialect) AutoIncrInsertSuffix(col *ColumnMap) string { + return "" + } // Returns suffix + func (d OracleDialect) CreateTableSuffix() string { + return "" + } func (d OracleDialect) TruncateClause() string { + return "truncate" + } // Returns "$(i+1)" + func (d OracleDialect) BindVar(i int) string { + return fmt.Sprintf(":%d", i+1) + } // After executing the insert uses the ColMap IdQuery to get the generated id + func (d OracleDialect) InsertQueryToTarget(exec SqlExecutor, insertSql, idSql string, target interface{}, params ...interface{}) error { + _, err := exec.Exec(insertSql, params...) + if err != nil { + return err + } + id, err := exec.SelectInt(idSql) + if err != nil { + return err + } + switch target.(type) { + case *int64: + *(target.(*int64)) = id + case *int32: + *(target.(*int32)) = int32(id) + case int: + *(target.(*int)) = int(id) + default: + return fmt.Errorf("Id field can be int, int32 or int64") + } + return nil + } func (d OracleDialect) QuoteField(f string) string { + return `"` + strings.ToUpper(f) + `"` + } func (d OracleDialect) QuotedTableForQuery(schema string, table string) string { + if strings.TrimSpace(schema) == "" { + return d.QuoteField(table) + } return schema + "." + d.QuoteField(table) + } func (d OracleDialect) IfSchemaNotExists(command, schema string) string { + return fmt.Sprintf("%s if not exists", command) + } func (d OracleDialect) IfTableExists(command, schema, table string) string { + return fmt.Sprintf("%s if exists", command) + } func (d OracleDialect) IfTableNotExists(command, schema, table string) string { + return fmt.Sprintf("%s if not exists", command) + } diff --git a/vendor/github.com/go-gorp/gorp/v3/dialect_postgres.go b/vendor/github.com/go-gorp/gorp/v3/dialect_postgres.go index 7a9c50b..d514a6e 100644 --- a/vendor/github.com/go-gorp/gorp/v3/dialect_postgres.go +++ b/vendor/github.com/go-gorp/gorp/v3/dialect_postgres.go @@ -1,5 +1,7 @@ // Copyright 2012 James Cooper. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package gorp @@ -12,138 +14,227 @@ import ( ) type PostgresDialect struct { - suffix string + suffix string + LowercaseFields bool } func (d PostgresDialect) QuerySuffix() string { return ";" } func (d PostgresDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string { + switch val.Kind() { + case reflect.Ptr: + return d.ToSqlType(val.Elem(), maxsize, isAutoIncr) + case reflect.Bool: + return "boolean" + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32: + if isAutoIncr { + return "serial" + } + return "integer" + case reflect.Int64, reflect.Uint64: + if isAutoIncr { + return "bigserial" + } + return "bigint" + case reflect.Float64: + return "double precision" + case reflect.Float32: + return "real" + case reflect.Slice: + if val.Elem().Kind() == reflect.Uint8 { + return "bytea" + } + } switch val.Name() { + case "NullInt64": + return "bigint" + case "NullFloat64": + return "double precision" + case "NullBool": + return "boolean" + case "Time", "NullTime": + return "timestamp with time zone" + } if maxsize > 0 { + return fmt.Sprintf("varchar(%d)", maxsize) + } else { + return "text" + } } // Returns empty string + func (d PostgresDialect) AutoIncrStr() string { + return "" + } func (d PostgresDialect) AutoIncrBindValue() string { + return "default" + } func (d PostgresDialect) AutoIncrInsertSuffix(col *ColumnMap) string { + return " returning " + d.QuoteField(col.ColumnName) + } // Returns suffix + func (d PostgresDialect) CreateTableSuffix() string { + return d.suffix + } func (d PostgresDialect) CreateIndexSuffix() string { + return "using" + } func (d PostgresDialect) DropIndexSuffix() string { + return "" + } func (d PostgresDialect) TruncateClause() string { + return "truncate" + } func (d PostgresDialect) SleepClause(s time.Duration) string { + return fmt.Sprintf("pg_sleep(%f)", s.Seconds()) + } // Returns "$(i+1)" + func (d PostgresDialect) BindVar(i int) string { + return fmt.Sprintf("$%d", i+1) + } func (d PostgresDialect) InsertAutoIncrToTarget(exec SqlExecutor, insertSql string, target interface{}, params ...interface{}) error { + rows, err := exec.Query(insertSql, params...) + if err != nil { + return err + } + defer rows.Close() if !rows.Next() { + return fmt.Errorf("No serial value returned for insert: %s Encountered error: %s", insertSql, rows.Err()) + } + if err := rows.Scan(target); err != nil { + return err + } + if rows.Next() { + return fmt.Errorf("more than two serial value returned for insert: %s", insertSql) + } + return rows.Err() + } func (d PostgresDialect) QuoteField(f string) string { + if d.LowercaseFields { + return `"` + strings.ToLower(f) + `"` + } + return `"` + f + `"` + } func (d PostgresDialect) QuotedTableForQuery(schema string, table string) string { + if strings.TrimSpace(schema) == "" { + return d.QuoteField(table) + } return schema + "." + d.QuoteField(table) + } func (d PostgresDialect) IfSchemaNotExists(command, schema string) string { + return fmt.Sprintf("%s if not exists", command) + } func (d PostgresDialect) IfTableExists(command, schema, table string) string { + return fmt.Sprintf("%s if exists", command) + } func (d PostgresDialect) IfTableNotExists(command, schema, table string) string { + return fmt.Sprintf("%s if not exists", command) + } diff --git a/vendor/github.com/go-gorp/gorp/v3/dialect_snowflake.go b/vendor/github.com/go-gorp/gorp/v3/dialect_snowflake.go index 6335e52..459b649 100644 --- a/vendor/github.com/go-gorp/gorp/v3/dialect_snowflake.go +++ b/vendor/github.com/go-gorp/gorp/v3/dialect_snowflake.go @@ -1,5 +1,7 @@ // Copyright 2012 James Cooper. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package gorp @@ -11,142 +13,235 @@ import ( ) type SnowflakeDialect struct { - suffix string + suffix string + LowercaseFields bool } func (d SnowflakeDialect) QuerySuffix() string { return ";" } func (d SnowflakeDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string { + switch val.Kind() { + case reflect.Ptr: + return d.ToSqlType(val.Elem(), maxsize, isAutoIncr) + case reflect.Bool: + return "boolean" + case reflect.Int, + reflect.Int8, + reflect.Int16, + reflect.Int32, + reflect.Uint, + reflect.Uint8, + reflect.Uint16, + reflect.Uint32: if isAutoIncr { + return "serial" + } + return "integer" + case reflect.Int64, reflect.Uint64: + if isAutoIncr { + return "bigserial" + } + return "bigint" + case reflect.Float64: + return "double precision" + case reflect.Float32: + return "real" + case reflect.Slice: + if val.Elem().Kind() == reflect.Uint8 { + return "binary" + } + } switch val.Name() { + case "NullInt64": + return "bigint" + case "NullFloat64": + return "double precision" + case "NullBool": + return "boolean" + case "Time", "NullTime": + return "timestamp with time zone" + } if maxsize > 0 { + return fmt.Sprintf("varchar(%d)", maxsize) + } else { + return "text" + } } // Returns empty string + func (d SnowflakeDialect) AutoIncrStr() string { + return "" + } func (d SnowflakeDialect) AutoIncrBindValue() string { + return "default" + } func (d SnowflakeDialect) AutoIncrInsertSuffix(col *ColumnMap) string { + return "" + } // Returns suffix + func (d SnowflakeDialect) CreateTableSuffix() string { + return d.suffix + } func (d SnowflakeDialect) CreateIndexSuffix() string { + return "" + } func (d SnowflakeDialect) DropIndexSuffix() string { + return "" + } func (d SnowflakeDialect) TruncateClause() string { + return "truncate" + } // Returns "$(i+1)" + func (d SnowflakeDialect) BindVar(i int) string { + return "?" + } func (d SnowflakeDialect) InsertAutoIncrToTarget(exec SqlExecutor, insertSql string, target interface{}, params ...interface{}) error { + rows, err := exec.Query(insertSql, params...) + if err != nil { + return err + } + defer rows.Close() if !rows.Next() { + return fmt.Errorf("No serial value returned for insert: %s Encountered error: %s", insertSql, rows.Err()) + } + if err := rows.Scan(target); err != nil { + return err + } + if rows.Next() { + return fmt.Errorf("more than two serial value returned for insert: %s", insertSql) + } + return rows.Err() + } func (d SnowflakeDialect) QuoteField(f string) string { + if d.LowercaseFields { + return `"` + strings.ToLower(f) + `"` + } + return `"` + f + `"` + } func (d SnowflakeDialect) QuotedTableForQuery(schema string, table string) string { + if strings.TrimSpace(schema) == "" { + return d.QuoteField(table) + } return schema + "." + d.QuoteField(table) + } func (d SnowflakeDialect) IfSchemaNotExists(command, schema string) string { + return fmt.Sprintf("%s if not exists", command) + } func (d SnowflakeDialect) IfTableExists(command, schema, table string) string { + return fmt.Sprintf("%s if exists", command) + } func (d SnowflakeDialect) IfTableNotExists(command, schema, table string) string { + return fmt.Sprintf("%s if not exists", command) + } diff --git a/vendor/github.com/go-gorp/gorp/v3/dialect_sqlite.go b/vendor/github.com/go-gorp/gorp/v3/dialect_sqlite.go index 2296275..04b750b 100644 --- a/vendor/github.com/go-gorp/gorp/v3/dialect_sqlite.go +++ b/vendor/github.com/go-gorp/gorp/v3/dialect_sqlite.go @@ -1,5 +1,7 @@ // Copyright 2012 James Cooper. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package gorp @@ -16,97 +18,159 @@ type SqliteDialect struct { func (d SqliteDialect) QuerySuffix() string { return ";" } func (d SqliteDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string { + switch val.Kind() { + case reflect.Ptr: + return d.ToSqlType(val.Elem(), maxsize, isAutoIncr) + case reflect.Bool: + return "integer" + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return "integer" + case reflect.Float64, reflect.Float32: + return "real" + case reflect.Slice: + if val.Elem().Kind() == reflect.Uint8 { + return "blob" + } + } switch val.Name() { + case "NullInt64": + return "integer" + case "NullFloat64": + return "real" + case "NullBool": + return "integer" + case "Time": + return "datetime" + } if maxsize < 1 { + maxsize = 255 + } + return fmt.Sprintf("varchar(%d)", maxsize) + } // Returns autoincrement + func (d SqliteDialect) AutoIncrStr() string { + return "autoincrement" + } func (d SqliteDialect) AutoIncrBindValue() string { + return "null" + } func (d SqliteDialect) AutoIncrInsertSuffix(col *ColumnMap) string { + return "" + } // Returns suffix + func (d SqliteDialect) CreateTableSuffix() string { + return d.suffix + } func (d SqliteDialect) CreateIndexSuffix() string { + return "" + } func (d SqliteDialect) DropIndexSuffix() string { + return "" + } // With sqlite, there technically isn't a TRUNCATE statement, + // but a DELETE FROM uses a truncate optimization: + // http://www.sqlite.org/lang_delete.html + func (d SqliteDialect) TruncateClause() string { + return "delete from" + } // Returns "?" + func (d SqliteDialect) BindVar(i int) string { + return "?" + } func (d SqliteDialect) InsertAutoIncr(exec SqlExecutor, insertSql string, params ...interface{}) (int64, error) { + return standardInsertAutoIncr(exec, insertSql, params...) + } func (d SqliteDialect) QuoteField(f string) string { + return `"` + f + `"` + } // sqlite does not have schemas like PostgreSQL does, so just escape it like normal + func (d SqliteDialect) QuotedTableForQuery(schema string, table string) string { + return d.QuoteField(table) + } func (d SqliteDialect) IfSchemaNotExists(command, schema string) string { + return fmt.Sprintf("%s if not exists", command) + } func (d SqliteDialect) IfTableExists(command, schema, table string) string { + return fmt.Sprintf("%s if exists", command) + } func (d SqliteDialect) IfTableNotExists(command, schema, table string) string { + return fmt.Sprintf("%s if not exists", command) + } diff --git a/vendor/github.com/go-gorp/gorp/v3/dialect_sqlserver.go b/vendor/github.com/go-gorp/gorp/v3/dialect_sqlserver.go index ec06aed..675f195 100644 --- a/vendor/github.com/go-gorp/gorp/v3/dialect_sqlserver.go +++ b/vendor/github.com/go-gorp/gorp/v3/dialect_sqlserver.go @@ -1,5 +1,7 @@ // Copyright 2012 James Cooper. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package gorp @@ -11,135 +13,228 @@ import ( ) // Implementation of Dialect for Microsoft SQL Server databases. + // Use gorp.SqlServerDialect{"2005"} for legacy datatypes. + // Tested with driver: github.com/denisenkom/go-mssqldb type SqlServerDialect struct { // If set to "2005" legacy datatypes will be used + Version string } func (d SqlServerDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string { + switch val.Kind() { + case reflect.Ptr: + return d.ToSqlType(val.Elem(), maxsize, isAutoIncr) + case reflect.Bool: + return "bit" + case reflect.Int8: + return "tinyint" + case reflect.Uint8: + return "smallint" + case reflect.Int16: + return "smallint" + case reflect.Uint16: + return "int" + case reflect.Int, reflect.Int32: + return "int" + case reflect.Uint, reflect.Uint32: + return "bigint" + case reflect.Int64: + return "bigint" + case reflect.Uint64: + return "numeric(20,0)" + case reflect.Float32: + return "float(24)" + case reflect.Float64: + return "float(53)" + case reflect.Slice: + if val.Elem().Kind() == reflect.Uint8 { + return "varbinary" + } + } switch val.Name() { + case "NullInt64": + return "bigint" + case "NullFloat64": + return "float(53)" + case "NullBool": + return "bit" + case "NullTime", "Time": + if d.Version == "2005" { + return "datetime" + } + return "datetime2" + } if maxsize < 1 { + if d.Version == "2005" { + maxsize = 255 + } else { + return fmt.Sprintf("nvarchar(max)") + } + } + return fmt.Sprintf("nvarchar(%d)", maxsize) + } // Returns auto_increment + func (d SqlServerDialect) AutoIncrStr() string { + return "identity(0,1)" + } // Empty string removes autoincrement columns from the INSERT statements. + func (d SqlServerDialect) AutoIncrBindValue() string { + return "" + } func (d SqlServerDialect) AutoIncrInsertSuffix(col *ColumnMap) string { + return "" + } func (d SqlServerDialect) CreateTableSuffix() string { return ";" } func (d SqlServerDialect) TruncateClause() string { + return "truncate table" + } // Returns "?" + func (d SqlServerDialect) BindVar(i int) string { + return "?" + } func (d SqlServerDialect) InsertAutoIncr(exec SqlExecutor, insertSql string, params ...interface{}) (int64, error) { + return standardInsertAutoIncr(exec, insertSql, params...) + } func (d SqlServerDialect) QuoteField(f string) string { + return "[" + strings.Replace(f, "]", "]]", -1) + "]" + } func (d SqlServerDialect) QuotedTableForQuery(schema string, table string) string { + if strings.TrimSpace(schema) == "" { + return d.QuoteField(table) + } + return d.QuoteField(schema) + "." + d.QuoteField(table) + } func (d SqlServerDialect) QuerySuffix() string { return ";" } func (d SqlServerDialect) IfSchemaNotExists(command, schema string) string { + s := fmt.Sprintf("if schema_id(N'%s') is null %s", schema, command) + return s + } func (d SqlServerDialect) IfTableExists(command, schema, table string) string { + var schema_clause string + if strings.TrimSpace(schema) != "" { + schema_clause = fmt.Sprintf("%s.", d.QuoteField(schema)) + } + s := fmt.Sprintf("if object_id('%s%s') is not null %s", schema_clause, d.QuoteField(table), command) + return s + } func (d SqlServerDialect) IfTableNotExists(command, schema, table string) string { + var schema_clause string + if strings.TrimSpace(schema) != "" { + schema_clause = fmt.Sprintf("%s.", schema) + } + s := fmt.Sprintf("if object_id('%s%s') is null %s", schema_clause, table, command) + return s + } func (d SqlServerDialect) CreateIndexSuffix() string { return "" } -func (d SqlServerDialect) DropIndexSuffix() string { return "" } + +func (d SqlServerDialect) DropIndexSuffix() string { return "" } diff --git a/vendor/github.com/go-gorp/gorp/v3/gorp.go b/vendor/github.com/go-gorp/gorp/v3/gorp.go index fc65456..e3826b7 100644 --- a/vendor/github.com/go-gorp/gorp/v3/gorp.go +++ b/vendor/github.com/go-gorp/gorp/v3/gorp.go @@ -1,5 +1,7 @@ // Copyright 2012 James Cooper. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package gorp @@ -16,657 +18,1116 @@ import ( ) // OracleString (empty string is null) + // TODO: move to dialect/oracle?, rename to String? + type OracleString struct { sql.NullString } // Scan implements the Scanner interface. + func (os *OracleString) Scan(value interface{}) error { + if value == nil { + os.String, os.Valid = "", false + return nil + } + os.Valid = true + return os.NullString.Scan(value) + } // Value implements the driver Valuer interface. + func (os OracleString) Value() (driver.Value, error) { + if !os.Valid || os.String == "" { + return nil, nil + } + return os.String, nil + } // SqlTyper is a type that returns its database type. Most of the + // time, the type can just use "database/sql/driver".Valuer; but when + // it returns nil for its empty value, it needs to implement SqlTyper + // to have its column type detected properly during table creation. + type SqlTyper interface { SqlType() driver.Value } // legacySqlTyper prevents breaking clients who depended on the previous + // SqlTyper interface + type legacySqlTyper interface { SqlType() driver.Valuer } // for fields that exists in DB table, but not exists in struct + type dummyField struct{} // Scan implements the Scanner interface. + func (nt *dummyField) Scan(value interface{}) error { + return nil + } var zeroVal reflect.Value + var versFieldConst = "[gorp_ver_field]" // The TypeConverter interface provides a way to map a value of one + // type to another type when persisting to, or loading from, a database. + // + // Example use cases: Implement type converter to convert bool types to "y"/"n" strings, + // or serialize a struct member as a JSON blob. + type TypeConverter interface { + // ToDb converts val to another type. Called before INSERT/UPDATE operations + ToDb(val interface{}) (interface{}, error) // FromDb returns a CustomScanner appropriate for this type. This will be used + // to hold values returned from SELECT queries. + // + // In particular the CustomScanner returned should implement a Binder + // function appropriate for the Go type you wish to convert the db value to + // + // If bool==false, then no custom scanner will be used for this field. + FromDb(target interface{}) (CustomScanner, bool) } // SqlExecutor exposes gorp operations that can be run from Pre/Post + // hooks. This hides whether the current operation that triggered the + // hook is in a transaction. + // + // See the DbMap function docs for each of the functions below for more + // information. + type SqlExecutor interface { WithContext(ctx context.Context) SqlExecutor + Get(i interface{}, keys ...interface{}) (interface{}, error) + Insert(list ...interface{}) error + Update(list ...interface{}) (int64, error) + Delete(list ...interface{}) (int64, error) + Exec(query string, args ...interface{}) (sql.Result, error) + Select(i interface{}, query string, args ...interface{}) ([]interface{}, error) + SelectInt(query string, args ...interface{}) (int64, error) + SelectNullInt(query string, args ...interface{}) (sql.NullInt64, error) + SelectFloat(query string, args ...interface{}) (float64, error) + SelectNullFloat(query string, args ...interface{}) (sql.NullFloat64, error) + SelectStr(query string, args ...interface{}) (string, error) + SelectNullStr(query string, args ...interface{}) (sql.NullString, error) + SelectOne(holder interface{}, query string, args ...interface{}) error + Query(query string, args ...interface{}) (*sql.Rows, error) + QueryRow(query string, args ...interface{}) *sql.Row } // DynamicTable allows the users of gorp to dynamically + // use different database table names during runtime + // while sharing the same golang struct for in-memory data + type DynamicTable interface { TableName() string + SetTableName(string) } // Compile-time check that DbMap and Transaction implement the SqlExecutor + // interface. + var _, _ SqlExecutor = &DbMap{}, &Transaction{} func argValue(a interface{}) interface{} { + v, ok := a.(driver.Valuer) + if !ok { + return a + } + vV := reflect.ValueOf(v) + if vV.Kind() == reflect.Ptr && vV.IsNil() { + return nil + } + ret, err := v.Value() + if err != nil { + return a + } + return ret + } func argsString(args ...interface{}) string { + var margs string + for i, a := range args { + v := argValue(a) + switch v.(type) { + case string: + v = fmt.Sprintf("%q", v) + default: + v = fmt.Sprintf("%v", v) + } + margs += fmt.Sprintf("%d:%s", i+1, v) + if i+1 < len(args) { + margs += " " + } + } + return margs + } // Calls the Exec function on the executor, but attempts to expand any eligible named + // query arguments first. + func maybeExpandNamedQueryAndExec(e SqlExecutor, query string, args ...interface{}) (sql.Result, error) { + dbMap := extractDbMap(e) if len(args) == 1 { + query, args = maybeExpandNamedQuery(dbMap, query, args) + } return exec(e, query, args...) + } func extractDbMap(e SqlExecutor) *DbMap { + switch m := e.(type) { + case *DbMap: + return m + case *Transaction: + return m.dbmap + } + return nil + } // executor exposes the sql.DB and sql.Tx functions so that it can be used + // on internal functions that need to be agnostic to the underlying object. + type executor interface { Exec(query string, args ...interface{}) (sql.Result, error) + Prepare(query string) (*sql.Stmt, error) + QueryRow(query string, args ...interface{}) *sql.Row + Query(query string, args ...interface{}) (*sql.Rows, error) + ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) + PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) + QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row + QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) } func extractExecutorAndContext(e SqlExecutor) (executor, context.Context) { + switch m := e.(type) { + case *DbMap: + return m.Db, m.ctx + case *Transaction: + return m.tx, m.ctx + } + return nil, nil + } // maybeExpandNamedQuery checks the given arg to see if it's eligible to be used + // as input to a named query. If so, it rewrites the query to use + // dialect-dependent bindvars and instantiates the corresponding slice of + // parameters by extracting data from the map / struct. + // If not, returns the input values unchanged. + func maybeExpandNamedQuery(m *DbMap, query string, args []interface{}) (string, []interface{}) { + var ( - arg = args[0] + arg = args[0] + argval = reflect.ValueOf(arg) ) + if argval.Kind() == reflect.Ptr { + argval = argval.Elem() + } if argval.Kind() == reflect.Map && argval.Type().Key().Kind() == reflect.String { + return expandNamedQuery(m, query, func(key string) reflect.Value { + return argval.MapIndex(reflect.ValueOf(key)) + }) + } + if argval.Kind() != reflect.Struct { + return query, args + } + if _, ok := arg.(time.Time); ok { + // time.Time is driver.Value + return query, args + } + if _, ok := arg.(driver.Valuer); ok { + // driver.Valuer will be converted to driver.Value. + return query, args + } return expandNamedQuery(m, query, argval.FieldByName) + } var keyRegexp = regexp.MustCompile(`:[[:word:]]+`) // expandNamedQuery accepts a query with placeholders of the form ":key", and a + // single arg of Kind Struct or Map[string]. It returns the query with the + // dialect's placeholders, and a slice of args ready for positional insertion + // into the query. + func expandNamedQuery(m *DbMap, query string, keyGetter func(key string) reflect.Value) (string, []interface{}) { + var ( - n int + n int + args []interface{} ) + return keyRegexp.ReplaceAllStringFunc(query, func(key string) string { + val := keyGetter(key[1:]) + if !val.IsValid() { + return key + } + args = append(args, val.Interface()) + newVar := m.Dialect.BindVar(n) + n++ + return newVar + }), args + } func columnToFieldIndex(m *DbMap, t reflect.Type, name string, cols []string) ([][]int, error) { + colToFieldIndex := make([][]int, len(cols)) // check if type t is a mapped table - if so we'll + // check the table for column aliasing below + tableMapped := false + table := tableOrNil(m, t, name) + if table != nil { + tableMapped = true + } // Loop over column names and find field in i to bind to + // based on column name. all returned columns must match + // a field in the i struct + missingColNames := []string{} + for x := range cols { + colName := strings.ToLower(cols[x]) + field, found := t.FieldByNameFunc(func(fieldName string) bool { + field, _ := t.FieldByName(fieldName) + cArguments := strings.Split(field.Tag.Get("db"), ",") + fieldName = cArguments[0] if fieldName == "-" { + return false + } else if fieldName == "" { + fieldName = field.Name + } + if tableMapped { + colMap := colMapOrNil(table, fieldName) + if colMap != nil { + fieldName = colMap.ColumnName + } + } + return colName == strings.ToLower(fieldName) + }) + if found { + colToFieldIndex[x] = field.Index + } + if colToFieldIndex[x] == nil { + missingColNames = append(missingColNames, colName) + } + } + if len(missingColNames) > 0 { + return colToFieldIndex, &NoFieldInTypeError{ - TypeName: t.Name(), + + TypeName: t.Name(), + MissingColNames: missingColNames, } + } + return colToFieldIndex, nil + } func fieldByName(val reflect.Value, fieldName string) *reflect.Value { + // try to find field by exact match + f := val.FieldByName(fieldName) if f != zeroVal { + return &f + } // try to find by case insensitive match - only the Postgres driver + // seems to require this - in the case where columns are aliased in the sql + fieldNameL := strings.ToLower(fieldName) + fieldCount := val.NumField() + t := val.Type() + for i := 0; i < fieldCount; i++ { + sf := t.Field(i) + if strings.ToLower(sf.Name) == fieldNameL { + f := val.Field(i) + return &f + } + } return nil + } // toSliceType returns the element type of the given object, if the object is a + // "*[]*Element" or "*[]Element". If not, returns nil. + // err is returned if the user was trying to pass a pointer-to-slice but failed. + func toSliceType(i interface{}) (reflect.Type, error) { + t := reflect.TypeOf(i) + if t.Kind() != reflect.Ptr { + // If it's a slice, return a more helpful error message + if t.Kind() == reflect.Slice { + return nil, fmt.Errorf("gorp: cannot SELECT into a non-pointer slice: %v", t) + } + return nil, nil + } + if t = t.Elem(); t.Kind() != reflect.Slice { + return nil, nil + } + return t.Elem(), nil + } func toType(i interface{}) (reflect.Type, error) { + t := reflect.TypeOf(i) // If a Pointer to a type, follow + for t.Kind() == reflect.Ptr { + t = t.Elem() + } if t.Kind() != reflect.Struct { + return nil, fmt.Errorf("gorp: cannot SELECT into this type: %v", reflect.TypeOf(i)) + } + return t, nil + } type foundTable struct { - table *TableMap + table *TableMap + dynName *string } func tableFor(m *DbMap, t reflect.Type, i interface{}) (*foundTable, error) { + if dyn, isDynamic := i.(DynamicTable); isDynamic { + tableName := dyn.TableName() + table, err := m.DynamicTableFor(tableName, true) + if err != nil { + return nil, err + } + return &foundTable{ - table: table, + + table: table, + dynName: &tableName, }, nil + } + table, err := m.TableFor(t, true) + if err != nil { + return nil, err + } + return &foundTable{table: table}, nil + } func get(m *DbMap, exec SqlExecutor, i interface{}, + keys ...interface{}) (interface{}, error) { t, err := toType(i) + if err != nil { + return nil, err + } foundTable, err := tableFor(m, t, i) + if err != nil { + return nil, err + } + table := foundTable.table plan := table.bindGet() v := reflect.New(t) + if foundTable.dynName != nil { + retDyn := v.Interface().(DynamicTable) + retDyn.SetTableName(*foundTable.dynName) + } dest := make([]interface{}, len(plan.argFields)) conv := m.TypeConverter + custScan := make([]CustomScanner, 0) for x, fieldName := range plan.argFields { + f := v.Elem().FieldByName(fieldName) + target := f.Addr().Interface() + if conv != nil { + scanner, ok := conv.FromDb(target) + if ok { + target = scanner.Holder + custScan = append(custScan, scanner) + } + } + dest[x] = target + } row := exec.QueryRow(plan.query, keys...) + err = row.Scan(dest...) + if err != nil { + if err == sql.ErrNoRows { + err = nil + } + return nil, err + } for _, c := range custScan { + err = c.Bind() + if err != nil { + return nil, err + } + } if v, ok := v.Interface().(HasPostGet); ok { + err := v.PostGet(exec) + if err != nil { + return nil, err + } + } return v.Interface(), nil + } func delete(m *DbMap, exec SqlExecutor, list ...interface{}) (int64, error) { + count := int64(0) + for _, ptr := range list { + table, elem, err := m.tableForPointer(ptr, true) + if err != nil { + return -1, err + } eval := elem.Addr().Interface() + if v, ok := eval.(HasPreDelete); ok { + err = v.PreDelete(exec) + if err != nil { + return -1, err + } + } bi, err := table.bindDelete(elem) + if err != nil { + return -1, err + } res, err := exec.Exec(bi.query, bi.args...) + if err != nil { + return -1, err + } + rows, err := res.RowsAffected() + if err != nil { + return -1, err + } if rows == 0 && bi.existingVersion > 0 { + return lockError(m, exec, table.TableName, + bi.existingVersion, elem, bi.keys...) + } count += rows if v, ok := eval.(HasPostDelete); ok { + err := v.PostDelete(exec) + if err != nil { + return -1, err + } + } + } return count, nil + } func update(m *DbMap, exec SqlExecutor, colFilter ColumnFilter, list ...interface{}) (int64, error) { + count := int64(0) + for _, ptr := range list { + table, elem, err := m.tableForPointer(ptr, true) + if err != nil { + return -1, err + } eval := elem.Addr().Interface() + if v, ok := eval.(HasPreUpdate); ok { + err = v.PreUpdate(exec) + if err != nil { + return -1, err + } + } bi, err := table.bindUpdate(elem, colFilter) + if err != nil { + return -1, err + } res, err := exec.Exec(bi.query, bi.args...) + if err != nil { + return -1, err + } rows, err := res.RowsAffected() + if err != nil { + return -1, err + } if rows == 0 && bi.existingVersion > 0 { + return lockError(m, exec, table.TableName, + bi.existingVersion, elem, bi.keys...) + } if bi.versField != "" { + elem.FieldByName(bi.versField).SetInt(bi.existingVersion + 1) + } count += rows if v, ok := eval.(HasPostUpdate); ok { + err = v.PostUpdate(exec) + if err != nil { + return -1, err + } + } + } + return count, nil + } func insert(m *DbMap, exec SqlExecutor, list ...interface{}) error { + for _, ptr := range list { + table, elem, err := m.tableForPointer(ptr, false) + if err != nil { + return err + } eval := elem.Addr().Interface() + if v, ok := eval.(HasPreInsert); ok { + err := v.PreInsert(exec) + if err != nil { + return err + } + } bi, err := table.bindInsert(elem) + if err != nil { + return err + } if bi.autoIncrIdx > -1 { + f := elem.FieldByName(bi.autoIncrFieldName) + switch inserter := m.Dialect.(type) { + case IntegerAutoIncrInserter: + id, err := inserter.InsertAutoIncr(exec, bi.query, bi.args...) + if err != nil { + return err + } + k := f.Kind() + if (k == reflect.Int) || (k == reflect.Int16) || (k == reflect.Int32) || (k == reflect.Int64) { + f.SetInt(id) + } else if (k == reflect.Uint) || (k == reflect.Uint16) || (k == reflect.Uint32) || (k == reflect.Uint64) { + f.SetUint(uint64(id)) + } else { + return fmt.Errorf("gorp: cannot set autoincrement value on non-Int field. SQL=%s autoIncrIdx=%d autoIncrFieldName=%s", bi.query, bi.autoIncrIdx, bi.autoIncrFieldName) + } + case TargetedAutoIncrInserter: + err := inserter.InsertAutoIncrToTarget(exec, bi.query, f.Addr().Interface(), bi.args...) + if err != nil { + return err + } + case TargetQueryInserter: + var idQuery = table.ColMap(bi.autoIncrFieldName).GeneratedIdQuery + if idQuery == "" { + return fmt.Errorf("gorp: cannot set %s value if its ColumnMap.GeneratedIdQuery is empty", bi.autoIncrFieldName) + } + err := inserter.InsertQueryToTarget(exec, bi.query, idQuery, f.Addr().Interface(), bi.args...) + if err != nil { + return err + } + default: + return fmt.Errorf("gorp: cannot use autoincrement fields on dialects that do not implement an autoincrementing interface") + } + } else { + _, err := exec.Exec(bi.query, bi.args...) + if err != nil { + return err + } + } if v, ok := eval.(HasPostInsert); ok { + err := v.PostInsert(exec) + if err != nil { + return err + } + } + } + return nil + } func exec(e SqlExecutor, query string, args ...interface{}) (sql.Result, error) { + executor, ctx := extractExecutorAndContext(e) if ctx != nil { + return executor.ExecContext(ctx, query, args...) + } return executor.Exec(query, args...) + } func prepare(e SqlExecutor, query string) (*sql.Stmt, error) { + executor, ctx := extractExecutorAndContext(e) if ctx != nil { + return executor.PrepareContext(ctx, query) + } return executor.Prepare(query) + } func queryRow(e SqlExecutor, query string, args ...interface{}) *sql.Row { + executor, ctx := extractExecutorAndContext(e) if ctx != nil { + return executor.QueryRowContext(ctx, query, args...) + } return executor.QueryRow(query, args...) + } func query(e SqlExecutor, query string, args ...interface{}) (*sql.Rows, error) { + executor, ctx := extractExecutorAndContext(e) if ctx != nil { + return executor.QueryContext(ctx, query, args...) + } return executor.Query(query, args...) + } func begin(m *DbMap) (*sql.Tx, error) { + if m.ctx != nil { + return m.Db.BeginTx(m.ctx, nil) + } return m.Db.Begin() + } diff --git a/vendor/github.com/go-gorp/gorp/v3/lockerror.go b/vendor/github.com/go-gorp/gorp/v3/lockerror.go index 7e81891..6c1ff5e 100644 --- a/vendor/github.com/go-gorp/gorp/v3/lockerror.go +++ b/vendor/github.com/go-gorp/gorp/v3/lockerror.go @@ -1,5 +1,7 @@ // Copyright 2012 James Cooper. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package gorp @@ -10,47 +12,74 @@ import ( ) // OptimisticLockError is returned by Update() or Delete() if the + // struct being modified has a Version field and the value is not equal to + // the current value in the database + type OptimisticLockError struct { + // Table name where the lock error occurred + TableName string // Primary key values of the row being updated/deleted + Keys []interface{} // true if a row was found with those keys, indicating the + // LocalVersion is stale. false if no value was found with those + // keys, suggesting the row has been deleted since loaded, or + // was never inserted to begin with + RowExists bool // Version value on the struct passed to Update/Delete. This value is + // out of sync with the database. + LocalVersion int64 } // Error returns a description of the cause of the lock error + func (e OptimisticLockError) Error() string { + if e.RowExists { + return fmt.Sprintf("gorp: OptimisticLockError table=%s keys=%v out of date version=%d", e.TableName, e.Keys, e.LocalVersion) + } return fmt.Sprintf("gorp: OptimisticLockError no row found for table=%s keys=%v", e.TableName, e.Keys) + } func lockError(m *DbMap, exec SqlExecutor, tableName string, + existingVer int64, elem reflect.Value, + keys ...interface{}) (int64, error) { existing, err := get(m, exec, elem.Interface(), keys...) + if err != nil { + return -1, err + } ole := OptimisticLockError{tableName, keys, true, existingVer} + if existing == nil { + ole.RowExists = false + } + return -1, ole + } diff --git a/vendor/github.com/go-gorp/gorp/v3/nulltypes.go b/vendor/github.com/go-gorp/gorp/v3/nulltypes.go index 87b21f8..81da1f7 100644 --- a/vendor/github.com/go-gorp/gorp/v3/nulltypes.go +++ b/vendor/github.com/go-gorp/gorp/v3/nulltypes.go @@ -1,5 +1,7 @@ // Copyright 2012 James Cooper. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package gorp @@ -11,55 +13,99 @@ import ( ) // A nullable Time value + type NullTime struct { - Time time.Time + Time time.Time + Valid bool // Valid is true if Time is not NULL + } // Scan implements the Scanner interface. + func (nt *NullTime) Scan(value interface{}) error { + log.Printf("Time scan value is: %#v", value) + switch t := value.(type) { + case time.Time: + nt.Time, nt.Valid = t, true + case []byte: + v := strToTime(string(t)) + if v != nil { + nt.Valid = true + nt.Time = *v + } + case string: + v := strToTime(t) + if v != nil { + nt.Valid = true + nt.Time = *v + } + } + return nil + } func strToTime(v string) *time.Time { + for _, dtfmt := range []string{ + "2006-01-02 15:04:05.999999999", + "2006-01-02T15:04:05.999999999", + "2006-01-02 15:04:05", + "2006-01-02T15:04:05", + "2006-01-02 15:04", + "2006-01-02T15:04", + "2006-01-02", + "2006-01-02 15:04:05-07:00", } { + if t, err := time.Parse(dtfmt, v); err == nil { + return &t + } + } + return nil + } // Value implements the driver Valuer interface. + func (nt NullTime) Value() (driver.Value, error) { + if !nt.Valid { + return nil, nil + } + return nt.Time, nil + } diff --git a/vendor/github.com/go-gorp/gorp/v3/select.go b/vendor/github.com/go-gorp/gorp/v3/select.go index 4b89641..9ca2bae 100644 --- a/vendor/github.com/go-gorp/gorp/v3/select.go +++ b/vendor/github.com/go-gorp/gorp/v3/select.go @@ -1,5 +1,7 @@ // Copyright 2012 James Cooper. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package gorp @@ -11,293 +13,508 @@ import ( ) // SelectInt executes the given query, which should be a SELECT statement for a single + // integer column, and returns the value of the first row returned. If no rows are + // found, zero is returned. + func SelectInt(e SqlExecutor, query string, args ...interface{}) (int64, error) { + var h int64 + err := selectVal(e, &h, query, args...) + if err != nil && err != sql.ErrNoRows { + return 0, err + } + return h, nil + } // SelectNullInt executes the given query, which should be a SELECT statement for a single + // integer column, and returns the value of the first row returned. If no rows are + // found, the empty sql.NullInt64 value is returned. + func SelectNullInt(e SqlExecutor, query string, args ...interface{}) (sql.NullInt64, error) { + var h sql.NullInt64 + err := selectVal(e, &h, query, args...) + if err != nil && err != sql.ErrNoRows { + return h, err + } + return h, nil + } // SelectFloat executes the given query, which should be a SELECT statement for a single + // float column, and returns the value of the first row returned. If no rows are + // found, zero is returned. + func SelectFloat(e SqlExecutor, query string, args ...interface{}) (float64, error) { + var h float64 + err := selectVal(e, &h, query, args...) + if err != nil && err != sql.ErrNoRows { + return 0, err + } + return h, nil + } // SelectNullFloat executes the given query, which should be a SELECT statement for a single + // float column, and returns the value of the first row returned. If no rows are + // found, the empty sql.NullInt64 value is returned. + func SelectNullFloat(e SqlExecutor, query string, args ...interface{}) (sql.NullFloat64, error) { + var h sql.NullFloat64 + err := selectVal(e, &h, query, args...) + if err != nil && err != sql.ErrNoRows { + return h, err + } + return h, nil + } // SelectStr executes the given query, which should be a SELECT statement for a single + // char/varchar column, and returns the value of the first row returned. If no rows are + // found, an empty string is returned. + func SelectStr(e SqlExecutor, query string, args ...interface{}) (string, error) { + var h string + err := selectVal(e, &h, query, args...) + if err != nil && err != sql.ErrNoRows { + return "", err + } + return h, nil + } // SelectNullStr executes the given query, which should be a SELECT + // statement for a single char/varchar column, and returns the value + // of the first row returned. If no rows are found, the empty + // sql.NullString is returned. + func SelectNullStr(e SqlExecutor, query string, args ...interface{}) (sql.NullString, error) { + var h sql.NullString + err := selectVal(e, &h, query, args...) + if err != nil && err != sql.ErrNoRows { + return h, err + } + return h, nil + } // SelectOne executes the given query (which should be a SELECT statement) + // and binds the result to holder, which must be a pointer. + // + // # If no row is found, an error (sql.ErrNoRows specifically) will be returned + // + // If more than one row is found, an error will be returned. + func SelectOne(m *DbMap, e SqlExecutor, holder interface{}, query string, args ...interface{}) error { + t := reflect.TypeOf(holder) + if t.Kind() == reflect.Ptr { + t = t.Elem() + } else { + return fmt.Errorf("gorp: SelectOne holder must be a pointer, but got: %t", holder) + } // Handle pointer to pointer + isptr := false + if t.Kind() == reflect.Ptr { + isptr = true + t = t.Elem() + } if t.Kind() == reflect.Struct { + var nonFatalErr error list, err := hookedselect(m, e, holder, query, args...) + if err != nil { + if !NonFatalError(err) { // FIXME: double negative, rename NonFatalError to FatalError + return err + } + nonFatalErr = err + } dest := reflect.ValueOf(holder) + if isptr { + dest = dest.Elem() + } if list != nil && len(list) > 0 { // FIXME: invert if/else + // check for multiple rows + if len(list) > 1 { + return fmt.Errorf("gorp: multiple rows returned for: %s - %v", query, args) + } // Initialize if nil + if dest.IsNil() { + dest.Set(reflect.New(t)) + } // only one row found + src := reflect.ValueOf(list[0]) + dest.Elem().Set(src.Elem()) + } else { + // No rows found, return a proper error. + return sql.ErrNoRows + } return nonFatalErr + } return selectVal(e, holder, query, args...) + } func selectVal(e SqlExecutor, holder interface{}, query string, args ...interface{}) error { + if len(args) == 1 { + switch m := e.(type) { + case *DbMap: + query, args = maybeExpandNamedQuery(m, query, args) + case *Transaction: + query, args = maybeExpandNamedQuery(m.dbmap, query, args) + } + } + rows, err := e.Query(query, args...) + if err != nil { + return err + } + defer rows.Close() if !rows.Next() { + if err := rows.Err(); err != nil { + return err + } + return sql.ErrNoRows + } return rows.Scan(holder) + } func hookedselect(m *DbMap, exec SqlExecutor, i interface{}, query string, + args ...interface{}) ([]interface{}, error) { var nonFatalErr error list, err := rawselect(m, exec, i, query, args...) + if err != nil { + if !NonFatalError(err) { + return nil, err + } + nonFatalErr = err + } // Determine where the results are: written to i, or returned in list + if t, _ := toSliceType(i); t == nil { + for _, v := range list { + if v, ok := v.(HasPostGet); ok { + err := v.PostGet(exec) + if err != nil { + return nil, err + } + } + } + } else { + resultsValue := reflect.Indirect(reflect.ValueOf(i)) + for i := 0; i < resultsValue.Len(); i++ { + if v, ok := resultsValue.Index(i).Interface().(HasPostGet); ok { + err := v.PostGet(exec) + if err != nil { + return nil, err + } + } + } + } + return list, nonFatalErr + } func rawselect(m *DbMap, exec SqlExecutor, i interface{}, query string, + args ...interface{}) ([]interface{}, error) { + var ( - appendToSlice = false // Write results to i directly? - intoStruct = true // Selecting into a struct? - pointerElements = true // Are the slice elements pointers (vs values)? + appendToSlice = false // Write results to i directly? + + intoStruct = true // Selecting into a struct? + + pointerElements = true // Are the slice elements pointers (vs values)? + ) var nonFatalErr error tableName := "" + var dynObj DynamicTable + isDynamic := false + if dynObj, isDynamic = i.(DynamicTable); isDynamic { + tableName = dynObj.TableName() + } // get type for i, verifying it's a supported destination + t, err := toType(i) + if err != nil { + var err2 error + if t, err2 = toSliceType(i); t == nil { + if err2 != nil { + return nil, err2 + } + return nil, err + } + pointerElements = t.Kind() == reflect.Ptr + if pointerElements { + t = t.Elem() + } + appendToSlice = true + intoStruct = t.Kind() == reflect.Struct + } // If the caller supplied a single struct/map argument, assume a "named + // parameter" query. Extract the named arguments from the struct/map, create + // the flat arg slice, and rewrite the query to use the dialect's placeholder. + if len(args) == 1 { + query, args = maybeExpandNamedQuery(m, query, args) + } // Run the query + rows, err := exec.Query(query, args...) + if err != nil { + return nil, err + } + defer rows.Close() // Fetch the column names as returned from db + cols, err := rows.Columns() + if err != nil { + return nil, err + } if !intoStruct && len(cols) > 1 { + return nil, fmt.Errorf("gorp: select into non-struct slice requires 1 column, got %d", len(cols)) + } var colToFieldIndex [][]int + if intoStruct { + colToFieldIndex, err = columnToFieldIndex(m, t, tableName, cols) + if err != nil { + if !NonFatalError(err) { + return nil, err + } + nonFatalErr = err + } + } conv := m.TypeConverter // Add results to one of these two slices. + var ( - list = make([]interface{}, 0) + list = make([]interface{}, 0) + sliceValue = reflect.Indirect(reflect.ValueOf(i)) ) for { + if !rows.Next() { + // if error occured return rawselect + if rows.Err() != nil { + return nil, rows.Err() + } + // time to exit from outer "for" loop + break + } + v := reflect.New(t) if isDynamic { + v.Interface().(DynamicTable).SetTableName(tableName) + } dest := make([]interface{}, len(cols)) @@ -305,54 +522,95 @@ func rawselect(m *DbMap, exec SqlExecutor, i interface{}, query string, custScan := make([]CustomScanner, 0) for x := range cols { + f := v.Elem() + if intoStruct { + index := colToFieldIndex[x] + if index == nil { + // this field is not present in the struct, so create a dummy + // value for rows.Scan to scan into + var dummy dummyField + dest[x] = &dummy + continue + } + f = f.FieldByIndex(index) + } + target := f.Addr().Interface() + if conv != nil { + scanner, ok := conv.FromDb(target) + if ok { + target = scanner.Holder + custScan = append(custScan, scanner) + } + } + dest[x] = target + } err = rows.Scan(dest...) + if err != nil { + return nil, err + } for _, c := range custScan { + err = c.Bind() + if err != nil { + return nil, err + } + } if appendToSlice { + if !pointerElements { + v = v.Elem() + } + sliceValue.Set(reflect.Append(sliceValue, v)) + } else { + list = append(list, v.Interface()) + } + } if appendToSlice && sliceValue.IsNil() { + sliceValue.Set(reflect.MakeSlice(sliceValue.Type(), 0, 0)) + } return list, nonFatalErr + } diff --git a/vendor/github.com/go-gorp/gorp/v3/table.go b/vendor/github.com/go-gorp/gorp/v3/table.go index edab08a..d3c16d3 100644 --- a/vendor/github.com/go-gorp/gorp/v3/table.go +++ b/vendor/github.com/go-gorp/gorp/v3/table.go @@ -1,5 +1,7 @@ // Copyright 2012 James Cooper. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package gorp @@ -12,244 +14,442 @@ import ( ) // TableMap represents a mapping between a Go struct and a database table + // Use dbmap.AddTable() or dbmap.AddTableWithName() to create these + type TableMap struct { + // Name of database table. - TableName string - SchemaName string - gotype reflect.Type - Columns []*ColumnMap - keys []*ColumnMap - indexes []*IndexMap + + TableName string + + SchemaName string + + gotype reflect.Type + + Columns []*ColumnMap + + keys []*ColumnMap + + indexes []*IndexMap + uniqueTogether [][]string - version *ColumnMap - insertPlan bindPlan - updatePlan bindPlan - deletePlan bindPlan - getPlan bindPlan - dbmap *DbMap + + version *ColumnMap + + insertPlan bindPlan + + updatePlan bindPlan + + deletePlan bindPlan + + getPlan bindPlan + + dbmap *DbMap } // ResetSql removes cached insert/update/select/delete SQL strings + // associated with this TableMap. Call this if you've modified + // any column names or the table name itself. + func (t *TableMap) ResetSql() { + t.insertPlan = bindPlan{} + t.updatePlan = bindPlan{} + t.deletePlan = bindPlan{} + t.getPlan = bindPlan{} + } // SetKeys lets you specify the fields on a struct that map to primary + // key columns on the table. If isAutoIncr is set, result.LastInsertId() + // will be used after INSERT to bind the generated id to the Go struct. + // + // Automatically calls ResetSql() to ensure SQL statements are regenerated. + // + // Panics if isAutoIncr is true, and fieldNames length != 1 + func (t *TableMap) SetKeys(isAutoIncr bool, fieldNames ...string) *TableMap { + if isAutoIncr && len(fieldNames) != 1 { + panic(fmt.Sprintf( + "gorp: SetKeys: fieldNames length must be 1 if key is auto-increment. (Saw %v fieldNames)", + len(fieldNames))) + } + t.keys = make([]*ColumnMap, 0) + for _, name := range fieldNames { + colmap := t.ColMap(name) + colmap.isPK = true + colmap.isAutoIncr = isAutoIncr + t.keys = append(t.keys, colmap) + } + t.ResetSql() return t + } // SetUniqueTogether lets you specify uniqueness constraints across multiple + // columns on the table. Each call adds an additional constraint for the + // specified columns. + // + // Automatically calls ResetSql() to ensure SQL statements are regenerated. + // + // Panics if fieldNames length < 2. + func (t *TableMap) SetUniqueTogether(fieldNames ...string) *TableMap { + if len(fieldNames) < 2 { + panic(fmt.Sprintf( + "gorp: SetUniqueTogether: must provide at least two fieldNames to set uniqueness constraint.")) + } columns := make([]string, 0, len(fieldNames)) + for _, name := range fieldNames { + columns = append(columns, name) + } for _, existingColumns := range t.uniqueTogether { + if equal(existingColumns, columns) { + return t + } + } + t.uniqueTogether = append(t.uniqueTogether, columns) + t.ResetSql() return t + } // ColMap returns the ColumnMap pointer matching the given struct field + // name. It panics if the struct does not contain a field matching this + // name. + func (t *TableMap) ColMap(field string) *ColumnMap { + col := colMapOrNil(t, field) + if col == nil { + e := fmt.Sprintf("No ColumnMap in table %s type %s with field %s", + t.TableName, t.gotype.Name(), field) panic(e) + } + return col + } func colMapOrNil(t *TableMap, field string) *ColumnMap { + for _, col := range t.Columns { + if col.fieldName == field || col.ColumnName == field { + return col + } + } + return nil + } // IdxMap returns the IndexMap pointer matching the given index name. + func (t *TableMap) IdxMap(field string) *IndexMap { + for _, idx := range t.indexes { + if idx.IndexName == field { + return idx + } + } + return nil + } // AddIndex registers the index with gorp for specified table with given parameters. + // This operation is idempotent. If index is already mapped, the + // existing *IndexMap is returned + // Function will panic if one of the given for index columns does not exists + // + // Automatically calls ResetSql() to ensure SQL statements are regenerated. + func (t *TableMap) AddIndex(name string, idxtype string, columns []string) *IndexMap { + // check if we have a index with this name already + for _, idx := range t.indexes { + if idx.IndexName == name { + return idx + } + } + for _, icol := range columns { + if res := t.ColMap(icol); res == nil { + e := fmt.Sprintf("No ColumnName in table %s to create index on", t.TableName) + panic(e) + } + } idx := &IndexMap{IndexName: name, Unique: false, IndexType: idxtype, columns: columns} + t.indexes = append(t.indexes, idx) + t.ResetSql() + return idx + } // SetVersionCol sets the column to use as the Version field. By default + // the "Version" field is used. Returns the column found, or panics + // if the struct does not contain a field matching this name. + // + // Automatically calls ResetSql() to ensure SQL statements are regenerated. + func (t *TableMap) SetVersionCol(field string) *ColumnMap { + c := t.ColMap(field) + t.version = c + t.ResetSql() + return c + } // SqlForCreateTable gets a sequence of SQL commands that will create + // the specified table and any associated schema + func (t *TableMap) SqlForCreate(ifNotExists bool) string { + s := bytes.Buffer{} + dialect := t.dbmap.Dialect if strings.TrimSpace(t.SchemaName) != "" { + schemaCreate := "create schema" + if ifNotExists { + s.WriteString(dialect.IfSchemaNotExists(schemaCreate, t.SchemaName)) + } else { + s.WriteString(schemaCreate) + } + s.WriteString(fmt.Sprintf(" %s;", t.SchemaName)) + } tableCreate := "create table" + if ifNotExists { + s.WriteString(dialect.IfTableNotExists(tableCreate, t.SchemaName, t.TableName)) + } else { + s.WriteString(tableCreate) + } + s.WriteString(fmt.Sprintf(" %s (", dialect.QuotedTableForQuery(t.SchemaName, t.TableName))) x := 0 + for _, col := range t.Columns { + if !col.Transient { + if x > 0 { + s.WriteString(", ") + } + stype := dialect.ToSqlType(col.gotype, col.MaxSize, col.isAutoIncr) + s.WriteString(fmt.Sprintf("%s %s", dialect.QuoteField(col.ColumnName), stype)) if col.isPK || col.isNotNull { + s.WriteString(" not null") + } + if col.isPK && len(t.keys) == 1 { + s.WriteString(" primary key") + } + if col.Unique { + s.WriteString(" unique") + } + if col.isAutoIncr { + s.WriteString(fmt.Sprintf(" %s", dialect.AutoIncrStr())) + } x++ + } + } + if len(t.keys) > 1 { + s.WriteString(", primary key (") + for x := range t.keys { + if x > 0 { + s.WriteString(", ") + } + s.WriteString(dialect.QuoteField(t.keys[x].ColumnName)) + } + s.WriteString(")") + } + if len(t.uniqueTogether) > 0 { + for _, columns := range t.uniqueTogether { + s.WriteString(", unique (") + for i, column := range columns { + if i > 0 { + s.WriteString(", ") + } + s.WriteString(dialect.QuoteField(column)) + } + s.WriteString(")") + } + } + s.WriteString(") ") + s.WriteString(dialect.CreateTableSuffix()) + s.WriteString(dialect.QuerySuffix()) + return s.String() + } func equal(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true + } diff --git a/vendor/github.com/go-gorp/gorp/v3/table_bindings.go b/vendor/github.com/go-gorp/gorp/v3/table_bindings.go index 43c0b3d..106afd0 100644 --- a/vendor/github.com/go-gorp/gorp/v3/table_bindings.go +++ b/vendor/github.com/go-gorp/gorp/v3/table_bindings.go @@ -1,5 +1,7 @@ // Copyright 2012 James Cooper. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package gorp @@ -12,294 +14,508 @@ import ( ) // CustomScanner binds a database column value to a Go type + type CustomScanner struct { + // After a row is scanned, Holder will contain the value from the database column. + // Initialize the CustomScanner with the concrete Go type you wish the database + // driver to scan the raw column into. + Holder interface{} + // Target typically holds a pointer to the target struct field to bind the Holder + // value to. + Target interface{} + // Binder is a custom function that converts the holder value to the target type + // and sets target accordingly. This function should return error if a problem + // occurs converting the holder to the target. + Binder func(holder interface{}, target interface{}) error } // Used to filter columns when selectively updating + type ColumnFilter func(*ColumnMap) bool func acceptAllFilter(col *ColumnMap) bool { + return true + } // Bind is called automatically by gorp after Scan() + func (me CustomScanner) Bind() error { + return me.Binder(me.Holder, me.Target) + } type bindPlan struct { - query string - argFields []string - keyFields []string - versField string - autoIncrIdx int + query string + + argFields []string + + keyFields []string + + versField string + + autoIncrIdx int + autoIncrFieldName string - once sync.Once + + once sync.Once } func (plan *bindPlan) createBindInstance(elem reflect.Value, conv TypeConverter) (bindInstance, error) { + bi := bindInstance{query: plan.query, autoIncrIdx: plan.autoIncrIdx, autoIncrFieldName: plan.autoIncrFieldName, versField: plan.versField} + if plan.versField != "" { + bi.existingVersion = elem.FieldByName(plan.versField).Int() + } var err error for i := 0; i < len(plan.argFields); i++ { + k := plan.argFields[i] + if k == versFieldConst { + newVer := bi.existingVersion + 1 + bi.args = append(bi.args, newVer) + if bi.existingVersion == 0 { + elem.FieldByName(plan.versField).SetInt(int64(newVer)) + } + } else { + val := elem.FieldByName(k).Interface() + if conv != nil { + val, err = conv.ToDb(val) + if err != nil { + return bindInstance{}, err + } + } + bi.args = append(bi.args, val) + } + } for i := 0; i < len(plan.keyFields); i++ { + k := plan.keyFields[i] + val := elem.FieldByName(k).Interface() + if conv != nil { + val, err = conv.ToDb(val) + if err != nil { + return bindInstance{}, err + } + } + bi.keys = append(bi.keys, val) + } return bi, nil + } type bindInstance struct { - query string - args []interface{} - keys []interface{} - existingVersion int64 - versField string - autoIncrIdx int + query string + + args []interface{} + + keys []interface{} + + existingVersion int64 + + versField string + + autoIncrIdx int + autoIncrFieldName string } func (t *TableMap) bindInsert(elem reflect.Value) (bindInstance, error) { + plan := &t.insertPlan + plan.once.Do(func() { + plan.autoIncrIdx = -1 s := bytes.Buffer{} + s2 := bytes.Buffer{} + s.WriteString(fmt.Sprintf("insert into %s (", t.dbmap.Dialect.QuotedTableForQuery(t.SchemaName, t.TableName))) x := 0 + first := true + for y := range t.Columns { + col := t.Columns[y] + if !(col.isAutoIncr && t.dbmap.Dialect.AutoIncrBindValue() == "") { + if !col.Transient { + if !first { + s.WriteString(",") + s2.WriteString(",") + } + s.WriteString(t.dbmap.Dialect.QuoteField(col.ColumnName)) if col.isAutoIncr { + s2.WriteString(t.dbmap.Dialect.AutoIncrBindValue()) + plan.autoIncrIdx = y + plan.autoIncrFieldName = col.fieldName + } else { + if col.DefaultValue == "" { + s2.WriteString(t.dbmap.Dialect.BindVar(x)) + if col == t.version { + plan.versField = col.fieldName + plan.argFields = append(plan.argFields, versFieldConst) + } else { + plan.argFields = append(plan.argFields, col.fieldName) + } + x++ + } else { + s2.WriteString(col.DefaultValue) + } + } + first = false + } + } else { + plan.autoIncrIdx = y + plan.autoIncrFieldName = col.fieldName + } + } + s.WriteString(") values (") + s.WriteString(s2.String()) + s.WriteString(")") + if plan.autoIncrIdx > -1 { + s.WriteString(t.dbmap.Dialect.AutoIncrInsertSuffix(t.Columns[plan.autoIncrIdx])) + } + s.WriteString(t.dbmap.Dialect.QuerySuffix()) plan.query = s.String() + }) return plan.createBindInstance(elem, t.dbmap.TypeConverter) + } func (t *TableMap) bindUpdate(elem reflect.Value, colFilter ColumnFilter) (bindInstance, error) { + if colFilter == nil { + colFilter = acceptAllFilter + } plan := &t.updatePlan + plan.once.Do(func() { + s := bytes.Buffer{} + s.WriteString(fmt.Sprintf("update %s set ", t.dbmap.Dialect.QuotedTableForQuery(t.SchemaName, t.TableName))) + x := 0 for y := range t.Columns { + col := t.Columns[y] + if !col.isAutoIncr && !col.Transient && colFilter(col) { + if x > 0 { + s.WriteString(", ") + } + s.WriteString(t.dbmap.Dialect.QuoteField(col.ColumnName)) + s.WriteString("=") + s.WriteString(t.dbmap.Dialect.BindVar(x)) if col == t.version { + plan.versField = col.fieldName + plan.argFields = append(plan.argFields, versFieldConst) + } else { + plan.argFields = append(plan.argFields, col.fieldName) + } + x++ + } + } s.WriteString(" where ") + for y := range t.keys { + col := t.keys[y] + if y > 0 { + s.WriteString(" and ") + } + s.WriteString(t.dbmap.Dialect.QuoteField(col.ColumnName)) + s.WriteString("=") + s.WriteString(t.dbmap.Dialect.BindVar(x)) plan.argFields = append(plan.argFields, col.fieldName) + plan.keyFields = append(plan.keyFields, col.fieldName) + x++ + } + if plan.versField != "" { + s.WriteString(" and ") + s.WriteString(t.dbmap.Dialect.QuoteField(t.version.ColumnName)) + s.WriteString("=") + s.WriteString(t.dbmap.Dialect.BindVar(x)) + plan.argFields = append(plan.argFields, plan.versField) + } + s.WriteString(t.dbmap.Dialect.QuerySuffix()) plan.query = s.String() + }) return plan.createBindInstance(elem, t.dbmap.TypeConverter) + } func (t *TableMap) bindDelete(elem reflect.Value) (bindInstance, error) { + plan := &t.deletePlan + plan.once.Do(func() { + s := bytes.Buffer{} + s.WriteString(fmt.Sprintf("delete from %s", t.dbmap.Dialect.QuotedTableForQuery(t.SchemaName, t.TableName))) for y := range t.Columns { + col := t.Columns[y] + if !col.Transient { + if col == t.version { + plan.versField = col.fieldName + } + } + } s.WriteString(" where ") + for x := range t.keys { + k := t.keys[x] + if x > 0 { + s.WriteString(" and ") + } + s.WriteString(t.dbmap.Dialect.QuoteField(k.ColumnName)) + s.WriteString("=") + s.WriteString(t.dbmap.Dialect.BindVar(x)) plan.keyFields = append(plan.keyFields, k.fieldName) + plan.argFields = append(plan.argFields, k.fieldName) + } + if plan.versField != "" { + s.WriteString(" and ") + s.WriteString(t.dbmap.Dialect.QuoteField(t.version.ColumnName)) + s.WriteString("=") + s.WriteString(t.dbmap.Dialect.BindVar(len(plan.argFields))) plan.argFields = append(plan.argFields, plan.versField) + } + s.WriteString(t.dbmap.Dialect.QuerySuffix()) plan.query = s.String() + }) return plan.createBindInstance(elem, t.dbmap.TypeConverter) + } func (t *TableMap) bindGet() *bindPlan { + plan := &t.getPlan + plan.once.Do(func() { + s := bytes.Buffer{} + s.WriteString("select ") x := 0 + for _, col := range t.Columns { + if !col.Transient { + if x > 0 { + s.WriteString(",") + } + s.WriteString(t.dbmap.Dialect.QuoteField(col.ColumnName)) + plan.argFields = append(plan.argFields, col.fieldName) + x++ + } + } + s.WriteString(" from ") + s.WriteString(t.dbmap.Dialect.QuotedTableForQuery(t.SchemaName, t.TableName)) + s.WriteString(" where ") + for x := range t.keys { + col := t.keys[x] + if x > 0 { + s.WriteString(" and ") + } + s.WriteString(t.dbmap.Dialect.QuoteField(col.ColumnName)) + s.WriteString("=") + s.WriteString(t.dbmap.Dialect.BindVar(x)) plan.keyFields = append(plan.keyFields, col.fieldName) + } + s.WriteString(t.dbmap.Dialect.QuerySuffix()) plan.query = s.String() + }) return plan + } diff --git a/vendor/github.com/go-gorp/gorp/v3/transaction.go b/vendor/github.com/go-gorp/gorp/v3/transaction.go index d505d94..c1d59a9 100644 --- a/vendor/github.com/go-gorp/gorp/v3/transaction.go +++ b/vendor/github.com/go-gorp/gorp/v3/transaction.go @@ -1,5 +1,7 @@ // Copyright 2012 James Cooper. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package gorp @@ -11,229 +13,381 @@ import ( ) // Transaction represents a database transaction. + // Insert/Update/Delete/Get/Exec operations will be run in the context + // of that transaction. Transactions should be terminated with + // a call to Commit() or Rollback() + type Transaction struct { - ctx context.Context - dbmap *DbMap - tx *sql.Tx + ctx context.Context + + dbmap *DbMap + + tx *sql.Tx + closed bool } func (t *Transaction) WithContext(ctx context.Context) SqlExecutor { + copy := &Transaction{} + *copy = *t + copy.ctx = ctx + return copy + } // Insert has the same behavior as DbMap.Insert(), but runs in a transaction. + func (t *Transaction) Insert(list ...interface{}) error { + return insert(t.dbmap, t, list...) + } // Update had the same behavior as DbMap.Update(), but runs in a transaction. + func (t *Transaction) Update(list ...interface{}) (int64, error) { + return update(t.dbmap, t, nil, list...) + } // UpdateColumns had the same behavior as DbMap.UpdateColumns(), but runs in a transaction. + func (t *Transaction) UpdateColumns(filter ColumnFilter, list ...interface{}) (int64, error) { + return update(t.dbmap, t, filter, list...) + } // Delete has the same behavior as DbMap.Delete(), but runs in a transaction. + func (t *Transaction) Delete(list ...interface{}) (int64, error) { + return delete(t.dbmap, t, list...) + } // Get has the same behavior as DbMap.Get(), but runs in a transaction. + func (t *Transaction) Get(i interface{}, keys ...interface{}) (interface{}, error) { + return get(t.dbmap, t, i, keys...) + } // Select has the same behavior as DbMap.Select(), but runs in a transaction. + func (t *Transaction) Select(i interface{}, query string, args ...interface{}) ([]interface{}, error) { + if t.dbmap.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } return hookedselect(t.dbmap, t, i, query, args...) + } // Exec has the same behavior as DbMap.Exec(), but runs in a transaction. + func (t *Transaction) Exec(query string, args ...interface{}) (sql.Result, error) { + if t.dbmap.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } if t.dbmap.logger != nil { + now := time.Now() + defer t.dbmap.trace(now, query, args...) + } + return maybeExpandNamedQueryAndExec(t, query, args...) + } // SelectInt is a convenience wrapper around the gorp.SelectInt function. + func (t *Transaction) SelectInt(query string, args ...interface{}) (int64, error) { + if t.dbmap.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } return SelectInt(t, query, args...) + } // SelectNullInt is a convenience wrapper around the gorp.SelectNullInt function. + func (t *Transaction) SelectNullInt(query string, args ...interface{}) (sql.NullInt64, error) { + if t.dbmap.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } return SelectNullInt(t, query, args...) + } // SelectFloat is a convenience wrapper around the gorp.SelectFloat function. + func (t *Transaction) SelectFloat(query string, args ...interface{}) (float64, error) { + if t.dbmap.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } return SelectFloat(t, query, args...) + } // SelectNullFloat is a convenience wrapper around the gorp.SelectNullFloat function. + func (t *Transaction) SelectNullFloat(query string, args ...interface{}) (sql.NullFloat64, error) { + if t.dbmap.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } return SelectNullFloat(t, query, args...) + } // SelectStr is a convenience wrapper around the gorp.SelectStr function. + func (t *Transaction) SelectStr(query string, args ...interface{}) (string, error) { + if t.dbmap.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } return SelectStr(t, query, args...) + } // SelectNullStr is a convenience wrapper around the gorp.SelectNullStr function. + func (t *Transaction) SelectNullStr(query string, args ...interface{}) (sql.NullString, error) { + if t.dbmap.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } return SelectNullStr(t, query, args...) + } // SelectOne is a convenience wrapper around the gorp.SelectOne function. + func (t *Transaction) SelectOne(holder interface{}, query string, args ...interface{}) error { + if t.dbmap.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } return SelectOne(t.dbmap, t, holder, query, args...) + } // Commit commits the underlying database transaction. + func (t *Transaction) Commit() error { + if !t.closed { + t.closed = true + if t.dbmap.logger != nil { + now := time.Now() + defer t.dbmap.trace(now, "commit;") + } + return t.tx.Commit() + } return sql.ErrTxDone + } // Rollback rolls back the underlying database transaction. + func (t *Transaction) Rollback() error { + if !t.closed { + t.closed = true + if t.dbmap.logger != nil { + now := time.Now() + defer t.dbmap.trace(now, "rollback;") + } + return t.tx.Rollback() + } return sql.ErrTxDone + } // Savepoint creates a savepoint with the given name. The name is interpolated + // directly into the SQL SAVEPOINT statement, so you must sanitize it if it is + // derived from user input. + func (t *Transaction) Savepoint(name string) error { + query := "savepoint " + t.dbmap.Dialect.QuoteField(name) + if t.dbmap.logger != nil { + now := time.Now() + defer t.dbmap.trace(now, query, nil) + } + _, err := exec(t, query) + return err + } // RollbackToSavepoint rolls back to the savepoint with the given name. The + // name is interpolated directly into the SQL SAVEPOINT statement, so you must + // sanitize it if it is derived from user input. + func (t *Transaction) RollbackToSavepoint(savepoint string) error { + query := "rollback to savepoint " + t.dbmap.Dialect.QuoteField(savepoint) + if t.dbmap.logger != nil { + now := time.Now() + defer t.dbmap.trace(now, query, nil) + } + _, err := exec(t, query) + return err + } // ReleaseSavepint releases the savepoint with the given name. The name is + // interpolated directly into the SQL SAVEPOINT statement, so you must sanitize + // it if it is derived from user input. + func (t *Transaction) ReleaseSavepoint(savepoint string) error { + query := "release savepoint " + t.dbmap.Dialect.QuoteField(savepoint) + if t.dbmap.logger != nil { + now := time.Now() + defer t.dbmap.trace(now, query, nil) + } + _, err := exec(t, query) + return err + } // Prepare has the same behavior as DbMap.Prepare(), but runs in a transaction. + func (t *Transaction) Prepare(query string) (*sql.Stmt, error) { + if t.dbmap.logger != nil { + now := time.Now() + defer t.dbmap.trace(now, query, nil) + } + return prepare(t, query) + } func (t *Transaction) QueryRow(query string, args ...interface{}) *sql.Row { + if t.dbmap.ExpandSliceArgs { + expandSliceArgs(&query, args...) + } if t.dbmap.logger != nil { + now := time.Now() + defer t.dbmap.trace(now, query, args...) + } + return queryRow(t, query, args...) + } func (t *Transaction) Query(q string, args ...interface{}) (*sql.Rows, error) { + if t.dbmap.ExpandSliceArgs { + expandSliceArgs(&q, args...) + } if t.dbmap.logger != nil { + now := time.Now() + defer t.dbmap.trace(now, q, args...) + } + return query(t, q, args...) + } diff --git a/vendor/github.com/go-openapi/jsonpointer/pointer.go b/vendor/github.com/go-openapi/jsonpointer/pointer.go index d970c7c..85beff3 100644 --- a/vendor/github.com/go-openapi/jsonpointer/pointer.go +++ b/vendor/github.com/go-openapi/jsonpointer/pointer.go @@ -1,26 +1,47 @@ // Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. // author sigu-399 + // author-github https://github.com/sigu-399 + // author-mail sigu.399@gmail.com + // + // repository-name jsonpointer + // repository-desc An implementation of JSON Pointer - Go language + // + // description Main and unique file. + // + // created 25-02-2013 package jsonpointer @@ -37,195 +58,307 @@ import ( ) const ( - emptyPointer = `` + emptyPointer = `` + pointerSeparator = `/` invalidStart = `JSON pointer must be empty or start with a "` + pointerSeparator - notFound = `Can't find the pointer in the document` + + notFound = `Can't find the pointer in the document` ) var jsonPointableType = reflect.TypeOf(new(JSONPointable)).Elem() + var jsonSetableType = reflect.TypeOf(new(JSONSetable)).Elem() // JSONPointable is an interface for structs to implement when they need to customize the + // json pointer process + type JSONPointable interface { JSONLookup(string) (any, error) } // JSONSetable is an interface for structs to implement when they need to customize the + // json pointer process + type JSONSetable interface { JSONSet(string, any) error } // New creates a new json pointer for the given string + func New(jsonPointerString string) (Pointer, error) { var p Pointer + err := p.parse(jsonPointerString) + return p, err } // Pointer the json pointer reprsentation + type Pointer struct { referenceTokens []string } // "Constructor", parses the given string JSON pointer + func (p *Pointer) parse(jsonPointerString string) error { var err error if jsonPointerString != emptyPointer { + if !strings.HasPrefix(jsonPointerString, pointerSeparator) { + err = errors.New(invalidStart) + } else { + referenceTokens := strings.Split(jsonPointerString, pointerSeparator) + p.referenceTokens = append(p.referenceTokens, referenceTokens[1:]...) + } + } return err + } // Get uses the pointer to retrieve a value from a JSON document + func (p *Pointer) Get(document any) (any, reflect.Kind, error) { + return p.get(document, swag.DefaultJSONNameProvider) + } // Set uses the pointer to set a value from a JSON document + func (p *Pointer) Set(document any, value any) (any, error) { + return document, p.set(document, value, swag.DefaultJSONNameProvider) + } // GetForToken gets a value for a json pointer token 1 level deep + func GetForToken(document any, decodedToken string) (any, reflect.Kind, error) { + return getSingleImpl(document, decodedToken, swag.DefaultJSONNameProvider) + } // SetForToken gets a value for a json pointer token 1 level deep + func SetForToken(document any, decodedToken string, value any) (any, error) { + return document, setSingleImpl(document, value, decodedToken, swag.DefaultJSONNameProvider) + } func isNil(input any) bool { + if input == nil { + return true + } kind := reflect.TypeOf(input).Kind() + switch kind { //nolint:exhaustive + case reflect.Ptr, reflect.Map, reflect.Slice, reflect.Chan: + return reflect.ValueOf(input).IsNil() + default: + return false + } + } func getSingleImpl(node any, decodedToken string, nameProvider *swag.NameProvider) (any, reflect.Kind, error) { + rValue := reflect.Indirect(reflect.ValueOf(node)) + kind := rValue.Kind() + if isNil(node) { + return nil, kind, fmt.Errorf("nil value has not field %q", decodedToken) + } switch typed := node.(type) { + case JSONPointable: + r, err := typed.JSONLookup(decodedToken) + if err != nil { + return nil, kind, err + } + return r, kind, nil + case *any: // case of a pointer to interface, that is not resolved by reflect.Indirect + return getSingleImpl(*typed, decodedToken, nameProvider) + } switch kind { //nolint:exhaustive + case reflect.Struct: + nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) + if !ok { + return nil, kind, fmt.Errorf("object has no field %q", decodedToken) + } + fld := rValue.FieldByName(nm) + return fld.Interface(), kind, nil case reflect.Map: + kv := reflect.ValueOf(decodedToken) + mv := rValue.MapIndex(kv) if mv.IsValid() { + return mv.Interface(), kind, nil + } + return nil, kind, fmt.Errorf("object has no key %q", decodedToken) case reflect.Slice: + tokenIndex, err := strconv.Atoi(decodedToken) + if err != nil { + return nil, kind, err + } + sLength := rValue.Len() + if tokenIndex < 0 || tokenIndex >= sLength { + return nil, kind, fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength-1, tokenIndex) + } elem := rValue.Index(tokenIndex) + return elem.Interface(), kind, nil default: + return nil, kind, fmt.Errorf("invalid token reference %q", decodedToken) + } } func setSingleImpl(node, data any, decodedToken string, nameProvider *swag.NameProvider) error { + rValue := reflect.Indirect(reflect.ValueOf(node)) if ns, ok := node.(JSONSetable); ok { // pointer impl + return ns.JSONSet(decodedToken, data) + } if rValue.Type().Implements(jsonSetableType) { + return node.(JSONSetable).JSONSet(decodedToken, data) + } switch rValue.Kind() { //nolint:exhaustive + case reflect.Struct: + nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) + if !ok { + return fmt.Errorf("object has no field %q", decodedToken) + } + fld := rValue.FieldByName(nm) + if fld.IsValid() { + fld.Set(reflect.ValueOf(data)) + } + return nil case reflect.Map: + kv := reflect.ValueOf(decodedToken) + rValue.SetMapIndex(kv, reflect.ValueOf(data)) + return nil case reflect.Slice: + tokenIndex, err := strconv.Atoi(decodedToken) + if err != nil { + return err + } + sLength := rValue.Len() + if tokenIndex < 0 || tokenIndex >= sLength { + return fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength, tokenIndex) + } elem := rValue.Index(tokenIndex) + if !elem.CanSet() { + return fmt.Errorf("can't set slice index %s to %v", decodedToken, data) + } + elem.Set(reflect.ValueOf(data)) + return nil default: + return fmt.Errorf("invalid token reference %q", decodedToken) + } } @@ -233,14 +366,19 @@ func setSingleImpl(node, data any, decodedToken string, nameProvider *swag.NameP func (p *Pointer) get(node any, nameProvider *swag.NameProvider) (any, reflect.Kind, error) { if nameProvider == nil { + nameProvider = swag.DefaultJSONNameProvider + } kind := reflect.Invalid // Full document when empty + if len(p.referenceTokens) == 0 { + return node, kind, nil + } for _, token := range p.referenceTokens { @@ -248,284 +386,491 @@ func (p *Pointer) get(node any, nameProvider *swag.NameProvider) (any, reflect.K decodedToken := Unescape(token) r, knd, err := getSingleImpl(node, decodedToken, nameProvider) + if err != nil { + return nil, knd, err + } + node = r + } rValue := reflect.ValueOf(node) + kind = rValue.Kind() return node, kind, nil + } func (p *Pointer) set(node, data any, nameProvider *swag.NameProvider) error { + knd := reflect.ValueOf(node).Kind() if knd != reflect.Ptr && knd != reflect.Struct && knd != reflect.Map && knd != reflect.Slice && knd != reflect.Array { + return errors.New("only structs, pointers, maps and slices are supported for setting values") + } if nameProvider == nil { + nameProvider = swag.DefaultJSONNameProvider + } // Full document when empty + if len(p.referenceTokens) == 0 { + return nil + } lastI := len(p.referenceTokens) - 1 + for i, token := range p.referenceTokens { + isLastToken := i == lastI + decodedToken := Unescape(token) if isLastToken { return setSingleImpl(node, data, decodedToken, nameProvider) + } rValue := reflect.Indirect(reflect.ValueOf(node)) + kind := rValue.Kind() if rValue.Type().Implements(jsonPointableType) { + r, err := node.(JSONPointable).JSONLookup(decodedToken) + if err != nil { + return err + } + fld := reflect.ValueOf(r) + if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Ptr { + node = fld.Addr().Interface() + continue + } + node = r + continue + } switch kind { //nolint:exhaustive + case reflect.Struct: + nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) + if !ok { + return fmt.Errorf("object has no field %q", decodedToken) + } + fld := rValue.FieldByName(nm) + if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Ptr { + node = fld.Addr().Interface() + continue + } + node = fld.Interface() case reflect.Map: + kv := reflect.ValueOf(decodedToken) + mv := rValue.MapIndex(kv) if !mv.IsValid() { + return fmt.Errorf("object has no key %q", decodedToken) + } + if mv.CanAddr() && mv.Kind() != reflect.Interface && mv.Kind() != reflect.Map && mv.Kind() != reflect.Slice && mv.Kind() != reflect.Ptr { + node = mv.Addr().Interface() + continue + } + node = mv.Interface() case reflect.Slice: + tokenIndex, err := strconv.Atoi(decodedToken) + if err != nil { + return err + } + sLength := rValue.Len() + if tokenIndex < 0 || tokenIndex >= sLength { + return fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength, tokenIndex) + } elem := rValue.Index(tokenIndex) + if elem.CanAddr() && elem.Kind() != reflect.Interface && elem.Kind() != reflect.Map && elem.Kind() != reflect.Slice && elem.Kind() != reflect.Ptr { + node = elem.Addr().Interface() + continue + } + node = elem.Interface() default: + return fmt.Errorf("invalid token reference %q", decodedToken) + } } return nil + } // DecodedTokens returns the decoded tokens + func (p *Pointer) DecodedTokens() []string { + result := make([]string, 0, len(p.referenceTokens)) + for _, t := range p.referenceTokens { + result = append(result, Unescape(t)) + } + return result + } // IsEmpty returns true if this is an empty json pointer + // this indicates that it points to the root document + func (p *Pointer) IsEmpty() bool { + return len(p.referenceTokens) == 0 + } // Pointer to string representation function + func (p *Pointer) String() string { if len(p.referenceTokens) == 0 { + return emptyPointer + } pointerString := pointerSeparator + strings.Join(p.referenceTokens, pointerSeparator) return pointerString + } func (p *Pointer) Offset(document string) (int64, error) { + dec := json.NewDecoder(strings.NewReader(document)) + var offset int64 + for _, ttk := range p.DecodedTokens() { + tk, err := dec.Token() + if err != nil { + return 0, err + } + switch tk := tk.(type) { + case json.Delim: + switch tk { + case '{': + offset, err = offsetSingleObject(dec, ttk) + if err != nil { + return 0, err + } + case '[': + offset, err = offsetSingleArray(dec, ttk) + if err != nil { + return 0, err + } + default: + return 0, fmt.Errorf("invalid token %#v", tk) + } + default: + return 0, fmt.Errorf("invalid token %#v", tk) + } + } + return offset, nil + } func offsetSingleObject(dec *json.Decoder, decodedToken string) (int64, error) { + for dec.More() { + offset := dec.InputOffset() + tk, err := dec.Token() + if err != nil { + return 0, err + } + switch tk := tk.(type) { + case json.Delim: + switch tk { + case '{': + if err = drainSingle(dec); err != nil { + return 0, err + } + case '[': + if err = drainSingle(dec); err != nil { + return 0, err + } + } + case string: + if tk == decodedToken { + return offset, nil + } + default: + return 0, fmt.Errorf("invalid token %#v", tk) + } + } + return 0, fmt.Errorf("token reference %q not found", decodedToken) + } func offsetSingleArray(dec *json.Decoder, decodedToken string) (int64, error) { + idx, err := strconv.Atoi(decodedToken) + if err != nil { + return 0, fmt.Errorf("token reference %q is not a number: %v", decodedToken, err) + } + var i int + for i = 0; i < idx && dec.More(); i++ { + tk, err := dec.Token() + if err != nil { + return 0, err + } if delim, isDelim := tk.(json.Delim); isDelim { + switch delim { + case '{': + if err = drainSingle(dec); err != nil { + return 0, err + } + case '[': + if err = drainSingle(dec); err != nil { + return 0, err + } + } + } + } if !dec.More() { + return 0, fmt.Errorf("token reference %q not found", decodedToken) + } + return dec.InputOffset(), nil + } // drainSingle drains a single level of object or array. + // The decoder has to guarantee the beginning delim (i.e. '{' or '[') has been consumed. + func drainSingle(dec *json.Decoder) error { + for dec.More() { + tk, err := dec.Token() + if err != nil { + return err + } + if delim, isDelim := tk.(json.Delim); isDelim { + switch delim { + case '{': + if err = drainSingle(dec); err != nil { + return err + } + case '[': + if err = drainSingle(dec); err != nil { + return err + } + } + } + } // Consumes the ending delim + if _, err := dec.Token(); err != nil { + return err + } + return nil + } // Specific JSON pointer encoding here + // ~0 => ~ + // ~1 => / + // ... and vice versa const ( encRefTok0 = `~0` + encRefTok1 = `~1` + decRefTok0 = `~` + decRefTok1 = `/` ) // Unescape unescapes a json pointer reference token string to the original representation + func Unescape(token string) string { + step1 := strings.ReplaceAll(token, encRefTok1, decRefTok1) + step2 := strings.ReplaceAll(step1, encRefTok0, decRefTok0) + return step2 + } // Escape escapes a pointer reference token string + func Escape(token string) string { + step1 := strings.ReplaceAll(token, decRefTok0, encRefTok0) + step2 := strings.ReplaceAll(step1, decRefTok1, encRefTok1) + return step2 + } diff --git a/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go b/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go index f0610cf..5308c96 100644 --- a/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go +++ b/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go @@ -7,63 +7,107 @@ import ( ) const ( - defaultHTTPPort = ":80" + defaultHTTPPort = ":80" + defaultHTTPSPort = ":443" ) // Regular expressions used by the normalizations + var rxPort = regexp.MustCompile(`(:\d+)/?$`) + var rxDupSlashes = regexp.MustCompile(`/{2,}`) // NormalizeURL will normalize the specified URL + // This was added to replace a previous call to the no longer maintained purell library: + // The call that was used looked like the following: + // + // url.Parse(purell.NormalizeURL(parsed, purell.FlagsSafe|purell.FlagRemoveDuplicateSlashes)) + // + // To explain all that was included in the call above, purell.FlagsSafe was really just the following: + // - FlagLowercaseScheme + // - FlagLowercaseHost + // - FlagRemoveDefaultPort + // - FlagRemoveDuplicateSlashes (and this was mixed in with the |) + // + // This also normalizes the URL into its urlencoded form by removing RawPath and RawFragment. + func NormalizeURL(u *url.URL) { + lowercaseScheme(u) + lowercaseHost(u) + removeDefaultPort(u) + removeDuplicateSlashes(u) u.RawPath = "" + u.RawFragment = "" + } func lowercaseScheme(u *url.URL) { + if len(u.Scheme) > 0 { + u.Scheme = strings.ToLower(u.Scheme) + } + } func lowercaseHost(u *url.URL) { + if len(u.Host) > 0 { + u.Host = strings.ToLower(u.Host) + } + } func removeDefaultPort(u *url.URL) { + if len(u.Host) > 0 { + scheme := strings.ToLower(u.Scheme) + u.Host = rxPort.ReplaceAllStringFunc(u.Host, func(val string) string { + if (scheme == "http" && val == defaultHTTPPort) || (scheme == "https" && val == defaultHTTPSPort) { + return "" + } + return val + }) + } + } func removeDuplicateSlashes(u *url.URL) { + if len(u.Path) > 0 { + u.Path = rxDupSlashes.ReplaceAllString(u.Path, "/") + } + } diff --git a/vendor/github.com/go-openapi/jsonreference/reference.go b/vendor/github.com/go-openapi/jsonreference/reference.go index cfdef03..1d37f9e 100644 --- a/vendor/github.com/go-openapi/jsonreference/reference.go +++ b/vendor/github.com/go-openapi/jsonreference/reference.go @@ -1,26 +1,47 @@ // Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. // author sigu-399 + // author-github https://github.com/sigu-399 + // author-mail sigu.399@gmail.com + // + // repository-name jsonreference + // repository-desc An implementation of JSON Reference - Go language + // + // description Main and unique file. + // + // created 26-02-2013 package jsonreference @@ -39,120 +60,189 @@ const ( ) // New creates a new reference for the given string + func New(jsonReferenceString string) (Ref, error) { var r Ref + err := r.parse(jsonReferenceString) + return r, err } // MustCreateRef parses the ref string and panics when it's invalid. + // Use the New method for a version that returns an error + func MustCreateRef(ref string) Ref { + r, err := New(ref) + if err != nil { + panic(err) + } + return r + } // Ref represents a json reference object + type Ref struct { - referenceURL *url.URL + referenceURL *url.URL + referencePointer jsonpointer.Pointer - HasFullURL bool - HasURLPathOnly bool + HasFullURL bool + + HasURLPathOnly bool + HasFragmentOnly bool - HasFileScheme bool + + HasFileScheme bool + HasFullFilePath bool } // GetURL gets the URL for this reference + func (r *Ref) GetURL() *url.URL { + return r.referenceURL + } // GetPointer gets the json pointer for this reference + func (r *Ref) GetPointer() *jsonpointer.Pointer { + return &r.referencePointer + } // String returns the best version of the url for this reference + func (r *Ref) String() string { if r.referenceURL != nil { + return r.referenceURL.String() + } if r.HasFragmentOnly { + return fragmentRune + r.referencePointer.String() + } return r.referencePointer.String() + } // IsRoot returns true if this reference is a root document + func (r *Ref) IsRoot() bool { + return r.referenceURL != nil && + !r.IsCanonical() && + !r.HasURLPathOnly && + r.referenceURL.Fragment == "" + } // IsCanonical returns true when this pointer starts with http(s):// or file:// + func (r *Ref) IsCanonical() bool { + return (r.HasFileScheme && r.HasFullFilePath) || (!r.HasFileScheme && r.HasFullURL) + } // "Constructor", parses the given string JSON reference + func (r *Ref) parse(jsonReferenceString string) error { parsed, err := url.Parse(jsonReferenceString) + if err != nil { + return err + } internal.NormalizeURL(parsed) r.referenceURL = parsed + refURL := r.referenceURL if refURL.Scheme != "" && refURL.Host != "" { + r.HasFullURL = true + } else { + if refURL.Path != "" { + r.HasURLPathOnly = true + } else if refURL.RawQuery == "" && refURL.Fragment != "" { + r.HasFragmentOnly = true + } + } r.HasFileScheme = refURL.Scheme == "file" + r.HasFullFilePath = strings.HasPrefix(refURL.Path, "/") // invalid json-pointer error means url has no json-pointer fragment. simply ignore error + r.referencePointer, _ = jsonpointer.New(refURL.Fragment) return nil + } // Inherits creates a new reference from a parent and a child + // If the child cannot inherit from the parent, an error is returned + func (r *Ref) Inherits(child Ref) (*Ref, error) { + childURL := child.GetURL() + parentURL := r.GetURL() + if childURL == nil { + return nil, errors.New("child url is nil") + } + if parentURL == nil { + return &child, nil + } ref, err := New(parentURL.ResolveReference(childURL).String()) + if err != nil { + return nil, err + } + return &ref, nil + } diff --git a/vendor/github.com/go-openapi/spec/contact_info.go b/vendor/github.com/go-openapi/spec/contact_info.go index 2f7bb21..a160586 100644 --- a/vendor/github.com/go-openapi/spec/contact_info.go +++ b/vendor/github.com/go-openapi/spec/contact_info.go @@ -1,15 +1,27 @@ // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -21,37 +33,61 @@ import ( ) // ContactInfo contact information for the exposed API. + // + // For more information: http://goo.gl/8us55a#contactObject + type ContactInfo struct { ContactInfoProps + VendorExtensible } // ContactInfoProps hold the properties of a ContactInfo object + type ContactInfoProps struct { - Name string `json:"name,omitempty"` - URL string `json:"url,omitempty"` + Name string `json:"name,omitempty"` + + URL string `json:"url,omitempty"` + Email string `json:"email,omitempty"` } // UnmarshalJSON hydrates ContactInfo from json + func (c *ContactInfo) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &c.ContactInfoProps); err != nil { + return err + } + return json.Unmarshal(data, &c.VendorExtensible) + } // MarshalJSON produces ContactInfo as json + func (c ContactInfo) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(c.ContactInfoProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(c.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2), nil + } diff --git a/vendor/github.com/go-openapi/spec/debug.go b/vendor/github.com/go-openapi/spec/debug.go index fc889f6..207e6b8 100644 --- a/vendor/github.com/go-openapi/spec/debug.go +++ b/vendor/github.com/go-openapi/spec/debug.go @@ -1,15 +1,27 @@ // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -23,27 +35,42 @@ import ( ) // Debug is true when the SWAGGER_DEBUG env var is not empty. + // + // It enables a more verbose logging of this package. + var Debug = os.Getenv("SWAGGER_DEBUG") != "" var ( + // specLogger is a debug logger for this package + specLogger *log.Logger ) func init() { + debugOptions() + } func debugOptions() { + specLogger = log.New(os.Stdout, "spec:", log.LstdFlags) + } func debugLog(msg string, args ...interface{}) { + // A private, trivial trace logger, based on go-openapi/spec/expander.go:debugLog() + if Debug { + _, file1, pos1, _ := runtime.Caller(1) + specLogger.Printf("%s:%d: %s", path.Base(file1), pos1, fmt.Sprintf(msg, args...)) + } + } diff --git a/vendor/github.com/go-openapi/spec/embed.go b/vendor/github.com/go-openapi/spec/embed.go index 1f42847..49d14e4 100644 --- a/vendor/github.com/go-openapi/spec/embed.go +++ b/vendor/github.com/go-openapi/spec/embed.go @@ -6,12 +6,17 @@ import ( ) //go:embed schemas/*.json schemas/*/*.json + var assets embed.FS func jsonschemaDraft04JSONBytes() ([]byte, error) { + return assets.ReadFile(path.Join("schemas", "jsonschema-draft-04.json")) + } func v2SchemaJSONBytes() ([]byte, error) { + return assets.ReadFile(path.Join("schemas", "v2", "schema.json")) + } diff --git a/vendor/github.com/go-openapi/spec/expander.go b/vendor/github.com/go-openapi/spec/expander.go index b81a569..74584f6 100644 --- a/vendor/github.com/go-openapi/spec/expander.go +++ b/vendor/github.com/go-openapi/spec/expander.go @@ -1,15 +1,27 @@ // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -20,138 +32,231 @@ import ( ) // ExpandOptions provides options for the spec expander. + // + // RelativeBase is the path to the root document. This can be a remote URL or a path to a local file. + // + // If left empty, the root document is assumed to be located in the current working directory: + // all relative $ref's will be resolved from there. + // + // PathLoader injects a document loading method. By default, this resolves to the function provided by the SpecLoader package variable. + type ExpandOptions struct { - RelativeBase string // the path to the root document to expand. This is a file, not a directory - SkipSchemas bool // do not expand schemas, just paths, parameters and responses - ContinueOnError bool // continue expanding even after and error is found - PathLoader func(string) (json.RawMessage, error) `json:"-"` // the document loading method that takes a path as input and yields a json document - AbsoluteCircularRef bool // circular $ref remaining after expansion remain absolute URLs + RelativeBase string // the path to the root document to expand. This is a file, not a directory + + SkipSchemas bool // do not expand schemas, just paths, parameters and responses + + ContinueOnError bool // continue expanding even after and error is found + + PathLoader func(string) (json.RawMessage, error) `json:"-"` // the document loading method that takes a path as input and yields a json document + + AbsoluteCircularRef bool // circular $ref remaining after expansion remain absolute URLs + } func optionsOrDefault(opts *ExpandOptions) *ExpandOptions { + if opts != nil { + clone := *opts // shallow clone to avoid internal changes to be propagated to the caller + if clone.RelativeBase != "" { + clone.RelativeBase = normalizeBase(clone.RelativeBase) + } + // if the relative base is empty, let the schema loader choose a pseudo root document + return &clone + } + return &ExpandOptions{} + } // ExpandSpec expands the references in a swagger spec + func ExpandSpec(spec *Swagger, options *ExpandOptions) error { + options = optionsOrDefault(options) + resolver := defaultSchemaLoader(spec, options, nil, nil) specBasePath := options.RelativeBase if !options.SkipSchemas { + for key, definition := range spec.Definitions { + parentRefs := make([]string, 0, 10) + parentRefs = append(parentRefs, "#/definitions/"+key) def, err := expandSchema(definition, parentRefs, resolver, specBasePath) + if resolver.shouldStopOnError(err) { + return err + } + if def != nil { + spec.Definitions[key] = *def + } + } + } for key := range spec.Parameters { + parameter := spec.Parameters[key] + if err := expandParameterOrResponse(¶meter, resolver, specBasePath); resolver.shouldStopOnError(err) { + return err + } + spec.Parameters[key] = parameter + } for key := range spec.Responses { + response := spec.Responses[key] + if err := expandParameterOrResponse(&response, resolver, specBasePath); resolver.shouldStopOnError(err) { + return err + } + spec.Responses[key] = response + } if spec.Paths != nil { + for key := range spec.Paths.Paths { + pth := spec.Paths.Paths[key] + if err := expandPathItem(&pth, resolver, specBasePath); resolver.shouldStopOnError(err) { + return err + } + spec.Paths.Paths[key] = pth + } + } return nil + } const rootBase = ".root" // baseForRoot loads in the cache the root document and produces a fake ".root" base path entry + // for further $ref resolution + func baseForRoot(root interface{}, cache ResolutionCache) string { + // cache the root document to resolve $ref's + normalizedBase := normalizeBase(rootBase) if root == nil { + // ensure that we never leave a nil root: always cache the root base pseudo-document + cachedRoot, found := cache.Get(normalizedBase) + if found && cachedRoot != nil { + // the cache is already preloaded with a root + return normalizedBase + } root = map[string]interface{}{} + } cache.Set(normalizedBase, root) return normalizedBase + } // ExpandSchema expands the refs in the schema object with reference to the root object. + // + // go-openapi/validate uses this function. + // + // Notice that it is impossible to reference a json schema in a different document other than root + // (use ExpandSchemaWithBasePath to resolve external references). + // + // Setting the cache is optional and this parameter may safely be left to nil. + func ExpandSchema(schema *Schema, root interface{}, cache ResolutionCache) error { + cache = cacheOrDefault(cache) + if root == nil { + root = schema + } opts := &ExpandOptions{ + // when a root is specified, cache the root as an in-memory document for $ref retrieval - RelativeBase: baseForRoot(root, cache), - SkipSchemas: false, + + RelativeBase: baseForRoot(root, cache), + + SkipSchemas: false, + ContinueOnError: false, } return ExpandSchemaWithBasePath(schema, cache, opts) + } // ExpandSchemaWithBasePath expands the refs in the schema object, base path configured through expand options. + // + // Setting the cache is optional and this parameter may safely be left to nil. + func ExpandSchemaWithBasePath(schema *Schema, cache ResolutionCache, opts *ExpandOptions) error { + if schema == nil { + return nil + } cache = cacheOrDefault(cache) @@ -161,447 +266,752 @@ func ExpandSchemaWithBasePath(schema *Schema, cache ResolutionCache, opts *Expan resolver := defaultSchemaLoader(nil, opts, cache, nil) parentRefs := make([]string, 0, 10) + s, err := expandSchema(*schema, parentRefs, resolver, opts.RelativeBase) + if err != nil { + return err + } + if s != nil { + // guard for when continuing on error + *schema = *s + } return nil + } func expandItems(target Schema, parentRefs []string, resolver *schemaLoader, basePath string) (*Schema, error) { + if target.Items == nil { + return &target, nil + } // array + if target.Items.Schema != nil { + t, err := expandSchema(*target.Items.Schema, parentRefs, resolver, basePath) + if err != nil { + return nil, err + } + *target.Items.Schema = *t + } // tuple + for i := range target.Items.Schemas { + t, err := expandSchema(target.Items.Schemas[i], parentRefs, resolver, basePath) + if err != nil { + return nil, err + } + target.Items.Schemas[i] = *t + } return &target, nil + } func expandSchema(target Schema, parentRefs []string, resolver *schemaLoader, basePath string) (*Schema, error) { + if target.Ref.String() == "" && target.Ref.IsRoot() { + newRef := normalizeRef(&target.Ref, basePath) + target.Ref = *newRef + return &target, nil + } // change the base path of resolution when an ID is encountered + // otherwise the basePath should inherit the parent's + if target.ID != "" { + basePath, _ = resolver.setSchemaID(target, target.ID, basePath) + } if target.Ref.String() != "" { + if !resolver.options.SkipSchemas { + return expandSchemaRef(target, parentRefs, resolver, basePath) + } // when "expand" with SkipSchema, we just rebase the existing $ref without replacing + // the full schema. + rebasedRef, err := NewRef(normalizeURI(target.Ref.String(), basePath)) + if err != nil { + return nil, err + } + target.Ref = denormalizeRef(&rebasedRef, resolver.context.basePath, resolver.context.rootID) return &target, nil + } for k := range target.Definitions { + tt, err := expandSchema(target.Definitions[k], parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if tt != nil { + target.Definitions[k] = *tt + } + } t, err := expandItems(target, parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if t != nil { + target = *t + } for i := range target.AllOf { + t, err := expandSchema(target.AllOf[i], parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if t != nil { + target.AllOf[i] = *t + } + } for i := range target.AnyOf { + t, err := expandSchema(target.AnyOf[i], parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if t != nil { + target.AnyOf[i] = *t + } + } for i := range target.OneOf { + t, err := expandSchema(target.OneOf[i], parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if t != nil { + target.OneOf[i] = *t + } + } if target.Not != nil { + t, err := expandSchema(*target.Not, parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if t != nil { + *target.Not = *t + } + } for k := range target.Properties { + t, err := expandSchema(target.Properties[k], parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if t != nil { + target.Properties[k] = *t + } + } if target.AdditionalProperties != nil && target.AdditionalProperties.Schema != nil { + t, err := expandSchema(*target.AdditionalProperties.Schema, parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if t != nil { + *target.AdditionalProperties.Schema = *t + } + } for k := range target.PatternProperties { + t, err := expandSchema(target.PatternProperties[k], parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if t != nil { + target.PatternProperties[k] = *t + } + } for k := range target.Dependencies { + if target.Dependencies[k].Schema != nil { + t, err := expandSchema(*target.Dependencies[k].Schema, parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if t != nil { + *target.Dependencies[k].Schema = *t + } + } + } if target.AdditionalItems != nil && target.AdditionalItems.Schema != nil { + t, err := expandSchema(*target.AdditionalItems.Schema, parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if t != nil { + *target.AdditionalItems.Schema = *t + } + } + return &target, nil + } func expandSchemaRef(target Schema, parentRefs []string, resolver *schemaLoader, basePath string) (*Schema, error) { + // if a Ref is found, all sibling fields are skipped + // Ref also changes the resolution scope of children expandSchema // here the resolution scope is changed because a $ref was encountered + normalizedRef := normalizeRef(&target.Ref, basePath) + normalizedBasePath := normalizedRef.RemoteURI() if resolver.isCircular(normalizedRef, basePath, parentRefs...) { + // this means there is a cycle in the recursion tree: return the Ref + // - circular refs cannot be expanded. We leave them as ref. + // - denormalization means that a new local file ref is set relative to the original basePath + debugLog("short circuit circular ref: basePath: %s, normalizedPath: %s, normalized ref: %s", + basePath, normalizedBasePath, normalizedRef.String()) + if !resolver.options.AbsoluteCircularRef { + target.Ref = denormalizeRef(normalizedRef, resolver.context.basePath, resolver.context.rootID) + } else { + target.Ref = *normalizedRef + } + return &target, nil + } var t *Schema + err := resolver.Resolve(&target.Ref, &t, basePath) + if resolver.shouldStopOnError(err) { + return nil, err + } if t == nil { + // guard for when continuing on error + return &target, nil + } parentRefs = append(parentRefs, normalizedRef.String()) + transitiveResolver := resolver.transitiveResolver(basePath, target.Ref) basePath = resolver.updateBasePath(transitiveResolver, normalizedBasePath) return expandSchema(*t, parentRefs, transitiveResolver, basePath) + } func expandPathItem(pathItem *PathItem, resolver *schemaLoader, basePath string) error { + if pathItem == nil { + return nil + } parentRefs := make([]string, 0, 10) + if err := resolver.deref(pathItem, parentRefs, basePath); resolver.shouldStopOnError(err) { + return err + } if pathItem.Ref.String() != "" { + transitiveResolver := resolver.transitiveResolver(basePath, pathItem.Ref) + basePath = transitiveResolver.updateBasePath(resolver, basePath) + resolver = transitiveResolver + } pathItem.Ref = Ref{} + for i := range pathItem.Parameters { + if err := expandParameterOrResponse(&(pathItem.Parameters[i]), resolver, basePath); resolver.shouldStopOnError(err) { + return err + } + } ops := []*Operation{ + pathItem.Get, + pathItem.Head, + pathItem.Options, + pathItem.Put, + pathItem.Post, + pathItem.Patch, + pathItem.Delete, } + for _, op := range ops { + if err := expandOperation(op, resolver, basePath); resolver.shouldStopOnError(err) { + return err + } + } return nil + } func expandOperation(op *Operation, resolver *schemaLoader, basePath string) error { + if op == nil { + return nil + } for i := range op.Parameters { + param := op.Parameters[i] + if err := expandParameterOrResponse(¶m, resolver, basePath); resolver.shouldStopOnError(err) { + return err + } + op.Parameters[i] = param + } if op.Responses == nil { + return nil + } responses := op.Responses + if err := expandParameterOrResponse(responses.Default, resolver, basePath); resolver.shouldStopOnError(err) { + return err + } for code := range responses.StatusCodeResponses { + response := responses.StatusCodeResponses[code] + if err := expandParameterOrResponse(&response, resolver, basePath); resolver.shouldStopOnError(err) { + return err + } + responses.StatusCodeResponses[code] = response + } return nil + } // ExpandResponseWithRoot expands a response based on a root document, not a fetchable document + // + // Notice that it is impossible to reference a json schema in a different document other than root + // (use ExpandResponse to resolve external references). + // + // Setting the cache is optional and this parameter may safely be left to nil. + func ExpandResponseWithRoot(response *Response, root interface{}, cache ResolutionCache) error { + cache = cacheOrDefault(cache) + opts := &ExpandOptions{ + RelativeBase: baseForRoot(root, cache), } + resolver := defaultSchemaLoader(root, opts, cache, nil) return expandParameterOrResponse(response, resolver, opts.RelativeBase) + } // ExpandResponse expands a response based on a basepath + // + // All refs inside response will be resolved relative to basePath + func ExpandResponse(response *Response, basePath string) error { + opts := optionsOrDefault(&ExpandOptions{ + RelativeBase: basePath, }) + resolver := defaultSchemaLoader(nil, opts, nil, nil) return expandParameterOrResponse(response, resolver, opts.RelativeBase) + } // ExpandParameterWithRoot expands a parameter based on a root document, not a fetchable document. + // + // Notice that it is impossible to reference a json schema in a different document other than root + // (use ExpandParameter to resolve external references). + func ExpandParameterWithRoot(parameter *Parameter, root interface{}, cache ResolutionCache) error { + cache = cacheOrDefault(cache) opts := &ExpandOptions{ + RelativeBase: baseForRoot(root, cache), } + resolver := defaultSchemaLoader(root, opts, cache, nil) return expandParameterOrResponse(parameter, resolver, opts.RelativeBase) + } // ExpandParameter expands a parameter based on a basepath. + // This is the exported version of expandParameter + // all refs inside parameter will be resolved relative to basePath + func ExpandParameter(parameter *Parameter, basePath string) error { + opts := optionsOrDefault(&ExpandOptions{ + RelativeBase: basePath, }) + resolver := defaultSchemaLoader(nil, opts, nil, nil) return expandParameterOrResponse(parameter, resolver, opts.RelativeBase) + } func getRefAndSchema(input interface{}) (*Ref, *Schema, error) { + var ( ref *Ref + sch *Schema ) switch refable := input.(type) { + case *Parameter: + if refable == nil { + return nil, nil, nil + } + ref = &refable.Ref + sch = refable.Schema + case *Response: + if refable == nil { + return nil, nil, nil + } + ref = &refable.Ref + sch = refable.Schema + default: + return nil, nil, fmt.Errorf("unsupported type: %T: %w", input, ErrExpandUnsupportedType) + } return ref, sch, nil + } func expandParameterOrResponse(input interface{}, resolver *schemaLoader, basePath string) error { + ref, sch, err := getRefAndSchema(input) + if err != nil { + return err + } if ref == nil && sch == nil { // nothing to do + return nil + } parentRefs := make([]string, 0, 10) + if ref != nil { + // dereference this $ref + if err = resolver.deref(input, parentRefs, basePath); resolver.shouldStopOnError(err) { + return err + } ref, sch, _ = getRefAndSchema(input) + } if ref.String() != "" { + transitiveResolver := resolver.transitiveResolver(basePath, *ref) + basePath = resolver.updateBasePath(transitiveResolver, basePath) + resolver = transitiveResolver + } if sch == nil { + // nothing to be expanded + if ref != nil { + *ref = Ref{} + } return nil + } if sch.Ref.String() != "" { + rebasedRef, ern := NewRef(normalizeURI(sch.Ref.String(), basePath)) + if ern != nil { + return ern + } if resolver.isCircular(&rebasedRef, basePath, parentRefs...) { + // this is a circular $ref: stop expansion + if !resolver.options.AbsoluteCircularRef { + sch.Ref = denormalizeRef(&rebasedRef, resolver.context.basePath, resolver.context.rootID) + } else { + sch.Ref = rebasedRef + } + } + } // $ref expansion or rebasing is performed by expandSchema below + if ref != nil { + *ref = Ref{} + } // expand schema + // yes, we do it even if options.SkipSchema is true: we have to go down that rabbit hole and rebase nested $ref) + s, err := expandSchema(*sch, parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return err + } if s != nil { // guard for when continuing on error + *sch = *s + } return nil + } diff --git a/vendor/github.com/go-openapi/spec/header.go b/vendor/github.com/go-openapi/spec/header.go index 9dfd17b..22ce942 100644 --- a/vendor/github.com/go-openapi/spec/header.go +++ b/vendor/github.com/go-openapi/spec/header.go @@ -1,15 +1,27 @@ // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -27,177 +39,303 @@ const ( ) // HeaderProps describes a response header + type HeaderProps struct { Description string `json:"description,omitempty"` } // Header describes a header for a response of the API + // + // For more information: http://goo.gl/8us55a#headerObject + type Header struct { CommonValidations + SimpleSchema + VendorExtensible + HeaderProps } // ResponseHeader creates a new header instance for use in a response + func ResponseHeader() *Header { + return new(Header) + } // WithDescription sets the description on this response, allows for chaining + func (h *Header) WithDescription(description string) *Header { + h.Description = description + return h + } // Typed a fluent builder method for the type of parameter + func (h *Header) Typed(tpe, format string) *Header { + h.Type = tpe + h.Format = format + return h + } // CollectionOf a fluent builder method for an array item + func (h *Header) CollectionOf(items *Items, format string) *Header { + h.Type = jsonArray + h.Items = items + h.CollectionFormat = format + return h + } // WithDefault sets the default value on this item + func (h *Header) WithDefault(defaultValue interface{}) *Header { + h.Default = defaultValue + return h + } // WithMaxLength sets a max length value + func (h *Header) WithMaxLength(max int64) *Header { + h.MaxLength = &max + return h + } // WithMinLength sets a min length value + func (h *Header) WithMinLength(min int64) *Header { + h.MinLength = &min + return h + } // WithPattern sets a pattern value + func (h *Header) WithPattern(pattern string) *Header { + h.Pattern = pattern + return h + } // WithMultipleOf sets a multiple of value + func (h *Header) WithMultipleOf(number float64) *Header { + h.MultipleOf = &number + return h + } // WithMaximum sets a maximum number value + func (h *Header) WithMaximum(max float64, exclusive bool) *Header { + h.Maximum = &max + h.ExclusiveMaximum = exclusive + return h + } // WithMinimum sets a minimum number value + func (h *Header) WithMinimum(min float64, exclusive bool) *Header { + h.Minimum = &min + h.ExclusiveMinimum = exclusive + return h + } // WithEnum sets a the enum values (replace) + func (h *Header) WithEnum(values ...interface{}) *Header { + h.Enum = append([]interface{}{}, values...) + return h + } // WithMaxItems sets the max items + func (h *Header) WithMaxItems(size int64) *Header { + h.MaxItems = &size + return h + } // WithMinItems sets the min items + func (h *Header) WithMinItems(size int64) *Header { + h.MinItems = &size + return h + } // UniqueValues dictates that this array can only have unique items + func (h *Header) UniqueValues() *Header { + h.UniqueItems = true + return h + } // AllowDuplicates this array can have duplicates + func (h *Header) AllowDuplicates() *Header { + h.UniqueItems = false + return h + } // WithValidations is a fluent method to set header validations + func (h *Header) WithValidations(val CommonValidations) *Header { + h.SetValidations(SchemaValidations{CommonValidations: val}) + return h + } // MarshalJSON marshal this to JSON + func (h Header) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(h.CommonValidations) + if err != nil { + return nil, err + } + b2, err := json.Marshal(h.SimpleSchema) + if err != nil { + return nil, err + } + b3, err := json.Marshal(h.HeaderProps) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2, b3), nil + } // UnmarshalJSON unmarshals this header from JSON + func (h *Header) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &h.CommonValidations); err != nil { + return err + } + if err := json.Unmarshal(data, &h.SimpleSchema); err != nil { + return err + } + if err := json.Unmarshal(data, &h.VendorExtensible); err != nil { + return err + } + return json.Unmarshal(data, &h.HeaderProps) + } // JSONLookup look up a value by the json property name + func (h Header) JSONLookup(token string) (interface{}, error) { + if ex, ok := h.Extensions[token]; ok { + return &ex, nil + } r, _, err := jsonpointer.GetForToken(h.CommonValidations, token) + if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { + return nil, err + } + if r != nil { + return r, nil + } + r, _, err = jsonpointer.GetForToken(h.SimpleSchema, token) + if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { + return nil, err + } + if r != nil { + return r, nil + } + r, _, err = jsonpointer.GetForToken(h.HeaderProps, token) + return r, err + } diff --git a/vendor/github.com/go-openapi/spec/info.go b/vendor/github.com/go-openapi/spec/info.go index 582f0fd..193e804 100644 --- a/vendor/github.com/go-openapi/spec/info.go +++ b/vendor/github.com/go-openapi/spec/info.go @@ -1,15 +1,27 @@ // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -24,161 +36,281 @@ import ( ) // Extensions vendor specific extensions + type Extensions map[string]interface{} // Add adds a value to these extensions + func (e Extensions) Add(key string, value interface{}) { + realKey := strings.ToLower(key) + e[realKey] = value + } // GetString gets a string value from the extensions + func (e Extensions) GetString(key string) (string, bool) { + if v, ok := e[strings.ToLower(key)]; ok { + str, ok := v.(string) + return str, ok + } + return "", false + } // GetInt gets a int value from the extensions + func (e Extensions) GetInt(key string) (int, bool) { + realKey := strings.ToLower(key) if v, ok := e.GetString(realKey); ok { + if r, err := strconv.Atoi(v); err == nil { + return r, true + } + } if v, ok := e[realKey]; ok { + if r, rOk := v.(float64); rOk { + return int(r), true + } + } + return -1, false + } // GetBool gets a string value from the extensions + func (e Extensions) GetBool(key string) (bool, bool) { + if v, ok := e[strings.ToLower(key)]; ok { + str, ok := v.(bool) + return str, ok + } + return false, false + } // GetStringSlice gets a string value from the extensions + func (e Extensions) GetStringSlice(key string) ([]string, bool) { + if v, ok := e[strings.ToLower(key)]; ok { + arr, isSlice := v.([]interface{}) + if !isSlice { + return nil, false + } + var strs []string + for _, iface := range arr { + str, isString := iface.(string) + if !isString { + return nil, false + } + strs = append(strs, str) + } + return strs, ok + } + return nil, false + } // VendorExtensible composition block. + type VendorExtensible struct { Extensions Extensions } // AddExtension adds an extension to this extensible object + func (v *VendorExtensible) AddExtension(key string, value interface{}) { + if value == nil { + return + } + if v.Extensions == nil { + v.Extensions = make(map[string]interface{}) + } + v.Extensions.Add(key, value) + } // MarshalJSON marshals the extensions to json + func (v VendorExtensible) MarshalJSON() ([]byte, error) { + toser := make(map[string]interface{}) + for k, v := range v.Extensions { + lk := strings.ToLower(k) + if strings.HasPrefix(lk, "x-") { + toser[k] = v + } + } + return json.Marshal(toser) + } // UnmarshalJSON for this extensible object + func (v *VendorExtensible) UnmarshalJSON(data []byte) error { + var d map[string]interface{} + if err := json.Unmarshal(data, &d); err != nil { + return err + } + for k, vv := range d { + lk := strings.ToLower(k) + if strings.HasPrefix(lk, "x-") { + if v.Extensions == nil { + v.Extensions = map[string]interface{}{} + } + v.Extensions[k] = vv + } + } + return nil + } // InfoProps the properties for an info definition + type InfoProps struct { - Description string `json:"description,omitempty"` - Title string `json:"title,omitempty"` - TermsOfService string `json:"termsOfService,omitempty"` - Contact *ContactInfo `json:"contact,omitempty"` - License *License `json:"license,omitempty"` - Version string `json:"version,omitempty"` + Description string `json:"description,omitempty"` + + Title string `json:"title,omitempty"` + + TermsOfService string `json:"termsOfService,omitempty"` + + Contact *ContactInfo `json:"contact,omitempty"` + + License *License `json:"license,omitempty"` + + Version string `json:"version,omitempty"` } // Info object provides metadata about the API. + // The metadata can be used by the clients if needed, and can be presented in the Swagger-UI for convenience. + // + // For more information: http://goo.gl/8us55a#infoObject + type Info struct { VendorExtensible + InfoProps } // JSONLookup look up a value by the json property name + func (i Info) JSONLookup(token string) (interface{}, error) { + if ex, ok := i.Extensions[token]; ok { + return &ex, nil + } + r, _, err := jsonpointer.GetForToken(i.InfoProps, token) + return r, err + } // MarshalJSON marshal this to JSON + func (i Info) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(i.InfoProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(i.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2), nil + } // UnmarshalJSON marshal this from JSON + func (i *Info) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &i.InfoProps); err != nil { + return err + } + return json.Unmarshal(data, &i.VendorExtensible) + } diff --git a/vendor/github.com/go-openapi/spec/items.go b/vendor/github.com/go-openapi/spec/items.go index e2afb21..51abee0 100644 --- a/vendor/github.com/go-openapi/spec/items.go +++ b/vendor/github.com/go-openapi/spec/items.go @@ -1,15 +1,27 @@ // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -27,208 +39,361 @@ const ( ) // SimpleSchema describe swagger simple schemas for parameters and headers + type SimpleSchema struct { - Type string `json:"type,omitempty"` - Nullable bool `json:"nullable,omitempty"` - Format string `json:"format,omitempty"` - Items *Items `json:"items,omitempty"` - CollectionFormat string `json:"collectionFormat,omitempty"` - Default interface{} `json:"default,omitempty"` - Example interface{} `json:"example,omitempty"` + Type string `json:"type,omitempty"` + + Nullable bool `json:"nullable,omitempty"` + + Format string `json:"format,omitempty"` + + Items *Items `json:"items,omitempty"` + + CollectionFormat string `json:"collectionFormat,omitempty"` + + Default interface{} `json:"default,omitempty"` + + Example interface{} `json:"example,omitempty"` } // TypeName return the type (or format) of a simple schema + func (s *SimpleSchema) TypeName() string { + if s.Format != "" { + return s.Format + } + return s.Type + } // ItemsTypeName yields the type of items in a simple schema array + func (s *SimpleSchema) ItemsTypeName() string { + if s.Items == nil { + return "" + } + return s.Items.TypeName() + } // Items a limited subset of JSON-Schema's items object. + // It is used by parameter definitions that are not located in "body". + // + // For more information: http://goo.gl/8us55a#items-object + type Items struct { Refable + CommonValidations + SimpleSchema + VendorExtensible } // NewItems creates a new instance of items + func NewItems() *Items { + return &Items{} + } // Typed a fluent builder method for the type of item + func (i *Items) Typed(tpe, format string) *Items { + i.Type = tpe + i.Format = format + return i + } // AsNullable flags this schema as nullable. + func (i *Items) AsNullable() *Items { + i.Nullable = true + return i + } // CollectionOf a fluent builder method for an array item + func (i *Items) CollectionOf(items *Items, format string) *Items { + i.Type = jsonArray + i.Items = items + i.CollectionFormat = format + return i + } // WithDefault sets the default value on this item + func (i *Items) WithDefault(defaultValue interface{}) *Items { + i.Default = defaultValue + return i + } // WithMaxLength sets a max length value + func (i *Items) WithMaxLength(max int64) *Items { + i.MaxLength = &max + return i + } // WithMinLength sets a min length value + func (i *Items) WithMinLength(min int64) *Items { + i.MinLength = &min + return i + } // WithPattern sets a pattern value + func (i *Items) WithPattern(pattern string) *Items { + i.Pattern = pattern + return i + } // WithMultipleOf sets a multiple of value + func (i *Items) WithMultipleOf(number float64) *Items { + i.MultipleOf = &number + return i + } // WithMaximum sets a maximum number value + func (i *Items) WithMaximum(max float64, exclusive bool) *Items { + i.Maximum = &max + i.ExclusiveMaximum = exclusive + return i + } // WithMinimum sets a minimum number value + func (i *Items) WithMinimum(min float64, exclusive bool) *Items { + i.Minimum = &min + i.ExclusiveMinimum = exclusive + return i + } // WithEnum sets a the enum values (replace) + func (i *Items) WithEnum(values ...interface{}) *Items { + i.Enum = append([]interface{}{}, values...) + return i + } // WithMaxItems sets the max items + func (i *Items) WithMaxItems(size int64) *Items { + i.MaxItems = &size + return i + } // WithMinItems sets the min items + func (i *Items) WithMinItems(size int64) *Items { + i.MinItems = &size + return i + } // UniqueValues dictates that this array can only have unique items + func (i *Items) UniqueValues() *Items { + i.UniqueItems = true + return i + } // AllowDuplicates this array can have duplicates + func (i *Items) AllowDuplicates() *Items { + i.UniqueItems = false + return i + } // WithValidations is a fluent method to set Items validations + func (i *Items) WithValidations(val CommonValidations) *Items { + i.SetValidations(SchemaValidations{CommonValidations: val}) + return i + } // UnmarshalJSON hydrates this items instance with the data from JSON + func (i *Items) UnmarshalJSON(data []byte) error { + var validations CommonValidations + if err := json.Unmarshal(data, &validations); err != nil { + return err + } + var ref Refable + if err := json.Unmarshal(data, &ref); err != nil { + return err + } + var simpleSchema SimpleSchema + if err := json.Unmarshal(data, &simpleSchema); err != nil { + return err + } + var vendorExtensible VendorExtensible + if err := json.Unmarshal(data, &vendorExtensible); err != nil { + return err + } + i.Refable = ref + i.CommonValidations = validations + i.SimpleSchema = simpleSchema + i.VendorExtensible = vendorExtensible + return nil + } // MarshalJSON converts this items object to JSON + func (i Items) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(i.CommonValidations) + if err != nil { + return nil, err + } + b2, err := json.Marshal(i.SimpleSchema) + if err != nil { + return nil, err + } + b3, err := json.Marshal(i.Refable) + if err != nil { + return nil, err + } + b4, err := json.Marshal(i.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b4, b3, b1, b2), nil + } // JSONLookup look up a value by the json property name + func (i Items) JSONLookup(token string) (interface{}, error) { + if token == jsonRef { + return &i.Ref, nil + } r, _, err := jsonpointer.GetForToken(i.CommonValidations, token) + if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { + return nil, err + } + if r != nil { + return r, nil + } + r, _, err = jsonpointer.GetForToken(i.SimpleSchema, token) + return r, err + } diff --git a/vendor/github.com/go-openapi/spec/license.go b/vendor/github.com/go-openapi/spec/license.go index b42f803..bdfc6a9 100644 --- a/vendor/github.com/go-openapi/spec/license.go +++ b/vendor/github.com/go-openapi/spec/license.go @@ -1,15 +1,27 @@ // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -21,36 +33,59 @@ import ( ) // License information for the exposed API. + // + // For more information: http://goo.gl/8us55a#licenseObject + type License struct { LicenseProps + VendorExtensible } // LicenseProps holds the properties of a License object + type LicenseProps struct { Name string `json:"name,omitempty"` - URL string `json:"url,omitempty"` + + URL string `json:"url,omitempty"` } // UnmarshalJSON hydrates License from json + func (l *License) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &l.LicenseProps); err != nil { + return err + } + return json.Unmarshal(data, &l.VendorExtensible) + } // MarshalJSON produces License as json + func (l License) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(l.LicenseProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(l.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2), nil + } diff --git a/vendor/github.com/go-openapi/spec/normalizer.go b/vendor/github.com/go-openapi/spec/normalizer.go index e8b6009..27da40c 100644 --- a/vendor/github.com/go-openapi/spec/normalizer.go +++ b/vendor/github.com/go-openapi/spec/normalizer.go @@ -1,15 +1,27 @@ // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -23,83 +35,145 @@ import ( const fileScheme = "file" // normalizeURI ensures that all $ref paths used internally by the expander are canonicalized. + // + // NOTE(windows): there is a tolerance over the strict URI format on windows. + // + // The normalizer accepts relative file URLs like 'Path\File.JSON' as well as absolute file URLs like + // 'C:\Path\file.Yaml'. + // + // Both are canonicalized with a "file://" scheme, slashes and a lower-cased path: + // 'file:///c:/path/file.yaml' + // + // URLs can be specified with a file scheme, like in 'file:///folder/file.json' or + // 'file:///c:\folder\File.json'. + // + // URLs like file://C:\folder are considered invalid (i.e. there is no host 'c:\folder') and a "repair" + // is attempted. + // + // The base path argument is assumed to be canonicalized (e.g. using normalizeBase()). + func normalizeURI(refPath, base string) string { + refURL, err := parseURL(refPath) + if err != nil { + specLogger.Printf("warning: invalid URI in $ref %q: %v", refPath, err) + refURL, refPath = repairURI(refPath) + } fixWindowsURI(refURL, refPath) // noop on non-windows OS refURL.Path = path.Clean(refURL.Path) + if refURL.Path == "." { + refURL.Path = "" + } r := MustCreateRef(refURL.String()) + if r.IsCanonical() { + return refURL.String() + } baseURL, _ := parseURL(base) + if path.IsAbs(refURL.Path) { + baseURL.Path = refURL.Path + } else if refURL.Path != "" { + baseURL.Path = path.Join(path.Dir(baseURL.Path), refURL.Path) + } + // copying fragment from ref to base + baseURL.Fragment = refURL.Fragment return baseURL.String() + } // denormalizeRef returns the simplest notation for a normalized $ref, given the path of the original root document. + // + // When calling this, we assume that: + // * $ref is a canonical URI + // * originalRelativeBase is a canonical URI + // + // denormalizeRef is currently used when we rewrite a $ref after a circular $ref has been detected. + // In this case, expansion stops and normally renders the internal canonical $ref. + // + // This internal $ref is eventually rebased to the original RelativeBase used for the expansion. + // + // There is a special case for schemas that are anchored with an "id": + // in that case, the rebasing is performed // against the id only if this is an anchor for the initial root document. + // All other intermediate "id"'s found along the way are ignored for the purpose of rebasing. + func denormalizeRef(ref *Ref, originalRelativeBase, id string) Ref { + debugLog("denormalizeRef called:\n$ref: %q\noriginal: %s\nroot ID:%s", ref.String(), originalRelativeBase, id) if ref.String() == "" || ref.IsRoot() || ref.HasFragmentOnly { + // short circuit: $ref to current doc + return *ref + } if id != "" { + idBaseURL, err := parseURL(id) + if err == nil { // if the schema id is not usable as a URI, ignore it + if ref, ok := rebase(ref, idBaseURL, true); ok { // rebase, but keep references to root unchaged (do not want $ref: "") + // $ref relative to the ID of the schema in the root document + return ref + } + } + } originalRelativeBaseURL, _ := parseURL(originalRelativeBase) @@ -107,70 +181,111 @@ func denormalizeRef(ref *Ref, originalRelativeBase, id string) Ref { r, _ := rebase(ref, originalRelativeBaseURL, false) return r + } func rebase(ref *Ref, v *url.URL, notEqual bool) (Ref, bool) { + var newBase url.URL u := ref.GetURL() if u.Scheme != v.Scheme || u.Host != v.Host { + return *ref, false + } docPath := v.Path + v.Path = path.Dir(v.Path) if v.Path == "." { + v.Path = "" + } else if !strings.HasSuffix(v.Path, "/") { + v.Path += "/" + } newBase.Fragment = u.Fragment if strings.HasPrefix(u.Path, docPath) { + newBase.Path = strings.TrimPrefix(u.Path, docPath) + } else { + newBase.Path = strings.TrimPrefix(u.Path, v.Path) + } if notEqual && newBase.Path == "" && newBase.Fragment == "" { + // do not want rebasing to end up in an empty $ref + return *ref, false + } if path.IsAbs(newBase.Path) { + // whenever we end up with an absolute path, specify the scheme and host + newBase.Scheme = v.Scheme + newBase.Host = v.Host + } return MustCreateRef(newBase.String()), true + } // normalizeRef canonicalize a Ref, using a canonical relativeBase as its absolute anchor + func normalizeRef(ref *Ref, relativeBase string) *Ref { + r := MustCreateRef(normalizeURI(ref.String(), relativeBase)) + return &r + } // normalizeBase performs a normalization of the input base path. + // + // This always yields a canonical URI (absolute), usable for the document cache. + // + // It ensures that all further internal work on basePath may safely assume + // a non-empty, cross-platform, canonical URI (i.e. absolute). + // + // This normalization tolerates windows paths (e.g. C:\x\y\File.dat) and transform this + // in a file:// URL with lower cased drive letter and path. + // + // See also: https://en.wikipedia.org/wiki/File_URI_scheme + func normalizeBase(in string) string { + u, err := parseURL(in) + if err != nil { + specLogger.Printf("warning: invalid URI in RelativeBase %q: %v", in, err) + u, in = repairURI(in) + } u.Fragment = "" // any fragment in the base is irrelevant @@ -178,25 +293,41 @@ func normalizeBase(in string) string { fixWindowsURI(u, in) // noop on non-windows OS u.Path = path.Clean(u.Path) + if u.Path == "." { // empty after Clean() + u.Path = "" + } if u.Scheme != "" { + if path.IsAbs(u.Path) || u.Scheme != fileScheme { + // this is absolute or explicitly not a local file: we're good + return u.String() + } + } // no scheme or file scheme with relative path: assume file and make it absolute + // enforce scheme file://... with absolute path. + // + // If the input path is relative, we anchor the path to the current working directory. + // NOTE: we may end up with a host component. Leave it unchanged: e.g. file://host/folder/file.json u.Scheme = fileScheme + u.Path = absPath(u.Path) // platform-dependent - u.RawQuery = "" // any query component is irrelevant for a base + + u.RawQuery = "" // any query component is irrelevant for a base + return u.String() + } diff --git a/vendor/github.com/go-openapi/spec/normalizer_nonwindows.go b/vendor/github.com/go-openapi/spec/normalizer_nonwindows.go index f19f1a8..4985cc5 100644 --- a/vendor/github.com/go-openapi/spec/normalizer_nonwindows.go +++ b/vendor/github.com/go-openapi/spec/normalizer_nonwindows.go @@ -2,17 +2,29 @@ // +build !windows // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -23,22 +35,37 @@ import ( ) // absPath makes a file path absolute and compatible with a URI path component. + // + // The parameter must be a path, not an URI. + func absPath(in string) string { + anchored, err := filepath.Abs(in) + if err != nil { + specLogger.Printf("warning: could not resolve current working directory: %v", err) + return in + } + return anchored + } func repairURI(in string) (*url.URL, string) { + u, _ := parseURL("") + debugLog("repaired URI: original: %q, repaired: %q", in, "") + return u, "" + } func fixWindowsURI(_ *url.URL, _ string) { + } diff --git a/vendor/github.com/go-openapi/spec/normalizer_windows.go b/vendor/github.com/go-openapi/spec/normalizer_windows.go index a66c532..fd88b39 100644 --- a/vendor/github.com/go-openapi/spec/normalizer_windows.go +++ b/vendor/github.com/go-openapi/spec/normalizer_windows.go @@ -1,17 +1,29 @@ // -build windows // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -25,130 +37,223 @@ import ( ) // absPath makes a file path absolute and compatible with a URI path component + // + // The parameter must be a path, not an URI. + func absPath(in string) string { + // NOTE(windows): filepath.Abs exhibits a special behavior on windows for empty paths. + // See https://github.com/golang/go/issues/24441 + if in == "" { + in = "." + } anchored, err := filepath.Abs(in) + if err != nil { + specLogger.Printf("warning: could not resolve current working directory: %v", err) + return in + } pth := strings.ReplaceAll(strings.ToLower(anchored), `\`, `/`) + if !strings.HasPrefix(pth, "/") { + pth = "/" + pth + } return path.Clean(pth) + } // repairURI tolerates invalid file URIs with common typos + // such as 'file://E:\folder\file', that break the regular URL parser. + // + // Adopting the same defaults as for unixes (e.g. return an empty path) would + // result into a counter-intuitive result for that case (e.g. E:\folder\file is + // eventually resolved as the current directory). The repair will detect the missing "/". + // + // Note that this only works for the file scheme. + func repairURI(in string) (*url.URL, string) { + const prefix = fileScheme + "://" + if !strings.HasPrefix(in, prefix) { + // giving up: resolve to empty path + u, _ := parseURL("") return u, "" + } // attempt the repair, stripping the scheme should be sufficient + u, _ := parseURL(strings.TrimPrefix(in, prefix)) + debugLog("repaired URI: original: %q, repaired: %q", in, u.String()) return u, u.String() + } // fixWindowsURI tolerates an absolute file path on windows such as C:\Base\File.yaml or \\host\share\Base\File.yaml + // and makes it a canonical URI: file:///c:/base/file.yaml + // + // Catch 22 notes for Windows: + // + // * There may be a drive letter on windows (it is lower-cased) + // * There may be a share UNC, e.g. \\server\folder\data.xml + // * Paths are case insensitive + // * Paths may already contain slashes + // * Paths must be slashed + // + // NOTE: there is no escaping. "/" may be valid separators just like "\". + // We don't use ToSlash() (which escapes everything) because windows now also + // tolerates the use of "/". Hence, both C:\File.yaml and C:/File.yaml will work. + func fixWindowsURI(u *url.URL, in string) { + drive := filepath.VolumeName(in) if len(drive) > 0 { + if len(u.Scheme) == 1 && strings.EqualFold(u.Scheme, drive[:1]) { // a path with a drive letter + u.Scheme = fileScheme + u.Host = "" + u.Path = strings.Join([]string{drive, u.Opaque, u.Path}, `/`) // reconstruct the full path component (no fragment, no query) + } else if u.Host == "" && strings.HasPrefix(u.Path, drive) { // a path with a \\host volume + // NOTE: the special host@port syntax for UNC is not supported (yet) + u.Scheme = fileScheme // this is a modified version of filepath.Dir() to apply on the VolumeName itself + i := len(drive) - 1 + for i >= 0 && !os.IsPathSeparator(drive[i]) { + i-- + } + host := drive[:i] // \\host\share => host u.Path = strings.TrimPrefix(u.Path, host) + u.Host = strings.TrimPrefix(host, `\\`) + } u.Opaque = "" + u.Path = strings.ReplaceAll(strings.ToLower(u.Path), `\`, `/`) // ensure we form an absolute path + if !strings.HasPrefix(u.Path, "/") { + u.Path = "/" + u.Path + } u.Path = path.Clean(u.Path) return + } if u.Scheme == fileScheme { + // Handle dodgy cases for file://{...} URIs on windows. + // A canonical URI should always be followed by an absolute path. + // + // Examples: + // * file:///folder/file => valid, unchanged + // * file:///c:\folder\file => slashed + // * file:///./folder/file => valid, cleaned to remove the dot + // * file:///.\folder\file => remapped to cwd + // * file:///. => dodgy, remapped to / (consistent with the behavior on unix) + // * file:///.. => dodgy, remapped to / (consistent with the behavior on unix) + if (!path.IsAbs(u.Path) && !filepath.IsAbs(u.Path)) || (strings.HasPrefix(u.Path, `/.`) && strings.Contains(u.Path, `\`)) { + // ensure we form an absolute path + u.Path, _ = filepath.Abs(strings.TrimLeft(u.Path, `/`)) + if !strings.HasPrefix(u.Path, "/") { + u.Path = "/" + u.Path + } + } + u.Path = strings.ToLower(u.Path) + } // NOTE: lower case normalization does not propagate to inner resources, + // generated when rebasing: when joining a relative URI with a file to an absolute base, + // only the base is currently lower-cased. + // + // For now, we assume this is good enough for most use cases + // and try not to generate too many differences + // between the output produced on different platforms. + u.Path = path.Clean(strings.ReplaceAll(u.Path, `\`, `/`)) + } diff --git a/vendor/github.com/go-openapi/spec/operation.go b/vendor/github.com/go-openapi/spec/operation.go index a69cca8..0301369 100644 --- a/vendor/github.com/go-openapi/spec/operation.go +++ b/vendor/github.com/go-openapi/spec/operation.go @@ -1,15 +1,27 @@ // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -25,255 +37,439 @@ import ( ) func init() { + gob.Register(map[string]interface{}{}) + gob.Register([]interface{}{}) + } // OperationProps describes an operation + // + // NOTES: + // - schemes, when present must be from [http, https, ws, wss]: see validate + // - Security is handled as a special case: see MarshalJSON function + type OperationProps struct { - Description string `json:"description,omitempty"` - Consumes []string `json:"consumes,omitempty"` - Produces []string `json:"produces,omitempty"` - Schemes []string `json:"schemes,omitempty"` - Tags []string `json:"tags,omitempty"` - Summary string `json:"summary,omitempty"` + Description string `json:"description,omitempty"` + + Consumes []string `json:"consumes,omitempty"` + + Produces []string `json:"produces,omitempty"` + + Schemes []string `json:"schemes,omitempty"` + + Tags []string `json:"tags,omitempty"` + + Summary string `json:"summary,omitempty"` + ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` - ID string `json:"operationId,omitempty"` - Deprecated bool `json:"deprecated,omitempty"` - Security []map[string][]string `json:"security,omitempty"` - Parameters []Parameter `json:"parameters,omitempty"` - Responses *Responses `json:"responses,omitempty"` + + ID string `json:"operationId,omitempty"` + + Deprecated bool `json:"deprecated,omitempty"` + + Security []map[string][]string `json:"security,omitempty"` + + Parameters []Parameter `json:"parameters,omitempty"` + + Responses *Responses `json:"responses,omitempty"` } // MarshalJSON takes care of serializing operation properties to JSON + // + // We use a custom marhaller here to handle a special cases related to + // the Security field. We need to preserve zero length slice + // while omitting the field when the value is nil/unset. + func (op OperationProps) MarshalJSON() ([]byte, error) { + type Alias OperationProps + if op.Security == nil { + return json.Marshal(&struct { Security []map[string][]string `json:"security,omitempty"` + *Alias }{ + Security: op.Security, - Alias: (*Alias)(&op), + + Alias: (*Alias)(&op), }) + } + return json.Marshal(&struct { Security []map[string][]string `json:"security"` + *Alias }{ + Security: op.Security, - Alias: (*Alias)(&op), + + Alias: (*Alias)(&op), }) + } // Operation describes a single API operation on a path. + // + // For more information: http://goo.gl/8us55a#operationObject + type Operation struct { VendorExtensible + OperationProps } // SuccessResponse gets a success response model + func (o *Operation) SuccessResponse() (*Response, int, bool) { + if o.Responses == nil { + return nil, 0, false + } responseCodes := make([]int, 0, len(o.Responses.StatusCodeResponses)) + for k := range o.Responses.StatusCodeResponses { + if k >= 200 && k < 300 { + responseCodes = append(responseCodes, k) + } + } + if len(responseCodes) > 0 { + sort.Ints(responseCodes) + v := o.Responses.StatusCodeResponses[responseCodes[0]] + return &v, responseCodes[0], true + } return o.Responses.Default, 0, false + } // JSONLookup look up a value by the json property name + func (o Operation) JSONLookup(token string) (interface{}, error) { + if ex, ok := o.Extensions[token]; ok { + return &ex, nil + } + r, _, err := jsonpointer.GetForToken(o.OperationProps, token) + return r, err + } // UnmarshalJSON hydrates this items instance with the data from JSON + func (o *Operation) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &o.OperationProps); err != nil { + return err + } + return json.Unmarshal(data, &o.VendorExtensible) + } // MarshalJSON converts this items object to JSON + func (o Operation) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(o.OperationProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(o.VendorExtensible) + if err != nil { + return nil, err + } + concated := swag.ConcatJSON(b1, b2) + return concated, nil + } // NewOperation creates a new operation instance. + // It expects an ID as parameter but not passing an ID is also valid. + func NewOperation(id string) *Operation { + op := new(Operation) + op.ID = id + return op + } // WithID sets the ID property on this operation, allows for chaining. + func (o *Operation) WithID(id string) *Operation { + o.ID = id + return o + } // WithDescription sets the description on this operation, allows for chaining + func (o *Operation) WithDescription(description string) *Operation { + o.Description = description + return o + } // WithSummary sets the summary on this operation, allows for chaining + func (o *Operation) WithSummary(summary string) *Operation { + o.Summary = summary + return o + } // WithExternalDocs sets/removes the external docs for/from this operation. + // When you pass empty strings as params the external documents will be removed. + // When you pass non-empty string as one value then those values will be used on the external docs object. + // So when you pass a non-empty description, you should also pass the url and vice versa. + func (o *Operation) WithExternalDocs(description, url string) *Operation { + if description == "" && url == "" { + o.ExternalDocs = nil + return o + } if o.ExternalDocs == nil { + o.ExternalDocs = &ExternalDocumentation{} + } + o.ExternalDocs.Description = description + o.ExternalDocs.URL = url + return o + } // Deprecate marks the operation as deprecated + func (o *Operation) Deprecate() *Operation { + o.Deprecated = true + return o + } // Undeprecate marks the operation as not deprected + func (o *Operation) Undeprecate() *Operation { + o.Deprecated = false + return o + } // WithConsumes adds media types for incoming body values + func (o *Operation) WithConsumes(mediaTypes ...string) *Operation { + o.Consumes = append(o.Consumes, mediaTypes...) + return o + } // WithProduces adds media types for outgoing body values + func (o *Operation) WithProduces(mediaTypes ...string) *Operation { + o.Produces = append(o.Produces, mediaTypes...) + return o + } // WithTags adds tags for this operation + func (o *Operation) WithTags(tags ...string) *Operation { + o.Tags = append(o.Tags, tags...) + return o + } // AddParam adds a parameter to this operation, when a parameter for that location + // and with that name already exists it will be replaced + func (o *Operation) AddParam(param *Parameter) *Operation { + if param == nil { + return o + } for i, p := range o.Parameters { + if p.Name == param.Name && p.In == param.In { + params := make([]Parameter, 0, len(o.Parameters)+1) + params = append(params, o.Parameters[:i]...) + params = append(params, *param) + params = append(params, o.Parameters[i+1:]...) + o.Parameters = params return o + } + } o.Parameters = append(o.Parameters, *param) + return o + } // RemoveParam removes a parameter from the operation + func (o *Operation) RemoveParam(name, in string) *Operation { + for i, p := range o.Parameters { + if p.Name == name && p.In == in { + o.Parameters = append(o.Parameters[:i], o.Parameters[i+1:]...) + return o + } + } + return o + } // SecuredWith adds a security scope to this operation. + func (o *Operation) SecuredWith(name string, scopes ...string) *Operation { + o.Security = append(o.Security, map[string][]string{name: scopes}) + return o + } // WithDefaultResponse adds a default response to the operation. + // Passing a nil value will remove the response + func (o *Operation) WithDefaultResponse(response *Response) *Operation { + return o.RespondsWith(0, response) + } // RespondsWith adds a status code response to the operation. + // When the code is 0 the value of the response will be used as default response value. + // When the value of the response is nil it will be removed from the operation + func (o *Operation) RespondsWith(code int, response *Response) *Operation { + if o.Responses == nil { + o.Responses = new(Responses) + } + if code == 0 { + o.Responses.Default = response + return o + } + if response == nil { + delete(o.Responses.StatusCodeResponses, code) + return o + } + if o.Responses.StatusCodeResponses == nil { + o.Responses.StatusCodeResponses = make(map[int]Response) + } + o.Responses.StatusCodeResponses[code] = *response + return o + } type opsAlias OperationProps @@ -281,120 +477,198 @@ type opsAlias OperationProps type gobAlias struct { Security []map[string]struct { List []string - Pad bool + + Pad bool } - Alias *opsAlias + + Alias *opsAlias + SecurityIsEmpty bool } // GobEncode provides a safe gob encoder for Operation, including empty security requirements + func (o Operation) GobEncode() ([]byte, error) { + raw := struct { - Ext VendorExtensible + Ext VendorExtensible + Props OperationProps }{ - Ext: o.VendorExtensible, + + Ext: o.VendorExtensible, + Props: o.OperationProps, } + var b bytes.Buffer + err := gob.NewEncoder(&b).Encode(raw) + return b.Bytes(), err + } // GobDecode provides a safe gob decoder for Operation, including empty security requirements + func (o *Operation) GobDecode(b []byte) error { + var raw struct { - Ext VendorExtensible + Ext VendorExtensible + Props OperationProps } buf := bytes.NewBuffer(b) + err := gob.NewDecoder(buf).Decode(&raw) + if err != nil { + return err + } + o.VendorExtensible = raw.Ext + o.OperationProps = raw.Props + return nil + } // GobEncode provides a safe gob encoder for Operation, including empty security requirements + func (op OperationProps) GobEncode() ([]byte, error) { + raw := gobAlias{ + Alias: (*opsAlias)(&op), } var b bytes.Buffer + if op.Security == nil { + // nil security requirement + err := gob.NewEncoder(&b).Encode(raw) + return b.Bytes(), err + } if len(op.Security) == 0 { + // empty, but non-nil security requirement + raw.SecurityIsEmpty = true + raw.Alias.Security = nil + err := gob.NewEncoder(&b).Encode(raw) + return b.Bytes(), err + } raw.Security = make([]map[string]struct { List []string - Pad bool + + Pad bool }, 0, len(op.Security)) + for _, req := range op.Security { + v := make(map[string]struct { List []string - Pad bool + + Pad bool }, len(req)) + for k, val := range req { + v[k] = struct { List []string - Pad bool + + Pad bool }{ + List: val, } + } + raw.Security = append(raw.Security, v) + } err := gob.NewEncoder(&b).Encode(raw) + return b.Bytes(), err + } // GobDecode provides a safe gob decoder for Operation, including empty security requirements + func (op *OperationProps) GobDecode(b []byte) error { + var raw gobAlias buf := bytes.NewBuffer(b) + err := gob.NewDecoder(buf).Decode(&raw) + if err != nil { + return err + } + if raw.Alias == nil { + return nil + } switch { + case raw.SecurityIsEmpty: + // empty, but non-nil security requirement + raw.Alias.Security = []map[string][]string{} + case len(raw.Alias.Security) == 0: + // nil security requirement + raw.Alias.Security = nil + default: + raw.Alias.Security = make([]map[string][]string, 0, len(raw.Security)) + for _, req := range raw.Security { + v := make(map[string][]string, len(req)) + for k, val := range req { + v[k] = make([]string, 0, len(val.List)) + v[k] = append(v[k], val.List...) + } + raw.Alias.Security = append(raw.Alias.Security, v) + } + } *op = *(*OperationProps)(raw.Alias) + return nil + } diff --git a/vendor/github.com/go-openapi/spec/parameter.go b/vendor/github.com/go-openapi/spec/parameter.go index bd4f1cd..add9919 100644 --- a/vendor/github.com/go-openapi/spec/parameter.go +++ b/vendor/github.com/go-openapi/spec/parameter.go @@ -1,15 +1,27 @@ // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -23,304 +35,531 @@ import ( ) // QueryParam creates a query parameter + func QueryParam(name string) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name, In: "query"}} + } // HeaderParam creates a header parameter, this is always required by default + func HeaderParam(name string) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name, In: "header", Required: true}} + } // PathParam creates a path parameter, this is always required + func PathParam(name string) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name, In: "path", Required: true}} + } // BodyParam creates a body parameter + func BodyParam(name string, schema *Schema) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name, In: "body", Schema: schema}} + } // FormDataParam creates a body parameter + func FormDataParam(name string) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name, In: "formData"}} + } // FileParam creates a body parameter + func FileParam(name string) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name, In: "formData"}, + SimpleSchema: SimpleSchema{Type: "file"}} + } // SimpleArrayParam creates a param for a simple array (string, int, date etc) + func SimpleArrayParam(name, tpe, fmt string) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name}, + SimpleSchema: SimpleSchema{Type: jsonArray, CollectionFormat: "csv", + Items: &Items{SimpleSchema: SimpleSchema{Type: tpe, Format: fmt}}}} + } // ParamRef creates a parameter that's a json reference + func ParamRef(uri string) *Parameter { + p := new(Parameter) + p.Ref = MustCreateRef(uri) + return p + } // ParamProps describes the specific attributes of an operation parameter + // + // NOTE: + // - Schema is defined when "in" == "body": see validate + // - AllowEmptyValue is allowed where "in" == "query" || "formData" + type ParamProps struct { - Description string `json:"description,omitempty"` - Name string `json:"name,omitempty"` - In string `json:"in,omitempty"` - Required bool `json:"required,omitempty"` - Schema *Schema `json:"schema,omitempty"` - AllowEmptyValue bool `json:"allowEmptyValue,omitempty"` + Description string `json:"description,omitempty"` + + Name string `json:"name,omitempty"` + + In string `json:"in,omitempty"` + + Required bool `json:"required,omitempty"` + + Schema *Schema `json:"schema,omitempty"` + + AllowEmptyValue bool `json:"allowEmptyValue,omitempty"` } // Parameter a unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). + // + // There are five possible parameter types. + // - Path - Used together with [Path Templating](#pathTemplating), where the parameter value is actually part + // of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, + // the path parameter is `itemId`. + // - Query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`. + // - Header - Custom headers that are expected as part of the request. + // - Body - The payload that's appended to the HTTP request. Since there can only be one payload, there can only be + // _one_ body parameter. The name of the body parameter has no effect on the parameter itself and is used for + // documentation purposes only. Since Form parameters are also in the payload, body and form parameters cannot exist + // together for the same operation. + // - Form - Used to describe the payload of an HTTP request when either `application/x-www-form-urlencoded` or + // `multipart/form-data` are used as the content type of the request (in Swagger's definition, + // the [`consumes`](#operationConsumes) property of an operation). This is the only parameter type that can be used + // to send files, thus supporting the `file` type. Since form parameters are sent in the payload, they cannot be + // declared together with a body parameter for the same operation. Form parameters have a different format based on + // the content-type used (for further details, consult http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4). + // - `application/x-www-form-urlencoded` - Similar to the format of Query parameters but as a payload. + // For example, `foo=1&bar=swagger` - both `foo` and `bar` are form parameters. This is normally used for simple + // parameters that are being transferred. + // - `multipart/form-data` - each parameter takes a section in the payload with an internal header. + // For example, for the header `Content-Disposition: form-data; name="submit-name"` the name of the parameter is + // `submit-name`. This type of form parameters is more commonly used for file transfers. + // + // For more information: http://goo.gl/8us55a#parameterObject + type Parameter struct { Refable + CommonValidations + SimpleSchema + VendorExtensible + ParamProps } // JSONLookup look up a value by the json property name + func (p Parameter) JSONLookup(token string) (interface{}, error) { + if ex, ok := p.Extensions[token]; ok { + return &ex, nil + } + if token == jsonRef { + return &p.Ref, nil + } r, _, err := jsonpointer.GetForToken(p.CommonValidations, token) + if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { + return nil, err + } + if r != nil { + return r, nil + } + r, _, err = jsonpointer.GetForToken(p.SimpleSchema, token) + if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { + return nil, err + } + if r != nil { + return r, nil + } + r, _, err = jsonpointer.GetForToken(p.ParamProps, token) + return r, err + } // WithDescription a fluent builder method for the description of the parameter + func (p *Parameter) WithDescription(description string) *Parameter { + p.Description = description + return p + } // Named a fluent builder method to override the name of the parameter + func (p *Parameter) Named(name string) *Parameter { + p.Name = name + return p + } // WithLocation a fluent builder method to override the location of the parameter + func (p *Parameter) WithLocation(in string) *Parameter { + p.In = in + return p + } // Typed a fluent builder method for the type of the parameter value + func (p *Parameter) Typed(tpe, format string) *Parameter { + p.Type = tpe + p.Format = format + return p + } // CollectionOf a fluent builder method for an array parameter + func (p *Parameter) CollectionOf(items *Items, format string) *Parameter { + p.Type = jsonArray + p.Items = items + p.CollectionFormat = format + return p + } // WithDefault sets the default value on this parameter + func (p *Parameter) WithDefault(defaultValue interface{}) *Parameter { + p.AsOptional() // with default implies optional + p.Default = defaultValue + return p + } // AllowsEmptyValues flags this parameter as being ok with empty values + func (p *Parameter) AllowsEmptyValues() *Parameter { + p.AllowEmptyValue = true + return p + } // NoEmptyValues flags this parameter as not liking empty values + func (p *Parameter) NoEmptyValues() *Parameter { + p.AllowEmptyValue = false + return p + } // AsOptional flags this parameter as optional + func (p *Parameter) AsOptional() *Parameter { + p.Required = false + return p + } // AsRequired flags this parameter as required + func (p *Parameter) AsRequired() *Parameter { + if p.Default != nil { // with a default required makes no sense + return p + } + p.Required = true + return p + } // WithMaxLength sets a max length value + func (p *Parameter) WithMaxLength(max int64) *Parameter { + p.MaxLength = &max + return p + } // WithMinLength sets a min length value + func (p *Parameter) WithMinLength(min int64) *Parameter { + p.MinLength = &min + return p + } // WithPattern sets a pattern value + func (p *Parameter) WithPattern(pattern string) *Parameter { + p.Pattern = pattern + return p + } // WithMultipleOf sets a multiple of value + func (p *Parameter) WithMultipleOf(number float64) *Parameter { + p.MultipleOf = &number + return p + } // WithMaximum sets a maximum number value + func (p *Parameter) WithMaximum(max float64, exclusive bool) *Parameter { + p.Maximum = &max + p.ExclusiveMaximum = exclusive + return p + } // WithMinimum sets a minimum number value + func (p *Parameter) WithMinimum(min float64, exclusive bool) *Parameter { + p.Minimum = &min + p.ExclusiveMinimum = exclusive + return p + } // WithEnum sets a the enum values (replace) + func (p *Parameter) WithEnum(values ...interface{}) *Parameter { + p.Enum = append([]interface{}{}, values...) + return p + } // WithMaxItems sets the max items + func (p *Parameter) WithMaxItems(size int64) *Parameter { + p.MaxItems = &size + return p + } // WithMinItems sets the min items + func (p *Parameter) WithMinItems(size int64) *Parameter { + p.MinItems = &size + return p + } // UniqueValues dictates that this array can only have unique items + func (p *Parameter) UniqueValues() *Parameter { + p.UniqueItems = true + return p + } // AllowDuplicates this array can have duplicates + func (p *Parameter) AllowDuplicates() *Parameter { + p.UniqueItems = false + return p + } // WithValidations is a fluent method to set parameter validations + func (p *Parameter) WithValidations(val CommonValidations) *Parameter { + p.SetValidations(SchemaValidations{CommonValidations: val}) + return p + } // UnmarshalJSON hydrates this items instance with the data from JSON + func (p *Parameter) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &p.CommonValidations); err != nil { + return err + } + if err := json.Unmarshal(data, &p.Refable); err != nil { + return err + } + if err := json.Unmarshal(data, &p.SimpleSchema); err != nil { + return err + } + if err := json.Unmarshal(data, &p.VendorExtensible); err != nil { + return err + } + return json.Unmarshal(data, &p.ParamProps) + } // MarshalJSON converts this items object to JSON + func (p Parameter) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(p.CommonValidations) + if err != nil { + return nil, err + } + b2, err := json.Marshal(p.SimpleSchema) + if err != nil { + return nil, err + } + b3, err := json.Marshal(p.Refable) + if err != nil { + return nil, err + } + b4, err := json.Marshal(p.VendorExtensible) + if err != nil { + return nil, err + } + b5, err := json.Marshal(p.ParamProps) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b3, b1, b2, b4, b5), nil + } diff --git a/vendor/github.com/go-openapi/spec/path_item.go b/vendor/github.com/go-openapi/spec/path_item.go index 68fc8e9..7b4de15 100644 --- a/vendor/github.com/go-openapi/spec/path_item.go +++ b/vendor/github.com/go-openapi/spec/path_item.go @@ -1,15 +1,27 @@ // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -22,66 +34,117 @@ import ( ) // PathItemProps the path item specific properties + type PathItemProps struct { - Get *Operation `json:"get,omitempty"` - Put *Operation `json:"put,omitempty"` - Post *Operation `json:"post,omitempty"` - Delete *Operation `json:"delete,omitempty"` - Options *Operation `json:"options,omitempty"` - Head *Operation `json:"head,omitempty"` - Patch *Operation `json:"patch,omitempty"` + Get *Operation `json:"get,omitempty"` + + Put *Operation `json:"put,omitempty"` + + Post *Operation `json:"post,omitempty"` + + Delete *Operation `json:"delete,omitempty"` + + Options *Operation `json:"options,omitempty"` + + Head *Operation `json:"head,omitempty"` + + Patch *Operation `json:"patch,omitempty"` + Parameters []Parameter `json:"parameters,omitempty"` } // PathItem describes the operations available on a single path. + // A Path Item may be empty, due to [ACL constraints](http://goo.gl/8us55a#securityFiltering). + // The path itself is still exposed to the documentation viewer but they will + // not know which operations and parameters are available. + // + // For more information: http://goo.gl/8us55a#pathItemObject + type PathItem struct { Refable + VendorExtensible + PathItemProps } // JSONLookup look up a value by the json property name + func (p PathItem) JSONLookup(token string) (interface{}, error) { + if ex, ok := p.Extensions[token]; ok { + return &ex, nil + } + if token == jsonRef { + return &p.Ref, nil + } + r, _, err := jsonpointer.GetForToken(p.PathItemProps, token) + return r, err + } // UnmarshalJSON hydrates this items instance with the data from JSON + func (p *PathItem) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &p.Refable); err != nil { + return err + } + if err := json.Unmarshal(data, &p.VendorExtensible); err != nil { + return err + } + return json.Unmarshal(data, &p.PathItemProps) + } // MarshalJSON converts this items object to JSON + func (p PathItem) MarshalJSON() ([]byte, error) { + b3, err := json.Marshal(p.Refable) + if err != nil { + return nil, err + } + b4, err := json.Marshal(p.VendorExtensible) + if err != nil { + return nil, err + } + b5, err := json.Marshal(p.PathItemProps) + if err != nil { + return nil, err + } + concated := swag.ConcatJSON(b3, b4, b5) + return concated, nil + } diff --git a/vendor/github.com/go-openapi/spec/paths.go b/vendor/github.com/go-openapi/spec/paths.go index 9dc82a2..c578502 100644 --- a/vendor/github.com/go-openapi/spec/paths.go +++ b/vendor/github.com/go-openapi/spec/paths.go @@ -1,15 +1,27 @@ // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -23,75 +35,138 @@ import ( ) // Paths holds the relative paths to the individual endpoints. + // The path is appended to the [`basePath`](http://goo.gl/8us55a#swaggerBasePath) in order + // to construct the full URL. + // The Paths may be empty, due to [ACL constraints](http://goo.gl/8us55a#securityFiltering). + // + // For more information: http://goo.gl/8us55a#pathsObject + type Paths struct { VendorExtensible + Paths map[string]PathItem `json:"-"` // custom serializer to flatten this, each entry must start with "/" + } // JSONLookup look up a value by the json property name + func (p Paths) JSONLookup(token string) (interface{}, error) { + if pi, ok := p.Paths[token]; ok { + return &pi, nil + } + if ex, ok := p.Extensions[token]; ok { + return &ex, nil + } + return nil, fmt.Errorf("object has no field %q", token) + } // UnmarshalJSON hydrates this items instance with the data from JSON + func (p *Paths) UnmarshalJSON(data []byte) error { + var res map[string]json.RawMessage + if err := json.Unmarshal(data, &res); err != nil { + return err + } + for k, v := range res { + if strings.HasPrefix(strings.ToLower(k), "x-") { + if p.Extensions == nil { + p.Extensions = make(map[string]interface{}) + } + var d interface{} + if err := json.Unmarshal(v, &d); err != nil { + return err + } + p.Extensions[k] = d + } + if strings.HasPrefix(k, "/") { + if p.Paths == nil { + p.Paths = make(map[string]PathItem) + } + var pi PathItem + if err := json.Unmarshal(v, &pi); err != nil { + return err + } + p.Paths[k] = pi + } + } + return nil + } // MarshalJSON converts this items object to JSON + func (p Paths) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(p.VendorExtensible) + if err != nil { + return nil, err + } pths := make(map[string]PathItem) + for k, v := range p.Paths { + if strings.HasPrefix(k, "/") { + pths[k] = v + } + } + b2, err := json.Marshal(pths) + if err != nil { + return nil, err + } + concated := swag.ConcatJSON(b1, b2) + return concated, nil + } diff --git a/vendor/github.com/go-openapi/spec/properties.go b/vendor/github.com/go-openapi/spec/properties.go index 91d2435..c7844e1 100644 --- a/vendor/github.com/go-openapi/spec/properties.go +++ b/vendor/github.com/go-openapi/spec/properties.go @@ -8,84 +8,150 @@ import ( ) // OrderSchemaItem holds a named schema (e.g. from a property of an object) + type OrderSchemaItem struct { Name string + Schema } // OrderSchemaItems is a sortable slice of named schemas. + // The ordering is defined by the x-order schema extension. + type OrderSchemaItems []OrderSchemaItem // MarshalJSON produces a json object with keys defined by the name schemas + // of the OrderSchemaItems slice, keeping the original order of the slice. + func (items OrderSchemaItems) MarshalJSON() ([]byte, error) { + buf := bytes.NewBuffer(nil) + buf.WriteString("{") + for i := range items { + if i > 0 { + buf.WriteString(",") + } + buf.WriteString("\"") + buf.WriteString(items[i].Name) + buf.WriteString("\":") + bs, err := json.Marshal(&items[i].Schema) + if err != nil { + return nil, err + } + buf.Write(bs) + } + buf.WriteString("}") + return buf.Bytes(), nil + } -func (items OrderSchemaItems) Len() int { return len(items) } +func (items OrderSchemaItems) Len() int { return len(items) } + func (items OrderSchemaItems) Swap(i, j int) { items[i], items[j] = items[j], items[i] } + func (items OrderSchemaItems) Less(i, j int) (ret bool) { + ii, oki := items[i].Extensions.GetInt("x-order") + ij, okj := items[j].Extensions.GetInt("x-order") + if oki { + if okj { + defer func() { + if err := recover(); err != nil { + defer func() { + if err = recover(); err != nil { + ret = items[i].Name < items[j].Name + } + }() + ret = reflect.ValueOf(ii).String() < reflect.ValueOf(ij).String() + } + }() + return ii < ij + } + return true + } else if okj { + return false + } + return items[i].Name < items[j].Name + } // SchemaProperties is a map representing the properties of a Schema object. + // It knows how to transform its keys into an ordered slice. + type SchemaProperties map[string]Schema // ToOrderedSchemaItems transforms the map of properties into a sortable slice + func (properties SchemaProperties) ToOrderedSchemaItems() OrderSchemaItems { + items := make(OrderSchemaItems, 0, len(properties)) + for k, v := range properties { + items = append(items, OrderSchemaItem{ - Name: k, + + Name: k, + Schema: v, }) + } + sort.Sort(items) + return items + } // MarshalJSON produces properties as json, keeping their order. + func (properties SchemaProperties) MarshalJSON() ([]byte, error) { + if properties == nil { + return []byte("null"), nil + } + return json.Marshal(properties.ToOrderedSchemaItems()) + } diff --git a/vendor/github.com/go-openapi/spec/ref.go b/vendor/github.com/go-openapi/spec/ref.go index b0ef9bd..552f909 100644 --- a/vendor/github.com/go-openapi/spec/ref.go +++ b/vendor/github.com/go-openapi/spec/ref.go @@ -1,15 +1,27 @@ // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -26,168 +38,283 @@ import ( ) // Refable is a struct for things that accept a $ref property + type Refable struct { Ref Ref } // MarshalJSON marshals the ref to json + func (r Refable) MarshalJSON() ([]byte, error) { + return r.Ref.MarshalJSON() + } // UnmarshalJSON unmarshalss the ref from json + func (r *Refable) UnmarshalJSON(d []byte) error { + return json.Unmarshal(d, &r.Ref) + } // Ref represents a json reference that is potentially resolved + type Ref struct { jsonreference.Ref } // RemoteURI gets the remote uri part of the ref + func (r *Ref) RemoteURI() string { + if r.String() == "" { + return "" + } u := *r.GetURL() + u.Fragment = "" + return u.String() + } // IsValidURI returns true when the url the ref points to can be found + func (r *Ref) IsValidURI(basepaths ...string) bool { + if r.String() == "" { + return true + } v := r.RemoteURI() + if v == "" { + return true + } if r.HasFullURL { + //nolint:noctx,gosec + rr, err := http.Get(v) + if err != nil { + return false + } + defer rr.Body.Close() return rr.StatusCode/100 == 2 + } if !(r.HasFileScheme || r.HasFullFilePath || r.HasURLPathOnly) { + return false + } // check for local file + pth := v + if r.HasURLPathOnly { + base := "." + if len(basepaths) > 0 { + base = filepath.Dir(filepath.Join(basepaths...)) + } + p, e := filepath.Abs(filepath.ToSlash(filepath.Join(base, pth))) + if e != nil { + return false + } + pth = p + } fi, err := os.Stat(filepath.ToSlash(pth)) + if err != nil { + return false + } return !fi.IsDir() + } // Inherits creates a new reference from a parent and a child + // If the child cannot inherit from the parent, an error is returned + func (r *Ref) Inherits(child Ref) (*Ref, error) { + ref, err := r.Ref.Inherits(child.Ref) + if err != nil { + return nil, err + } + return &Ref{Ref: *ref}, nil + } // NewRef creates a new instance of a ref object + // returns an error when the reference uri is an invalid uri + func NewRef(refURI string) (Ref, error) { + ref, err := jsonreference.New(refURI) + if err != nil { + return Ref{}, err + } + return Ref{Ref: ref}, nil + } // MustCreateRef creates a ref object but panics when refURI is invalid. + // Use the NewRef method for a version that returns an error. + func MustCreateRef(refURI string) Ref { + return Ref{Ref: jsonreference.MustCreateRef(refURI)} + } // MarshalJSON marshals this ref into a JSON object + func (r Ref) MarshalJSON() ([]byte, error) { + str := r.String() + if str == "" { + if r.IsRoot() { + return []byte(`{"$ref":""}`), nil + } + return []byte("{}"), nil + } + v := map[string]interface{}{"$ref": str} + return json.Marshal(v) + } // UnmarshalJSON unmarshals this ref from a JSON object + func (r *Ref) UnmarshalJSON(d []byte) error { + var v map[string]interface{} + if err := json.Unmarshal(d, &v); err != nil { + return err + } + return r.fromMap(v) + } // GobEncode provides a safe gob encoder for Ref + func (r Ref) GobEncode() ([]byte, error) { + var b bytes.Buffer + raw, err := r.MarshalJSON() + if err != nil { + return nil, err + } + err = gob.NewEncoder(&b).Encode(raw) + return b.Bytes(), err + } // GobDecode provides a safe gob decoder for Ref + func (r *Ref) GobDecode(b []byte) error { + var raw []byte + buf := bytes.NewBuffer(b) + err := gob.NewDecoder(buf).Decode(&raw) + if err != nil { + return err + } + return json.Unmarshal(raw, r) + } func (r *Ref) fromMap(v map[string]interface{}) error { + if v == nil { + return nil + } if vv, ok := v["$ref"]; ok { + if str, ok := vv.(string); ok { + ref, err := jsonreference.New(str) + if err != nil { + return err + } + *r = Ref{Ref: ref} + } + } return nil + } diff --git a/vendor/github.com/go-openapi/spec/resolver.go b/vendor/github.com/go-openapi/spec/resolver.go index 47d1ee1..1c0c95e 100644 --- a/vendor/github.com/go-openapi/spec/resolver.go +++ b/vendor/github.com/go-openapi/spec/resolver.go @@ -7,121 +7,193 @@ import ( ) func resolveAnyWithBase(root interface{}, ref *Ref, result interface{}, options *ExpandOptions) error { + options = optionsOrDefault(options) + resolver := defaultSchemaLoader(root, options, nil, nil) if err := resolver.Resolve(ref, result, options.RelativeBase); err != nil { + return err + } return nil + } // ResolveRefWithBase resolves a reference against a context root with preservation of base path + func ResolveRefWithBase(root interface{}, ref *Ref, options *ExpandOptions) (*Schema, error) { + result := new(Schema) if err := resolveAnyWithBase(root, ref, result, options); err != nil { + return nil, err + } return result, nil + } // ResolveRef resolves a reference for a schema against a context root + // ref is guaranteed to be in root (no need to go to external files) + // + // ResolveRef is ONLY called from the code generation module + func ResolveRef(root interface{}, ref *Ref) (*Schema, error) { + res, _, err := ref.GetPointer().Get(root) + if err != nil { + return nil, err + } switch sch := res.(type) { + case Schema: + return &sch, nil + case *Schema: + return sch, nil + case map[string]interface{}: + newSch := new(Schema) + if err = swag.DynamicJSONToStruct(sch, newSch); err != nil { + return nil, err + } + return newSch, nil + default: + return nil, fmt.Errorf("type: %T: %w", sch, ErrUnknownTypeForReference) + } + } // ResolveParameterWithBase resolves a parameter reference against a context root and base path + func ResolveParameterWithBase(root interface{}, ref Ref, options *ExpandOptions) (*Parameter, error) { + result := new(Parameter) if err := resolveAnyWithBase(root, &ref, result, options); err != nil { + return nil, err + } return result, nil + } // ResolveParameter resolves a parameter reference against a context root + func ResolveParameter(root interface{}, ref Ref) (*Parameter, error) { + return ResolveParameterWithBase(root, ref, nil) + } // ResolveResponseWithBase resolves response a reference against a context root and base path + func ResolveResponseWithBase(root interface{}, ref Ref, options *ExpandOptions) (*Response, error) { + result := new(Response) err := resolveAnyWithBase(root, &ref, result, options) + if err != nil { + return nil, err + } return result, nil + } // ResolveResponse resolves response a reference against a context root + func ResolveResponse(root interface{}, ref Ref) (*Response, error) { + return ResolveResponseWithBase(root, ref, nil) + } // ResolvePathItemWithBase resolves response a path item against a context root and base path + func ResolvePathItemWithBase(root interface{}, ref Ref, options *ExpandOptions) (*PathItem, error) { + result := new(PathItem) if err := resolveAnyWithBase(root, &ref, result, options); err != nil { + return nil, err + } return result, nil + } // ResolvePathItem resolves response a path item against a context root and base path + // + // Deprecated: use ResolvePathItemWithBase instead + func ResolvePathItem(root interface{}, ref Ref, options *ExpandOptions) (*PathItem, error) { + return ResolvePathItemWithBase(root, ref, options) + } // ResolveItemsWithBase resolves parameter items reference against a context root and base path. + // + // NOTE: stricly speaking, this construct is not supported by Swagger 2.0. + // Similarly, $ref are forbidden in response headers. + func ResolveItemsWithBase(root interface{}, ref Ref, options *ExpandOptions) (*Items, error) { + result := new(Items) if err := resolveAnyWithBase(root, &ref, result, options); err != nil { + return nil, err + } return result, nil + } // ResolveItems resolves parameter items reference against a context root and base path. + // + // Deprecated: use ResolveItemsWithBase instead + func ResolveItems(root interface{}, ref Ref, options *ExpandOptions) (*Items, error) { + return ResolveItemsWithBase(root, ref, options) + } diff --git a/vendor/github.com/go-openapi/spec/response.go b/vendor/github.com/go-openapi/spec/response.go index 0340b60..06ee52d 100644 --- a/vendor/github.com/go-openapi/spec/response.go +++ b/vendor/github.com/go-openapi/spec/response.go @@ -1,15 +1,27 @@ // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -22,131 +34,224 @@ import ( ) // ResponseProps properties specific to a response + type ResponseProps struct { - Description string `json:"description"` - Schema *Schema `json:"schema,omitempty"` - Headers map[string]Header `json:"headers,omitempty"` - Examples map[string]interface{} `json:"examples,omitempty"` + Description string `json:"description"` + + Schema *Schema `json:"schema,omitempty"` + + Headers map[string]Header `json:"headers,omitempty"` + + Examples map[string]interface{} `json:"examples,omitempty"` } // Response describes a single response from an API Operation. + // + // For more information: http://goo.gl/8us55a#responseObject + type Response struct { Refable + ResponseProps + VendorExtensible } // JSONLookup look up a value by the json property name + func (r Response) JSONLookup(token string) (interface{}, error) { + if ex, ok := r.Extensions[token]; ok { + return &ex, nil + } + if token == "$ref" { + return &r.Ref, nil + } + ptr, _, err := jsonpointer.GetForToken(r.ResponseProps, token) + return ptr, err + } // UnmarshalJSON hydrates this items instance with the data from JSON + func (r *Response) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &r.ResponseProps); err != nil { + return err + } + if err := json.Unmarshal(data, &r.Refable); err != nil { + return err + } + return json.Unmarshal(data, &r.VendorExtensible) + } // MarshalJSON converts this items object to JSON + func (r Response) MarshalJSON() ([]byte, error) { + var ( - b1 []byte + b1 []byte + err error ) if r.Ref.String() == "" { + // when there is no $ref, empty description is rendered as an empty string + b1, err = json.Marshal(r.ResponseProps) + } else { + // when there is $ref inside the schema, description should be omitempty-ied + b1, err = json.Marshal(struct { - Description string `json:"description,omitempty"` - Schema *Schema `json:"schema,omitempty"` - Headers map[string]Header `json:"headers,omitempty"` - Examples map[string]interface{} `json:"examples,omitempty"` + Description string `json:"description,omitempty"` + + Schema *Schema `json:"schema,omitempty"` + + Headers map[string]Header `json:"headers,omitempty"` + + Examples map[string]interface{} `json:"examples,omitempty"` }{ + Description: r.ResponseProps.Description, - Schema: r.ResponseProps.Schema, - Examples: r.ResponseProps.Examples, + + Schema: r.ResponseProps.Schema, + + Examples: r.ResponseProps.Examples, }) + } + if err != nil { + return nil, err + } b2, err := json.Marshal(r.Refable) + if err != nil { + return nil, err + } + b3, err := json.Marshal(r.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2, b3), nil + } // NewResponse creates a new response instance + func NewResponse() *Response { + return new(Response) + } // ResponseRef creates a response as a json reference + func ResponseRef(url string) *Response { + resp := NewResponse() + resp.Ref = MustCreateRef(url) + return resp + } // WithDescription sets the description on this response, allows for chaining + func (r *Response) WithDescription(description string) *Response { + r.Description = description + return r + } // WithSchema sets the schema on this response, allows for chaining. + // Passing a nil argument removes the schema from this response + func (r *Response) WithSchema(schema *Schema) *Response { + r.Schema = schema + return r + } // AddHeader adds a header to this response + func (r *Response) AddHeader(name string, header *Header) *Response { + if header == nil { + return r.RemoveHeader(name) + } + if r.Headers == nil { + r.Headers = make(map[string]Header) + } + r.Headers[name] = *header + return r + } // RemoveHeader removes a header from this response + func (r *Response) RemoveHeader(name string) *Response { + delete(r.Headers, name) + return r + } // AddExample adds an example to this response + func (r *Response) AddExample(mediaType string, example interface{}) *Response { + if r.Examples == nil { + r.Examples = make(map[string]interface{}) + } + r.Examples[mediaType] = example + return r + } diff --git a/vendor/github.com/go-openapi/spec/responses.go b/vendor/github.com/go-openapi/spec/responses.go index 16c3076..fd71940 100644 --- a/vendor/github.com/go-openapi/spec/responses.go +++ b/vendor/github.com/go-openapi/spec/responses.go @@ -1,15 +1,27 @@ // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -25,116 +37,209 @@ import ( ) // Responses is a container for the expected responses of an operation. + // The container maps a HTTP response code to the expected response. + // It is not expected from the documentation to necessarily cover all possible HTTP response codes, + // since they may not be known in advance. However, it is expected from the documentation to cover + // a successful operation response and any known errors. + // + // The `default` can be used a default response object for all HTTP codes that are not covered + // individually by the specification. + // + // The `Responses Object` MUST contain at least one response code, and it SHOULD be the response + // for a successful operation call. + // + // For more information: http://goo.gl/8us55a#responsesObject + type Responses struct { VendorExtensible + ResponsesProps } // JSONLookup implements an interface to customize json pointer lookup + func (r Responses) JSONLookup(token string) (interface{}, error) { + if token == "default" { + return r.Default, nil + } + if ex, ok := r.Extensions[token]; ok { + return &ex, nil + } + if i, err := strconv.Atoi(token); err == nil { + if scr, ok := r.StatusCodeResponses[i]; ok { + return scr, nil + } + } + return nil, fmt.Errorf("object has no field %q", token) + } // UnmarshalJSON hydrates this items instance with the data from JSON + func (r *Responses) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &r.ResponsesProps); err != nil { + return err + } if err := json.Unmarshal(data, &r.VendorExtensible); err != nil { + return err + } + if reflect.DeepEqual(ResponsesProps{}, r.ResponsesProps) { + r.ResponsesProps = ResponsesProps{} + } + return nil + } // MarshalJSON converts this items object to JSON + func (r Responses) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(r.ResponsesProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(r.VendorExtensible) + if err != nil { + return nil, err + } + concated := swag.ConcatJSON(b1, b2) + return concated, nil + } // ResponsesProps describes all responses for an operation. + // It tells what is the default response and maps all responses with a + // HTTP status code. + type ResponsesProps struct { - Default *Response + Default *Response + StatusCodeResponses map[int]Response } // MarshalJSON marshals responses as JSON + func (r ResponsesProps) MarshalJSON() ([]byte, error) { + toser := map[string]Response{} + if r.Default != nil { + toser["default"] = *r.Default + } + for k, v := range r.StatusCodeResponses { + toser[strconv.Itoa(k)] = v + } + return json.Marshal(toser) + } // UnmarshalJSON unmarshals responses from JSON + func (r *ResponsesProps) UnmarshalJSON(data []byte) error { + var res map[string]json.RawMessage + if err := json.Unmarshal(data, &res); err != nil { + return err + } if v, ok := res["default"]; ok { + var defaultRes Response + if err := json.Unmarshal(v, &defaultRes); err != nil { + return err + } + r.Default = &defaultRes + delete(res, "default") + } + for k, v := range res { + if !strings.HasPrefix(k, "x-") { + var statusCodeResp Response + if err := json.Unmarshal(v, &statusCodeResp); err != nil { + return err + } + if nk, err := strconv.Atoi(k); err == nil { + if r.StatusCodeResponses == nil { + r.StatusCodeResponses = map[int]Response{} + } + r.StatusCodeResponses[nk] = statusCodeResp + } + } + } + return nil + } diff --git a/vendor/github.com/go-openapi/spec/schema.go b/vendor/github.com/go-openapi/spec/schema.go index 4e9be85..4bcf7a2 100644 --- a/vendor/github.com/go-openapi/spec/schema.go +++ b/vendor/github.com/go-openapi/spec/schema.go @@ -1,15 +1,27 @@ // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -24,622 +36,1070 @@ import ( ) // BooleanProperty creates a boolean property + func BooleanProperty() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"boolean"}}} + } // BoolProperty creates a boolean property + func BoolProperty() *Schema { return BooleanProperty() } // StringProperty creates a string property + func StringProperty() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}} + } // CharProperty creates a string property + func CharProperty() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}} + } // Float64Property creates a float64/double property + func Float64Property() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"number"}, Format: "double"}} + } // Float32Property creates a float32/float property + func Float32Property() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"number"}, Format: "float"}} + } // Int8Property creates an int8 property + func Int8Property() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int8"}} + } // Int16Property creates an int16 property + func Int16Property() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int16"}} + } // Int32Property creates an int32 property + func Int32Property() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int32"}} + } // Int64Property creates an int64 property + func Int64Property() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int64"}} + } // StrFmtProperty creates a property for the named string format + func StrFmtProperty(format string) *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: format}} + } // DateProperty creates a date property + func DateProperty() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: "date"}} + } // DateTimeProperty creates a date time property + func DateTimeProperty() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: "date-time"}} + } // MapProperty creates a map property + func MapProperty(property *Schema) *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"object"}, + AdditionalProperties: &SchemaOrBool{Allows: true, Schema: property}}} + } // RefProperty creates a ref property + func RefProperty(name string) *Schema { + return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}} + } // RefSchema creates a ref property + func RefSchema(name string) *Schema { + return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}} + } // ArrayProperty creates an array property + func ArrayProperty(items *Schema) *Schema { + if items == nil { + return &Schema{SchemaProps: SchemaProps{Type: []string{"array"}}} + } + return &Schema{SchemaProps: SchemaProps{Items: &SchemaOrArray{Schema: items}, Type: []string{"array"}}} + } // ComposedSchema creates a schema with allOf + func ComposedSchema(schemas ...Schema) *Schema { + s := new(Schema) + s.AllOf = schemas + return s + } // SchemaURL represents a schema url + type SchemaURL string // MarshalJSON marshal this to JSON + func (r SchemaURL) MarshalJSON() ([]byte, error) { + if r == "" { + return []byte("{}"), nil + } + v := map[string]interface{}{"$schema": string(r)} + return json.Marshal(v) + } // UnmarshalJSON unmarshal this from JSON + func (r *SchemaURL) UnmarshalJSON(data []byte) error { + var v map[string]interface{} + if err := json.Unmarshal(data, &v); err != nil { + return err + } + return r.fromMap(v) + } func (r *SchemaURL) fromMap(v map[string]interface{}) error { + if v == nil { + return nil + } + if vv, ok := v["$schema"]; ok { + if str, ok := vv.(string); ok { + u, err := parseURL(str) + if err != nil { + return err + } *r = SchemaURL(u.String()) + } + } + return nil + } // SchemaProps describes a JSON schema (draft 4) + type SchemaProps struct { - ID string `json:"id,omitempty"` - Ref Ref `json:"-"` - Schema SchemaURL `json:"-"` - Description string `json:"description,omitempty"` - Type StringOrArray `json:"type,omitempty"` - Nullable bool `json:"nullable,omitempty"` - Format string `json:"format,omitempty"` - Title string `json:"title,omitempty"` - Default interface{} `json:"default,omitempty"` - Maximum *float64 `json:"maximum,omitempty"` - ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"` - Minimum *float64 `json:"minimum,omitempty"` - ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"` - MaxLength *int64 `json:"maxLength,omitempty"` - MinLength *int64 `json:"minLength,omitempty"` - Pattern string `json:"pattern,omitempty"` - MaxItems *int64 `json:"maxItems,omitempty"` - MinItems *int64 `json:"minItems,omitempty"` - UniqueItems bool `json:"uniqueItems,omitempty"` - MultipleOf *float64 `json:"multipleOf,omitempty"` - Enum []interface{} `json:"enum,omitempty"` - MaxProperties *int64 `json:"maxProperties,omitempty"` - MinProperties *int64 `json:"minProperties,omitempty"` - Required []string `json:"required,omitempty"` - Items *SchemaOrArray `json:"items,omitempty"` - AllOf []Schema `json:"allOf,omitempty"` - OneOf []Schema `json:"oneOf,omitempty"` - AnyOf []Schema `json:"anyOf,omitempty"` - Not *Schema `json:"not,omitempty"` - Properties SchemaProperties `json:"properties,omitempty"` - AdditionalProperties *SchemaOrBool `json:"additionalProperties,omitempty"` - PatternProperties SchemaProperties `json:"patternProperties,omitempty"` - Dependencies Dependencies `json:"dependencies,omitempty"` - AdditionalItems *SchemaOrBool `json:"additionalItems,omitempty"` - Definitions Definitions `json:"definitions,omitempty"` + ID string `json:"id,omitempty"` + + Ref Ref `json:"-"` + + Schema SchemaURL `json:"-"` + + Description string `json:"description,omitempty"` + + Type StringOrArray `json:"type,omitempty"` + + Nullable bool `json:"nullable,omitempty"` + + Format string `json:"format,omitempty"` + + Title string `json:"title,omitempty"` + + Default interface{} `json:"default,omitempty"` + + Maximum *float64 `json:"maximum,omitempty"` + + ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"` + + Minimum *float64 `json:"minimum,omitempty"` + + ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"` + + MaxLength *int64 `json:"maxLength,omitempty"` + + MinLength *int64 `json:"minLength,omitempty"` + + Pattern string `json:"pattern,omitempty"` + + MaxItems *int64 `json:"maxItems,omitempty"` + + MinItems *int64 `json:"minItems,omitempty"` + + UniqueItems bool `json:"uniqueItems,omitempty"` + + MultipleOf *float64 `json:"multipleOf,omitempty"` + + Enum []interface{} `json:"enum,omitempty"` + + MaxProperties *int64 `json:"maxProperties,omitempty"` + + MinProperties *int64 `json:"minProperties,omitempty"` + + Required []string `json:"required,omitempty"` + + Items *SchemaOrArray `json:"items,omitempty"` + + AllOf []Schema `json:"allOf,omitempty"` + + OneOf []Schema `json:"oneOf,omitempty"` + + AnyOf []Schema `json:"anyOf,omitempty"` + + Not *Schema `json:"not,omitempty"` + + Properties SchemaProperties `json:"properties,omitempty"` + + AdditionalProperties *SchemaOrBool `json:"additionalProperties,omitempty"` + + PatternProperties SchemaProperties `json:"patternProperties,omitempty"` + + Dependencies Dependencies `json:"dependencies,omitempty"` + + AdditionalItems *SchemaOrBool `json:"additionalItems,omitempty"` + + Definitions Definitions `json:"definitions,omitempty"` } // SwaggerSchemaProps are additional properties supported by swagger schemas, but not JSON-schema (draft 4) + type SwaggerSchemaProps struct { - Discriminator string `json:"discriminator,omitempty"` - ReadOnly bool `json:"readOnly,omitempty"` - XML *XMLObject `json:"xml,omitempty"` - ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` - Example interface{} `json:"example,omitempty"` + Discriminator string `json:"discriminator,omitempty"` + + ReadOnly bool `json:"readOnly,omitempty"` + + XML *XMLObject `json:"xml,omitempty"` + + ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` + + Example interface{} `json:"example,omitempty"` } // Schema the schema object allows the definition of input and output data types. + // These types can be objects, but also primitives and arrays. + // This object is based on the [JSON Schema Specification Draft 4](http://json-schema.org/) + // and uses a predefined subset of it. + // On top of this subset, there are extensions provided by this specification to allow for more complete documentation. + // + // For more information: http://goo.gl/8us55a#schemaObject + type Schema struct { VendorExtensible + SchemaProps + SwaggerSchemaProps + ExtraProps map[string]interface{} `json:"-"` } // JSONLookup implements an interface to customize json pointer lookup + func (s Schema) JSONLookup(token string) (interface{}, error) { + if ex, ok := s.Extensions[token]; ok { + return &ex, nil + } if ex, ok := s.ExtraProps[token]; ok { + return &ex, nil + } r, _, err := jsonpointer.GetForToken(s.SchemaProps, token) + if r != nil || (err != nil && !strings.HasPrefix(err.Error(), "object has no field")) { + return r, err + } + r, _, err = jsonpointer.GetForToken(s.SwaggerSchemaProps, token) + return r, err + } // WithID sets the id for this schema, allows for chaining + func (s *Schema) WithID(id string) *Schema { + s.ID = id + return s + } // WithTitle sets the title for this schema, allows for chaining + func (s *Schema) WithTitle(title string) *Schema { + s.Title = title + return s + } // WithDescription sets the description for this schema, allows for chaining + func (s *Schema) WithDescription(description string) *Schema { + s.Description = description + return s + } // WithProperties sets the properties for this schema + func (s *Schema) WithProperties(schemas map[string]Schema) *Schema { + s.Properties = schemas + return s + } // SetProperty sets a property on this schema + func (s *Schema) SetProperty(name string, schema Schema) *Schema { + if s.Properties == nil { + s.Properties = make(map[string]Schema) + } + s.Properties[name] = schema + return s + } // WithAllOf sets the all of property + func (s *Schema) WithAllOf(schemas ...Schema) *Schema { + s.AllOf = schemas + return s + } // WithMaxProperties sets the max number of properties an object can have + func (s *Schema) WithMaxProperties(max int64) *Schema { + s.MaxProperties = &max + return s + } // WithMinProperties sets the min number of properties an object must have + func (s *Schema) WithMinProperties(min int64) *Schema { + s.MinProperties = &min + return s + } // Typed sets the type of this schema for a single value item + func (s *Schema) Typed(tpe, format string) *Schema { + s.Type = []string{tpe} + s.Format = format + return s + } // AddType adds a type with potential format to the types for this schema + func (s *Schema) AddType(tpe, format string) *Schema { + s.Type = append(s.Type, tpe) + if format != "" { + s.Format = format + } + return s + } // AsNullable flags this schema as nullable. + func (s *Schema) AsNullable() *Schema { + s.Nullable = true + return s + } // CollectionOf a fluent builder method for an array parameter + func (s *Schema) CollectionOf(items Schema) *Schema { + s.Type = []string{jsonArray} + s.Items = &SchemaOrArray{Schema: &items} + return s + } // WithDefault sets the default value on this parameter + func (s *Schema) WithDefault(defaultValue interface{}) *Schema { + s.Default = defaultValue + return s + } // WithRequired flags this parameter as required + func (s *Schema) WithRequired(items ...string) *Schema { + s.Required = items + return s + } // AddRequired adds field names to the required properties array + func (s *Schema) AddRequired(items ...string) *Schema { + s.Required = append(s.Required, items...) + return s + } // WithMaxLength sets a max length value + func (s *Schema) WithMaxLength(max int64) *Schema { + s.MaxLength = &max + return s + } // WithMinLength sets a min length value + func (s *Schema) WithMinLength(min int64) *Schema { + s.MinLength = &min + return s + } // WithPattern sets a pattern value + func (s *Schema) WithPattern(pattern string) *Schema { + s.Pattern = pattern + return s + } // WithMultipleOf sets a multiple of value + func (s *Schema) WithMultipleOf(number float64) *Schema { + s.MultipleOf = &number + return s + } // WithMaximum sets a maximum number value + func (s *Schema) WithMaximum(max float64, exclusive bool) *Schema { + s.Maximum = &max + s.ExclusiveMaximum = exclusive + return s + } // WithMinimum sets a minimum number value + func (s *Schema) WithMinimum(min float64, exclusive bool) *Schema { + s.Minimum = &min + s.ExclusiveMinimum = exclusive + return s + } // WithEnum sets a the enum values (replace) + func (s *Schema) WithEnum(values ...interface{}) *Schema { + s.Enum = append([]interface{}{}, values...) + return s + } // WithMaxItems sets the max items + func (s *Schema) WithMaxItems(size int64) *Schema { + s.MaxItems = &size + return s + } // WithMinItems sets the min items + func (s *Schema) WithMinItems(size int64) *Schema { + s.MinItems = &size + return s + } // UniqueValues dictates that this array can only have unique items + func (s *Schema) UniqueValues() *Schema { + s.UniqueItems = true + return s + } // AllowDuplicates this array can have duplicates + func (s *Schema) AllowDuplicates() *Schema { + s.UniqueItems = false + return s + } // AddToAllOf adds a schema to the allOf property + func (s *Schema) AddToAllOf(schemas ...Schema) *Schema { + s.AllOf = append(s.AllOf, schemas...) + return s + } // WithDiscriminator sets the name of the discriminator field + func (s *Schema) WithDiscriminator(discriminator string) *Schema { + s.Discriminator = discriminator + return s + } // AsReadOnly flags this schema as readonly + func (s *Schema) AsReadOnly() *Schema { + s.ReadOnly = true + return s + } // AsWritable flags this schema as writeable (not read-only) + func (s *Schema) AsWritable() *Schema { + s.ReadOnly = false + return s + } // WithExample sets the example for this schema + func (s *Schema) WithExample(example interface{}) *Schema { + s.Example = example + return s + } // WithExternalDocs sets/removes the external docs for/from this schema. + // When you pass empty strings as params the external documents will be removed. + // When you pass non-empty string as one value then those values will be used on the external docs object. + // So when you pass a non-empty description, you should also pass the url and vice versa. + func (s *Schema) WithExternalDocs(description, url string) *Schema { + if description == "" && url == "" { + s.ExternalDocs = nil + return s + } if s.ExternalDocs == nil { + s.ExternalDocs = &ExternalDocumentation{} + } + s.ExternalDocs.Description = description + s.ExternalDocs.URL = url + return s + } // WithXMLName sets the xml name for the object + func (s *Schema) WithXMLName(name string) *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Name = name + return s + } // WithXMLNamespace sets the xml namespace for the object + func (s *Schema) WithXMLNamespace(namespace string) *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Namespace = namespace + return s + } // WithXMLPrefix sets the xml prefix for the object + func (s *Schema) WithXMLPrefix(prefix string) *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Prefix = prefix + return s + } // AsXMLAttribute flags this object as xml attribute + func (s *Schema) AsXMLAttribute() *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Attribute = true + return s + } // AsXMLElement flags this object as an xml node + func (s *Schema) AsXMLElement() *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Attribute = false + return s + } // AsWrappedXML flags this object as wrapped, this is mostly useful for array types + func (s *Schema) AsWrappedXML() *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Wrapped = true + return s + } // AsUnwrappedXML flags this object as an xml node + func (s *Schema) AsUnwrappedXML() *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Wrapped = false + return s + } // SetValidations defines all schema validations. + // + // NOTE: Required, ReadOnly, AllOf, AnyOf, OneOf and Not are not considered. + func (s *Schema) SetValidations(val SchemaValidations) { + s.Maximum = val.Maximum + s.ExclusiveMaximum = val.ExclusiveMaximum + s.Minimum = val.Minimum + s.ExclusiveMinimum = val.ExclusiveMinimum + s.MaxLength = val.MaxLength + s.MinLength = val.MinLength + s.Pattern = val.Pattern + s.MaxItems = val.MaxItems + s.MinItems = val.MinItems + s.UniqueItems = val.UniqueItems + s.MultipleOf = val.MultipleOf + s.Enum = val.Enum + s.MinProperties = val.MinProperties + s.MaxProperties = val.MaxProperties + s.PatternProperties = val.PatternProperties + } // WithValidations is a fluent method to set schema validations + func (s *Schema) WithValidations(val SchemaValidations) *Schema { + s.SetValidations(val) + return s + } // Validations returns a clone of the validations for this schema + func (s Schema) Validations() SchemaValidations { + return SchemaValidations{ + CommonValidations: CommonValidations{ - Maximum: s.Maximum, + + Maximum: s.Maximum, + ExclusiveMaximum: s.ExclusiveMaximum, - Minimum: s.Minimum, + + Minimum: s.Minimum, + ExclusiveMinimum: s.ExclusiveMinimum, - MaxLength: s.MaxLength, - MinLength: s.MinLength, - Pattern: s.Pattern, - MaxItems: s.MaxItems, - MinItems: s.MinItems, - UniqueItems: s.UniqueItems, - MultipleOf: s.MultipleOf, - Enum: s.Enum, + + MaxLength: s.MaxLength, + + MinLength: s.MinLength, + + Pattern: s.Pattern, + + MaxItems: s.MaxItems, + + MinItems: s.MinItems, + + UniqueItems: s.UniqueItems, + + MultipleOf: s.MultipleOf, + + Enum: s.Enum, }, - MinProperties: s.MinProperties, - MaxProperties: s.MaxProperties, + + MinProperties: s.MinProperties, + + MaxProperties: s.MaxProperties, + PatternProperties: s.PatternProperties, } + } // MarshalJSON marshal this to JSON + func (s Schema) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(s.SchemaProps) + if err != nil { + return nil, fmt.Errorf("schema props %v", err) + } + b2, err := json.Marshal(s.VendorExtensible) + if err != nil { + return nil, fmt.Errorf("vendor props %v", err) + } + b3, err := s.Ref.MarshalJSON() + if err != nil { + return nil, fmt.Errorf("ref prop %v", err) + } + b4, err := s.Schema.MarshalJSON() + if err != nil { + return nil, fmt.Errorf("schema prop %v", err) + } + b5, err := json.Marshal(s.SwaggerSchemaProps) + if err != nil { + return nil, fmt.Errorf("common validations %v", err) + } + var b6 []byte + if s.ExtraProps != nil { + jj, err := json.Marshal(s.ExtraProps) + if err != nil { + return nil, fmt.Errorf("extra props %v", err) + } + b6 = jj + } + return swag.ConcatJSON(b1, b2, b3, b4, b5, b6), nil + } // UnmarshalJSON marshal this from JSON + func (s *Schema) UnmarshalJSON(data []byte) error { + props := struct { SchemaProps + SwaggerSchemaProps }{} + if err := json.Unmarshal(data, &props); err != nil { + return err + } sch := Schema{ - SchemaProps: props.SchemaProps, + + SchemaProps: props.SchemaProps, + SwaggerSchemaProps: props.SwaggerSchemaProps, } var d map[string]interface{} + if err := json.Unmarshal(data, &d); err != nil { + return err + } _ = sch.Ref.fromMap(d) + _ = sch.Schema.fromMap(d) delete(d, "$ref") + delete(d, "$schema") + for _, pn := range swag.DefaultJSONNameProvider.GetJSONNames(s) { + delete(d, pn) + } for k, vv := range d { + lk := strings.ToLower(k) + if strings.HasPrefix(lk, "x-") { + if sch.Extensions == nil { + sch.Extensions = map[string]interface{}{} + } + sch.Extensions[k] = vv + continue + } + if sch.ExtraProps == nil { + sch.ExtraProps = map[string]interface{}{} + } + sch.ExtraProps[k] = vv + } *s = sch return nil + } diff --git a/vendor/github.com/go-openapi/spec/schema_loader.go b/vendor/github.com/go-openapi/spec/schema_loader.go index 0059b99..e655e24 100644 --- a/vendor/github.com/go-openapi/spec/schema_loader.go +++ b/vendor/github.com/go-openapi/spec/schema_loader.go @@ -1,15 +1,27 @@ // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -26,306 +38,506 @@ import ( ) // PathLoader is a function to use when loading remote refs. + // + // This is a package level default. It may be overridden or bypassed by + // specifying the loader in ExpandOptions. + // + // NOTE: if you are using the go-openapi/loads package, it will override + // this value with its own default (a loader to retrieve YAML documents as + // well as JSON ones). + var PathLoader = func(pth string) (json.RawMessage, error) { + data, err := swag.LoadFromFileOrHTTP(pth) + if err != nil { + return nil, err + } + return json.RawMessage(data), nil + } // resolverContext allows to share a context during spec processing. + // At the moment, it just holds the index of circular references found. + type resolverContext struct { + // circulars holds all visited circular references, to shortcircuit $ref resolution. + // + // This structure is privately instantiated and needs not be locked against + // concurrent access, unless we chose to implement a parallel spec walking. + circulars map[string]bool - basePath string - loadDoc func(string) (json.RawMessage, error) - rootID string + + basePath string + + loadDoc func(string) (json.RawMessage, error) + + rootID string } func newResolverContext(options *ExpandOptions) *resolverContext { + expandOptions := optionsOrDefault(options) // path loader may be overridden by options + var loader func(string) (json.RawMessage, error) + if expandOptions.PathLoader == nil { + loader = PathLoader + } else { + loader = expandOptions.PathLoader + } return &resolverContext{ + circulars: make(map[string]bool), - basePath: expandOptions.RelativeBase, // keep the root base path in context - loadDoc: loader, + + basePath: expandOptions.RelativeBase, // keep the root base path in context + + loadDoc: loader, } + } type schemaLoader struct { - root interface{} + root interface{} + options *ExpandOptions - cache ResolutionCache + + cache ResolutionCache + context *resolverContext } func (r *schemaLoader) transitiveResolver(basePath string, ref Ref) *schemaLoader { + if ref.IsRoot() || ref.HasFragmentOnly { + return r + } baseRef := MustCreateRef(basePath) + currentRef := normalizeRef(&ref, basePath) + if strings.HasPrefix(currentRef.String(), baseRef.String()) { + return r + } // set a new root against which to resolve + rootURL := currentRef.GetURL() + rootURL.Fragment = "" + root, _ := r.cache.Get(rootURL.String()) // shallow copy of resolver options to set a new RelativeBase when + // traversing multiple documents + newOptions := r.options + newOptions.RelativeBase = rootURL.String() return defaultSchemaLoader(root, newOptions, r.cache, r.context) + } func (r *schemaLoader) updateBasePath(transitive *schemaLoader, basePath string) string { + if transitive != r { + if transitive.options != nil && transitive.options.RelativeBase != "" { + return normalizeBase(transitive.options.RelativeBase) + } + } return basePath + } func (r *schemaLoader) resolveRef(ref *Ref, target interface{}, basePath string) error { + tgt := reflect.ValueOf(target) + if tgt.Kind() != reflect.Ptr { + return ErrResolveRefNeedsAPointer + } if ref.GetURL() == nil { + return nil + } var ( - res interface{} + res interface{} + data interface{} - err error + + err error ) // Resolve against the root if it isn't nil, and if ref is pointing at the root, or has a fragment only which means + // it is pointing somewhere in the root. + root := r.root + if (ref.IsRoot() || ref.HasFragmentOnly) && root == nil && basePath != "" { + if baseRef, erb := NewRef(basePath); erb == nil { + root, _, _, _ = r.load(baseRef.GetURL()) + } + } if (ref.IsRoot() || ref.HasFragmentOnly) && root != nil { + data = root + } else { + baseRef := normalizeRef(ref, basePath) + data, _, _, err = r.load(baseRef.GetURL()) + if err != nil { + return err + } + } res = data + if ref.String() != "" { + res, _, err = ref.GetPointer().Get(data) + if err != nil { + return err + } + } + return swag.DynamicJSONToStruct(res, target) + } func (r *schemaLoader) load(refURL *url.URL) (interface{}, url.URL, bool, error) { + debugLog("loading schema from url: %s", refURL) + toFetch := *refURL + toFetch.Fragment = "" var err error + pth := toFetch.String() + normalized := normalizeBase(pth) + debugLog("loading doc from: %s", normalized) data, fromCache := r.cache.Get(normalized) + if fromCache { + return data, toFetch, fromCache, nil + } b, err := r.context.loadDoc(normalized) + if err != nil { + return nil, url.URL{}, false, err + } var doc interface{} + if err := json.Unmarshal(b, &doc); err != nil { + return nil, url.URL{}, false, err + } + r.cache.Set(normalized, doc) return doc, toFetch, fromCache, nil + } // isCircular detects cycles in sequences of $ref. + // + // It relies on a private context (which needs not be locked). + func (r *schemaLoader) isCircular(ref *Ref, basePath string, parentRefs ...string) (foundCycle bool) { + normalizedRef := normalizeURI(ref.String(), basePath) + if _, ok := r.context.circulars[normalizedRef]; ok { + // circular $ref has been already detected in another explored cycle + foundCycle = true + return + } + foundCycle = swag.ContainsStrings(parentRefs, normalizedRef) // normalized windows url's are lower cased + if foundCycle { + r.context.circulars[normalizedRef] = true + } + return + } // Resolve resolves a reference against basePath and stores the result in target. + // + // Resolve is not in charge of following references: it only resolves ref by following its URL. + // + // If the schema the ref is referring to holds nested refs, Resolve doesn't resolve them. + // + // If basePath is an empty string, ref is resolved against the root schema stored in the schemaLoader struct + func (r *schemaLoader) Resolve(ref *Ref, target interface{}, basePath string) error { + return r.resolveRef(ref, target, basePath) + } func (r *schemaLoader) deref(input interface{}, parentRefs []string, basePath string) error { + var ref *Ref + switch refable := input.(type) { + case *Schema: + ref = &refable.Ref + case *Parameter: + ref = &refable.Ref + case *Response: + ref = &refable.Ref + case *PathItem: + ref = &refable.Ref + default: + return fmt.Errorf("unsupported type: %T: %w", input, ErrDerefUnsupportedType) + } curRef := ref.String() + if curRef == "" { + return nil + } normalizedRef := normalizeRef(ref, basePath) + normalizedBasePath := normalizedRef.RemoteURI() if r.isCircular(normalizedRef, basePath, parentRefs...) { + return nil + } if err := r.resolveRef(ref, input, basePath); r.shouldStopOnError(err) { + return err + } if ref.String() == "" || ref.String() == curRef { + // done with rereferencing + return nil + } parentRefs = append(parentRefs, normalizedRef.String()) + return r.deref(input, parentRefs, normalizedBasePath) + } func (r *schemaLoader) shouldStopOnError(err error) bool { + if err != nil && !r.options.ContinueOnError { + return true + } if err != nil { + log.Println(err) + } return false + } func (r *schemaLoader) setSchemaID(target interface{}, id, basePath string) (string, string) { + debugLog("schema has ID: %s", id) // handling the case when id is a folder + // remember that basePath has to point to a file + var refPath string + if strings.HasSuffix(id, "/") { + // ensure this is detected as a file, not a folder + refPath = fmt.Sprintf("%s%s", id, "placeholder.json") + } else { + refPath = id + } // updates the current base path + // * important: ID can be a relative path + // * registers target to be fetchable from the new base proposed by this id + newBasePath := normalizeURI(refPath, basePath) // store found IDs for possible future reuse in $ref + r.cache.Set(newBasePath, target) // the root document has an ID: all $ref relative to that ID may + // be rebased relative to the root document + if basePath == r.context.basePath { + debugLog("root document is a schema with ID: %s (normalized as:%s)", id, newBasePath) + r.context.rootID = newBasePath + } return newBasePath, refPath + } func defaultSchemaLoader( + root interface{}, + expandOptions *ExpandOptions, + cache ResolutionCache, + context *resolverContext) *schemaLoader { if expandOptions == nil { + expandOptions = &ExpandOptions{} + } cache = cacheOrDefault(cache) if expandOptions.RelativeBase == "" { + // if no relative base is provided, assume the root document + // contains all $ref, or at least, that the relative documents + // may be resolved from the current working directory. + expandOptions.RelativeBase = baseForRoot(root, cache) + } + debugLog("effective expander options: %#v", expandOptions) if context == nil { + context = newResolverContext(expandOptions) + } return &schemaLoader{ - root: root, + + root: root, + options: expandOptions, - cache: cache, + + cache: cache, + context: context, } + } diff --git a/vendor/github.com/go-openapi/spec/security_scheme.go b/vendor/github.com/go-openapi/spec/security_scheme.go index 9d0bdae..32b6f1c 100644 --- a/vendor/github.com/go-openapi/spec/security_scheme.go +++ b/vendor/github.com/go-openapi/spec/security_scheme.go @@ -1,15 +1,27 @@ // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -22,149 +34,252 @@ import ( ) const ( - basic = "basic" - apiKey = "apiKey" - oauth2 = "oauth2" - implicit = "implicit" - password = "password" + basic = "basic" + + apiKey = "apiKey" + + oauth2 = "oauth2" + + implicit = "implicit" + + password = "password" + application = "application" - accessCode = "accessCode" + + accessCode = "accessCode" ) // BasicAuth creates a basic auth security scheme + func BasicAuth() *SecurityScheme { + return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{Type: basic}} + } // APIKeyAuth creates an api key auth security scheme + func APIKeyAuth(fieldName, valueSource string) *SecurityScheme { + return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{Type: apiKey, Name: fieldName, In: valueSource}} + } // OAuth2Implicit creates an implicit flow oauth2 security scheme + func OAuth2Implicit(authorizationURL string) *SecurityScheme { + return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ - Type: oauth2, - Flow: implicit, + + Type: oauth2, + + Flow: implicit, + AuthorizationURL: authorizationURL, }} + } // OAuth2Password creates a password flow oauth2 security scheme + func OAuth2Password(tokenURL string) *SecurityScheme { + return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ - Type: oauth2, - Flow: password, + + Type: oauth2, + + Flow: password, + TokenURL: tokenURL, }} + } // OAuth2Application creates an application flow oauth2 security scheme + func OAuth2Application(tokenURL string) *SecurityScheme { + return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ - Type: oauth2, - Flow: application, + + Type: oauth2, + + Flow: application, + TokenURL: tokenURL, }} + } // OAuth2AccessToken creates an access token flow oauth2 security scheme + func OAuth2AccessToken(authorizationURL, tokenURL string) *SecurityScheme { + return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ - Type: oauth2, - Flow: accessCode, + + Type: oauth2, + + Flow: accessCode, + AuthorizationURL: authorizationURL, - TokenURL: tokenURL, + + TokenURL: tokenURL, }} + } // SecuritySchemeProps describes a swagger security scheme in the securityDefinitions section + type SecuritySchemeProps struct { - Description string `json:"description,omitempty"` - Type string `json:"type"` - Name string `json:"name,omitempty"` // api key - In string `json:"in,omitempty"` // api key - Flow string `json:"flow,omitempty"` // oauth2 - AuthorizationURL string `json:"authorizationUrl"` // oauth2 - TokenURL string `json:"tokenUrl,omitempty"` // oauth2 - Scopes map[string]string `json:"scopes,omitempty"` // oauth2 + Description string `json:"description,omitempty"` + + Type string `json:"type"` + + Name string `json:"name,omitempty"` // api key + + In string `json:"in,omitempty"` // api key + + Flow string `json:"flow,omitempty"` // oauth2 + + AuthorizationURL string `json:"authorizationUrl"` // oauth2 + + TokenURL string `json:"tokenUrl,omitempty"` // oauth2 + + Scopes map[string]string `json:"scopes,omitempty"` // oauth2 + } // AddScope adds a scope to this security scheme + func (s *SecuritySchemeProps) AddScope(scope, description string) { + if s.Scopes == nil { + s.Scopes = make(map[string]string) + } + s.Scopes[scope] = description + } // SecurityScheme allows the definition of a security scheme that can be used by the operations. + // Supported schemes are basic authentication, an API key (either as a header or as a query parameter) + // and OAuth2's common flows (implicit, password, application and access code). + // + // For more information: http://goo.gl/8us55a#securitySchemeObject + type SecurityScheme struct { VendorExtensible + SecuritySchemeProps } // JSONLookup implements an interface to customize json pointer lookup + func (s SecurityScheme) JSONLookup(token string) (interface{}, error) { + if ex, ok := s.Extensions[token]; ok { + return &ex, nil + } r, _, err := jsonpointer.GetForToken(s.SecuritySchemeProps, token) + return r, err + } // MarshalJSON marshal this to JSON + func (s SecurityScheme) MarshalJSON() ([]byte, error) { + var ( - b1 []byte + b1 []byte + err error ) if s.Type == oauth2 && (s.Flow == "implicit" || s.Flow == "accessCode") { + // when oauth2 for implicit or accessCode flows, empty AuthorizationURL is added as empty string + b1, err = json.Marshal(s.SecuritySchemeProps) + } else { + // when not oauth2, empty AuthorizationURL should be omitted + b1, err = json.Marshal(struct { - Description string `json:"description,omitempty"` - Type string `json:"type"` - Name string `json:"name,omitempty"` // api key - In string `json:"in,omitempty"` // api key - Flow string `json:"flow,omitempty"` // oauth2 - AuthorizationURL string `json:"authorizationUrl,omitempty"` // oauth2 - TokenURL string `json:"tokenUrl,omitempty"` // oauth2 - Scopes map[string]string `json:"scopes,omitempty"` // oauth2 + Description string `json:"description,omitempty"` + + Type string `json:"type"` + + Name string `json:"name,omitempty"` // api key + + In string `json:"in,omitempty"` // api key + + Flow string `json:"flow,omitempty"` // oauth2 + + AuthorizationURL string `json:"authorizationUrl,omitempty"` // oauth2 + + TokenURL string `json:"tokenUrl,omitempty"` // oauth2 + + Scopes map[string]string `json:"scopes,omitempty"` // oauth2 + }{ - Description: s.Description, - Type: s.Type, - Name: s.Name, - In: s.In, - Flow: s.Flow, + + Description: s.Description, + + Type: s.Type, + + Name: s.Name, + + In: s.In, + + Flow: s.Flow, + AuthorizationURL: s.AuthorizationURL, - TokenURL: s.TokenURL, - Scopes: s.Scopes, + + TokenURL: s.TokenURL, + + Scopes: s.Scopes, }) + } + if err != nil { + return nil, err + } b2, err := json.Marshal(s.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2), nil + } // UnmarshalJSON marshal this from JSON + func (s *SecurityScheme) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &s.SecuritySchemeProps); err != nil { + return err + } + return json.Unmarshal(data, &s.VendorExtensible) + } diff --git a/vendor/github.com/go-openapi/spec/swagger.go b/vendor/github.com/go-openapi/spec/swagger.go index 1590fd1..3ec2cb4 100644 --- a/vendor/github.com/go-openapi/spec/swagger.go +++ b/vendor/github.com/go-openapi/spec/swagger.go @@ -1,15 +1,27 @@ // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -26,103 +38,180 @@ import ( ) // Swagger this is the root document object for the API specification. + // It combines what previously was the Resource Listing and API Declaration (version 1.2 and earlier) + // together into one document. + // + // For more information: http://goo.gl/8us55a#swagger-object- + type Swagger struct { VendorExtensible + SwaggerProps } // JSONLookup look up a value by the json property name + func (s Swagger) JSONLookup(token string) (interface{}, error) { + if ex, ok := s.Extensions[token]; ok { + return &ex, nil + } + r, _, err := jsonpointer.GetForToken(s.SwaggerProps, token) + return r, err + } // MarshalJSON marshals this swagger structure to json + func (s Swagger) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(s.SwaggerProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(s.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2), nil + } // UnmarshalJSON unmarshals a swagger spec from json + func (s *Swagger) UnmarshalJSON(data []byte) error { + var sw Swagger + if err := json.Unmarshal(data, &sw.SwaggerProps); err != nil { + return err + } + if err := json.Unmarshal(data, &sw.VendorExtensible); err != nil { + return err + } + *s = sw + return nil + } // GobEncode provides a safe gob encoder for Swagger, including extensions + func (s Swagger) GobEncode() ([]byte, error) { + var b bytes.Buffer + raw := struct { Props SwaggerProps - Ext VendorExtensible + + Ext VendorExtensible }{ + Props: s.SwaggerProps, - Ext: s.VendorExtensible, + + Ext: s.VendorExtensible, } + err := gob.NewEncoder(&b).Encode(raw) + return b.Bytes(), err + } // GobDecode provides a safe gob decoder for Swagger, including extensions + func (s *Swagger) GobDecode(b []byte) error { + var raw struct { Props SwaggerProps - Ext VendorExtensible + + Ext VendorExtensible } + buf := bytes.NewBuffer(b) + err := gob.NewDecoder(buf).Decode(&raw) + if err != nil { + return err + } + s.SwaggerProps = raw.Props + s.VendorExtensible = raw.Ext + return nil + } // SwaggerProps captures the top-level properties of an Api specification + // + // NOTE: validation rules + // - the scheme, when present must be from [http, https, ws, wss] + // - BasePath must start with a leading "/" + // - Paths is required + type SwaggerProps struct { - ID string `json:"id,omitempty"` - Consumes []string `json:"consumes,omitempty"` - Produces []string `json:"produces,omitempty"` - Schemes []string `json:"schemes,omitempty"` - Swagger string `json:"swagger,omitempty"` - Info *Info `json:"info,omitempty"` - Host string `json:"host,omitempty"` - BasePath string `json:"basePath,omitempty"` - Paths *Paths `json:"paths"` - Definitions Definitions `json:"definitions,omitempty"` - Parameters map[string]Parameter `json:"parameters,omitempty"` - Responses map[string]Response `json:"responses,omitempty"` - SecurityDefinitions SecurityDefinitions `json:"securityDefinitions,omitempty"` - Security []map[string][]string `json:"security,omitempty"` - Tags []Tag `json:"tags,omitempty"` - ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` + ID string `json:"id,omitempty"` + + Consumes []string `json:"consumes,omitempty"` + + Produces []string `json:"produces,omitempty"` + + Schemes []string `json:"schemes,omitempty"` + + Swagger string `json:"swagger,omitempty"` + + Info *Info `json:"info,omitempty"` + + Host string `json:"host,omitempty"` + + BasePath string `json:"basePath,omitempty"` + + Paths *Paths `json:"paths"` + + Definitions Definitions `json:"definitions,omitempty"` + + Parameters map[string]Parameter `json:"parameters,omitempty"` + + Responses map[string]Response `json:"responses,omitempty"` + + SecurityDefinitions SecurityDefinitions `json:"securityDefinitions,omitempty"` + + Security []map[string][]string `json:"security,omitempty"` + + Tags []Tag `json:"tags,omitempty"` + + ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` } type swaggerPropsAlias SwaggerProps @@ -130,319 +219,549 @@ type swaggerPropsAlias SwaggerProps type gobSwaggerPropsAlias struct { Security []map[string]struct { List []string - Pad bool + + Pad bool } - Alias *swaggerPropsAlias + + Alias *swaggerPropsAlias + SecurityIsEmpty bool } // GobEncode provides a safe gob encoder for SwaggerProps, including empty security requirements + func (o SwaggerProps) GobEncode() ([]byte, error) { + raw := gobSwaggerPropsAlias{ + Alias: (*swaggerPropsAlias)(&o), } var b bytes.Buffer + if o.Security == nil { + // nil security requirement + err := gob.NewEncoder(&b).Encode(raw) + return b.Bytes(), err + } if len(o.Security) == 0 { + // empty, but non-nil security requirement + raw.SecurityIsEmpty = true + raw.Alias.Security = nil + err := gob.NewEncoder(&b).Encode(raw) + return b.Bytes(), err + } raw.Security = make([]map[string]struct { List []string - Pad bool + + Pad bool }, 0, len(o.Security)) + for _, req := range o.Security { + v := make(map[string]struct { List []string - Pad bool + + Pad bool }, len(req)) + for k, val := range req { + v[k] = struct { List []string - Pad bool + + Pad bool }{ + List: val, } + } + raw.Security = append(raw.Security, v) + } err := gob.NewEncoder(&b).Encode(raw) + return b.Bytes(), err + } // GobDecode provides a safe gob decoder for SwaggerProps, including empty security requirements + func (o *SwaggerProps) GobDecode(b []byte) error { + var raw gobSwaggerPropsAlias buf := bytes.NewBuffer(b) + err := gob.NewDecoder(buf).Decode(&raw) + if err != nil { + return err + } + if raw.Alias == nil { + return nil + } switch { + case raw.SecurityIsEmpty: + // empty, but non-nil security requirement + raw.Alias.Security = []map[string][]string{} + case len(raw.Alias.Security) == 0: + // nil security requirement + raw.Alias.Security = nil + default: + raw.Alias.Security = make([]map[string][]string, 0, len(raw.Security)) + for _, req := range raw.Security { + v := make(map[string][]string, len(req)) + for k, val := range req { + v[k] = make([]string, 0, len(val.List)) + v[k] = append(v[k], val.List...) + } + raw.Alias.Security = append(raw.Alias.Security, v) + } + } *o = *(*SwaggerProps)(raw.Alias) + return nil + } // Dependencies represent a dependencies property + type Dependencies map[string]SchemaOrStringArray // SchemaOrBool represents a schema or boolean value, is biased towards true for the boolean property + type SchemaOrBool struct { Allows bool + Schema *Schema } // JSONLookup implements an interface to customize json pointer lookup + func (s SchemaOrBool) JSONLookup(token string) (interface{}, error) { + if token == "allows" { + return s.Allows, nil + } + r, _, err := jsonpointer.GetForToken(s.Schema, token) + return r, err + } var jsTrue = []byte("true") + var jsFalse = []byte("false") // MarshalJSON convert this object to JSON + func (s SchemaOrBool) MarshalJSON() ([]byte, error) { + if s.Schema != nil { + return json.Marshal(s.Schema) + } if s.Schema == nil && !s.Allows { + return jsFalse, nil + } + return jsTrue, nil + } // UnmarshalJSON converts this bool or schema object from a JSON structure + func (s *SchemaOrBool) UnmarshalJSON(data []byte) error { + var nw SchemaOrBool + if len(data) > 0 { + if data[0] == '{' { + var sch Schema + if err := json.Unmarshal(data, &sch); err != nil { + return err + } + nw.Schema = &sch + } + nw.Allows = !bytes.Equal(data, []byte("false")) + } + *s = nw + return nil + } // SchemaOrStringArray represents a schema or a string array + type SchemaOrStringArray struct { - Schema *Schema + Schema *Schema + Property []string } // JSONLookup implements an interface to customize json pointer lookup + func (s SchemaOrStringArray) JSONLookup(token string) (interface{}, error) { + r, _, err := jsonpointer.GetForToken(s.Schema, token) + return r, err + } // MarshalJSON converts this schema object or array into JSON structure + func (s SchemaOrStringArray) MarshalJSON() ([]byte, error) { + if len(s.Property) > 0 { + return json.Marshal(s.Property) + } + if s.Schema != nil { + return json.Marshal(s.Schema) + } + return []byte("null"), nil + } // UnmarshalJSON converts this schema object or array from a JSON structure + func (s *SchemaOrStringArray) UnmarshalJSON(data []byte) error { + var first byte + if len(data) > 1 { + first = data[0] + } + var nw SchemaOrStringArray + if first == '{' { + var sch Schema + if err := json.Unmarshal(data, &sch); err != nil { + return err + } + nw.Schema = &sch + } + if first == '[' { + if err := json.Unmarshal(data, &nw.Property); err != nil { + return err + } + } + *s = nw + return nil + } // Definitions contains the models explicitly defined in this spec + // An object to hold data types that can be consumed and produced by operations. + // These data types can be primitives, arrays or models. + // + // For more information: http://goo.gl/8us55a#definitionsObject + type Definitions map[string]Schema // SecurityDefinitions a declaration of the security schemes available to be used in the specification. + // This does not enforce the security schemes on the operations and only serves to provide + // the relevant details for each scheme. + // + // For more information: http://goo.gl/8us55a#securityDefinitionsObject + type SecurityDefinitions map[string]*SecurityScheme // StringOrArray represents a value that can either be a string + // or an array of strings. Mainly here for serialization purposes + type StringOrArray []string // Contains returns true when the value is contained in the slice + func (s StringOrArray) Contains(value string) bool { + for _, str := range s { + if str == value { + return true + } + } + return false + } // JSONLookup implements an interface to customize json pointer lookup + func (s SchemaOrArray) JSONLookup(token string) (interface{}, error) { + if _, err := strconv.Atoi(token); err == nil { + r, _, err := jsonpointer.GetForToken(s.Schemas, token) + return r, err + } + r, _, err := jsonpointer.GetForToken(s.Schema, token) + return r, err + } // UnmarshalJSON unmarshals this string or array object from a JSON array or JSON string + func (s *StringOrArray) UnmarshalJSON(data []byte) error { + var first byte + if len(data) > 1 { + first = data[0] + } if first == '[' { + var parsed []string + if err := json.Unmarshal(data, &parsed); err != nil { + return err + } + *s = StringOrArray(parsed) + return nil + } var single interface{} + if err := json.Unmarshal(data, &single); err != nil { + return err + } + if single == nil { + return nil + } + switch v := single.(type) { + case string: + *s = StringOrArray([]string{v}) + return nil + default: + return fmt.Errorf("only string or array is allowed, not %T", single) + } + } // MarshalJSON converts this string or array to a JSON array or JSON string + func (s StringOrArray) MarshalJSON() ([]byte, error) { + if len(s) == 1 { + return json.Marshal([]string(s)[0]) + } + return json.Marshal([]string(s)) + } // SchemaOrArray represents a value that can either be a Schema + // or an array of Schema. Mainly here for serialization purposes + type SchemaOrArray struct { - Schema *Schema + Schema *Schema + Schemas []Schema } // Len returns the number of schemas in this property + func (s SchemaOrArray) Len() int { + if s.Schema != nil { + return 1 + } + return len(s.Schemas) + } // ContainsType returns true when one of the schemas is of the specified type + func (s *SchemaOrArray) ContainsType(name string) bool { + if s.Schema != nil { + return s.Schema.Type != nil && s.Schema.Type.Contains(name) + } + return false + } // MarshalJSON converts this schema object or array into JSON structure + func (s SchemaOrArray) MarshalJSON() ([]byte, error) { + if len(s.Schemas) > 0 { + return json.Marshal(s.Schemas) + } + return json.Marshal(s.Schema) + } // UnmarshalJSON converts this schema object or array from a JSON structure + func (s *SchemaOrArray) UnmarshalJSON(data []byte) error { + var nw SchemaOrArray + var first byte + if len(data) > 1 { + first = data[0] + } + if first == '{' { + var sch Schema + if err := json.Unmarshal(data, &sch); err != nil { + return err + } + nw.Schema = &sch + } + if first == '[' { + if err := json.Unmarshal(data, &nw.Schemas); err != nil { + return err + } + } + *s = nw + return nil + } // vim:set ft=go noet sts=2 sw=2 ts=2: diff --git a/vendor/github.com/go-openapi/spec/tag.go b/vendor/github.com/go-openapi/spec/tag.go index faa3d3d..1414808 100644 --- a/vendor/github.com/go-openapi/spec/tag.go +++ b/vendor/github.com/go-openapi/spec/tag.go @@ -1,15 +1,27 @@ // Copyright 2015 go-swagger maintainers + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package spec @@ -22,54 +34,89 @@ import ( ) // TagProps describe a tag entry in the top level tags section of a swagger spec + type TagProps struct { - Description string `json:"description,omitempty"` - Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + + Name string `json:"name,omitempty"` + ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` } // NewTag creates a new tag + func NewTag(name, description string, externalDocs *ExternalDocumentation) Tag { + return Tag{TagProps: TagProps{Description: description, Name: name, ExternalDocs: externalDocs}} + } // Tag allows adding meta data to a single tag that is used by the + // [Operation Object](http://goo.gl/8us55a#operationObject). + // It is not mandatory to have a Tag Object per tag used there. + // + // For more information: http://goo.gl/8us55a#tagObject + type Tag struct { VendorExtensible + TagProps } // JSONLookup implements an interface to customize json pointer lookup + func (t Tag) JSONLookup(token string) (interface{}, error) { + if ex, ok := t.Extensions[token]; ok { + return &ex, nil + } r, _, err := jsonpointer.GetForToken(t.TagProps, token) + return r, err + } // MarshalJSON marshal this to JSON + func (t Tag) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(t.TagProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(t.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2), nil + } // UnmarshalJSON marshal this from JSON + func (t *Tag) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &t.TagProps); err != nil { + return err + } + return json.Unmarshal(data, &t.VendorExtensible) + } diff --git a/vendor/github.com/go-ozzo/ozzo-validation/date.go b/vendor/github.com/go-ozzo/ozzo-validation/date.go index 9ba71fb..94cff5b 100644 --- a/vendor/github.com/go-ozzo/ozzo-validation/date.go +++ b/vendor/github.com/go-ozzo/ozzo-validation/date.go @@ -1,5 +1,7 @@ // Copyright 2016 Qiang Xue. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package validation @@ -10,76 +12,126 @@ import ( ) type DateRule struct { - layout string - min, max time.Time - message string + layout string + + min, max time.Time + + message string + rangeMessage string } // Date returns a validation rule that checks if a string value is in a format that can be parsed into a date. + // The format of the date should be specified as the layout parameter which accepts the same value as that for time.Parse. + // For example, + // + // validation.Date(time.ANSIC) + // validation.Date("02 Jan 06 15:04 MST") + // validation.Date("2006-01-02") + // + // By calling Min() and/or Max(), you can let the Date rule to check if a parsed date value is within + // the specified date range. + // + // An empty value is considered valid. Use the Required rule to make sure a value is not empty. + func Date(layout string) *DateRule { + return &DateRule{ - layout: layout, - message: "must be a valid date", + + layout: layout, + + message: "must be a valid date", + rangeMessage: "the data is out of range", } + } // Error sets the error message that is used when the value being validated is not a valid date. + func (r *DateRule) Error(message string) *DateRule { + r.message = message + return r + } // RangeError sets the error message that is used when the value being validated is out of the specified Min/Max date range. + func (r *DateRule) RangeError(message string) *DateRule { + r.rangeMessage = message + return r + } // Min sets the minimum date range. A zero value means skipping the minimum range validation. + func (r *DateRule) Min(min time.Time) *DateRule { + r.min = min + return r + } // Max sets the maximum date range. A zero value means skipping the maximum range validation. + func (r *DateRule) Max(max time.Time) *DateRule { + r.max = max + return r + } // Validate checks if the given value is a valid date. + func (r *DateRule) Validate(value interface{}) error { + value, isNil := Indirect(value) + if isNil || IsEmpty(value) { + return nil + } str, err := EnsureString(value) + if err != nil { + return err + } date, err := time.Parse(r.layout, str) + if err != nil { + return errors.New(r.message) + } if !r.min.IsZero() && r.min.After(date) || !r.max.IsZero() && date.After(r.max) { + return errors.New(r.rangeMessage) + } return nil + } diff --git a/vendor/github.com/go-ozzo/ozzo-validation/each.go b/vendor/github.com/go-ozzo/ozzo-validation/each.go index d014ab4..faadfa2 100644 --- a/vendor/github.com/go-ozzo/ozzo-validation/each.go +++ b/vendor/github.com/go-ozzo/ozzo-validation/each.go @@ -1,5 +1,7 @@ // Copyright 2016 Qiang Xue. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package validation @@ -11,12 +13,18 @@ import ( ) // Each returns a validation rule that loops through an iterable (map, slice or array) + // and validates each value inside with the provided rules. + // An empty iterable is considered valid. Use the Required rule to make sure the iterable is not empty. + func Each(rules ...Rule) *EachRule { + return &EachRule{ + rules: rules, } + } type EachRule struct { @@ -24,55 +32,99 @@ type EachRule struct { } // Loops through the given iterable and calls the Ozzo Validate() method for each value. + func (r *EachRule) Validate(value interface{}) error { + errs := Errors{} v := reflect.ValueOf(value) + switch v.Kind() { + case reflect.Map: + for _, k := range v.MapKeys() { + val := r.getInterface(v.MapIndex(k)) + if err := Validate(val, r.rules...); err != nil { + errs[r.getString(k)] = err + } + } + case reflect.Slice, reflect.Array: + for i := 0; i < v.Len(); i++ { + val := r.getInterface(v.Index(i)) + if err := Validate(val, r.rules...); err != nil { + errs[strconv.Itoa(i)] = err + } + } + default: + return errors.New("must be an iterable (map, slice or array)") + } if len(errs) > 0 { + return errs + } + return nil + } func (r *EachRule) getInterface(value reflect.Value) interface{} { + switch value.Kind() { + case reflect.Ptr, reflect.Interface: + if value.IsNil() { + return nil + } + return value.Elem().Interface() + default: + return value.Interface() + } + } func (r *EachRule) getString(value reflect.Value) string { + switch value.Kind() { + case reflect.Ptr, reflect.Interface: + if value.IsNil() { + return "" + } + return value.Elem().String() + default: + return value.String() + } + } diff --git a/vendor/github.com/go-ozzo/ozzo-validation/error.go b/vendor/github.com/go-ozzo/ozzo-validation/error.go index d89d628..0bb2fcb 100644 --- a/vendor/github.com/go-ozzo/ozzo-validation/error.go +++ b/vendor/github.com/go-ozzo/ozzo-validation/error.go @@ -1,5 +1,7 @@ // Copyright 2016 Qiang Xue. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package validation @@ -11,12 +13,16 @@ import ( ) type ( + // Errors represents the validation errors that are indexed by struct field names, map or slice keys. + Errors map[string]error // InternalError represents an error that should NOT be treated as a validation error. + InternalError interface { error + InternalError() error } @@ -26,64 +32,113 @@ type ( ) // NewInternalError wraps a given error into an InternalError. + func NewInternalError(err error) InternalError { + return &internalError{error: err} + } // InternalError returns the actual error that it wraps around. + func (e *internalError) InternalError() error { + return e.error + } // Error returns the error string of Errors. + func (es Errors) Error() string { + if len(es) == 0 { + return "" + } keys := []string{} + for key := range es { + keys = append(keys, key) + } + sort.Strings(keys) s := "" + for i, key := range keys { + if i > 0 { + s += "; " + } + if errs, ok := es[key].(Errors); ok { + s += fmt.Sprintf("%v: (%v)", key, errs) + } else { + s += fmt.Sprintf("%v: %v", key, es[key].Error()) + } + } + return s + "." + } // MarshalJSON converts the Errors into a valid JSON. + func (es Errors) MarshalJSON() ([]byte, error) { + errs := map[string]interface{}{} + for key, err := range es { + if ms, ok := err.(json.Marshaler); ok { + errs[key] = ms + } else { + errs[key] = err.Error() + } + } + return json.Marshal(errs) + } // Filter removes all nils from Errors and returns back the updated Errors as an error. + // If the length of Errors becomes 0, it will return nil. + func (es Errors) Filter() error { + for key, value := range es { + if value == nil { + delete(es, key) + } + } + if len(es) == 0 { + return nil + } + return es + } diff --git a/vendor/github.com/go-ozzo/ozzo-validation/is/rules.go b/vendor/github.com/go-ozzo/ozzo-validation/is/rules.go index 164dc11..2427243 100644 --- a/vendor/github.com/go-ozzo/ozzo-validation/is/rules.go +++ b/vendor/github.com/go-ozzo/ozzo-validation/is/rules.go @@ -1,8 +1,11 @@ // Copyright 2016 Qiang Xue. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. // Package is provides a list of commonly used string validation rules. + package is import ( @@ -14,157 +17,292 @@ import ( ) var ( + // Email validates if a string is an email or not. + Email = validation.NewStringRule(govalidator.IsEmail, "must be a valid email address") + // URL validates if a string is a valid URL + URL = validation.NewStringRule(govalidator.IsURL, "must be a valid URL") + // RequestURL validates if a string is a valid request URL + RequestURL = validation.NewStringRule(govalidator.IsRequestURL, "must be a valid request URL") + // RequestURI validates if a string is a valid request URI + RequestURI = validation.NewStringRule(govalidator.IsRequestURI, "must be a valid request URI") + // Alpha validates if a string contains English letters only (a-zA-Z) + Alpha = validation.NewStringRule(govalidator.IsAlpha, "must contain English letters only") + // Digit validates if a string contains digits only (0-9) + Digit = validation.NewStringRule(isDigit, "must contain digits only") + // Alphanumeric validates if a string contains English letters and digits only (a-zA-Z0-9) + Alphanumeric = validation.NewStringRule(govalidator.IsAlphanumeric, "must contain English letters and digits only") + // UTFLetter validates if a string contains unicode letters only + UTFLetter = validation.NewStringRule(govalidator.IsUTFLetter, "must contain unicode letter characters only") + // UTFDigit validates if a string contains unicode decimal digits only + UTFDigit = validation.NewStringRule(govalidator.IsUTFDigit, "must contain unicode decimal digits only") + // UTFLetterNumeric validates if a string contains unicode letters and numbers only + UTFLetterNumeric = validation.NewStringRule(govalidator.IsUTFLetterNumeric, "must contain unicode letters and numbers only") + // UTFNumeric validates if a string contains unicode number characters (category N) only + UTFNumeric = validation.NewStringRule(isUTFNumeric, "must contain unicode number characters only") + // LowerCase validates if a string contains lower case unicode letters only + LowerCase = validation.NewStringRule(govalidator.IsLowerCase, "must be in lower case") + // UpperCase validates if a string contains upper case unicode letters only + UpperCase = validation.NewStringRule(govalidator.IsUpperCase, "must be in upper case") + // Hexadecimal validates if a string is a valid hexadecimal number + Hexadecimal = validation.NewStringRule(govalidator.IsHexadecimal, "must be a valid hexadecimal number") + // HexColor validates if a string is a valid hexadecimal color code + HexColor = validation.NewStringRule(govalidator.IsHexcolor, "must be a valid hexadecimal color code") + // RGBColor validates if a string is a valid RGB color in the form of rgb(R, G, B) + RGBColor = validation.NewStringRule(govalidator.IsRGBcolor, "must be a valid RGB color code") + // Int validates if a string is a valid integer number + Int = validation.NewStringRule(govalidator.IsInt, "must be an integer number") + // Float validates if a string is a floating point number + Float = validation.NewStringRule(govalidator.IsFloat, "must be a floating point number") + // UUIDv3 validates if a string is a valid version 3 UUID + UUIDv3 = validation.NewStringRule(govalidator.IsUUIDv3, "must be a valid UUID v3") + // UUIDv4 validates if a string is a valid version 4 UUID + UUIDv4 = validation.NewStringRule(govalidator.IsUUIDv4, "must be a valid UUID v4") + // UUIDv5 validates if a string is a valid version 5 UUID + UUIDv5 = validation.NewStringRule(govalidator.IsUUIDv5, "must be a valid UUID v5") + // UUID validates if a string is a valid UUID + UUID = validation.NewStringRule(govalidator.IsUUID, "must be a valid UUID") + // CreditCard validates if a string is a valid credit card number + CreditCard = validation.NewStringRule(govalidator.IsCreditCard, "must be a valid credit card number") + // ISBN10 validates if a string is an ISBN version 10 + ISBN10 = validation.NewStringRule(govalidator.IsISBN10, "must be a valid ISBN-10") + // ISBN13 validates if a string is an ISBN version 13 + ISBN13 = validation.NewStringRule(govalidator.IsISBN13, "must be a valid ISBN-13") + // ISBN validates if a string is an ISBN (either version 10 or 13) + ISBN = validation.NewStringRule(isISBN, "must be a valid ISBN") + // JSON validates if a string is in valid JSON format + JSON = validation.NewStringRule(govalidator.IsJSON, "must be in valid JSON format") + // ASCII validates if a string contains ASCII characters only + ASCII = validation.NewStringRule(govalidator.IsASCII, "must contain ASCII characters only") + // PrintableASCII validates if a string contains printable ASCII characters only + PrintableASCII = validation.NewStringRule(govalidator.IsPrintableASCII, "must contain printable ASCII characters only") + // Multibyte validates if a string contains multibyte characters + Multibyte = validation.NewStringRule(govalidator.IsMultibyte, "must contain multibyte characters") + // FullWidth validates if a string contains full-width characters + FullWidth = validation.NewStringRule(govalidator.IsFullWidth, "must contain full-width characters") + // HalfWidth validates if a string contains half-width characters + HalfWidth = validation.NewStringRule(govalidator.IsHalfWidth, "must contain half-width characters") + // VariableWidth validates if a string contains both full-width and half-width characters + VariableWidth = validation.NewStringRule(govalidator.IsVariableWidth, "must contain both full-width and half-width characters") + // Base64 validates if a string is encoded in Base64 + Base64 = validation.NewStringRule(govalidator.IsBase64, "must be encoded in Base64") + // DataURI validates if a string is a valid base64-encoded data URI + DataURI = validation.NewStringRule(govalidator.IsDataURI, "must be a Base64-encoded data URI") + // E164 validates if a string is a valid ISO3166 Alpha 2 country code + E164 = validation.NewStringRule(isE164Number, "must be a valid E164 number") + // CountryCode2 validates if a string is a valid ISO3166 Alpha 2 country code + CountryCode2 = validation.NewStringRule(govalidator.IsISO3166Alpha2, "must be a valid two-letter country code") + // CountryCode3 validates if a string is a valid ISO3166 Alpha 3 country code + CountryCode3 = validation.NewStringRule(govalidator.IsISO3166Alpha3, "must be a valid three-letter country code") + // CurrencyCode validates if a string is a valid IsISO4217 currency code. + CurrencyCode = validation.NewStringRule(govalidator.IsISO4217, "must be valid ISO 4217 currency code") + // DialString validates if a string is a valid dial string that can be passed to Dial() + DialString = validation.NewStringRule(govalidator.IsDialString, "must be a valid dial string") + // MAC validates if a string is a MAC address + MAC = validation.NewStringRule(govalidator.IsMAC, "must be a valid MAC address") + // IP validates if a string is a valid IP address (either version 4 or 6) + IP = validation.NewStringRule(govalidator.IsIP, "must be a valid IP address") + // IPv4 validates if a string is a valid version 4 IP address + IPv4 = validation.NewStringRule(govalidator.IsIPv4, "must be a valid IPv4 address") + // IPv6 validates if a string is a valid version 6 IP address + IPv6 = validation.NewStringRule(govalidator.IsIPv6, "must be a valid IPv6 address") + // Subdomain validates if a string is valid subdomain + Subdomain = validation.NewStringRule(isSubdomain, "must be a valid subdomain") + // Domain validates if a string is valid domain + Domain = validation.NewStringRule(isDomain, "must be a valid domain") + // DNSName validates if a string is valid DNS name + DNSName = validation.NewStringRule(govalidator.IsDNSName, "must be a valid DNS name") + // Host validates if a string is a valid IP (both v4 and v6) or a valid DNS name + Host = validation.NewStringRule(govalidator.IsHost, "must be a valid IP address or DNS name") + // Port validates if a string is a valid port number + Port = validation.NewStringRule(govalidator.IsPort, "must be a valid port number") + // MongoID validates if a string is a valid Mongo ID + MongoID = validation.NewStringRule(govalidator.IsMongoID, "must be a valid hex-encoded MongoDB ObjectId") + // Latitude validates if a string is a valid latitude + Latitude = validation.NewStringRule(govalidator.IsLatitude, "must be a valid latitude") + // Longitude validates if a string is a valid longitude + Longitude = validation.NewStringRule(govalidator.IsLongitude, "must be a valid longitude") + // SSN validates if a string is a social security number (SSN) + SSN = validation.NewStringRule(govalidator.IsSSN, "must be a valid social security number") + // Semver validates if a string is a valid semantic version + Semver = validation.NewStringRule(govalidator.IsSemver, "must be a valid semantic version") ) var ( reDigit = regexp.MustCompile("^[0-9]+$") + // Subdomain regex source: https://stackoverflow.com/a/7933253 + reSubdomain = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9\-]{0,61}[A-Za-z0-9])?$`) + // E164 regex source: https://stackoverflow.com/a/23299989 + reE164 = regexp.MustCompile(`^\+?[1-9]\d{1,14}$`) + // Domain regex source: https://stackoverflow.com/a/7933253 + // Slightly modified: Removed 255 max length validation since Go regex does not + // support lookarounds. More info: https://stackoverflow.com/a/38935027 + reDomain = regexp.MustCompile(`^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+(?:[a-z]{1,63}| xn--[a-z0-9]{1,59})$`) ) func isISBN(value string) bool { + return govalidator.IsISBN(value, 10) || govalidator.IsISBN(value, 13) + } func isDigit(value string) bool { + return reDigit.MatchString(value) + } func isE164Number(value string) bool { + return reE164.MatchString(value) + } func isSubdomain(value string) bool { + return reSubdomain.MatchString(value) + } func isDomain(value string) bool { + if len(value) > 255 { + return false + } return reDomain.MatchString(value) + } func isUTFNumeric(value string) bool { + for _, c := range value { + if unicode.IsNumber(c) == false { + return false + } + } + return true + } diff --git a/vendor/github.com/go-ozzo/ozzo-validation/length.go b/vendor/github.com/go-ozzo/ozzo-validation/length.go index d5effdf..7c13d31 100644 --- a/vendor/github.com/go-ozzo/ozzo-validation/length.go +++ b/vendor/github.com/go-ozzo/ozzo-validation/length.go @@ -1,5 +1,7 @@ // Copyright 2016 Qiang Xue. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package validation @@ -11,71 +13,122 @@ import ( ) // Length returns a validation rule that checks if a value's length is within the specified range. + // If max is 0, it means there is no upper bound for the length. + // This rule should only be used for validating strings, slices, maps, and arrays. + // An empty value is considered valid. Use the Required rule to make sure a value is not empty. + func Length(min, max int) *LengthRule { + message := "the value must be empty" + if min == 0 && max > 0 { + message = fmt.Sprintf("the length must be no more than %v", max) + } else if min > 0 && max == 0 { + message = fmt.Sprintf("the length must be no less than %v", min) + } else if min > 0 && max > 0 { + if min == max { + message = fmt.Sprintf("the length must be exactly %v", min) + } else { + message = fmt.Sprintf("the length must be between %v and %v", min, max) + } + } + return &LengthRule{ - min: min, - max: max, + + min: min, + + max: max, + message: message, } + } // RuneLength returns a validation rule that checks if a string's rune length is within the specified range. + // If max is 0, it means there is no upper bound for the length. + // This rule should only be used for validating strings, slices, maps, and arrays. + // An empty value is considered valid. Use the Required rule to make sure a value is not empty. + // If the value being validated is not a string, the rule works the same as Length. + func RuneLength(min, max int) *LengthRule { + r := Length(min, max) + r.rune = true + return r + } type LengthRule struct { min, max int - message string - rune bool + + message string + + rune bool } // Validate checks if the given value is valid or not. + func (v *LengthRule) Validate(value interface{}) error { + value, isNil := Indirect(value) + if isNil || IsEmpty(value) { + return nil + } var ( - l int + l int + err error ) + if s, ok := value.(string); ok && v.rune { + l = utf8.RuneCountInString(s) + } else if l, err = LengthOfValue(value); err != nil { + return err + } if v.min > 0 && l < v.min || v.max > 0 && l > v.max { + return errors.New(v.message) + } + return nil + } // Error sets the error message for the rule. + func (v *LengthRule) Error(message string) *LengthRule { + v.message = message + return v + } diff --git a/vendor/github.com/go-ozzo/ozzo-validation/match.go b/vendor/github.com/go-ozzo/ozzo-validation/match.go index 4a842be..bd547a6 100644 --- a/vendor/github.com/go-ozzo/ozzo-validation/match.go +++ b/vendor/github.com/go-ozzo/ozzo-validation/match.go @@ -1,5 +1,7 @@ // Copyright 2016 Qiang Xue. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package validation @@ -10,38 +12,62 @@ import ( ) // Match returns a validation rule that checks if a value matches the specified regular expression. + // This rule should only be used for validating strings and byte slices, or a validation error will be reported. + // An empty value is considered valid. Use the Required rule to make sure a value is not empty. + func Match(re *regexp.Regexp) *MatchRule { + return &MatchRule{ - re: re, + + re: re, + message: "must be in a valid format", } + } type MatchRule struct { - re *regexp.Regexp + re *regexp.Regexp + message string } // Validate checks if the given value is valid or not. + func (v *MatchRule) Validate(value interface{}) error { + value, isNil := Indirect(value) + if isNil { + return nil + } isString, str, isBytes, bs := StringOrBytes(value) + if isString && (str == "" || v.re.MatchString(str)) { + return nil + } else if isBytes && (len(bs) == 0 || v.re.Match(bs)) { + return nil + } + return errors.New(v.message) + } // Error sets the error message for the rule. + func (v *MatchRule) Error(message string) *MatchRule { + v.message = message + return v + } diff --git a/vendor/github.com/go-ozzo/ozzo-validation/minmax.go b/vendor/github.com/go-ozzo/ozzo-validation/minmax.go index 5eded0a..e288110 100644 --- a/vendor/github.com/go-ozzo/ozzo-validation/minmax.go +++ b/vendor/github.com/go-ozzo/ozzo-validation/minmax.go @@ -1,5 +1,7 @@ // Copyright 2016 Qiang Xue. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package validation @@ -13,165 +15,290 @@ import ( type ThresholdRule struct { threshold interface{} - operator int - message string + + operator int + + message string } const ( greaterThan = iota + greaterEqualThan + lessThan + lessEqualThan ) // Min is a validation rule that checks if a value is greater or equal than the specified value. + // By calling Exclusive, the rule will check if the value is strictly greater than the specified value. + // Note that the value being checked and the threshold value must be of the same type. + // Only int, uint, float and time.Time types are supported. + // An empty value is considered valid. Please use the Required rule to make sure a value is not empty. + func Min(min interface{}) *ThresholdRule { + return &ThresholdRule{ + threshold: min, - operator: greaterEqualThan, - message: fmt.Sprintf("must be no less than %v", min), + + operator: greaterEqualThan, + + message: fmt.Sprintf("must be no less than %v", min), } + } // Max is a validation rule that checks if a value is less or equal than the specified value. + // By calling Exclusive, the rule will check if the value is strictly less than the specified value. + // Note that the value being checked and the threshold value must be of the same type. + // Only int, uint, float and time.Time types are supported. + // An empty value is considered valid. Please use the Required rule to make sure a value is not empty. + func Max(max interface{}) *ThresholdRule { + return &ThresholdRule{ + threshold: max, - operator: lessEqualThan, - message: fmt.Sprintf("must be no greater than %v", max), + + operator: lessEqualThan, + + message: fmt.Sprintf("must be no greater than %v", max), } + } // Exclusive sets the comparison to exclude the boundary value. + func (r *ThresholdRule) Exclusive() *ThresholdRule { + if r.operator == greaterEqualThan { + r.operator = greaterThan + r.message = fmt.Sprintf("must be greater than %v", r.threshold) + } else if r.operator == lessEqualThan { + r.operator = lessThan + r.message = fmt.Sprintf("must be less than %v", r.threshold) + } + return r + } // Validate checks if the given value is valid or not. + func (r *ThresholdRule) Validate(value interface{}) error { + value, isNil := Indirect(value) + if isNil || IsEmpty(value) { + return nil + } rv := reflect.ValueOf(r.threshold) + switch rv.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + v, err := ToInt(value) + if err != nil { + return err + } + if r.compareInt(rv.Int(), v) { + return nil + } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + v, err := ToUint(value) + if err != nil { + return err + } + if r.compareUint(rv.Uint(), v) { + return nil + } case reflect.Float32, reflect.Float64: + v, err := ToFloat(value) + if err != nil { + return err + } + if r.compareFloat(rv.Float(), v) { + return nil + } case reflect.Struct: + t, ok := r.threshold.(time.Time) + if !ok { + return fmt.Errorf("type not supported: %v", rv.Type()) + } + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("cannot convert %v to time.Time", reflect.TypeOf(value)) + } + if v.IsZero() || r.compareTime(t, v) { + return nil + } default: + return fmt.Errorf("type not supported: %v", rv.Type()) + } return errors.New(r.message) + } // Error sets the error message for the rule. + func (r *ThresholdRule) Error(message string) *ThresholdRule { + r.message = message + return r + } func (r *ThresholdRule) compareInt(threshold, value int64) bool { + switch r.operator { + case greaterThan: + return value > threshold + case greaterEqualThan: + return value >= threshold + case lessThan: + return value < threshold + default: + return value <= threshold + } + } func (r *ThresholdRule) compareUint(threshold, value uint64) bool { + switch r.operator { + case greaterThan: + return value > threshold + case greaterEqualThan: + return value >= threshold + case lessThan: + return value < threshold + default: + return value <= threshold + } + } func (r *ThresholdRule) compareFloat(threshold, value float64) bool { + switch r.operator { + case greaterThan: + return value > threshold + case greaterEqualThan: + return value >= threshold + case lessThan: + return value < threshold + default: + return value <= threshold + } + } func (r *ThresholdRule) compareTime(threshold, value time.Time) bool { + switch r.operator { + case greaterThan: + return value.After(threshold) + case greaterEqualThan: + return value.After(threshold) || value.Equal(threshold) + case lessThan: + return value.Before(threshold) + default: + return value.Before(threshold) || value.Equal(threshold) + } + } diff --git a/vendor/github.com/go-ozzo/ozzo-validation/multipleof.go b/vendor/github.com/go-ozzo/ozzo-validation/multipleof.go index da3ed94..7a59088 100644 --- a/vendor/github.com/go-ozzo/ozzo-validation/multipleof.go +++ b/vendor/github.com/go-ozzo/ozzo-validation/multipleof.go @@ -7,48 +7,76 @@ import ( ) func MultipleOf(threshold interface{}) *multipleOfRule { + return &multipleOfRule{ + threshold, + fmt.Sprintf("must be multiple of %v", threshold), } + } type multipleOfRule struct { threshold interface{} - message string + + message string } // Error sets the error message for the rule. + func (r *multipleOfRule) Error(message string) *multipleOfRule { + r.message = message + return r + } func (r *multipleOfRule) Validate(value interface{}) error { rv := reflect.ValueOf(r.threshold) + switch rv.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + v, err := ToInt(value) + if err != nil { + return err + } + if v%rv.Int() == 0 { + return nil + } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + v, err := ToUint(value) + if err != nil { + return err + } if v%rv.Uint() == 0 { + return nil + } + default: + return fmt.Errorf("type not supported: %v", rv.Type()) + } return errors.New(r.message) + } diff --git a/vendor/github.com/go-ozzo/ozzo-validation/struct.go b/vendor/github.com/go-ozzo/ozzo-validation/struct.go index d380029..237b8f2 100644 --- a/vendor/github.com/go-ozzo/ozzo-validation/struct.go +++ b/vendor/github.com/go-ozzo/ozzo-validation/struct.go @@ -1,5 +1,7 @@ // Copyright 2016 Qiang Xue. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package validation @@ -12,143 +14,254 @@ import ( ) var ( + // ErrStructPointer is the error that a struct being validated is not specified as a pointer. + ErrStructPointer = errors.New("only a pointer to a struct can be validated") ) type ( + // ErrFieldPointer is the error that a field is not specified as a pointer. + ErrFieldPointer int // ErrFieldNotFound is the error that a field cannot be found in the struct. + ErrFieldNotFound int // FieldRules represents a rule set associated with a struct field. + FieldRules struct { fieldPtr interface{} - rules []Rule + + rules []Rule } ) // Error returns the error string of ErrFieldPointer. + func (e ErrFieldPointer) Error() string { + return fmt.Sprintf("field #%v must be specified as a pointer", int(e)) + } // Error returns the error string of ErrFieldNotFound. + func (e ErrFieldNotFound) Error() string { + return fmt.Sprintf("field #%v cannot be found in the struct", int(e)) + } // ValidateStruct validates a struct by checking the specified struct fields against the corresponding validation rules. + // Note that the struct being validated must be specified as a pointer to it. If the pointer is nil, it is considered valid. + // Use Field() to specify struct fields that need to be validated. Each Field() call specifies a single field which + // should be specified as a pointer to the field. A field can be associated with multiple rules. + // For example, + // + // value := struct { + // Name string + // Value string + // }{"name", "demo"} + // err := validation.ValidateStruct(&value, + // validation.Field(&a.Name, validation.Required), + // validation.Field(&a.Value, validation.Required, validation.Length(5, 10)), + // ) + // fmt.Println(err) + // // Value: the length must be between 5 and 10. + // + // An error will be returned if validation fails. + func ValidateStruct(structPtr interface{}, fields ...*FieldRules) error { + value := reflect.ValueOf(structPtr) + if value.Kind() != reflect.Ptr || !value.IsNil() && value.Elem().Kind() != reflect.Struct { + // must be a pointer to a struct + return NewInternalError(ErrStructPointer) + } + if value.IsNil() { + // treat a nil struct pointer as valid + return nil + } + value = value.Elem() errs := Errors{} for i, fr := range fields { + fv := reflect.ValueOf(fr.fieldPtr) + if fv.Kind() != reflect.Ptr { + return NewInternalError(ErrFieldPointer(i)) + } + ft := findStructField(value, fv) + if ft == nil { + return NewInternalError(ErrFieldNotFound(i)) + } + if err := Validate(fv.Elem().Interface(), fr.rules...); err != nil { + if ie, ok := err.(InternalError); ok && ie.InternalError() != nil { + return err + } + if ft.Anonymous { + // merge errors from anonymous struct field + if es, ok := err.(Errors); ok { + for name, value := range es { + errs[name] = value + } + continue + } + } + errs[getErrorFieldName(ft)] = err + } + } if len(errs) > 0 { + return errs + } + return nil + } // Field specifies a struct field and the corresponding validation rules. + // The struct field must be specified as a pointer to it. + func Field(fieldPtr interface{}, rules ...Rule) *FieldRules { + return &FieldRules{ + fieldPtr: fieldPtr, - rules: rules, + + rules: rules, } + } // findStructField looks for a field in the given struct. + // The field being looked for should be a pointer to the actual struct field. + // If found, the field info will be returned. Otherwise, nil will be returned. + func findStructField(structValue reflect.Value, fieldValue reflect.Value) *reflect.StructField { + ptr := fieldValue.Pointer() + for i := structValue.NumField() - 1; i >= 0; i-- { + sf := structValue.Type().Field(i) + if ptr == structValue.Field(i).UnsafeAddr() { + // do additional type comparison because it's possible that the address of + // an embedded struct is the same as the first field of the embedded struct + if sf.Type == fieldValue.Elem().Type() { + return &sf + } + } + if sf.Anonymous { + // delve into anonymous struct to look for the field + fi := structValue.Field(i) + if sf.Type.Kind() == reflect.Ptr { + fi = fi.Elem() + } + if fi.Kind() == reflect.Struct { + if f := findStructField(fi, fieldValue); f != nil { + return f + } + } + } + } + return nil + } // getErrorFieldName returns the name that should be used to represent the validation error of a struct field. + func getErrorFieldName(f *reflect.StructField) string { + if tag := f.Tag.Get(ErrorTag); tag != "" { + if cps := strings.SplitN(tag, ",", 2); cps[0] != "" { + return cps[0] + } + } + return f.Name + } diff --git a/vendor/github.com/go-ozzo/ozzo-validation/util.go b/vendor/github.com/go-ozzo/ozzo-validation/util.go index b15fd9a..8db818b 100644 --- a/vendor/github.com/go-ozzo/ozzo-validation/util.go +++ b/vendor/github.com/go-ozzo/ozzo-validation/util.go @@ -1,5 +1,7 @@ // Copyright 2016 Qiang Xue. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package validation @@ -13,151 +15,273 @@ import ( ) var ( - bytesType = reflect.TypeOf([]byte(nil)) + bytesType = reflect.TypeOf([]byte(nil)) + valuerType = reflect.TypeOf((*driver.Valuer)(nil)).Elem() ) // EnsureString ensures the given value is a string. + // If the value is a byte slice, it will be typecast into a string. + // An error is returned otherwise. + func EnsureString(value interface{}) (string, error) { + v := reflect.ValueOf(value) + if v.Kind() == reflect.String { + return v.String(), nil + } + if v.Type() == bytesType { + return string(v.Interface().([]byte)), nil + } + return "", errors.New("must be either a string or byte slice") + } // StringOrBytes typecasts a value into a string or byte slice. + // Boolean flags are returned to indicate if the typecasting succeeds or not. + func StringOrBytes(value interface{}) (isString bool, str string, isBytes bool, bs []byte) { + v := reflect.ValueOf(value) + if v.Kind() == reflect.String { + str = v.String() + isString = true + } else if v.Kind() == reflect.Slice && v.Type() == bytesType { + bs = v.Interface().([]byte) + isBytes = true + } + return + } // LengthOfValue returns the length of a value that is a string, slice, map, or array. + // An error is returned for all other types. + func LengthOfValue(value interface{}) (int, error) { + v := reflect.ValueOf(value) + switch v.Kind() { + case reflect.String, reflect.Slice, reflect.Map, reflect.Array: + return v.Len(), nil + } + return 0, fmt.Errorf("cannot get the length of %v", v.Kind()) + } // ToInt converts the given value to an int64. + // An error is returned for all incompatible types. + func ToInt(value interface{}) (int64, error) { + v := reflect.ValueOf(value) + switch v.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int(), nil + } + return 0, fmt.Errorf("cannot convert %v to int64", v.Kind()) + } // ToUint converts the given value to an uint64. + // An error is returned for all incompatible types. + func ToUint(value interface{}) (uint64, error) { + v := reflect.ValueOf(value) + switch v.Kind() { + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint(), nil + } + return 0, fmt.Errorf("cannot convert %v to uint64", v.Kind()) + } // ToFloat converts the given value to a float64. + // An error is returned for all incompatible types. + func ToFloat(value interface{}) (float64, error) { + v := reflect.ValueOf(value) + switch v.Kind() { + case reflect.Float32, reflect.Float64: + return v.Float(), nil + } + return 0, fmt.Errorf("cannot convert %v to float64", v.Kind()) + } // IsEmpty checks if a value is empty or not. + // A value is considered empty if + // - integer, float: zero + // - bool: false + // - string, array: len() == 0 + // - slice, map: nil or len() == 0 + // - interface, pointer: nil or the referenced value is empty + func IsEmpty(value interface{}) bool { + v := reflect.ValueOf(value) + switch v.Kind() { + case reflect.String, reflect.Array, reflect.Map, reflect.Slice: + return v.Len() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Invalid: + return true + case reflect.Interface, reflect.Ptr: + if v.IsNil() { + return true + } + return IsEmpty(v.Elem().Interface()) + case reflect.Struct: + v, ok := value.(time.Time) + if ok && v.IsZero() { + return true + } + } return false + } // Indirect returns the value that the given interface or pointer references to. + // If the value implements driver.Valuer, it will deal with the value returned by + // the Value() method instead. A boolean value is also returned to indicate if + // the value is nil or not (only applicable to interface, pointer, map, and slice). + // If the value is neither an interface nor a pointer, it will be returned back. + func Indirect(value interface{}) (interface{}, bool) { + rv := reflect.ValueOf(value) + kind := rv.Kind() + switch kind { + case reflect.Invalid: + return nil, true + case reflect.Ptr, reflect.Interface: + if rv.IsNil() { + return nil, true + } + return Indirect(rv.Elem().Interface()) + case reflect.Slice, reflect.Map, reflect.Func, reflect.Chan: + if rv.IsNil() { + return nil, true + } + } if rv.Type().Implements(valuerType) { + return indirectValuer(value.(driver.Valuer)) + } return value, false + } func indirectValuer(valuer driver.Valuer) (interface{}, bool) { + if value, err := valuer.Value(); value != nil && err == nil { + return Indirect(value) + } + return nil, true + } diff --git a/vendor/github.com/go-ozzo/ozzo-validation/v4/each.go b/vendor/github.com/go-ozzo/ozzo-validation/v4/each.go index 2cc7253..59b3593 100644 --- a/vendor/github.com/go-ozzo/ozzo-validation/v4/each.go +++ b/vendor/github.com/go-ozzo/ozzo-validation/v4/each.go @@ -1,5 +1,7 @@ // Copyright 2016 Qiang Xue. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package validation @@ -12,86 +14,152 @@ import ( ) // Each returns a validation rule that loops through an iterable (map, slice or array) + // and validates each value inside with the provided rules. + // An empty iterable is considered valid. Use the Required rule to make sure the iterable is not empty. + func Each(rules ...Rule) EachRule { + return EachRule{ + rules: rules, } + } // EachRule is a validation rule that validates elements in a map/slice/array using the specified list of rules. + type EachRule struct { rules []Rule } // Validate loops through the given iterable and calls the Ozzo Validate() method for each value. + func (r EachRule) Validate(value interface{}) error { + return r.ValidateWithContext(nil, value) + } // ValidateWithContext loops through the given iterable and calls the Ozzo ValidateWithContext() method for each value. + func (r EachRule) ValidateWithContext(ctx context.Context, value interface{}) error { + errs := Errors{} v := reflect.ValueOf(value) + switch v.Kind() { + case reflect.Map: + for _, k := range v.MapKeys() { + val := r.getInterface(v.MapIndex(k)) + var err error + if ctx == nil { + err = Validate(val, r.rules...) + } else { + err = ValidateWithContext(ctx, val, r.rules...) + } + if err != nil { + errs[r.getString(k)] = err + } + } + case reflect.Slice, reflect.Array: + for i := 0; i < v.Len(); i++ { + val := r.getInterface(v.Index(i)) + var err error + if ctx == nil { + err = Validate(val, r.rules...) + } else { + err = ValidateWithContext(ctx, val, r.rules...) + } + if err != nil { + errs[strconv.Itoa(i)] = err + } + } + default: + return errors.New("must be an iterable (map, slice or array)") + } if len(errs) > 0 { + return errs + } + return nil + } func (r EachRule) getInterface(value reflect.Value) interface{} { + switch value.Kind() { + case reflect.Ptr, reflect.Interface: + if value.IsNil() { + return nil + } + return value.Elem().Interface() + default: + return value.Interface() + } + } func (r EachRule) getString(value reflect.Value) string { + switch value.Kind() { + case reflect.Ptr, reflect.Interface: + if value.IsNil() { + return "" + } + return value.Elem().String() + default: + return value.String() + } + } diff --git a/vendor/github.com/go-ozzo/ozzo-validation/v4/error.go b/vendor/github.com/go-ozzo/ozzo-validation/v4/error.go index e75b1de..3c0df66 100644 --- a/vendor/github.com/go-ozzo/ozzo-validation/v4/error.go +++ b/vendor/github.com/go-ozzo/ozzo-validation/v4/error.go @@ -1,5 +1,7 @@ // Copyright 2016 Qiang Xue. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package validation @@ -14,31 +16,46 @@ import ( ) type ( + // Error interface represents an validation error + Error interface { Error() string + Code() string + Message() string + SetMessage(string) Error + Params() map[string]interface{} + SetParams(map[string]interface{}) Error } // ErrorObject is the default validation error + // that implements the Error interface. + ErrorObject struct { - code string + code string + message string - params map[string]interface{} + + params map[string]interface{} } // Errors represents the validation errors that are indexed by struct field names, map or slice keys. + // values are Error or Errors (for map, slice and array error value is Errors). + Errors map[string]error // InternalError represents an error that should NOT be treated as a validation error. + InternalError interface { error + InternalError() error } @@ -48,133 +65,224 @@ type ( ) // NewInternalError wraps a given error into an InternalError. + func NewInternalError(err error) InternalError { + return internalError{error: err} + } // InternalError returns the actual error that it wraps around. + func (e internalError) InternalError() error { + return e.error + } // SetCode set the error's translation code. + func (e ErrorObject) SetCode(code string) Error { + e.code = code + return e + } // Code get the error's translation code. + func (e ErrorObject) Code() string { + return e.code + } // SetParams set the error's params. + func (e ErrorObject) SetParams(params map[string]interface{}) Error { + e.params = params + return e + } // AddParam add parameter to the error's parameters. + func (e ErrorObject) AddParam(name string, value interface{}) Error { + if e.params == nil { + e.params = make(map[string]interface{}) + } e.params[name] = value + return e + } // Params returns the error's params. + func (e ErrorObject) Params() map[string]interface{} { + return e.params + } // SetMessage set the error's message. + func (e ErrorObject) SetMessage(message string) Error { + e.message = message + return e + } // Message return the error's message. + func (e ErrorObject) Message() string { + return e.message + } // Error returns the error message. + func (e ErrorObject) Error() string { + if len(e.params) == 0 { + return e.message + } res := bytes.Buffer{} + _ = template.Must(template.New("err").Parse(e.message)).Execute(&res, e.params) return res.String() + } // Error returns the error string of Errors. + func (es Errors) Error() string { + if len(es) == 0 { + return "" + } keys := make([]string, len(es)) + i := 0 + for key := range es { + keys[i] = key + i++ + } + sort.Strings(keys) var s strings.Builder + for i, key := range keys { + if i > 0 { + s.WriteString("; ") + } + if errs, ok := es[key].(Errors); ok { + _, _ = fmt.Fprintf(&s, "%v: (%v)", key, errs) + } else { + _, _ = fmt.Fprintf(&s, "%v: %v", key, es[key].Error()) + } + } + s.WriteString(".") + return s.String() + } // MarshalJSON converts the Errors into a valid JSON. + func (es Errors) MarshalJSON() ([]byte, error) { + errs := map[string]interface{}{} + for key, err := range es { + if ms, ok := err.(json.Marshaler); ok { + errs[key] = ms + } else { + errs[key] = err.Error() + } + } + return json.Marshal(errs) + } // Filter removes all nils from Errors and returns back the updated Errors as an error. + // If the length of Errors becomes 0, it will return nil. + func (es Errors) Filter() error { + for key, value := range es { + if value == nil { + delete(es, key) + } + } + if len(es) == 0 { + return nil + } + return es + } // NewError create new validation error. + func NewError(code, message string) Error { + return ErrorObject{ - code: code, + + code: code, + message: message, } + } // Assert that our ErrorObject implements the Error interface. + var _ Error = ErrorObject{} diff --git a/vendor/github.com/go-ozzo/ozzo-validation/v4/map.go b/vendor/github.com/go-ozzo/ozzo-validation/v4/map.go index b3a87bd..b983305 100644 --- a/vendor/github.com/go-ozzo/ozzo-validation/v4/map.go +++ b/vendor/github.com/go-ozzo/ozzo-validation/v4/map.go @@ -8,138 +8,232 @@ import ( ) var ( + // ErrNotMap is the error that the value being validated is not a map. + ErrNotMap = errors.New("only a map can be validated") // ErrKeyWrongType is the error returned in case of an incorrect key type. + ErrKeyWrongType = NewError("validation_key_wrong_type", "key not the correct type") // ErrKeyMissing is the error returned in case of a missing key. + ErrKeyMissing = NewError("validation_key_missing", "required key is missing") // ErrKeyUnexpected is the error returned in case of an unexpected key. + ErrKeyUnexpected = NewError("validation_key_unexpected", "key not expected") ) type ( + // MapRule represents a rule set associated with a map. + MapRule struct { - keys []*KeyRules + keys []*KeyRules + allowExtraKeys bool } // KeyRules represents a rule set associated with a map key. + KeyRules struct { - key interface{} + key interface{} + optional bool - rules []Rule + + rules []Rule } ) // Map returns a validation rule that checks the keys and values of a map. + // This rule should only be used for validating maps, or a validation error will be reported. + // Use Key() to specify map keys that need to be validated. Each Key() call specifies a single key which can + // be associated with multiple rules. + // For example, + // + // validation.Map( + // validation.Key("Name", validation.Required), + // validation.Key("Value", validation.Required, validation.Length(5, 10)), + // ) + // + // A nil value is considered valid. Use the Required rule to make sure a map value is present. + func Map(keys ...*KeyRules) MapRule { + return MapRule{keys: keys} + } // AllowExtraKeys configures the rule to ignore extra keys. + func (r MapRule) AllowExtraKeys() MapRule { + r.allowExtraKeys = true + return r + } // Validate checks if the given value is valid or not. + func (r MapRule) Validate(m interface{}) error { + return r.ValidateWithContext(nil, m) + } // ValidateWithContext checks if the given value is valid or not. + func (r MapRule) ValidateWithContext(ctx context.Context, m interface{}) error { + value := reflect.ValueOf(m) + if value.Kind() == reflect.Ptr { + value = value.Elem() + } + if value.Kind() != reflect.Map { + // must be a map + return NewInternalError(ErrNotMap) + } + if value.IsNil() { + // treat a nil map as valid + return nil + } errs := Errors{} + kt := value.Type().Key() var extraKeys map[interface{}]bool + if !r.allowExtraKeys { + extraKeys = make(map[interface{}]bool, value.Len()) + for _, k := range value.MapKeys() { + extraKeys[k.Interface()] = true + } + } for _, kr := range r.keys { + var err error + if kv := reflect.ValueOf(kr.key); !kt.AssignableTo(kv.Type()) { + err = ErrKeyWrongType + } else if vv := value.MapIndex(kv); !vv.IsValid() { + if !kr.optional { + err = ErrKeyMissing + } + } else if ctx == nil { + err = Validate(vv.Interface(), kr.rules...) + } else { + err = ValidateWithContext(ctx, vv.Interface(), kr.rules...) + } + if err != nil { + if ie, ok := err.(InternalError); ok && ie.InternalError() != nil { + return err + } + errs[getErrorKeyName(kr.key)] = err + } + if !r.allowExtraKeys { + delete(extraKeys, kr.key) + } + } if !r.allowExtraKeys { + for key := range extraKeys { + errs[getErrorKeyName(key)] = ErrKeyUnexpected + } + } if len(errs) > 0 { + return errs + } + return nil + } // Key specifies a map key and the corresponding validation rules. + func Key(key interface{}, rules ...Rule) *KeyRules { + return &KeyRules{ - key: key, + + key: key, + rules: rules, } + } // Optional configures the rule to ignore the key if missing. + func (r *KeyRules) Optional() *KeyRules { + r.optional = true + return r + } // getErrorKeyName returns the name that should be used to represent the validation error of a map key. + func getErrorKeyName(key interface{}) string { + return fmt.Sprintf("%v", key) + } diff --git a/vendor/github.com/go-ozzo/ozzo-validation/v4/minmax.go b/vendor/github.com/go-ozzo/ozzo-validation/v4/minmax.go index f2a119f..b28ce3b 100644 --- a/vendor/github.com/go-ozzo/ozzo-validation/v4/minmax.go +++ b/vendor/github.com/go-ozzo/ozzo-validation/v4/minmax.go @@ -1,5 +1,7 @@ // Copyright 2016 Qiang Xue. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package validation @@ -11,185 +13,322 @@ import ( ) var ( + // ErrMinGreaterEqualThanRequired is the error that returns when a value is less than a specified threshold. + ErrMinGreaterEqualThanRequired = NewError("validation_min_greater_equal_than_required", "must be no less than {{.threshold}}") + // ErrMaxLessEqualThanRequired is the error that returns when a value is greater than a specified threshold. + ErrMaxLessEqualThanRequired = NewError("validation_max_less_equal_than_required", "must be no greater than {{.threshold}}") + // ErrMinGreaterThanRequired is the error that returns when a value is less than or equal to a specified threshold. + ErrMinGreaterThanRequired = NewError("validation_min_greater_than_required", "must be greater than {{.threshold}}") + // ErrMaxLessThanRequired is the error that returns when a value is greater than or equal to a specified threshold. + ErrMaxLessThanRequired = NewError("validation_max_less_than_required", "must be less than {{.threshold}}") ) // ThresholdRule is a validation rule that checks if a value satisfies the specified threshold requirement. + type ThresholdRule struct { threshold interface{} - operator int - err Error + + operator int + + err Error } const ( greaterThan = iota + greaterEqualThan + lessThan + lessEqualThan ) // Min returns a validation rule that checks if a value is greater or equal than the specified value. + // By calling Exclusive, the rule will check if the value is strictly greater than the specified value. + // Note that the value being checked and the threshold value must be of the same type. + // Only int, uint, float and time.Time types are supported. + // An empty value is considered valid. Please use the Required rule to make sure a value is not empty. + func Min(min interface{}) ThresholdRule { + return ThresholdRule{ + threshold: min, - operator: greaterEqualThan, - err: ErrMinGreaterEqualThanRequired, + + operator: greaterEqualThan, + + err: ErrMinGreaterEqualThanRequired, } } // Max returns a validation rule that checks if a value is less or equal than the specified value. + // By calling Exclusive, the rule will check if the value is strictly less than the specified value. + // Note that the value being checked and the threshold value must be of the same type. + // Only int, uint, float and time.Time types are supported. + // An empty value is considered valid. Please use the Required rule to make sure a value is not empty. + func Max(max interface{}) ThresholdRule { + return ThresholdRule{ + threshold: max, - operator: lessEqualThan, - err: ErrMaxLessEqualThanRequired, + + operator: lessEqualThan, + + err: ErrMaxLessEqualThanRequired, } + } // Exclusive sets the comparison to exclude the boundary value. + func (r ThresholdRule) Exclusive() ThresholdRule { + if r.operator == greaterEqualThan { + r.operator = greaterThan + r.err = ErrMinGreaterThanRequired + } else if r.operator == lessEqualThan { + r.operator = lessThan + r.err = ErrMaxLessThanRequired + } + return r + } // Validate checks if the given value is valid or not. + func (r ThresholdRule) Validate(value interface{}) error { + value, isNil := Indirect(value) + if isNil || IsEmpty(value) { + return nil + } rv := reflect.ValueOf(r.threshold) + switch rv.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + v, err := ToInt(value) + if err != nil { + return err + } + if r.compareInt(rv.Int(), v) { + return nil + } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + v, err := ToUint(value) + if err != nil { + return err + } + if r.compareUint(rv.Uint(), v) { + return nil + } case reflect.Float32, reflect.Float64: + v, err := ToFloat(value) + if err != nil { + return err + } + if r.compareFloat(rv.Float(), v) { + return nil + } case reflect.Struct: + t, ok := r.threshold.(time.Time) + if !ok { + return fmt.Errorf("type not supported: %v", rv.Type()) + } + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("cannot convert %v to time.Time", reflect.TypeOf(value)) + } + if v.IsZero() || r.compareTime(t, v) { + return nil + } default: + return fmt.Errorf("type not supported: %v", rv.Type()) + } return r.err.SetParams(map[string]interface{}{"threshold": r.threshold}) + } // Error sets the error message for the rule. + func (r ThresholdRule) Error(message string) ThresholdRule { + r.err = r.err.SetMessage(message) + return r + } // ErrorObject sets the error struct for the rule. + func (r ThresholdRule) ErrorObject(err Error) ThresholdRule { + r.err = err + return r + } func (r ThresholdRule) compareInt(threshold, value int64) bool { + switch r.operator { + case greaterThan: + return value > threshold + case greaterEqualThan: + return value >= threshold + case lessThan: + return value < threshold + default: + return value <= threshold + } + } func (r ThresholdRule) compareUint(threshold, value uint64) bool { + switch r.operator { + case greaterThan: + return value > threshold + case greaterEqualThan: + return value >= threshold + case lessThan: + return value < threshold + default: + return value <= threshold + } + } func (r ThresholdRule) compareFloat(threshold, value float64) bool { + switch r.operator { + case greaterThan: + return value > threshold + case greaterEqualThan: + return value >= threshold + case lessThan: + return value < threshold + default: + return value <= threshold + } + } func (r ThresholdRule) compareTime(threshold, value time.Time) bool { + switch r.operator { + case greaterThan: + return value.After(threshold) + case greaterEqualThan: + return value.After(threshold) || value.Equal(threshold) + case lessThan: + return value.Before(threshold) + default: + return value.Before(threshold) || value.Equal(threshold) + } + } diff --git a/vendor/github.com/go-ozzo/ozzo-validation/v4/multipleof.go b/vendor/github.com/go-ozzo/ozzo-validation/v4/multipleof.go index 864b8b7..e6714f5 100644 --- a/vendor/github.com/go-ozzo/ozzo-validation/v4/multipleof.go +++ b/vendor/github.com/go-ozzo/ozzo-validation/v4/multipleof.go @@ -6,60 +6,98 @@ import ( ) // ErrMultipleOfInvalid is the error that returns when a value is not multiple of a base. + var ErrMultipleOfInvalid = NewError("validation_multiple_of_invalid", "must be multiple of {{.base}}") // MultipleOf returns a validation rule that checks if a value is a multiple of the "base" value. + // Note that "base" should be of integer type. + func MultipleOf(base interface{}) MultipleOfRule { + return MultipleOfRule{ + base: base, - err: ErrMultipleOfInvalid, + + err: ErrMultipleOfInvalid, } + } // MultipleOfRule is a validation rule that checks if a value is a multiple of the "base" value. + type MultipleOfRule struct { base interface{} - err Error + + err Error } // Error sets the error message for the rule. + func (r MultipleOfRule) Error(message string) MultipleOfRule { + r.err = r.err.SetMessage(message) + return r + } // ErrorObject sets the error struct for the rule. + func (r MultipleOfRule) ErrorObject(err Error) MultipleOfRule { + r.err = err + return r + } // Validate checks if the value is a multiple of the "base" value. + func (r MultipleOfRule) Validate(value interface{}) error { + rv := reflect.ValueOf(r.base) + switch rv.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + v, err := ToInt(value) + if err != nil { + return err + } + if v%rv.Int() == 0 { + return nil + } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + v, err := ToUint(value) + if err != nil { + return err + } if v%rv.Uint() == 0 { + return nil + } + default: + return fmt.Errorf("type not supported: %v", rv.Type()) + } return r.err.SetParams(map[string]interface{}{"base": r.base}) + } diff --git a/vendor/github.com/go-ozzo/ozzo-validation/v4/struct.go b/vendor/github.com/go-ozzo/ozzo-validation/v4/struct.go index 08b63ba..c4bd630 100644 --- a/vendor/github.com/go-ozzo/ozzo-validation/v4/struct.go +++ b/vendor/github.com/go-ozzo/ozzo-validation/v4/struct.go @@ -1,5 +1,7 @@ // Copyright 2016 Qiang Xue. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package validation @@ -13,157 +15,280 @@ import ( ) var ( + // ErrStructPointer is the error that a struct being validated is not specified as a pointer. + ErrStructPointer = errors.New("only a pointer to a struct can be validated") ) type ( + // ErrFieldPointer is the error that a field is not specified as a pointer. + ErrFieldPointer int // ErrFieldNotFound is the error that a field cannot be found in the struct. + ErrFieldNotFound int // FieldRules represents a rule set associated with a struct field. + FieldRules struct { fieldPtr interface{} - rules []Rule + + rules []Rule } ) // Error returns the error string of ErrFieldPointer. + func (e ErrFieldPointer) Error() string { + return fmt.Sprintf("field #%v must be specified as a pointer", int(e)) + } // Error returns the error string of ErrFieldNotFound. + func (e ErrFieldNotFound) Error() string { + return fmt.Sprintf("field #%v cannot be found in the struct", int(e)) + } // ValidateStruct validates a struct by checking the specified struct fields against the corresponding validation rules. + // Note that the struct being validated must be specified as a pointer to it. If the pointer is nil, it is considered valid. + // Use Field() to specify struct fields that need to be validated. Each Field() call specifies a single field which + // should be specified as a pointer to the field. A field can be associated with multiple rules. + // For example, + // + // value := struct { + // Name string + // Value string + // }{"name", "demo"} + // err := validation.ValidateStruct(&value, + // validation.Field(&a.Name, validation.Required), + // validation.Field(&a.Value, validation.Required, validation.Length(5, 10)), + // ) + // fmt.Println(err) + // // Value: the length must be between 5 and 10. + // + // An error will be returned if validation fails. + func ValidateStruct(structPtr interface{}, fields ...*FieldRules) error { + return ValidateStructWithContext(nil, structPtr, fields...) + } // ValidateStructWithContext validates a struct with the given context. + // The only difference between ValidateStructWithContext and ValidateStruct is that the former will + // validate struct fields with the provided context. + // Please refer to ValidateStruct for the detailed instructions on how to use this function. + func ValidateStructWithContext(ctx context.Context, structPtr interface{}, fields ...*FieldRules) error { + value := reflect.ValueOf(structPtr) + if value.Kind() != reflect.Ptr || !value.IsNil() && value.Elem().Kind() != reflect.Struct { + // must be a pointer to a struct + return NewInternalError(ErrStructPointer) + } + if value.IsNil() { + // treat a nil struct pointer as valid + return nil + } + value = value.Elem() errs := Errors{} for i, fr := range fields { + fv := reflect.ValueOf(fr.fieldPtr) + if fv.Kind() != reflect.Ptr { + return NewInternalError(ErrFieldPointer(i)) + } + ft := findStructField(value, fv) + if ft == nil { + return NewInternalError(ErrFieldNotFound(i)) + } + var err error + if ctx == nil { + err = Validate(fv.Elem().Interface(), fr.rules...) + } else { + err = ValidateWithContext(ctx, fv.Elem().Interface(), fr.rules...) + } + if err != nil { + if ie, ok := err.(InternalError); ok && ie.InternalError() != nil { + return err + } + if ft.Anonymous { + // merge errors from anonymous struct field + if es, ok := err.(Errors); ok { + for name, value := range es { + errs[name] = value + } + continue + } + } + errs[getErrorFieldName(ft)] = err + } + } if len(errs) > 0 { + return errs + } + return nil + } // Field specifies a struct field and the corresponding validation rules. + // The struct field must be specified as a pointer to it. + func Field(fieldPtr interface{}, rules ...Rule) *FieldRules { + return &FieldRules{ + fieldPtr: fieldPtr, - rules: rules, + + rules: rules, } + } // findStructField looks for a field in the given struct. + // The field being looked for should be a pointer to the actual struct field. + // If found, the field info will be returned. Otherwise, nil will be returned. + func findStructField(structValue reflect.Value, fieldValue reflect.Value) *reflect.StructField { + ptr := fieldValue.Pointer() + for i := structValue.NumField() - 1; i >= 0; i-- { + sf := structValue.Type().Field(i) + if ptr == structValue.Field(i).UnsafeAddr() { + // do additional type comparison because it's possible that the address of + // an embedded struct is the same as the first field of the embedded struct + if sf.Type == fieldValue.Elem().Type() { + return &sf + } + } + if sf.Anonymous { + // delve into anonymous struct to look for the field + fi := structValue.Field(i) + if sf.Type.Kind() == reflect.Ptr { + fi = fi.Elem() + } + if fi.Kind() == reflect.Struct { + if f := findStructField(fi, fieldValue); f != nil { + return f + } + } + } + } + return nil + } // getErrorFieldName returns the name that should be used to represent the validation error of a struct field. + func getErrorFieldName(f *reflect.StructField) string { + if tag := f.Tag.Get(ErrorTag); tag != "" && tag != "-" { + if cps := strings.SplitN(tag, ",", 2); cps[0] != "" { + return cps[0] + } + } + return f.Name + } diff --git a/vendor/github.com/go-ozzo/ozzo-validation/v4/util.go b/vendor/github.com/go-ozzo/ozzo-validation/v4/util.go index b15fd9a..8db818b 100644 --- a/vendor/github.com/go-ozzo/ozzo-validation/v4/util.go +++ b/vendor/github.com/go-ozzo/ozzo-validation/v4/util.go @@ -1,5 +1,7 @@ // Copyright 2016 Qiang Xue. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. package validation @@ -13,151 +15,273 @@ import ( ) var ( - bytesType = reflect.TypeOf([]byte(nil)) + bytesType = reflect.TypeOf([]byte(nil)) + valuerType = reflect.TypeOf((*driver.Valuer)(nil)).Elem() ) // EnsureString ensures the given value is a string. + // If the value is a byte slice, it will be typecast into a string. + // An error is returned otherwise. + func EnsureString(value interface{}) (string, error) { + v := reflect.ValueOf(value) + if v.Kind() == reflect.String { + return v.String(), nil + } + if v.Type() == bytesType { + return string(v.Interface().([]byte)), nil + } + return "", errors.New("must be either a string or byte slice") + } // StringOrBytes typecasts a value into a string or byte slice. + // Boolean flags are returned to indicate if the typecasting succeeds or not. + func StringOrBytes(value interface{}) (isString bool, str string, isBytes bool, bs []byte) { + v := reflect.ValueOf(value) + if v.Kind() == reflect.String { + str = v.String() + isString = true + } else if v.Kind() == reflect.Slice && v.Type() == bytesType { + bs = v.Interface().([]byte) + isBytes = true + } + return + } // LengthOfValue returns the length of a value that is a string, slice, map, or array. + // An error is returned for all other types. + func LengthOfValue(value interface{}) (int, error) { + v := reflect.ValueOf(value) + switch v.Kind() { + case reflect.String, reflect.Slice, reflect.Map, reflect.Array: + return v.Len(), nil + } + return 0, fmt.Errorf("cannot get the length of %v", v.Kind()) + } // ToInt converts the given value to an int64. + // An error is returned for all incompatible types. + func ToInt(value interface{}) (int64, error) { + v := reflect.ValueOf(value) + switch v.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int(), nil + } + return 0, fmt.Errorf("cannot convert %v to int64", v.Kind()) + } // ToUint converts the given value to an uint64. + // An error is returned for all incompatible types. + func ToUint(value interface{}) (uint64, error) { + v := reflect.ValueOf(value) + switch v.Kind() { + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint(), nil + } + return 0, fmt.Errorf("cannot convert %v to uint64", v.Kind()) + } // ToFloat converts the given value to a float64. + // An error is returned for all incompatible types. + func ToFloat(value interface{}) (float64, error) { + v := reflect.ValueOf(value) + switch v.Kind() { + case reflect.Float32, reflect.Float64: + return v.Float(), nil + } + return 0, fmt.Errorf("cannot convert %v to float64", v.Kind()) + } // IsEmpty checks if a value is empty or not. + // A value is considered empty if + // - integer, float: zero + // - bool: false + // - string, array: len() == 0 + // - slice, map: nil or len() == 0 + // - interface, pointer: nil or the referenced value is empty + func IsEmpty(value interface{}) bool { + v := reflect.ValueOf(value) + switch v.Kind() { + case reflect.String, reflect.Array, reflect.Map, reflect.Slice: + return v.Len() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Invalid: + return true + case reflect.Interface, reflect.Ptr: + if v.IsNil() { + return true + } + return IsEmpty(v.Elem().Interface()) + case reflect.Struct: + v, ok := value.(time.Time) + if ok && v.IsZero() { + return true + } + } return false + } // Indirect returns the value that the given interface or pointer references to. + // If the value implements driver.Valuer, it will deal with the value returned by + // the Value() method instead. A boolean value is also returned to indicate if + // the value is nil or not (only applicable to interface, pointer, map, and slice). + // If the value is neither an interface nor a pointer, it will be returned back. + func Indirect(value interface{}) (interface{}, bool) { + rv := reflect.ValueOf(value) + kind := rv.Kind() + switch kind { + case reflect.Invalid: + return nil, true + case reflect.Ptr, reflect.Interface: + if rv.IsNil() { + return nil, true + } + return Indirect(rv.Elem().Interface()) + case reflect.Slice, reflect.Map, reflect.Func, reflect.Chan: + if rv.IsNil() { + return nil, true + } + } if rv.Type().Implements(valuerType) { + return indirectValuer(value.(driver.Valuer)) + } return value, false + } func indirectValuer(valuer driver.Valuer) (interface{}, bool) { + if value, err := valuer.Value(); value != nil && err == nil { + return Indirect(value) + } + return nil, true + } diff --git a/vendor/github.com/go-ozzo/ozzo-validation/v4/validation.go b/vendor/github.com/go-ozzo/ozzo-validation/v4/validation.go index 0495f32..837c0da 100644 --- a/vendor/github.com/go-ozzo/ozzo-validation/v4/validation.go +++ b/vendor/github.com/go-ozzo/ozzo-validation/v4/validation.go @@ -1,8 +1,11 @@ // Copyright 2016 Qiang Xue. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. // Package validation provides configurable and extensible rules for validating data of various types. + package validation import ( @@ -13,219 +16,381 @@ import ( ) type ( + // Validatable is the interface indicating the type implementing it supports data validation. + Validatable interface { + // Validate validates the data and returns an error if validation fails. + Validate() error } // ValidatableWithContext is the interface indicating the type implementing it supports context-aware data validation. + ValidatableWithContext interface { + // ValidateWithContext validates the data with the given context and returns an error if validation fails. + ValidateWithContext(ctx context.Context) error } // Rule represents a validation rule. + Rule interface { + // Validate validates a value and returns a value if validation fails. + Validate(value interface{}) error } // RuleWithContext represents a context-aware validation rule. + RuleWithContext interface { + // ValidateWithContext validates a value and returns a value if validation fails. + ValidateWithContext(ctx context.Context, value interface{}) error } // RuleFunc represents a validator function. + // You may wrap it as a Rule by calling By(). + RuleFunc func(value interface{}) error // RuleWithContextFunc represents a validator function that is context-aware. + // You may wrap it as a Rule by calling WithContext(). + RuleWithContextFunc func(ctx context.Context, value interface{}) error ) var ( + // ErrorTag is the struct tag name used to customize the error field name for a struct field. + ErrorTag = "json" // Skip is a special validation rule that indicates all rules following it should be skipped. + Skip = skipRule{skip: true} - validatableType = reflect.TypeOf((*Validatable)(nil)).Elem() + validatableType = reflect.TypeOf((*Validatable)(nil)).Elem() + validatableWithContextType = reflect.TypeOf((*ValidatableWithContext)(nil)).Elem() ) // Validate validates the given value and returns the validation error, if any. + // + // Validate performs validation using the following steps: + // 1. For each rule, call its `Validate()` to validate the value. Return if any error is found. + // 2. If the value being validated implements `Validatable`, call the value's `Validate()`. + // Return with the validation result. + // 3. If the value being validated is a map/slice/array, and the element type implements `Validatable`, + // for each element call the element value's `Validate()`. Return with the validation result. + func Validate(value interface{}, rules ...Rule) error { + for _, rule := range rules { + if s, ok := rule.(skipRule); ok && s.skip { + return nil + } + if err := rule.Validate(value); err != nil { + return err + } + } rv := reflect.ValueOf(value) + if (rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Interface) && rv.IsNil() { + return nil + } if v, ok := value.(Validatable); ok { + return v.Validate() + } switch rv.Kind() { + case reflect.Map: + if rv.Type().Elem().Implements(validatableType) { + return validateMap(rv) + } + case reflect.Slice, reflect.Array: + if rv.Type().Elem().Implements(validatableType) { + return validateSlice(rv) + } + case reflect.Ptr, reflect.Interface: + return Validate(rv.Elem().Interface()) + } return nil + } // ValidateWithContext validates the given value with the given context and returns the validation error, if any. + // + // ValidateWithContext performs validation using the following steps: + // 1. For each rule, call its `ValidateWithContext()` to validate the value if the rule implements `RuleWithContext`. + // Otherwise call `Validate()` of the rule. Return if any error is found. + // 2. If the value being validated implements `ValidatableWithContext`, call the value's `ValidateWithContext()` + // and return with the validation result. + // 3. If the value being validated implements `Validatable`, call the value's `Validate()` + // and return with the validation result. + // 4. If the value being validated is a map/slice/array, and the element type implements `ValidatableWithContext`, + // for each element call the element value's `ValidateWithContext()`. Return with the validation result. + // 5. If the value being validated is a map/slice/array, and the element type implements `Validatable`, + // for each element call the element value's `Validate()`. Return with the validation result. + func ValidateWithContext(ctx context.Context, value interface{}, rules ...Rule) error { + for _, rule := range rules { + if s, ok := rule.(skipRule); ok && s.skip { + return nil + } + if rc, ok := rule.(RuleWithContext); ok { + if err := rc.ValidateWithContext(ctx, value); err != nil { + return err + } + } else if err := rule.Validate(value); err != nil { + return err + } + } rv := reflect.ValueOf(value) + if (rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Interface) && rv.IsNil() { + return nil + } if v, ok := value.(ValidatableWithContext); ok { + return v.ValidateWithContext(ctx) + } if v, ok := value.(Validatable); ok { + return v.Validate() + } switch rv.Kind() { + case reflect.Map: + if rv.Type().Elem().Implements(validatableWithContextType) { + return validateMapWithContext(ctx, rv) + } + if rv.Type().Elem().Implements(validatableType) { + return validateMap(rv) + } + case reflect.Slice, reflect.Array: + if rv.Type().Elem().Implements(validatableWithContextType) { + return validateSliceWithContext(ctx, rv) + } + if rv.Type().Elem().Implements(validatableType) { + return validateSlice(rv) + } + case reflect.Ptr, reflect.Interface: + return ValidateWithContext(ctx, rv.Elem().Interface()) + } return nil + } // validateMap validates a map of validatable elements + func validateMap(rv reflect.Value) error { + errs := Errors{} + for _, key := range rv.MapKeys() { + if mv := rv.MapIndex(key).Interface(); mv != nil { + if err := mv.(Validatable).Validate(); err != nil { + errs[fmt.Sprintf("%v", key.Interface())] = err + } + } + } + if len(errs) > 0 { + return errs + } + return nil + } // validateMapWithContext validates a map of validatable elements with the given context. + func validateMapWithContext(ctx context.Context, rv reflect.Value) error { + errs := Errors{} + for _, key := range rv.MapKeys() { + if mv := rv.MapIndex(key).Interface(); mv != nil { + if err := mv.(ValidatableWithContext).ValidateWithContext(ctx); err != nil { + errs[fmt.Sprintf("%v", key.Interface())] = err + } + } + } + if len(errs) > 0 { + return errs + } + return nil + } // validateSlice validates a slice/array of validatable elements + func validateSlice(rv reflect.Value) error { + errs := Errors{} + l := rv.Len() + for i := 0; i < l; i++ { + if ev := rv.Index(i).Interface(); ev != nil { + if err := ev.(Validatable).Validate(); err != nil { + errs[strconv.Itoa(i)] = err + } + } + } + if len(errs) > 0 { + return errs + } + return nil + } // validateSliceWithContext validates a slice/array of validatable elements with the given context. + func validateSliceWithContext(ctx context.Context, rv reflect.Value) error { + errs := Errors{} + l := rv.Len() + for i := 0; i < l; i++ { + if ev := rv.Index(i).Interface(); ev != nil { + if err := ev.(ValidatableWithContext).ValidateWithContext(ctx); err != nil { + errs[strconv.Itoa(i)] = err + } + } + } + if len(errs) > 0 { + return errs + } + return nil + } type skipRule struct { @@ -233,40 +398,63 @@ type skipRule struct { } func (r skipRule) Validate(interface{}) error { + return nil + } // When determines if all rules following it should be skipped. + func (r skipRule) When(condition bool) skipRule { + r.skip = condition + return r + } type inlineRule struct { - f RuleFunc + f RuleFunc + fc RuleWithContextFunc } func (r *inlineRule) Validate(value interface{}) error { + if r.f == nil { + return r.fc(context.Background(), value) + } + return r.f(value) + } func (r *inlineRule) ValidateWithContext(ctx context.Context, value interface{}) error { + if r.fc == nil { + return r.f(value) + } + return r.fc(ctx, value) + } // By wraps a RuleFunc into a Rule. + func By(f RuleFunc) Rule { + return &inlineRule{f: f} + } // WithContext wraps a RuleWithContextFunc into a context-aware Rule. + func WithContext(f RuleWithContextFunc) Rule { + return &inlineRule{fc: f} + } diff --git a/vendor/github.com/go-ozzo/ozzo-validation/validation.go b/vendor/github.com/go-ozzo/ozzo-validation/validation.go index 1633258..c3f31c2 100644 --- a/vendor/github.com/go-ozzo/ozzo-validation/validation.go +++ b/vendor/github.com/go-ozzo/ozzo-validation/validation.go @@ -1,8 +1,11 @@ // Copyright 2016 Qiang Xue. All rights reserved. + // Use of this source code is governed by a MIT-style + // license that can be found in the LICENSE file. // Package validation provides configurable and extensible rules for validating data of various types. + package validation import ( @@ -12,111 +15,185 @@ import ( ) type ( + // Validatable is the interface indicating the type implementing it supports data validation. + Validatable interface { + // Validate validates the data and returns an error if validation fails. + Validate() error } // Rule represents a validation rule. + Rule interface { + // Validate validates a value and returns a value if validation fails. + Validate(value interface{}) error } // RuleFunc represents a validator function. + // You may wrap it as a Rule by calling By(). + RuleFunc func(value interface{}) error ) var ( + // ErrorTag is the struct tag name used to customize the error field name for a struct field. + ErrorTag = "json" // Skip is a special validation rule that indicates all rules following it should be skipped. + Skip = &skipRule{} validatableType = reflect.TypeOf((*Validatable)(nil)).Elem() ) // Validate validates the given value and returns the validation error, if any. + // + // Validate performs validation using the following steps: + // - validate the value against the rules passed in as parameters + // - if the value is a map and the map values implement `Validatable`, call `Validate` of every map value + // - if the value is a slice or array whose values implement `Validatable`, call `Validate` of every element + func Validate(value interface{}, rules ...Rule) error { + for _, rule := range rules { + if _, ok := rule.(*skipRule); ok { + return nil + } + if err := rule.Validate(value); err != nil { + return err + } + } rv := reflect.ValueOf(value) + if (rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Interface) && rv.IsNil() { + return nil + } if v, ok := value.(Validatable); ok { + return v.Validate() + } switch rv.Kind() { + case reflect.Map: + if rv.Type().Elem().Implements(validatableType) { + return validateMap(rv) + } + case reflect.Slice, reflect.Array: + if rv.Type().Elem().Implements(validatableType) { + return validateSlice(rv) + } + case reflect.Ptr, reflect.Interface: + return Validate(rv.Elem().Interface()) + } return nil + } // validateMap validates a map of validatable elements + func validateMap(rv reflect.Value) error { + errs := Errors{} + for _, key := range rv.MapKeys() { + if mv := rv.MapIndex(key).Interface(); mv != nil { + if err := mv.(Validatable).Validate(); err != nil { + errs[fmt.Sprintf("%v", key.Interface())] = err + } + } + } + if len(errs) > 0 { + return errs + } + return nil + } // validateMap validates a slice/array of validatable elements + func validateSlice(rv reflect.Value) error { + errs := Errors{} + l := rv.Len() + for i := 0; i < l; i++ { + if ev := rv.Index(i).Interface(); ev != nil { + if err := ev.(Validatable).Validate(); err != nil { + errs[strconv.Itoa(i)] = err + } + } + } + if len(errs) > 0 { + return errs + } + return nil + } type skipRule struct{} func (r *skipRule) Validate(interface{}) error { + return nil + } type inlineRule struct { @@ -124,10 +201,15 @@ type inlineRule struct { } func (r *inlineRule) Validate(value interface{}) error { + return r.f(value) + } // By wraps a RuleFunc into a Rule. + func By(f RuleFunc) Rule { + return &inlineRule{f} + } diff --git a/vendor/github.com/go-sql-driver/mysql/auth.go b/vendor/github.com/go-sql-driver/mysql/auth.go index d1371a4..dc020e7 100644 --- a/vendor/github.com/go-sql-driver/mysql/auth.go +++ b/vendor/github.com/go-sql-driver/mysql/auth.go @@ -1,9 +1,15 @@ // Go MySQL Driver - A MySQL-Driver for Go's database/sql package + // + // Copyright 2018 The Go-MySQL-Driver Authors. All rights reserved. + // + // This Source Code Form is subject to the terms of the Mozilla Public + // License, v. 2.0. If a copy of the MPL was not distributed with this file, + // You can obtain one at http://mozilla.org/MPL/2.0/. package mysql @@ -20,69 +26,121 @@ import ( ) // server pub keys registry + var ( - serverPubKeyLock sync.RWMutex + serverPubKeyLock sync.RWMutex + serverPubKeyRegistry map[string]*rsa.PublicKey ) // RegisterServerPubKey registers a server RSA public key which can be used to + // send data in a secure manner to the server without receiving the public key + // in a potentially insecure way from the server first. + // Registered keys can afterwards be used adding serverPubKey= to the DSN. + // + // Note: The provided rsa.PublicKey instance is exclusively owned by the driver + // after registering it and may not be modified. + // + // data, err := ioutil.ReadFile("mykey.pem") + // if err != nil { + // log.Fatal(err) + // } + // + // block, _ := pem.Decode(data) + // if block == nil || block.Type != "PUBLIC KEY" { + // log.Fatal("failed to decode PEM block containing public key") + // } + // + // pub, err := x509.ParsePKIXPublicKey(block.Bytes) + // if err != nil { + // log.Fatal(err) + // } + // + // if rsaPubKey, ok := pub.(*rsa.PublicKey); ok { + // mysql.RegisterServerPubKey("mykey", rsaPubKey) + // } else { + // log.Fatal("not a RSA public key") + // } + func RegisterServerPubKey(name string, pubKey *rsa.PublicKey) { + serverPubKeyLock.Lock() + if serverPubKeyRegistry == nil { + serverPubKeyRegistry = make(map[string]*rsa.PublicKey) + } serverPubKeyRegistry[name] = pubKey + serverPubKeyLock.Unlock() + } // DeregisterServerPubKey removes the public key registered with the given name. + func DeregisterServerPubKey(name string) { + serverPubKeyLock.Lock() + if serverPubKeyRegistry != nil { + delete(serverPubKeyRegistry, name) + } + serverPubKeyLock.Unlock() + } func getServerPubKey(name string) (pubKey *rsa.PublicKey) { + serverPubKeyLock.RLock() + if v, ok := serverPubKeyRegistry[name]; ok { + pubKey = v + } + serverPubKeyLock.RUnlock() + return + } // Hash password using pre 4.1 (old password) method + // https://github.com/atcurtis/mariadb/blob/master/mysys/my_rnd.c + type myRnd struct { seed1, seed2 uint32 } @@ -90,335 +148,560 @@ type myRnd struct { const myRndMaxVal = 0x3FFFFFFF // Pseudo random number generator + func newMyRnd(seed1, seed2 uint32) *myRnd { + return &myRnd{ + seed1: seed1 % myRndMaxVal, + seed2: seed2 % myRndMaxVal, } + } // Tested to be equivalent to MariaDB's floating point variant + // http://play.golang.org/p/QHvhd4qved + // http://play.golang.org/p/RG0q4ElWDx + func (r *myRnd) NextByte() byte { + r.seed1 = (r.seed1*3 + r.seed2) % myRndMaxVal + r.seed2 = (r.seed1 + r.seed2 + 33) % myRndMaxVal return byte(uint64(r.seed1) * 31 / myRndMaxVal) + } // Generate binary hash from byte string using insecure pre 4.1 method + func pwHash(password []byte) (result [2]uint32) { + var add uint32 = 7 + var tmp uint32 result[0] = 1345345333 + result[1] = 0x12345671 for _, c := range password { + // skip spaces and tabs in password + if c == ' ' || c == '\t' { + continue + } tmp = uint32(c) + result[0] ^= (((result[0] & 63) + add) * tmp) + (result[0] << 8) + result[1] += (result[1] << 8) ^ result[0] + add += tmp + } // Remove sign bit (1<<31)-1) + result[0] &= 0x7FFFFFFF + result[1] &= 0x7FFFFFFF return + } // Hash password using insecure pre 4.1 method + func scrambleOldPassword(scramble []byte, password string) []byte { + scramble = scramble[:8] hashPw := pwHash([]byte(password)) + hashSc := pwHash(scramble) r := newMyRnd(hashPw[0]^hashSc[0], hashPw[1]^hashSc[1]) var out [8]byte + for i := range out { + out[i] = r.NextByte() + 64 + } mask := r.NextByte() + for i := range out { + out[i] ^= mask + } return out[:] + } // Hash password using 4.1+ method (SHA1) + func scramblePassword(scramble []byte, password string) []byte { + if len(password) == 0 { + return nil + } // stage1Hash = SHA1(password) + crypt := sha1.New() + crypt.Write([]byte(password)) + stage1 := crypt.Sum(nil) // scrambleHash = SHA1(scramble + SHA1(stage1Hash)) + // inner Hash + crypt.Reset() + crypt.Write(stage1) + hash := crypt.Sum(nil) // outer Hash + crypt.Reset() + crypt.Write(scramble) + crypt.Write(hash) + scramble = crypt.Sum(nil) // token = scrambleHash XOR stage1Hash + for i := range scramble { + scramble[i] ^= stage1[i] + } + return scramble + } // Hash password using MySQL 8+ method (SHA256) + func scrambleSHA256Password(scramble []byte, password string) []byte { + if len(password) == 0 { + return nil + } // XOR(SHA256(password), SHA256(SHA256(SHA256(password)), scramble)) crypt := sha256.New() + crypt.Write([]byte(password)) + message1 := crypt.Sum(nil) crypt.Reset() + crypt.Write(message1) + message1Hash := crypt.Sum(nil) crypt.Reset() + crypt.Write(message1Hash) + crypt.Write(scramble) + message2 := crypt.Sum(nil) for i := range message1 { + message1[i] ^= message2[i] + } return message1 + } func encryptPassword(password string, seed []byte, pub *rsa.PublicKey) ([]byte, error) { + plain := make([]byte, len(password)+1) + copy(plain, password) + for i := range plain { + j := i % len(seed) + plain[i] ^= seed[j] + } + sha1 := sha1.New() + return rsa.EncryptOAEP(sha1, rand.Reader, pub, plain, nil) + } func (mc *mysqlConn) sendEncryptedPassword(seed []byte, pub *rsa.PublicKey) error { + enc, err := encryptPassword(mc.cfg.Passwd, seed, pub) + if err != nil { + return err + } + return mc.writeAuthSwitchPacket(enc) + } func (mc *mysqlConn) auth(authData []byte, plugin string) ([]byte, error) { + switch plugin { + case "caching_sha2_password": + authResp := scrambleSHA256Password(authData, mc.cfg.Passwd) + return authResp, nil case "mysql_old_password": + if !mc.cfg.AllowOldPasswords { + return nil, ErrOldPassword + } + if len(mc.cfg.Passwd) == 0 { + return nil, nil + } + // Note: there are edge cases where this should work but doesn't; + // this is currently "wontfix": + // https://github.com/go-sql-driver/mysql/issues/184 + authResp := append(scrambleOldPassword(authData[:8], mc.cfg.Passwd), 0) + return authResp, nil case "mysql_clear_password": + if !mc.cfg.AllowCleartextPasswords { + return nil, ErrCleartextPassword + } + // http://dev.mysql.com/doc/refman/5.7/en/cleartext-authentication-plugin.html + // http://dev.mysql.com/doc/refman/5.7/en/pam-authentication-plugin.html + return append([]byte(mc.cfg.Passwd), 0), nil case "mysql_native_password": + if !mc.cfg.AllowNativePasswords { + return nil, ErrNativePassword + } + // https://dev.mysql.com/doc/internals/en/secure-password-authentication.html + // Native password authentication only need and will need 20-byte challenge. + authResp := scramblePassword(authData[:20], mc.cfg.Passwd) + return authResp, nil case "sha256_password": + if len(mc.cfg.Passwd) == 0 { + return []byte{0}, nil + } + if mc.cfg.tls != nil || mc.cfg.Net == "unix" { + // write cleartext auth packet + return append([]byte(mc.cfg.Passwd), 0), nil + } pubKey := mc.cfg.pubKey + if pubKey == nil { + // request public key from server + return []byte{1}, nil + } // encrypted password + enc, err := encryptPassword(mc.cfg.Passwd, authData, pubKey) + return enc, err default: + errLog.Print("unknown auth plugin:", plugin) + return nil, ErrUnknownPlugin + } + } func (mc *mysqlConn) handleAuthResult(oldAuthData []byte, plugin string) error { + // Read Result Packet + authData, newPlugin, err := mc.readAuthResult() + if err != nil { + return err + } // handle auth plugin switch, if requested + if newPlugin != "" { + // If CLIENT_PLUGIN_AUTH capability is not supported, no new cipher is + // sent and we have to keep using the cipher sent in the init packet. + if authData == nil { + authData = oldAuthData + } else { + // copy data from read buffer to owned slice + copy(oldAuthData, authData) + } plugin = newPlugin authResp, err := mc.auth(authData, plugin) + if err != nil { + return err + } + if err = mc.writeAuthSwitchPacket(authResp); err != nil { + return err + } // Read Result Packet + authData, newPlugin, err = mc.readAuthResult() + if err != nil { + return err + } // Do not allow to change the auth plugin more than once + if newPlugin != "" { + return ErrMalformPkt + } + } switch plugin { // https://insidemysql.com/preparing-your-community-connector-for-mysql-8-part-2-sha256/ + case "caching_sha2_password": + switch len(authData) { + case 0: + return nil // auth successful + case 1: + switch authData[0] { + case cachingSha2PasswordFastAuthSuccess: + if err = mc.readResultOK(); err == nil { + return nil // auth successful + } case cachingSha2PasswordPerformFullAuthentication: + if mc.cfg.tls != nil || mc.cfg.Net == "unix" { + // write cleartext auth packet + err = mc.writeAuthSwitchPacket(append([]byte(mc.cfg.Passwd), 0)) + if err != nil { + return err + } + } else { + pubKey := mc.cfg.pubKey + if pubKey == nil { + // request public key from server + data, err := mc.buf.takeSmallBuffer(4 + 1) + if err != nil { + return err + } + data[4] = cachingSha2PasswordRequestPublicKey + mc.writePacket(data) // parse public key + if data, err = mc.readPacket(); err != nil { + return err + } block, rest := pem.Decode(data[1:]) + if block == nil { + return fmt.Errorf("No Pem data found, data: %s", rest) + } + pkix, err := x509.ParsePKIXPublicKey(block.Bytes) + if err != nil { + return err + } + pubKey = pkix.(*rsa.PublicKey) + } // send encrypted password + err = mc.sendEncryptedPassword(oldAuthData, pubKey) + if err != nil { + return err + } + } + return mc.readResultOK() default: + return ErrMalformPkt + } + default: + return ErrMalformPkt + } case "sha256_password": + switch len(authData) { + case 0: + return nil // auth successful + default: + block, _ := pem.Decode(authData) + pub, err := x509.ParsePKIXPublicKey(block.Bytes) + if err != nil { + return err + } // send encrypted password + err = mc.sendEncryptedPassword(oldAuthData, pub.(*rsa.PublicKey)) + if err != nil { + return err + } + return mc.readResultOK() + } default: + return nil // auth successful + } return err + } diff --git a/vendor/github.com/go-sql-driver/mysql/buffer.go b/vendor/github.com/go-sql-driver/mysql/buffer.go index 0774c5c..cf63aae 100644 --- a/vendor/github.com/go-sql-driver/mysql/buffer.go +++ b/vendor/github.com/go-sql-driver/mysql/buffer.go @@ -1,9 +1,15 @@ // Go MySQL Driver - A MySQL-Driver for Go's database/sql package + // + // Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. + // + // This Source Code Form is subject to the terms of the Mozilla Public + // License, v. 2.0. If a copy of the MPL was not distributed with this file, + // You can obtain one at http://mozilla.org/MPL/2.0/. package mysql @@ -15,168 +21,287 @@ import ( ) const defaultBufSize = 4096 + const maxCachedBufSize = 256 * 1024 // A buffer which is used for both reading and writing. + // This is possible since communication on each connection is synchronous. + // In other words, we can't write and read simultaneously on the same connection. + // The buffer is similar to bufio.Reader / Writer but zero-copy-ish + // Also highly optimized for this particular use case. + // This buffer is backed by two byte slices in a double-buffering scheme + type buffer struct { - buf []byte // buf is a byte buffer who's length and capacity are equal. - nc net.Conn - idx int - length int + buf []byte // buf is a byte buffer who's length and capacity are equal. + + nc net.Conn + + idx int + + length int + timeout time.Duration - dbuf [2][]byte // dbuf is an array with the two byte slices that back this buffer - flipcnt uint // flipccnt is the current buffer counter for double-buffering + + dbuf [2][]byte // dbuf is an array with the two byte slices that back this buffer + + flipcnt uint // flipccnt is the current buffer counter for double-buffering + } // newBuffer allocates and returns a new buffer. + func newBuffer(nc net.Conn) buffer { + fg := make([]byte, defaultBufSize) + return buffer{ - buf: fg, - nc: nc, + + buf: fg, + + nc: nc, + dbuf: [2][]byte{fg, nil}, } + } // flip replaces the active buffer with the background buffer + // this is a delayed flip that simply increases the buffer counter; + // the actual flip will be performed the next time we call `buffer.fill` + func (b *buffer) flip() { + b.flipcnt += 1 + } // fill reads into the buffer until at least _need_ bytes are in it + func (b *buffer) fill(need int) error { + n := b.length + // fill data into its double-buffering target: if we've called + // flip on this buffer, we'll be copying to the background buffer, + // and then filling it with network data; otherwise we'll just move + // the contents of the current buffer to the front before filling it + dest := b.dbuf[b.flipcnt&1] // grow buffer if necessary to fit the whole packet. + if need > len(dest) { + // Round up to the next multiple of the default size + dest = make([]byte, ((need/defaultBufSize)+1)*defaultBufSize) // if the allocated buffer is not too large, move it to backing storage + // to prevent extra allocations on applications that perform large reads + if len(dest) <= maxCachedBufSize { + b.dbuf[b.flipcnt&1] = dest + } + } // if we're filling the fg buffer, move the existing data to the start of it. + // if we're filling the bg buffer, copy over the data + if n > 0 { + copy(dest[:n], b.buf[b.idx:]) + } b.buf = dest + b.idx = 0 for { + if b.timeout > 0 { + if err := b.nc.SetReadDeadline(time.Now().Add(b.timeout)); err != nil { + return err + } + } nn, err := b.nc.Read(b.buf[n:]) + n += nn switch err { + case nil: + if n < need { + continue + } + b.length = n + return nil case io.EOF: + if n >= need { + b.length = n + return nil + } + return io.ErrUnexpectedEOF default: + return err + } + } + } // returns next N bytes from buffer. + // The returned slice is only guaranteed to be valid until the next read + func (b *buffer) readNext(need int) ([]byte, error) { + if b.length < need { + // refill + if err := b.fill(need); err != nil { + return nil, err + } + } offset := b.idx + b.idx += need + b.length -= need + return b.buf[offset:b.idx], nil + } // takeBuffer returns a buffer with the requested size. + // If possible, a slice from the existing buffer is returned. + // Otherwise a bigger buffer is made. + // Only one buffer (total) can be used at a time. + func (b *buffer) takeBuffer(length int) ([]byte, error) { + if b.length > 0 { + return nil, ErrBusyBuffer + } // test (cheap) general case first + if length <= cap(b.buf) { + return b.buf[:length], nil + } if length < maxPacketSize { + b.buf = make([]byte, length) + return b.buf, nil + } // buffer is larger than we want to store. + return make([]byte, length), nil + } // takeSmallBuffer is shortcut which can be used if length is + // known to be smaller than defaultBufSize. + // Only one buffer (total) can be used at a time. + func (b *buffer) takeSmallBuffer(length int) ([]byte, error) { + if b.length > 0 { + return nil, ErrBusyBuffer + } + return b.buf[:length], nil + } // takeCompleteBuffer returns the complete existing buffer. + // This can be used if the necessary buffer size is unknown. + // cap and len of the returned buffer will be equal. + // Only one buffer (total) can be used at a time. + func (b *buffer) takeCompleteBuffer() ([]byte, error) { + if b.length > 0 { + return nil, ErrBusyBuffer + } + return b.buf, nil + } // store stores buf, an updated buffer, if its suitable to do so. + func (b *buffer) store(buf []byte) error { + if b.length > 0 { + return ErrBusyBuffer + } else if cap(buf) <= maxPacketSize && cap(buf) > cap(b.buf) { + b.buf = buf[:cap(buf)] + } + return nil + } diff --git a/vendor/github.com/go-sql-driver/mysql/conncheck.go b/vendor/github.com/go-sql-driver/mysql/conncheck.go index 0ea7217..0f8bd80 100644 --- a/vendor/github.com/go-sql-driver/mysql/conncheck.go +++ b/vendor/github.com/go-sql-driver/mysql/conncheck.go @@ -1,9 +1,15 @@ // Go MySQL Driver - A MySQL-Driver for Go's database/sql package + // + // Copyright 2019 The Go-MySQL-Driver Authors. All rights reserved. + // + // This Source Code Form is subject to the terms of the Mozilla Public + // License, v. 2.0. If a copy of the MPL was not distributed with this file, + // You can obtain one at http://mozilla.org/MPL/2.0/. //go:build linux || darwin || dragonfly || freebsd || netbsd || openbsd || solaris || illumos @@ -21,35 +27,61 @@ import ( var errUnexpectedRead = errors.New("unexpected read from socket") func connCheck(conn net.Conn) error { + var sysErr error sysConn, ok := conn.(syscall.Conn) + if !ok { + return nil + } + rawConn, err := sysConn.SyscallConn() + if err != nil { + return err + } err = rawConn.Read(func(fd uintptr) bool { + var buf [1]byte + n, err := syscall.Read(int(fd), buf[:]) + switch { + case n == 0 && err == nil: + sysErr = io.EOF + case n > 0: + sysErr = errUnexpectedRead + case err == syscall.EAGAIN || err == syscall.EWOULDBLOCK: + sysErr = nil + default: + sysErr = err + } + return true + }) + if err != nil { + return err + } return sysErr + } diff --git a/vendor/github.com/go-sql-driver/mysql/connection.go b/vendor/github.com/go-sql-driver/mysql/connection.go index 835f897..cebfd4f 100644 --- a/vendor/github.com/go-sql-driver/mysql/connection.go +++ b/vendor/github.com/go-sql-driver/mysql/connection.go @@ -1,9 +1,15 @@ // Go MySQL Driver - A MySQL-Driver for Go's database/sql package + // + // Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. + // + // This Source Code Form is subject to the terms of the Mozilla Public + // License, v. 2.0. If a copy of the MPL was not distributed with this file, + // You can obtain one at http://mozilla.org/MPL/2.0/. package mysql @@ -21,630 +27,1106 @@ import ( ) type mysqlConn struct { - buf buffer - netConn net.Conn - rawConn net.Conn // underlying connection when netConn is TLS connection. - affectedRows uint64 - insertId uint64 - cfg *Config + buf buffer + + netConn net.Conn + + rawConn net.Conn // underlying connection when netConn is TLS connection. + + affectedRows uint64 + + insertId uint64 + + cfg *Config + maxAllowedPacket int - maxWriteSize int - writeTimeout time.Duration - flags clientFlag - status statusFlag - sequence uint8 - parseTime bool - reset bool // set when the Go SQL package calls ResetSession + + maxWriteSize int + + writeTimeout time.Duration + + flags clientFlag + + status statusFlag + + sequence uint8 + + parseTime bool + + reset bool // set when the Go SQL package calls ResetSession // for context support (Go 1.8+) + watching bool - watcher chan<- context.Context - closech chan struct{} + + watcher chan<- context.Context + + closech chan struct{} + finished chan<- struct{} + canceled atomicError // set non-nil if conn is canceled - closed atomicBool // set when conn is closed, before closech is closed + + closed atomicBool // set when conn is closed, before closech is closed + } // Handles parameters set in DSN after the connection is established + func (mc *mysqlConn) handleParams() (err error) { + var cmdSet strings.Builder + for param, val := range mc.cfg.Params { + switch param { + // Charset: character_set_connection, character_set_client, character_set_results + case "charset": + charsets := strings.Split(val, ",") + for i := range charsets { + // ignore errors here - a charset may not exist + err = mc.exec("SET NAMES " + charsets[i]) + if err == nil { + break + } + } + if err != nil { + return + } // Other system vars accumulated in a single SET command + default: + if cmdSet.Len() == 0 { + // Heuristic: 29 chars for each other key=value to reduce reallocations + cmdSet.Grow(4 + len(param) + 1 + len(val) + 30*(len(mc.cfg.Params)-1)) + cmdSet.WriteString("SET ") + } else { + cmdSet.WriteByte(',') + } + cmdSet.WriteString(param) + cmdSet.WriteByte('=') + cmdSet.WriteString(val) + } + } if cmdSet.Len() > 0 { + err = mc.exec(cmdSet.String()) + if err != nil { + return + } + } return + } func (mc *mysqlConn) markBadConn(err error) error { + if mc == nil { + return err + } + if err != errBadConnNoWrite { + return err + } + return driver.ErrBadConn + } func (mc *mysqlConn) Begin() (driver.Tx, error) { + return mc.begin(false) + } func (mc *mysqlConn) begin(readOnly bool) (driver.Tx, error) { + if mc.closed.IsSet() { + errLog.Print(ErrInvalidConn) + return nil, driver.ErrBadConn + } + var q string + if readOnly { + q = "START TRANSACTION READ ONLY" + } else { + q = "START TRANSACTION" + } + err := mc.exec(q) + if err == nil { + return &mysqlTx{mc}, err + } + return nil, mc.markBadConn(err) + } func (mc *mysqlConn) Close() (err error) { + // Makes Close idempotent + if !mc.closed.IsSet() { + err = mc.writeCommandPacket(comQuit) + } mc.cleanup() return + } // Closes the network connection and unsets internal variables. Do not call this + // function after successfully authentication, call Close instead. This function + // is called before auth or on auth failure because MySQL will have already + // closed the network connection. + func (mc *mysqlConn) cleanup() { + if !mc.closed.TrySet(true) { + return + } // Makes cleanup idempotent + close(mc.closech) + if mc.netConn == nil { + return + } + if err := mc.netConn.Close(); err != nil { + errLog.Print(err) + } + } func (mc *mysqlConn) error() error { + if mc.closed.IsSet() { + if err := mc.canceled.Value(); err != nil { + return err + } + return ErrInvalidConn + } + return nil + } func (mc *mysqlConn) Prepare(query string) (driver.Stmt, error) { + if mc.closed.IsSet() { + errLog.Print(ErrInvalidConn) + return nil, driver.ErrBadConn + } + // Send command + err := mc.writeCommandPacketStr(comStmtPrepare, query) + if err != nil { + // STMT_PREPARE is safe to retry. So we can return ErrBadConn here. + errLog.Print(err) + return nil, driver.ErrBadConn + } stmt := &mysqlStmt{ + mc: mc, } // Read Result + columnCount, err := stmt.readPrepareResultPacket() + if err == nil { + if stmt.paramCount > 0 { + if err = mc.readUntilEOF(); err != nil { + return nil, err + } + } if columnCount > 0 { + err = mc.readUntilEOF() + } + } return stmt, err + } func (mc *mysqlConn) interpolateParams(query string, args []driver.Value) (string, error) { + // Number of ? should be same to len(args) + if strings.Count(query, "?") != len(args) { + return "", driver.ErrSkip + } buf, err := mc.buf.takeCompleteBuffer() + if err != nil { + // can not take the buffer. Something must be wrong with the connection + errLog.Print(err) + return "", ErrInvalidConn + } + buf = buf[:0] + argPos := 0 for i := 0; i < len(query); i++ { + q := strings.IndexByte(query[i:], '?') + if q == -1 { + buf = append(buf, query[i:]...) + break + } + buf = append(buf, query[i:i+q]...) + i += q arg := args[argPos] + argPos++ if arg == nil { + buf = append(buf, "NULL"...) + continue + } switch v := arg.(type) { + case int64: + buf = strconv.AppendInt(buf, v, 10) + case uint64: + // Handle uint64 explicitly because our custom ConvertValue emits unsigned values + buf = strconv.AppendUint(buf, v, 10) + case float64: + buf = strconv.AppendFloat(buf, v, 'g', -1, 64) + case bool: + if v { + buf = append(buf, '1') + } else { + buf = append(buf, '0') + } + case time.Time: + if v.IsZero() { + buf = append(buf, "'0000-00-00'"...) + } else { + buf = append(buf, '\'') + buf, err = appendDateTime(buf, v.In(mc.cfg.Loc)) + if err != nil { + return "", err + } + buf = append(buf, '\'') + } + case json.RawMessage: + buf = append(buf, '\'') + if mc.status&statusNoBackslashEscapes == 0 { + buf = escapeBytesBackslash(buf, v) + } else { + buf = escapeBytesQuotes(buf, v) + } + buf = append(buf, '\'') + case []byte: + if v == nil { + buf = append(buf, "NULL"...) + } else { + buf = append(buf, "_binary'"...) + if mc.status&statusNoBackslashEscapes == 0 { + buf = escapeBytesBackslash(buf, v) + } else { + buf = escapeBytesQuotes(buf, v) + } + buf = append(buf, '\'') + } + case string: + buf = append(buf, '\'') + if mc.status&statusNoBackslashEscapes == 0 { + buf = escapeStringBackslash(buf, v) + } else { + buf = escapeStringQuotes(buf, v) + } + buf = append(buf, '\'') + default: + return "", driver.ErrSkip + } if len(buf)+4 > mc.maxAllowedPacket { + return "", driver.ErrSkip + } + } + if argPos != len(args) { + return "", driver.ErrSkip + } + return string(buf), nil + } func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, error) { + if mc.closed.IsSet() { + errLog.Print(ErrInvalidConn) + return nil, driver.ErrBadConn + } + if len(args) != 0 { + if !mc.cfg.InterpolateParams { + return nil, driver.ErrSkip + } + // try to interpolate the parameters to save extra roundtrips for preparing and closing a statement + prepared, err := mc.interpolateParams(query, args) + if err != nil { + return nil, err + } + query = prepared + } + mc.affectedRows = 0 + mc.insertId = 0 err := mc.exec(query) + if err == nil { + return &mysqlResult{ + affectedRows: int64(mc.affectedRows), - insertId: int64(mc.insertId), + + insertId: int64(mc.insertId), }, err + } + return nil, mc.markBadConn(err) + } // Internal function to execute commands + func (mc *mysqlConn) exec(query string) error { + // Send command + if err := mc.writeCommandPacketStr(comQuery, query); err != nil { + return mc.markBadConn(err) + } // Read Result + resLen, err := mc.readResultSetHeaderPacket() + if err != nil { + return err + } if resLen > 0 { + // columns + if err := mc.readUntilEOF(); err != nil { + return err + } // rows + if err := mc.readUntilEOF(); err != nil { + return err + } + } return mc.discardResults() + } func (mc *mysqlConn) Query(query string, args []driver.Value) (driver.Rows, error) { + return mc.query(query, args) + } func (mc *mysqlConn) query(query string, args []driver.Value) (*textRows, error) { + if mc.closed.IsSet() { + errLog.Print(ErrInvalidConn) + return nil, driver.ErrBadConn + } + if len(args) != 0 { + if !mc.cfg.InterpolateParams { + return nil, driver.ErrSkip + } + // try client-side prepare to reduce roundtrip + prepared, err := mc.interpolateParams(query, args) + if err != nil { + return nil, err + } + query = prepared + } + // Send command + err := mc.writeCommandPacketStr(comQuery, query) + if err == nil { + // Read Result + var resLen int + resLen, err = mc.readResultSetHeaderPacket() + if err == nil { + rows := new(textRows) + rows.mc = mc if resLen == 0 { + rows.rs.done = true switch err := rows.NextResultSet(); err { + case nil, io.EOF: + return rows, nil + default: + return nil, err + } + } // Columns + rows.rs.columns, err = mc.readColumns(resLen) + return rows, err + } + } + return nil, mc.markBadConn(err) + } // Gets the value of the given MySQL System Variable + // The returned byte slice is only valid until the next read + func (mc *mysqlConn) getSystemVar(name string) ([]byte, error) { + // Send command + if err := mc.writeCommandPacketStr(comQuery, "SELECT @@"+name); err != nil { + return nil, err + } // Read Result + resLen, err := mc.readResultSetHeaderPacket() + if err == nil { + rows := new(textRows) + rows.mc = mc + rows.rs.columns = []mysqlField{{fieldType: fieldTypeVarChar}} if resLen > 0 { + // Columns + if err := mc.readUntilEOF(); err != nil { + return nil, err + } + } dest := make([]driver.Value, resLen) + if err = rows.readRow(dest); err == nil { + return dest[0].([]byte), mc.readUntilEOF() + } + } + return nil, err + } // finish is called when the query has canceled. + func (mc *mysqlConn) cancel(err error) { + mc.canceled.Set(err) + mc.cleanup() + } // finish is called when the query has succeeded. + func (mc *mysqlConn) finish() { + if !mc.watching || mc.finished == nil { + return + } + select { + case mc.finished <- struct{}{}: + mc.watching = false + case <-mc.closech: + } + } // Ping implements driver.Pinger interface + func (mc *mysqlConn) Ping(ctx context.Context) (err error) { + if mc.closed.IsSet() { + errLog.Print(ErrInvalidConn) + return driver.ErrBadConn + } if err = mc.watchCancel(ctx); err != nil { + return + } + defer mc.finish() if err = mc.writeCommandPacket(comPing); err != nil { + return mc.markBadConn(err) + } return mc.readResultOK() + } // BeginTx implements driver.ConnBeginTx interface + func (mc *mysqlConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { + if mc.closed.IsSet() { + return nil, driver.ErrBadConn + } if err := mc.watchCancel(ctx); err != nil { + return nil, err + } + defer mc.finish() if sql.IsolationLevel(opts.Isolation) != sql.LevelDefault { + level, err := mapIsolationLevel(opts.Isolation) + if err != nil { + return nil, err + } + err = mc.exec("SET TRANSACTION ISOLATION LEVEL " + level) + if err != nil { + return nil, err + } + } return mc.begin(opts.ReadOnly) + } func (mc *mysqlConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { + dargs, err := namedValueToValue(args) + if err != nil { + return nil, err + } if err := mc.watchCancel(ctx); err != nil { + return nil, err + } rows, err := mc.query(query, dargs) + if err != nil { + mc.finish() + return nil, err + } + rows.finish = mc.finish + return rows, err + } func (mc *mysqlConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { + dargs, err := namedValueToValue(args) + if err != nil { + return nil, err + } if err := mc.watchCancel(ctx); err != nil { + return nil, err + } + defer mc.finish() return mc.Exec(query, dargs) + } func (mc *mysqlConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { + if err := mc.watchCancel(ctx); err != nil { + return nil, err + } stmt, err := mc.Prepare(query) + mc.finish() + if err != nil { + return nil, err + } select { + default: + case <-ctx.Done(): + stmt.Close() + return nil, ctx.Err() + } + return stmt, nil + } func (stmt *mysqlStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) { + dargs, err := namedValueToValue(args) + if err != nil { + return nil, err + } if err := stmt.mc.watchCancel(ctx); err != nil { + return nil, err + } rows, err := stmt.query(dargs) + if err != nil { + stmt.mc.finish() + return nil, err + } + rows.finish = stmt.mc.finish + return rows, err + } func (stmt *mysqlStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) { + dargs, err := namedValueToValue(args) + if err != nil { + return nil, err + } if err := stmt.mc.watchCancel(ctx); err != nil { + return nil, err + } + defer stmt.mc.finish() return stmt.Exec(dargs) + } func (mc *mysqlConn) watchCancel(ctx context.Context) error { + if mc.watching { + // Reach here if canceled, + // so the connection is already invalid + mc.cleanup() + return nil + } + // When ctx is already cancelled, don't watch it. + if err := ctx.Err(); err != nil { + return err + } + // When ctx is not cancellable, don't watch it. + if ctx.Done() == nil { + return nil + } + // When watcher is not alive, can't watch it. + if mc.watcher == nil { + return nil + } mc.watching = true + mc.watcher <- ctx + return nil + } func (mc *mysqlConn) startWatcher() { + watcher := make(chan context.Context, 1) + mc.watcher = watcher + finished := make(chan struct{}) + mc.finished = finished + go func() { + for { + var ctx context.Context + select { + case ctx = <-watcher: + case <-mc.closech: + return + } select { + case <-ctx.Done(): + mc.cancel(ctx.Err()) + case <-finished: + case <-mc.closech: + return + } + } + }() + } func (mc *mysqlConn) CheckNamedValue(nv *driver.NamedValue) (err error) { + nv.Value, err = converter{}.ConvertValue(nv.Value) + return + } // ResetSession implements driver.SessionResetter. + // (From Go 1.10) + func (mc *mysqlConn) ResetSession(ctx context.Context) error { + if mc.closed.IsSet() { + return driver.ErrBadConn + } + mc.reset = true + return nil + } // IsValid implements driver.Validator interface + // (From Go 1.15) + func (mc *mysqlConn) IsValid() bool { + return !mc.closed.IsSet() + } diff --git a/vendor/github.com/go-sql-driver/mysql/connector.go b/vendor/github.com/go-sql-driver/mysql/connector.go index d567b4e..89d023b 100644 --- a/vendor/github.com/go-sql-driver/mysql/connector.go +++ b/vendor/github.com/go-sql-driver/mysql/connector.go @@ -1,9 +1,15 @@ // Go MySQL Driver - A MySQL-Driver for Go's database/sql package + // + // Copyright 2018 The Go-MySQL-Driver Authors. All rights reserved. + // + // This Source Code Form is subject to the terms of the Mozilla Public + // License, v. 2.0. If a copy of the MPL was not distributed with this file, + // You can obtain one at http://mozilla.org/MPL/2.0/. package mysql @@ -16,131 +22,226 @@ import ( type connector struct { cfg *Config // immutable private copy. + } // Connect implements driver.Connector interface. + // Connect returns a connection to the database. + func (c *connector) Connect(ctx context.Context) (driver.Conn, error) { + var err error // New mysqlConn + mc := &mysqlConn{ + maxAllowedPacket: maxPacketSize, - maxWriteSize: maxPacketSize - 1, - closech: make(chan struct{}), - cfg: c.cfg, + + maxWriteSize: maxPacketSize - 1, + + closech: make(chan struct{}), + + cfg: c.cfg, } + mc.parseTime = mc.cfg.ParseTime // Connect to Server + dialsLock.RLock() + dial, ok := dials[mc.cfg.Net] + dialsLock.RUnlock() + if ok { + dctx := ctx + if mc.cfg.Timeout > 0 { + var cancel context.CancelFunc + dctx, cancel = context.WithTimeout(ctx, c.cfg.Timeout) + defer cancel() + } + mc.netConn, err = dial(dctx, mc.cfg.Addr) + } else { + nd := net.Dialer{Timeout: mc.cfg.Timeout} + mc.netConn, err = nd.DialContext(ctx, mc.cfg.Net, mc.cfg.Addr) + } if err != nil { + return nil, err + } // Enable TCP Keepalives on TCP connections + if tc, ok := mc.netConn.(*net.TCPConn); ok { + if err := tc.SetKeepAlive(true); err != nil { + // Don't send COM_QUIT before handshake. + mc.netConn.Close() + mc.netConn = nil + return nil, err + } + } // Call startWatcher for context support (From Go 1.8) + mc.startWatcher() + if err := mc.watchCancel(ctx); err != nil { + mc.cleanup() + return nil, err + } + defer mc.finish() mc.buf = newBuffer(mc.netConn) // Set I/O timeouts + mc.buf.timeout = mc.cfg.ReadTimeout + mc.writeTimeout = mc.cfg.WriteTimeout // Reading Handshake Initialization Packet + authData, plugin, err := mc.readHandshakePacket() + if err != nil { + mc.cleanup() + return nil, err + } if plugin == "" { + plugin = defaultAuthPlugin + } // Send Client Authentication Packet + authResp, err := mc.auth(authData, plugin) + if err != nil { + // try the default auth plugin, if using the requested plugin failed + errLog.Print("could not use requested auth plugin '"+plugin+"': ", err.Error()) + plugin = defaultAuthPlugin + authResp, err = mc.auth(authData, plugin) + if err != nil { + mc.cleanup() + return nil, err + } + } + if err = mc.writeHandshakeResponsePacket(authResp, plugin); err != nil { + mc.cleanup() + return nil, err + } // Handle response to auth packet, switch methods if possible + if err = mc.handleAuthResult(authData, plugin); err != nil { + // Authentication failed and MySQL has already closed the connection + // (https://dev.mysql.com/doc/internals/en/authentication-fails.html). + // Do not send COM_QUIT, just cleanup and return the error. + mc.cleanup() + return nil, err + } if mc.cfg.MaxAllowedPacket > 0 { + mc.maxAllowedPacket = mc.cfg.MaxAllowedPacket + } else { + // Get max allowed packet size + maxap, err := mc.getSystemVar("max_allowed_packet") + if err != nil { + mc.Close() + return nil, err + } + mc.maxAllowedPacket = stringToInt(maxap) - 1 + } + if mc.maxAllowedPacket < maxPacketSize { + mc.maxWriteSize = mc.maxAllowedPacket + } // Handle DSN Params + err = mc.handleParams() + if err != nil { + mc.Close() + return nil, err + } return mc, nil + } // Driver implements driver.Connector interface. + // Driver returns &MySQLDriver{}. + func (c *connector) Driver() driver.Driver { + return &MySQLDriver{} + } diff --git a/vendor/github.com/go-sql-driver/mysql/driver.go b/vendor/github.com/go-sql-driver/mysql/driver.go index ad7aec2..365a697 100644 --- a/vendor/github.com/go-sql-driver/mysql/driver.go +++ b/vendor/github.com/go-sql-driver/mysql/driver.go @@ -1,19 +1,33 @@ // Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. + // + // This Source Code Form is subject to the terms of the Mozilla Public + // License, v. 2.0. If a copy of the MPL was not distributed with this file, + // You can obtain one at http://mozilla.org/MPL/2.0/. // Package mysql provides a MySQL driver for Go's database/sql package. + // + // The driver should be used via the database/sql package: + // + // import "database/sql" + // import _ "github.com/go-sql-driver/mysql" + // + // db, err := sql.Open("mysql", "user:password@/dbname") + // + // See https://github.com/go-sql-driver/mysql#usage for details + package mysql import ( @@ -25,83 +39,141 @@ import ( ) // MySQLDriver is exported to make the driver directly accessible. + // In general the driver is used via the database/sql package. + type MySQLDriver struct{} // DialFunc is a function which can be used to establish the network connection. + // Custom dial functions must be registered with RegisterDial + // + // Deprecated: users should register a DialContextFunc instead + type DialFunc func(addr string) (net.Conn, error) // DialContextFunc is a function which can be used to establish the network connection. + // Custom dial functions must be registered with RegisterDialContext + type DialContextFunc func(ctx context.Context, addr string) (net.Conn, error) var ( dialsLock sync.RWMutex - dials map[string]DialContextFunc + + dials map[string]DialContextFunc ) // RegisterDialContext registers a custom dial function. It can then be used by the + // network address mynet(addr), where mynet is the registered new network. + // The current context for the connection and its address is passed to the dial function. + func RegisterDialContext(net string, dial DialContextFunc) { + dialsLock.Lock() + defer dialsLock.Unlock() + if dials == nil { + dials = make(map[string]DialContextFunc) + } + dials[net] = dial + } // RegisterDial registers a custom dial function. It can then be used by the + // network address mynet(addr), where mynet is the registered new network. + // addr is passed as a parameter to the dial function. + // + // Deprecated: users should call RegisterDialContext instead + func RegisterDial(network string, dial DialFunc) { + RegisterDialContext(network, func(_ context.Context, addr string) (net.Conn, error) { + return dial(addr) + }) + } // Open new Connection. + // See https://github.com/go-sql-driver/mysql#dsn-data-source-name for how + // the DSN string is formatted + func (d MySQLDriver) Open(dsn string) (driver.Conn, error) { + cfg, err := ParseDSN(dsn) + if err != nil { + return nil, err + } + c := &connector{ + cfg: cfg, } + return c.Connect(context.Background()) + } func init() { + sql.Register("mysql", &MySQLDriver{}) + } // NewConnector returns new driver.Connector. + func NewConnector(cfg *Config) (driver.Connector, error) { + cfg = cfg.Clone() + // normalize the contents of cfg so calls to NewConnector have the same + // behavior as MySQLDriver.OpenConnector + if err := cfg.normalize(); err != nil { + return nil, err + } + return &connector{cfg: cfg}, nil + } // OpenConnector implements driver.DriverContext. + func (d MySQLDriver) OpenConnector(dsn string) (driver.Connector, error) { + cfg, err := ParseDSN(dsn) + if err != nil { + return nil, err + } + return &connector{ + cfg: cfg, }, nil + } diff --git a/vendor/github.com/go-sql-driver/mysql/dsn.go b/vendor/github.com/go-sql-driver/mysql/dsn.go index 93f3548..0e60064 100644 --- a/vendor/github.com/go-sql-driver/mysql/dsn.go +++ b/vendor/github.com/go-sql-driver/mysql/dsn.go @@ -1,9 +1,15 @@ // Go MySQL Driver - A MySQL-Driver for Go's database/sql package + // + // Copyright 2016 The Go-MySQL-Driver Authors. All rights reserved. + // + // This Source Code Form is subject to the terms of the Mozilla Public + // License, v. 2.0. If a copy of the MPL was not distributed with this file, + // You can obtain one at http://mozilla.org/MPL/2.0/. package mysql @@ -24,537 +30,924 @@ import ( ) var ( - errInvalidDSNUnescaped = errors.New("invalid DSN: did you forget to escape a param value?") - errInvalidDSNAddr = errors.New("invalid DSN: network address not terminated (missing closing brace)") - errInvalidDSNNoSlash = errors.New("invalid DSN: missing the slash separating the database name") + errInvalidDSNUnescaped = errors.New("invalid DSN: did you forget to escape a param value?") + + errInvalidDSNAddr = errors.New("invalid DSN: network address not terminated (missing closing brace)") + + errInvalidDSNNoSlash = errors.New("invalid DSN: missing the slash separating the database name") + errInvalidDSNUnsafeCollation = errors.New("invalid DSN: interpolateParams can not be used with unsafe collations") ) // Config is a configuration parsed from a DSN string. -// If a new Config is created instead of being parsed from a DSN string, -// the NewConfig function should be used, which sets default values. -type Config struct { - User string // Username - Passwd string // Password (requires User) - Net string // Network type - Addr string // Network address (requires Net) - DBName string // Database name - Params map[string]string // Connection parameters - Collation string // Connection collation - Loc *time.Location // Location for time.Time values - MaxAllowedPacket int // Max packet size allowed - ServerPubKey string // Server public key name - pubKey *rsa.PublicKey // Server public key - TLSConfig string // TLS configuration name - tls *tls.Config // TLS configuration - Timeout time.Duration // Dial timeout - ReadTimeout time.Duration // I/O read timeout - WriteTimeout time.Duration // I/O write timeout - AllowAllFiles bool // Allow all files to be used with LOAD DATA LOCAL INFILE +// If a new Config is created instead of being parsed from a DSN string, + +// the NewConfig function should be used, which sets default values. + +type Config struct { + User string // Username + + Passwd string // Password (requires User) + + Net string // Network type + + Addr string // Network address (requires Net) + + DBName string // Database name + + Params map[string]string // Connection parameters + + Collation string // Connection collation + + Loc *time.Location // Location for time.Time values + + MaxAllowedPacket int // Max packet size allowed + + ServerPubKey string // Server public key name + + pubKey *rsa.PublicKey // Server public key + + TLSConfig string // TLS configuration name + + tls *tls.Config // TLS configuration + + Timeout time.Duration // Dial timeout + + ReadTimeout time.Duration // I/O read timeout + + WriteTimeout time.Duration // I/O write timeout + + AllowAllFiles bool // Allow all files to be used with LOAD DATA LOCAL INFILE + AllowCleartextPasswords bool // Allows the cleartext client side plugin - AllowNativePasswords bool // Allows the native password authentication method - AllowOldPasswords bool // Allows the old insecure password method - CheckConnLiveness bool // Check connections for liveness before using them - ClientFoundRows bool // Return number of matching rows instead of rows changed - ColumnsWithAlias bool // Prepend table alias to column names - InterpolateParams bool // Interpolate placeholders into query string - MultiStatements bool // Allow multiple statements in one query - ParseTime bool // Parse time values to time.Time - RejectReadOnly bool // Reject read-only connections + + AllowNativePasswords bool // Allows the native password authentication method + + AllowOldPasswords bool // Allows the old insecure password method + + CheckConnLiveness bool // Check connections for liveness before using them + + ClientFoundRows bool // Return number of matching rows instead of rows changed + + ColumnsWithAlias bool // Prepend table alias to column names + + InterpolateParams bool // Interpolate placeholders into query string + + MultiStatements bool // Allow multiple statements in one query + + ParseTime bool // Parse time values to time.Time + + RejectReadOnly bool // Reject read-only connections + } // NewConfig creates a new Config and sets default values. + func NewConfig() *Config { + return &Config{ - Collation: defaultCollation, - Loc: time.UTC, - MaxAllowedPacket: defaultMaxAllowedPacket, + + Collation: defaultCollation, + + Loc: time.UTC, + + MaxAllowedPacket: defaultMaxAllowedPacket, + AllowNativePasswords: true, - CheckConnLiveness: true, + + CheckConnLiveness: true, } + } func (cfg *Config) Clone() *Config { + cp := *cfg + if cp.tls != nil { + cp.tls = cfg.tls.Clone() + } + if len(cp.Params) > 0 { + cp.Params = make(map[string]string, len(cfg.Params)) + for k, v := range cfg.Params { + cp.Params[k] = v + } + } + if cfg.pubKey != nil { + cp.pubKey = &rsa.PublicKey{ + N: new(big.Int).Set(cfg.pubKey.N), + E: cfg.pubKey.E, } + } + return &cp + } func (cfg *Config) normalize() error { + if cfg.InterpolateParams && unsafeCollations[cfg.Collation] { + return errInvalidDSNUnsafeCollation + } // Set default network if empty + if cfg.Net == "" { + cfg.Net = "tcp" + } // Set default address if empty + if cfg.Addr == "" { + switch cfg.Net { + case "tcp": + cfg.Addr = "127.0.0.1:3306" + case "unix": + cfg.Addr = "/tmp/mysql.sock" + default: + return errors.New("default addr for network '" + cfg.Net + "' unknown") + } + } else if cfg.Net == "tcp" { + cfg.Addr = ensureHavePort(cfg.Addr) + } switch cfg.TLSConfig { + case "false", "": + // don't set anything + case "true": + cfg.tls = &tls.Config{} + case "skip-verify", "preferred": + cfg.tls = &tls.Config{InsecureSkipVerify: true} + default: + cfg.tls = getTLSConfigClone(cfg.TLSConfig) + if cfg.tls == nil { + return errors.New("invalid value / unknown config name: " + cfg.TLSConfig) + } + } if cfg.tls != nil && cfg.tls.ServerName == "" && !cfg.tls.InsecureSkipVerify { + host, _, err := net.SplitHostPort(cfg.Addr) + if err == nil { + cfg.tls.ServerName = host + } + } if cfg.ServerPubKey != "" { + cfg.pubKey = getServerPubKey(cfg.ServerPubKey) + if cfg.pubKey == nil { + return errors.New("invalid value / unknown server pub key name: " + cfg.ServerPubKey) + } + } return nil + } func writeDSNParam(buf *bytes.Buffer, hasParam *bool, name, value string) { + buf.Grow(1 + len(name) + 1 + len(value)) + if !*hasParam { + *hasParam = true + buf.WriteByte('?') + } else { + buf.WriteByte('&') + } + buf.WriteString(name) + buf.WriteByte('=') + buf.WriteString(value) + } // FormatDSN formats the given Config into a DSN string which can be passed to + // the driver. + func (cfg *Config) FormatDSN() string { + var buf bytes.Buffer // [username[:password]@] + if len(cfg.User) > 0 { + buf.WriteString(cfg.User) + if len(cfg.Passwd) > 0 { + buf.WriteByte(':') + buf.WriteString(cfg.Passwd) + } + buf.WriteByte('@') + } // [protocol[(address)]] + if len(cfg.Net) > 0 { + buf.WriteString(cfg.Net) + if len(cfg.Addr) > 0 { + buf.WriteByte('(') + buf.WriteString(cfg.Addr) + buf.WriteByte(')') + } + } // /dbname + buf.WriteByte('/') + buf.WriteString(cfg.DBName) // [?param1=value1&...¶mN=valueN] + hasParam := false if cfg.AllowAllFiles { + hasParam = true + buf.WriteString("?allowAllFiles=true") + } if cfg.AllowCleartextPasswords { + writeDSNParam(&buf, &hasParam, "allowCleartextPasswords", "true") + } if !cfg.AllowNativePasswords { + writeDSNParam(&buf, &hasParam, "allowNativePasswords", "false") + } if cfg.AllowOldPasswords { + writeDSNParam(&buf, &hasParam, "allowOldPasswords", "true") + } if !cfg.CheckConnLiveness { + writeDSNParam(&buf, &hasParam, "checkConnLiveness", "false") + } if cfg.ClientFoundRows { + writeDSNParam(&buf, &hasParam, "clientFoundRows", "true") + } if col := cfg.Collation; col != defaultCollation && len(col) > 0 { + writeDSNParam(&buf, &hasParam, "collation", col) + } if cfg.ColumnsWithAlias { + writeDSNParam(&buf, &hasParam, "columnsWithAlias", "true") + } if cfg.InterpolateParams { + writeDSNParam(&buf, &hasParam, "interpolateParams", "true") + } if cfg.Loc != time.UTC && cfg.Loc != nil { + writeDSNParam(&buf, &hasParam, "loc", url.QueryEscape(cfg.Loc.String())) + } if cfg.MultiStatements { + writeDSNParam(&buf, &hasParam, "multiStatements", "true") + } if cfg.ParseTime { + writeDSNParam(&buf, &hasParam, "parseTime", "true") + } if cfg.ReadTimeout > 0 { + writeDSNParam(&buf, &hasParam, "readTimeout", cfg.ReadTimeout.String()) + } if cfg.RejectReadOnly { + writeDSNParam(&buf, &hasParam, "rejectReadOnly", "true") + } if len(cfg.ServerPubKey) > 0 { + writeDSNParam(&buf, &hasParam, "serverPubKey", url.QueryEscape(cfg.ServerPubKey)) + } if cfg.Timeout > 0 { + writeDSNParam(&buf, &hasParam, "timeout", cfg.Timeout.String()) + } if len(cfg.TLSConfig) > 0 { + writeDSNParam(&buf, &hasParam, "tls", url.QueryEscape(cfg.TLSConfig)) + } if cfg.WriteTimeout > 0 { + writeDSNParam(&buf, &hasParam, "writeTimeout", cfg.WriteTimeout.String()) + } if cfg.MaxAllowedPacket != defaultMaxAllowedPacket { + writeDSNParam(&buf, &hasParam, "maxAllowedPacket", strconv.Itoa(cfg.MaxAllowedPacket)) + } // other params + if cfg.Params != nil { + var params []string + for param := range cfg.Params { + params = append(params, param) + } + sort.Strings(params) + for _, param := range params { + writeDSNParam(&buf, &hasParam, param, url.QueryEscape(cfg.Params[param])) + } + } return buf.String() + } // ParseDSN parses the DSN string to a Config + func ParseDSN(dsn string) (cfg *Config, err error) { + // New config with some default values + cfg = NewConfig() // [user[:password]@][net[(addr)]]/dbname[?param1=value1¶mN=valueN] + // Find the last '/' (since the password or the net addr might contain a '/') + foundSlash := false + for i := len(dsn) - 1; i >= 0; i-- { + if dsn[i] == '/' { + foundSlash = true + var j, k int // left part is empty if i <= 0 + if i > 0 { + // [username[:password]@][protocol[(address)]] + // Find the last '@' in dsn[:i] + for j = i; j >= 0; j-- { + if dsn[j] == '@' { + // username[:password] + // Find the first ':' in dsn[:j] + for k = 0; k < j; k++ { + if dsn[k] == ':' { + cfg.Passwd = dsn[k+1 : j] + break + } + } + cfg.User = dsn[:k] break + } + } // [protocol[(address)]] + // Find the first '(' in dsn[j+1:i] + for k = j + 1; k < i; k++ { + if dsn[k] == '(' { + // dsn[i-1] must be == ')' if an address is specified + if dsn[i-1] != ')' { + if strings.ContainsRune(dsn[k+1:i], ')') { + return nil, errInvalidDSNUnescaped + } + return nil, errInvalidDSNAddr + } + cfg.Addr = dsn[k+1 : i-1] + break + } + } + cfg.Net = dsn[j+1 : k] + } // dbname[?param1=value1&...¶mN=valueN] + // Find the first '?' in dsn[i+1:] + for j = i + 1; j < len(dsn); j++ { + if dsn[j] == '?' { + if err = parseDSNParams(cfg, dsn[j+1:]); err != nil { + return + } + break + } + } + cfg.DBName = dsn[i+1 : j] break + } + } if !foundSlash && len(dsn) > 0 { + return nil, errInvalidDSNNoSlash + } if err = cfg.normalize(); err != nil { + return nil, err + } + return + } // parseDSNParams parses the DSN "query string" + // Values must be url.QueryEscape'ed + func parseDSNParams(cfg *Config, params string) (err error) { + for _, v := range strings.Split(params, "&") { + param := strings.SplitN(v, "=", 2) + if len(param) != 2 { + continue + } // cfg params + switch value := param[1]; param[0] { + // Disable INFILE allowlist / enable all files + case "allowAllFiles": + var isBool bool + cfg.AllowAllFiles, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } // Use cleartext authentication mode (MySQL 5.5.10+) + case "allowCleartextPasswords": + var isBool bool + cfg.AllowCleartextPasswords, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } // Use native password authentication + case "allowNativePasswords": + var isBool bool + cfg.AllowNativePasswords, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } // Use old authentication mode (pre MySQL 4.1) + case "allowOldPasswords": + var isBool bool + cfg.AllowOldPasswords, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } // Check connections for Liveness before using them + case "checkConnLiveness": + var isBool bool + cfg.CheckConnLiveness, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } // Switch "rowsAffected" mode + case "clientFoundRows": + var isBool bool + cfg.ClientFoundRows, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } // Collation + case "collation": + cfg.Collation = value + break case "columnsWithAlias": + var isBool bool + cfg.ColumnsWithAlias, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } // Compression + case "compress": + return errors.New("compression not implemented yet") // Enable client side placeholder substitution + case "interpolateParams": + var isBool bool + cfg.InterpolateParams, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } // Time Location + case "loc": + if value, err = url.QueryUnescape(value); err != nil { + return + } + cfg.Loc, err = time.LoadLocation(value) + if err != nil { + return + } // multiple statements in one query + case "multiStatements": + var isBool bool + cfg.MultiStatements, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } // time.Time parsing + case "parseTime": + var isBool bool + cfg.ParseTime, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } // I/O read Timeout + case "readTimeout": + cfg.ReadTimeout, err = time.ParseDuration(value) + if err != nil { + return + } // Reject read-only connections + case "rejectReadOnly": + var isBool bool + cfg.RejectReadOnly, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } // Server public key + case "serverPubKey": + name, err := url.QueryUnescape(value) + if err != nil { + return fmt.Errorf("invalid value for server pub key name: %v", err) + } + cfg.ServerPubKey = name // Strict mode + case "strict": + panic("strict mode has been removed. See https://github.com/go-sql-driver/mysql/wiki/strict-mode") // Dial Timeout + case "timeout": + cfg.Timeout, err = time.ParseDuration(value) + if err != nil { + return + } // TLS-Encryption + case "tls": + boolValue, isBool := readBool(value) + if isBool { + if boolValue { + cfg.TLSConfig = "true" + } else { + cfg.TLSConfig = "false" + } + } else if vl := strings.ToLower(value); vl == "skip-verify" || vl == "preferred" { + cfg.TLSConfig = vl + } else { + name, err := url.QueryUnescape(value) + if err != nil { + return fmt.Errorf("invalid value for TLS config name: %v", err) + } + cfg.TLSConfig = name + } // I/O write Timeout + case "writeTimeout": + cfg.WriteTimeout, err = time.ParseDuration(value) + if err != nil { + return + } + case "maxAllowedPacket": + cfg.MaxAllowedPacket, err = strconv.Atoi(value) + if err != nil { + return + } + default: + // lazy init + if cfg.Params == nil { + cfg.Params = make(map[string]string) + } if cfg.Params[param[0]], err = url.QueryUnescape(value); err != nil { + return + } + } + } return + } func ensureHavePort(addr string) string { + if _, _, err := net.SplitHostPort(addr); err != nil { + return net.JoinHostPort(addr, "3306") + } + return addr + } diff --git a/vendor/github.com/go-sql-driver/mysql/errors.go b/vendor/github.com/go-sql-driver/mysql/errors.go index 760782f..b2b7ebc 100644 --- a/vendor/github.com/go-sql-driver/mysql/errors.go +++ b/vendor/github.com/go-sql-driver/mysql/errors.go @@ -1,9 +1,15 @@ // Go MySQL Driver - A MySQL-Driver for Go's database/sql package + // + // Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. + // + // This Source Code Form is subject to the terms of the Mozilla Public + // License, v. 2.0. If a copy of the MPL was not distributed with this file, + // You can obtain one at http://mozilla.org/MPL/2.0/. package mysql @@ -16,50 +22,79 @@ import ( ) // Various errors the driver might return. Can change between driver versions. + var ( - ErrInvalidConn = errors.New("invalid connection") - ErrMalformPkt = errors.New("malformed packet") - ErrNoTLS = errors.New("TLS requested but server does not support TLS") + ErrInvalidConn = errors.New("invalid connection") + + ErrMalformPkt = errors.New("malformed packet") + + ErrNoTLS = errors.New("TLS requested but server does not support TLS") + ErrCleartextPassword = errors.New("this user requires clear text authentication. If you still want to use it, please add 'allowCleartextPasswords=1' to your DSN") - ErrNativePassword = errors.New("this user requires mysql native password authentication.") - ErrOldPassword = errors.New("this user requires old password authentication. If you still want to use it, please add 'allowOldPasswords=1' to your DSN. See also https://github.com/go-sql-driver/mysql/wiki/old_passwords") - ErrUnknownPlugin = errors.New("this authentication plugin is not supported") - ErrOldProtocol = errors.New("MySQL server does not support required protocol 41+") - ErrPktSync = errors.New("commands out of sync. You can't run this command now") - ErrPktSyncMul = errors.New("commands out of sync. Did you run multiple statements at once?") - ErrPktTooLarge = errors.New("packet for query is too large. Try adjusting the 'max_allowed_packet' variable on the server") - ErrBusyBuffer = errors.New("busy buffer") + + ErrNativePassword = errors.New("this user requires mysql native password authentication.") + + ErrOldPassword = errors.New("this user requires old password authentication. If you still want to use it, please add 'allowOldPasswords=1' to your DSN. See also https://github.com/go-sql-driver/mysql/wiki/old_passwords") + + ErrUnknownPlugin = errors.New("this authentication plugin is not supported") + + ErrOldProtocol = errors.New("MySQL server does not support required protocol 41+") + + ErrPktSync = errors.New("commands out of sync. You can't run this command now") + + ErrPktSyncMul = errors.New("commands out of sync. Did you run multiple statements at once?") + + ErrPktTooLarge = errors.New("packet for query is too large. Try adjusting the 'max_allowed_packet' variable on the server") + + ErrBusyBuffer = errors.New("busy buffer") // errBadConnNoWrite is used for connection errors where nothing was sent to the database yet. + // If this happens first in a function starting a database interaction, it should be replaced by driver.ErrBadConn + // to trigger a resend. + // See https://github.com/go-sql-driver/mysql/pull/302 + errBadConnNoWrite = errors.New("bad connection") ) var errLog = Logger(log.New(os.Stderr, "[mysql] ", log.Ldate|log.Ltime|log.Lshortfile)) // Logger is used to log critical error messages. + type Logger interface { Print(v ...interface{}) } // SetLogger is used to set the logger for critical errors. + // The initial logger is os.Stderr. + func SetLogger(logger Logger) error { + if logger == nil { + return errors.New("logger is nil") + } + errLog = logger + return nil + } // MySQLError is an error type which represents a single MySQL error + type MySQLError struct { - Number uint16 + Number uint16 + Message string } func (me *MySQLError) Error() string { + return fmt.Sprintf("Error %d: %s", me.Number, me.Message) + } diff --git a/vendor/github.com/go-sql-driver/mysql/fields.go b/vendor/github.com/go-sql-driver/mysql/fields.go index ed6c7a3..38610a3 100644 --- a/vendor/github.com/go-sql-driver/mysql/fields.go +++ b/vendor/github.com/go-sql-driver/mysql/fields.go @@ -1,9 +1,15 @@ // Go MySQL Driver - A MySQL-Driver for Go's database/sql package + // + // Copyright 2017 The Go-MySQL-Driver Authors. All rights reserved. + // + // This Source Code Form is subject to the terms of the Mozilla Public + // License, v. 2.0. If a copy of the MPL was not distributed with this file, + // You can obtain one at http://mozilla.org/MPL/2.0/. package mysql @@ -14,181 +20,333 @@ import ( ) func (mf *mysqlField) typeDatabaseName() string { + switch mf.fieldType { + case fieldTypeBit: + return "BIT" + case fieldTypeBLOB: + if mf.charSet != collations[binaryCollation] { + return "TEXT" + } + return "BLOB" + case fieldTypeDate: + return "DATE" + case fieldTypeDateTime: + return "DATETIME" + case fieldTypeDecimal: + return "DECIMAL" + case fieldTypeDouble: + return "DOUBLE" + case fieldTypeEnum: + return "ENUM" + case fieldTypeFloat: + return "FLOAT" + case fieldTypeGeometry: + return "GEOMETRY" + case fieldTypeInt24: + return "MEDIUMINT" + case fieldTypeJSON: + return "JSON" + case fieldTypeLong: + return "INT" + case fieldTypeLongBLOB: + if mf.charSet != collations[binaryCollation] { + return "LONGTEXT" + } + return "LONGBLOB" + case fieldTypeLongLong: + return "BIGINT" + case fieldTypeMediumBLOB: + if mf.charSet != collations[binaryCollation] { + return "MEDIUMTEXT" + } + return "MEDIUMBLOB" + case fieldTypeNewDate: + return "DATE" + case fieldTypeNewDecimal: + return "DECIMAL" + case fieldTypeNULL: + return "NULL" + case fieldTypeSet: + return "SET" + case fieldTypeShort: + return "SMALLINT" + case fieldTypeString: + if mf.charSet == collations[binaryCollation] { + return "BINARY" + } + return "CHAR" + case fieldTypeTime: + return "TIME" + case fieldTypeTimestamp: + return "TIMESTAMP" + case fieldTypeTiny: + return "TINYINT" + case fieldTypeTinyBLOB: + if mf.charSet != collations[binaryCollation] { + return "TINYTEXT" + } + return "TINYBLOB" + case fieldTypeVarChar: + if mf.charSet == collations[binaryCollation] { + return "VARBINARY" + } + return "VARCHAR" + case fieldTypeVarString: + if mf.charSet == collations[binaryCollation] { + return "VARBINARY" + } + return "VARCHAR" + case fieldTypeYear: + return "YEAR" + default: + return "" + } + } var ( - scanTypeFloat32 = reflect.TypeOf(float32(0)) - scanTypeFloat64 = reflect.TypeOf(float64(0)) - scanTypeInt8 = reflect.TypeOf(int8(0)) - scanTypeInt16 = reflect.TypeOf(int16(0)) - scanTypeInt32 = reflect.TypeOf(int32(0)) - scanTypeInt64 = reflect.TypeOf(int64(0)) + scanTypeFloat32 = reflect.TypeOf(float32(0)) + + scanTypeFloat64 = reflect.TypeOf(float64(0)) + + scanTypeInt8 = reflect.TypeOf(int8(0)) + + scanTypeInt16 = reflect.TypeOf(int16(0)) + + scanTypeInt32 = reflect.TypeOf(int32(0)) + + scanTypeInt64 = reflect.TypeOf(int64(0)) + scanTypeNullFloat = reflect.TypeOf(sql.NullFloat64{}) - scanTypeNullInt = reflect.TypeOf(sql.NullInt64{}) - scanTypeNullTime = reflect.TypeOf(nullTime{}) - scanTypeUint8 = reflect.TypeOf(uint8(0)) - scanTypeUint16 = reflect.TypeOf(uint16(0)) - scanTypeUint32 = reflect.TypeOf(uint32(0)) - scanTypeUint64 = reflect.TypeOf(uint64(0)) - scanTypeRawBytes = reflect.TypeOf(sql.RawBytes{}) - scanTypeUnknown = reflect.TypeOf(new(interface{})) + + scanTypeNullInt = reflect.TypeOf(sql.NullInt64{}) + + scanTypeNullTime = reflect.TypeOf(nullTime{}) + + scanTypeUint8 = reflect.TypeOf(uint8(0)) + + scanTypeUint16 = reflect.TypeOf(uint16(0)) + + scanTypeUint32 = reflect.TypeOf(uint32(0)) + + scanTypeUint64 = reflect.TypeOf(uint64(0)) + + scanTypeRawBytes = reflect.TypeOf(sql.RawBytes{}) + + scanTypeUnknown = reflect.TypeOf(new(interface{})) ) type mysqlField struct { tableName string - name string - length uint32 - flags fieldFlag + + name string + + length uint32 + + flags fieldFlag + fieldType fieldType - decimals byte - charSet uint8 + + decimals byte + + charSet uint8 } func (mf *mysqlField) scanType() reflect.Type { + switch mf.fieldType { + case fieldTypeTiny: + if mf.flags&flagNotNULL != 0 { + if mf.flags&flagUnsigned != 0 { + return scanTypeUint8 + } + return scanTypeInt8 + } + return scanTypeNullInt case fieldTypeShort, fieldTypeYear: + if mf.flags&flagNotNULL != 0 { + if mf.flags&flagUnsigned != 0 { + return scanTypeUint16 + } + return scanTypeInt16 + } + return scanTypeNullInt case fieldTypeInt24, fieldTypeLong: + if mf.flags&flagNotNULL != 0 { + if mf.flags&flagUnsigned != 0 { + return scanTypeUint32 + } + return scanTypeInt32 + } + return scanTypeNullInt case fieldTypeLongLong: + if mf.flags&flagNotNULL != 0 { + if mf.flags&flagUnsigned != 0 { + return scanTypeUint64 + } + return scanTypeInt64 + } + return scanTypeNullInt case fieldTypeFloat: + if mf.flags&flagNotNULL != 0 { + return scanTypeFloat32 + } + return scanTypeNullFloat case fieldTypeDouble: + if mf.flags&flagNotNULL != 0 { + return scanTypeFloat64 + } + return scanTypeNullFloat case fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar, + fieldTypeBit, fieldTypeEnum, fieldTypeSet, fieldTypeTinyBLOB, + fieldTypeMediumBLOB, fieldTypeLongBLOB, fieldTypeBLOB, + fieldTypeVarString, fieldTypeString, fieldTypeGeometry, fieldTypeJSON, + fieldTypeTime: + return scanTypeRawBytes case fieldTypeDate, fieldTypeNewDate, + fieldTypeTimestamp, fieldTypeDateTime: + // NullTime is always returned for more consistent behavior as it can + // handle both cases of parseTime regardless if the field is nullable. + return scanTypeNullTime default: + return scanTypeUnknown + } + } diff --git a/vendor/github.com/go-sql-driver/mysql/infile.go b/vendor/github.com/go-sql-driver/mysql/infile.go index 955a00a..56f95fb 100644 --- a/vendor/github.com/go-sql-driver/mysql/infile.go +++ b/vendor/github.com/go-sql-driver/mysql/infile.go @@ -1,9 +1,15 @@ // Go MySQL Driver - A MySQL-Driver for Go's database/sql package + // + // Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. + // + // This Source Code Form is subject to the terms of the Mozilla Public + // License, v. 2.0. If a copy of the MPL was not distributed with this file, + // You can obtain one at http://mozilla.org/MPL/2.0/. package mysql @@ -17,164 +23,289 @@ import ( ) var ( - fileRegister map[string]bool - fileRegisterLock sync.RWMutex - readerRegister map[string]func() io.Reader + fileRegister map[string]bool + + fileRegisterLock sync.RWMutex + + readerRegister map[string]func() io.Reader + readerRegisterLock sync.RWMutex ) // RegisterLocalFile adds the given file to the file allowlist, + // so that it can be used by "LOAD DATA LOCAL INFILE ". + // Alternatively you can allow the use of all local files with + // the DSN parameter 'allowAllFiles=true' + // + // filePath := "/home/gopher/data.csv" + // mysql.RegisterLocalFile(filePath) + // err := db.Exec("LOAD DATA LOCAL INFILE '" + filePath + "' INTO TABLE foo") + // if err != nil { + // ... + func RegisterLocalFile(filePath string) { + fileRegisterLock.Lock() + // lazy map init + if fileRegister == nil { + fileRegister = make(map[string]bool) + } fileRegister[strings.Trim(filePath, `"`)] = true + fileRegisterLock.Unlock() + } // DeregisterLocalFile removes the given filepath from the allowlist. + func DeregisterLocalFile(filePath string) { + fileRegisterLock.Lock() + delete(fileRegister, strings.Trim(filePath, `"`)) + fileRegisterLock.Unlock() + } // RegisterReaderHandler registers a handler function which is used + // to receive a io.Reader. + // The Reader can be used by "LOAD DATA LOCAL INFILE Reader::". + // If the handler returns a io.ReadCloser Close() is called when the + // request is finished. + // + // mysql.RegisterReaderHandler("data", func() io.Reader { + // var csvReader io.Reader // Some Reader that returns CSV data + // ... // Open Reader here + // return csvReader + // }) + // err := db.Exec("LOAD DATA LOCAL INFILE 'Reader::data' INTO TABLE foo") + // if err != nil { + // ... + func RegisterReaderHandler(name string, handler func() io.Reader) { + readerRegisterLock.Lock() + // lazy map init + if readerRegister == nil { + readerRegister = make(map[string]func() io.Reader) + } readerRegister[name] = handler + readerRegisterLock.Unlock() + } // DeregisterReaderHandler removes the ReaderHandler function with + // the given name from the registry. + func DeregisterReaderHandler(name string) { + readerRegisterLock.Lock() + delete(readerRegister, name) + readerRegisterLock.Unlock() + } func deferredClose(err *error, closer io.Closer) { + closeErr := closer.Close() + if *err == nil { + *err = closeErr + } + } func (mc *mysqlConn) handleInFileRequest(name string) (err error) { + var rdr io.Reader + var data []byte + packetSize := 16 * 1024 // 16KB is small enough for disk readahead and large enough for TCP + if mc.maxWriteSize < packetSize { + packetSize = mc.maxWriteSize + } if idx := strings.Index(name, "Reader::"); idx == 0 || (idx > 0 && name[idx-1] == '/') { // io.Reader + // The server might return an an absolute path. See issue #355. + name = name[idx+8:] readerRegisterLock.RLock() + handler, inMap := readerRegister[name] + readerRegisterLock.RUnlock() if inMap { + rdr = handler() + if rdr != nil { + if cl, ok := rdr.(io.Closer); ok { + defer deferredClose(&err, cl) + } + } else { + err = fmt.Errorf("Reader '%s' is ", name) + } + } else { + err = fmt.Errorf("Reader '%s' is not registered", name) + } + } else { // File + name = strings.Trim(name, `"`) + fileRegisterLock.RLock() + fr := fileRegister[name] + fileRegisterLock.RUnlock() + if mc.cfg.AllowAllFiles || fr { + var file *os.File + var fi os.FileInfo if file, err = os.Open(name); err == nil { + defer deferredClose(&err, file) // get file size + if fi, err = file.Stat(); err == nil { + rdr = file + if fileSize := int(fi.Size()); fileSize < packetSize { + packetSize = fileSize + } + } + } + } else { + err = fmt.Errorf("local file '%s' is not registered", name) + } + } // send content packets + // if packetSize == 0, the Reader contains no data + if err == nil && packetSize > 0 { + data := make([]byte, 4+packetSize) + var n int + for err == nil { + n, err = rdr.Read(data[4:]) + if n > 0 { + if ioErr := mc.writePacket(data[:4+n]); ioErr != nil { + return ioErr + } + } + } + if err == io.EOF { + err = nil + } + } // send empty packet (termination) + if data == nil { + data = make([]byte, 4) + } + if ioErr := mc.writePacket(data[:4]); ioErr != nil { + return ioErr + } // read OK packet + if err == nil { + return mc.readResultOK() + } mc.readPacket() + return err + } diff --git a/vendor/github.com/go-sql-driver/mysql/nulltime.go b/vendor/github.com/go-sql-driver/mysql/nulltime.go index 651723a..ced862b 100644 --- a/vendor/github.com/go-sql-driver/mysql/nulltime.go +++ b/vendor/github.com/go-sql-driver/mysql/nulltime.go @@ -1,9 +1,15 @@ // Go MySQL Driver - A MySQL-Driver for Go's database/sql package + // + // Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. + // + // This Source Code Form is subject to the terms of the Mozilla Public + // License, v. 2.0. If a copy of the MPL was not distributed with this file, + // You can obtain one at http://mozilla.org/MPL/2.0/. package mysql @@ -15,36 +21,63 @@ import ( ) // Scan implements the Scanner interface. + // The value type must be time.Time or string / []byte (formatted time-string), + // otherwise Scan fails. + func (nt *NullTime) Scan(value interface{}) (err error) { + if value == nil { + nt.Time, nt.Valid = time.Time{}, false + return + } switch v := value.(type) { + case time.Time: + nt.Time, nt.Valid = v, true + return + case []byte: + nt.Time, err = parseDateTime(v, time.UTC) + nt.Valid = (err == nil) + return + case string: + nt.Time, err = parseDateTime([]byte(v), time.UTC) + nt.Valid = (err == nil) + return + } nt.Valid = false + return fmt.Errorf("Can't convert %T to time.Time", value) + } // Value implements the driver Valuer interface. + func (nt NullTime) Value() (driver.Value, error) { + if !nt.Valid { + return nil, nil + } + return nt.Time, nil + } diff --git a/vendor/github.com/go-sql-driver/mysql/packets.go b/vendor/github.com/go-sql-driver/mysql/packets.go index 6664e5a..ca071d7 100644 --- a/vendor/github.com/go-sql-driver/mysql/packets.go +++ b/vendor/github.com/go-sql-driver/mysql/packets.go @@ -1,9 +1,15 @@ // Go MySQL Driver - A MySQL-Driver for Go's database/sql package + // + // Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. + // + // This Source Code Form is subject to the terms of the Mozilla Public + // License, v. 2.0. If a copy of the MPL was not distributed with this file, + // You can obtain one at http://mozilla.org/MPL/2.0/. package mysql @@ -22,825 +28,1390 @@ import ( ) // Packets documentation: + // http://dev.mysql.com/doc/internals/en/client-server-protocol.html // Read packet to buffer 'data' + func (mc *mysqlConn) readPacket() ([]byte, error) { + var prevData []byte + for { + // read packet header + data, err := mc.buf.readNext(4) + if err != nil { + if cerr := mc.canceled.Value(); cerr != nil { + return nil, cerr + } + errLog.Print(err) + mc.Close() + return nil, ErrInvalidConn + } // packet length [24 bit] + pktLen := int(uint32(data[0]) | uint32(data[1])<<8 | uint32(data[2])<<16) // check packet sync [8 bit] + if data[3] != mc.sequence { + if data[3] > mc.sequence { + return nil, ErrPktSyncMul + } + return nil, ErrPktSync + } + mc.sequence++ // packets with length 0 terminate a previous packet which is a + // multiple of (2^24)-1 bytes long + if pktLen == 0 { + // there was no previous packet + if prevData == nil { + errLog.Print(ErrMalformPkt) + mc.Close() + return nil, ErrInvalidConn + } return prevData, nil + } // read packet body [pktLen bytes] + data, err = mc.buf.readNext(pktLen) + if err != nil { + if cerr := mc.canceled.Value(); cerr != nil { + return nil, cerr + } + errLog.Print(err) + mc.Close() + return nil, ErrInvalidConn + } // return data if this was the last packet + if pktLen < maxPacketSize { + // zero allocations for non-split packets + if prevData == nil { + return data, nil + } return append(prevData, data...), nil + } prevData = append(prevData, data...) + } + } // Write packet buffer 'data' + func (mc *mysqlConn) writePacket(data []byte) error { + pktLen := len(data) - 4 if pktLen > mc.maxAllowedPacket { + return ErrPktTooLarge + } // Perform a stale connection check. We only perform this check for + // the first query on a connection that has been checked out of the + // connection pool: a fresh connection from the pool is more likely + // to be stale, and it has not performed any previous writes that + // could cause data corruption, so it's safe to return ErrBadConn + // if the check fails. + if mc.reset { + mc.reset = false + conn := mc.netConn + if mc.rawConn != nil { + conn = mc.rawConn + } + var err error + // If this connection has a ReadTimeout which we've been setting on + // reads, reset it to its default value before we attempt a non-blocking + // read, otherwise the scheduler will just time us out before we can read + if mc.cfg.ReadTimeout != 0 { + err = conn.SetReadDeadline(time.Time{}) + } + if err == nil && mc.cfg.CheckConnLiveness { + err = connCheck(conn) + } + if err != nil { + errLog.Print("closing bad idle connection: ", err) + mc.Close() + return driver.ErrBadConn + } + } for { + var size int + if pktLen >= maxPacketSize { + data[0] = 0xff + data[1] = 0xff + data[2] = 0xff + size = maxPacketSize + } else { + data[0] = byte(pktLen) + data[1] = byte(pktLen >> 8) + data[2] = byte(pktLen >> 16) + size = pktLen + } + data[3] = mc.sequence // Write packet + if mc.writeTimeout > 0 { + if err := mc.netConn.SetWriteDeadline(time.Now().Add(mc.writeTimeout)); err != nil { + return err + } + } n, err := mc.netConn.Write(data[:4+size]) + if err == nil && n == 4+size { + mc.sequence++ + if size != maxPacketSize { + return nil + } + pktLen -= size + data = data[size:] + continue + } // Handle error + if err == nil { // n != len(data) + mc.cleanup() + errLog.Print(ErrMalformPkt) + } else { + if cerr := mc.canceled.Value(); cerr != nil { + return cerr + } + if n == 0 && pktLen == len(data)-4 { + // only for the first loop iteration when nothing was written yet + return errBadConnNoWrite + } + mc.cleanup() + errLog.Print(err) + } + return ErrInvalidConn + } + } /****************************************************************************** + * Initialization Process * + ******************************************************************************/ // Handshake Initialization Packet + // http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::Handshake + func (mc *mysqlConn) readHandshakePacket() (data []byte, plugin string, err error) { + data, err = mc.readPacket() + if err != nil { + // for init we can rewrite this to ErrBadConn for sql.Driver to retry, since + // in connection initialization we don't risk retrying non-idempotent actions. + if err == ErrInvalidConn { + return nil, "", driver.ErrBadConn + } + return + } if data[0] == iERR { + return nil, "", mc.handleErrorPacket(data) + } // protocol version [1 byte] + if data[0] < minProtocolVersion { + return nil, "", fmt.Errorf( + "unsupported protocol version %d. Version %d or higher is required", + data[0], + minProtocolVersion, ) + } // server version [null terminated string] + // connection id [4 bytes] + pos := 1 + bytes.IndexByte(data[1:], 0x00) + 1 + 4 // first part of the password cipher [8 bytes] + authData := data[pos : pos+8] // (filler) always 0x00 [1 byte] + pos += 8 + 1 // capability flags (lower 2 bytes) [2 bytes] + mc.flags = clientFlag(binary.LittleEndian.Uint16(data[pos : pos+2])) + if mc.flags&clientProtocol41 == 0 { + return nil, "", ErrOldProtocol + } + if mc.flags&clientSSL == 0 && mc.cfg.tls != nil { + if mc.cfg.TLSConfig == "preferred" { + mc.cfg.tls = nil + } else { + return nil, "", ErrNoTLS + } + } + pos += 2 if len(data) > pos { + // character set [1 byte] + // status flags [2 bytes] + // capability flags (upper 2 bytes) [2 bytes] + // length of auth-plugin-data [1 byte] + // reserved (all [00]) [10 bytes] + pos += 1 + 2 + 2 + 1 + 10 // second part of the password cipher [mininum 13 bytes], + // where len=MAX(13, length of auth-plugin-data - 8) + // + // The web documentation is ambiguous about the length. However, + // according to mysql-5.7/sql/auth/sql_authentication.cc line 538, + // the 13th byte is "\0 byte, terminating the second part of + // a scramble". So the second part of the password cipher is + // a NULL terminated string that's at least 13 bytes with the + // last byte being NULL. + // + // The official Python library uses the fixed length 12 + // which seems to work but technically could have a hidden bug. + authData = append(authData, data[pos:pos+12]...) + pos += 13 // EOF if version (>= 5.5.7 and < 5.5.10) or (>= 5.6.0 and < 5.6.2) + // \NUL otherwise + if end := bytes.IndexByte(data[pos:], 0x00); end != -1 { + plugin = string(data[pos : pos+end]) + } else { + plugin = string(data[pos:]) + } // make a memory safe copy of the cipher slice + var b [20]byte + copy(b[:], authData) + return b[:], plugin, nil + } // make a memory safe copy of the cipher slice + var b [8]byte + copy(b[:], authData) + return b[:], plugin, nil + } // Client Authentication Packet + // http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::HandshakeResponse + func (mc *mysqlConn) writeHandshakeResponsePacket(authResp []byte, plugin string) error { + // Adjust client flags based on server support + clientFlags := clientProtocol41 | + clientSecureConn | + clientLongPassword | + clientTransactions | + clientLocalFiles | + clientPluginAuth | + clientMultiResults | + mc.flags&clientLongFlag if mc.cfg.ClientFoundRows { + clientFlags |= clientFoundRows + } // To enable TLS / SSL + if mc.cfg.tls != nil { + clientFlags |= clientSSL + } if mc.cfg.MultiStatements { + clientFlags |= clientMultiStatements + } // encode length of the auth plugin data + var authRespLEIBuf [9]byte + authRespLen := len(authResp) + authRespLEI := appendLengthEncodedInteger(authRespLEIBuf[:0], uint64(authRespLen)) + if len(authRespLEI) > 1 { + // if the length can not be written in 1 byte, it must be written as a + // length encoded integer + clientFlags |= clientPluginAuthLenEncClientData + } pktLen := 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1 + len(authRespLEI) + len(authResp) + 21 + 1 // To specify a db name + if n := len(mc.cfg.DBName); n > 0 { + clientFlags |= clientConnectWithDB + pktLen += n + 1 + } // Calculate packet length and get buffer with that size + data, err := mc.buf.takeSmallBuffer(pktLen + 4) + if err != nil { + // cannot take the buffer. Something must be wrong with the connection + errLog.Print(err) + return errBadConnNoWrite + } // ClientFlags [32 bit] + data[4] = byte(clientFlags) + data[5] = byte(clientFlags >> 8) + data[6] = byte(clientFlags >> 16) + data[7] = byte(clientFlags >> 24) // MaxPacketSize [32 bit] (none) + data[8] = 0x00 + data[9] = 0x00 + data[10] = 0x00 + data[11] = 0x00 // Charset [1 byte] + var found bool + data[12], found = collations[mc.cfg.Collation] + if !found { + // Note possibility for false negatives: + // could be triggered although the collation is valid if the + // collations map does not contain entries the server supports. + return errors.New("unknown collation") + } // Filler [23 bytes] (all 0x00) + pos := 13 + for ; pos < 13+23; pos++ { + data[pos] = 0 + } // SSL Connection Request Packet + // http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::SSLRequest + if mc.cfg.tls != nil { + // Send TLS / SSL request packet + if err := mc.writePacket(data[:(4+4+1+23)+4]); err != nil { + return err + } // Switch to TLS + tlsConn := tls.Client(mc.netConn, mc.cfg.tls) + if err := tlsConn.Handshake(); err != nil { + return err + } + mc.rawConn = mc.netConn + mc.netConn = tlsConn + mc.buf.nc = tlsConn + } // User [null terminated string] + if len(mc.cfg.User) > 0 { + pos += copy(data[pos:], mc.cfg.User) + } + data[pos] = 0x00 + pos++ // Auth Data [length encoded integer] + pos += copy(data[pos:], authRespLEI) + pos += copy(data[pos:], authResp) // Databasename [null terminated string] + if len(mc.cfg.DBName) > 0 { + pos += copy(data[pos:], mc.cfg.DBName) + data[pos] = 0x00 + pos++ + } pos += copy(data[pos:], plugin) + data[pos] = 0x00 + pos++ // Send Auth packet + return mc.writePacket(data[:pos]) + } // http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::AuthSwitchResponse + func (mc *mysqlConn) writeAuthSwitchPacket(authData []byte) error { + pktLen := 4 + len(authData) + data, err := mc.buf.takeSmallBuffer(pktLen) + if err != nil { + // cannot take the buffer. Something must be wrong with the connection + errLog.Print(err) + return errBadConnNoWrite + } // Add the auth data [EOF] + copy(data[4:], authData) + return mc.writePacket(data) + } /****************************************************************************** + * Command Packets * + ******************************************************************************/ func (mc *mysqlConn) writeCommandPacket(command byte) error { + // Reset Packet Sequence + mc.sequence = 0 data, err := mc.buf.takeSmallBuffer(4 + 1) + if err != nil { + // cannot take the buffer. Something must be wrong with the connection + errLog.Print(err) + return errBadConnNoWrite + } // Add command byte + data[4] = command // Send CMD packet + return mc.writePacket(data) + } func (mc *mysqlConn) writeCommandPacketStr(command byte, arg string) error { + // Reset Packet Sequence + mc.sequence = 0 pktLen := 1 + len(arg) + data, err := mc.buf.takeBuffer(pktLen + 4) + if err != nil { + // cannot take the buffer. Something must be wrong with the connection + errLog.Print(err) + return errBadConnNoWrite + } // Add command byte + data[4] = command // Add arg + copy(data[5:], arg) // Send CMD packet + return mc.writePacket(data) + } func (mc *mysqlConn) writeCommandPacketUint32(command byte, arg uint32) error { + // Reset Packet Sequence + mc.sequence = 0 data, err := mc.buf.takeSmallBuffer(4 + 1 + 4) + if err != nil { + // cannot take the buffer. Something must be wrong with the connection + errLog.Print(err) + return errBadConnNoWrite + } // Add command byte + data[4] = command // Add arg [32 bit] + data[5] = byte(arg) + data[6] = byte(arg >> 8) + data[7] = byte(arg >> 16) + data[8] = byte(arg >> 24) // Send CMD packet + return mc.writePacket(data) + } /****************************************************************************** + * Result Packets * + ******************************************************************************/ func (mc *mysqlConn) readAuthResult() ([]byte, string, error) { + data, err := mc.readPacket() + if err != nil { + return nil, "", err + } // packet indicator + switch data[0] { case iOK: + return nil, "", mc.handleOkPacket(data) case iAuthMoreData: + return data[1:], "", err case iEOF: + if len(data) == 1 { + // https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::OldAuthSwitchRequest + return nil, "mysql_old_password", nil + } + pluginEndIndex := bytes.IndexByte(data, 0x00) + if pluginEndIndex < 0 { + return nil, "", ErrMalformPkt + } + plugin := string(data[1:pluginEndIndex]) + authData := data[pluginEndIndex+1:] + return authData, plugin, nil default: // Error otherwise + return nil, "", mc.handleErrorPacket(data) + } + } // Returns error if Packet is not an 'Result OK'-Packet + func (mc *mysqlConn) readResultOK() error { + data, err := mc.readPacket() + if err != nil { + return err + } if data[0] == iOK { + return mc.handleOkPacket(data) + } + return mc.handleErrorPacket(data) + } // Result Set Header Packet + // http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-ProtocolText::Resultset + func (mc *mysqlConn) readResultSetHeaderPacket() (int, error) { + data, err := mc.readPacket() + if err == nil { + switch data[0] { case iOK: + return 0, mc.handleOkPacket(data) case iERR: + return 0, mc.handleErrorPacket(data) case iLocalInFile: + return 0, mc.handleInFileRequest(string(data[1:])) + } // column count + num, _, n := readLengthEncodedInteger(data) + if n-len(data) == 0 { + return int(num), nil + } return 0, ErrMalformPkt + } + return 0, err + } // Error Packet + // http://dev.mysql.com/doc/internals/en/generic-response-packets.html#packet-ERR_Packet + func (mc *mysqlConn) handleErrorPacket(data []byte) error { + if data[0] != iERR { + return ErrMalformPkt + } // 0xff [1 byte] // Error Number [16 bit uint] + errno := binary.LittleEndian.Uint16(data[1:3]) // 1792: ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION + // 1290: ER_OPTION_PREVENTS_STATEMENT (returned by Aurora during failover) + if (errno == 1792 || errno == 1290) && mc.cfg.RejectReadOnly { + // Oops; we are connected to a read-only connection, and won't be able + // to issue any write statements. Since RejectReadOnly is configured, + // we throw away this connection hoping this one would have write + // permission. This is specifically for a possible race condition + // during failover (e.g. on AWS Aurora). See README.md for more. + // + // We explicitly close the connection before returning + // driver.ErrBadConn to ensure that `database/sql` purges this + // connection and initiates a new one for next statement next time. + mc.Close() + return driver.ErrBadConn + } pos := 3 // SQL State [optional: # + 5bytes string] + if data[3] == 0x23 { + //sqlstate := string(data[4 : 4+5]) + pos = 9 + } // Error Message [string] + return &MySQLError{ - Number: errno, + + Number: errno, + Message: string(data[pos:]), } + } func readStatus(b []byte) statusFlag { + return statusFlag(b[0]) | statusFlag(b[1])<<8 + } // Ok Packet + // http://dev.mysql.com/doc/internals/en/generic-response-packets.html#packet-OK_Packet + func (mc *mysqlConn) handleOkPacket(data []byte) error { + var n, m int // 0x00 [1 byte] // Affected rows [Length Coded Binary] + mc.affectedRows, _, n = readLengthEncodedInteger(data[1:]) // Insert id [Length Coded Binary] + mc.insertId, _, m = readLengthEncodedInteger(data[1+n:]) // server_status [2 bytes] + mc.status = readStatus(data[1+n+m : 1+n+m+2]) + if mc.status&statusMoreResultsExists != 0 { + return nil + } // warning count [2 bytes] return nil + } // Read Packets as Field Packets until EOF-Packet or an Error appears + // http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-Protocol::ColumnDefinition41 + func (mc *mysqlConn) readColumns(count int) ([]mysqlField, error) { + columns := make([]mysqlField, count) for i := 0; ; i++ { + data, err := mc.readPacket() + if err != nil { + return nil, err + } // EOF Packet + if data[0] == iEOF && (len(data) == 5 || len(data) == 1) { + if i == count { + return columns, nil + } + return nil, fmt.Errorf("column count mismatch n:%d len:%d", count, len(columns)) + } // Catalog + pos, err := skipLengthEncodedString(data) + if err != nil { + return nil, err + } // Database [len coded string] + n, err := skipLengthEncodedString(data[pos:]) + if err != nil { + return nil, err + } + pos += n // Table [len coded string] + if mc.cfg.ColumnsWithAlias { + tableName, _, n, err := readLengthEncodedString(data[pos:]) + if err != nil { + return nil, err + } + pos += n + columns[i].tableName = string(tableName) + } else { + n, err = skipLengthEncodedString(data[pos:]) + if err != nil { + return nil, err + } + pos += n + } // Original table [len coded string] + n, err = skipLengthEncodedString(data[pos:]) + if err != nil { + return nil, err + } + pos += n // Name [len coded string] + name, _, n, err := readLengthEncodedString(data[pos:]) + if err != nil { + return nil, err + } + columns[i].name = string(name) + pos += n // Original name [len coded string] + n, err = skipLengthEncodedString(data[pos:]) + if err != nil { + return nil, err + } + pos += n // Filler [uint8] + pos++ // Charset [charset, collation uint8] + columns[i].charSet = data[pos] + pos += 2 // Length [uint32] + columns[i].length = binary.LittleEndian.Uint32(data[pos : pos+4]) + pos += 4 // Field type [uint8] + columns[i].fieldType = fieldType(data[pos]) + pos++ // Flags [uint16] + columns[i].flags = fieldFlag(binary.LittleEndian.Uint16(data[pos : pos+2])) + pos += 2 // Decimals [uint8] + columns[i].decimals = data[pos] + //pos++ // Default value [len coded binary] + //if pos < len(data) { + // defaultVal, _, err = bytesToLengthCodedBinary(data[pos:]) + //} + } + } // Read Packets as Field Packets until EOF-Packet or an Error appears + // http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-ProtocolText::ResultsetRow + func (rows *textRows) readRow(dest []driver.Value) error { + mc := rows.mc if rows.rs.done { + return io.EOF + } data, err := mc.readPacket() + if err != nil { + return err + } // EOF Packet + if data[0] == iEOF && len(data) == 5 { + // server_status [2 bytes] + rows.mc.status = readStatus(data[3:]) + rows.rs.done = true + if !rows.HasNextResultSet() { + rows.mc = nil + } + return io.EOF + } + if data[0] == iERR { + rows.mc = nil + return mc.handleErrorPacket(data) + } // RowSet Packet + var n int + var isNull bool + pos := 0 for i := range dest { + // Read bytes and convert to string + dest[i], isNull, n, err = readLengthEncodedString(data[pos:]) + pos += n + if err == nil { + if !isNull { + if !mc.parseTime { + continue + } else { + switch rows.rs.columns[i].fieldType { + case fieldTypeTimestamp, fieldTypeDateTime, + fieldTypeDate, fieldTypeNewDate: + dest[i], err = parseDateTime( + dest[i].([]byte), + mc.cfg.Loc, ) + if err == nil { + continue + } + default: + continue + } + } } else { + dest[i] = nil + continue + } + } + return err // err != nil + } return nil + } // Reads Packets until EOF-Packet or an Error appears. Returns count of Packets read + func (mc *mysqlConn) readUntilEOF() error { + for { + data, err := mc.readPacket() + if err != nil { + return err + } switch data[0] { + case iERR: + return mc.handleErrorPacket(data) + case iEOF: + if len(data) == 5 { + mc.status = readStatus(data[3:]) + } + return nil + } + } + } /****************************************************************************** + * Prepared Statements * + ******************************************************************************/ // Prepare Result Packets + // http://dev.mysql.com/doc/internals/en/com-stmt-prepare-response.html + func (stmt *mysqlStmt) readPrepareResultPacket() (uint16, error) { + data, err := stmt.mc.readPacket() + if err == nil { + // packet indicator [1 byte] + if data[0] != iOK { + return 0, stmt.mc.handleErrorPacket(data) + } // statement id [4 bytes] + stmt.id = binary.LittleEndian.Uint32(data[1:5]) // Column count [16 bit uint] + columnCount := binary.LittleEndian.Uint16(data[5:7]) // Param count [16 bit uint] + stmt.paramCount = int(binary.LittleEndian.Uint16(data[7:9])) // Reserved [8 bit] @@ -848,502 +1419,853 @@ func (stmt *mysqlStmt) readPrepareResultPacket() (uint16, error) { // Warning count [16 bit uint] return columnCount, nil + } + return 0, err + } // http://dev.mysql.com/doc/internals/en/com-stmt-send-long-data.html + func (stmt *mysqlStmt) writeCommandLongData(paramID int, arg []byte) error { + maxLen := stmt.mc.maxAllowedPacket - 1 + pktLen := maxLen // After the header (bytes 0-3) follows before the data: + // 1 byte command + // 4 bytes stmtID + // 2 bytes paramID + const dataOffset = 1 + 4 + 2 // Cannot use the write buffer since + // a) the buffer is too small + // b) it is in use + data := make([]byte, 4+1+4+2+len(arg)) copy(data[4+dataOffset:], arg) for argLen := len(arg); argLen > 0; argLen -= pktLen - dataOffset { + if dataOffset+argLen < maxLen { + pktLen = dataOffset + argLen + } stmt.mc.sequence = 0 + // Add command byte [1 byte] + data[4] = comStmtSendLongData // Add stmtID [32 bit] + data[5] = byte(stmt.id) + data[6] = byte(stmt.id >> 8) + data[7] = byte(stmt.id >> 16) + data[8] = byte(stmt.id >> 24) // Add paramID [16 bit] + data[9] = byte(paramID) + data[10] = byte(paramID >> 8) // Send CMD packet + err := stmt.mc.writePacket(data[:4+pktLen]) + if err == nil { + data = data[pktLen-dataOffset:] + continue + } + return err } // Reset Packet Sequence + stmt.mc.sequence = 0 + return nil + } // Execute Prepared Statement + // http://dev.mysql.com/doc/internals/en/com-stmt-execute.html + func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error { + if len(args) != stmt.paramCount { + return fmt.Errorf( + "argument count mismatch (got: %d; has: %d)", + len(args), + stmt.paramCount, ) + } const minPktLen = 4 + 1 + 4 + 1 + 4 + mc := stmt.mc // Determine threshold dynamically to avoid packet size shortage. + longDataSize := mc.maxAllowedPacket / (stmt.paramCount + 1) + if longDataSize < 64 { + longDataSize = 64 + } // Reset packet-sequence + mc.sequence = 0 var data []byte + var err error if len(args) == 0 { + data, err = mc.buf.takeBuffer(minPktLen) + } else { + data, err = mc.buf.takeCompleteBuffer() + // In this case the len(data) == cap(data) which is used to optimise the flow below. + } + if err != nil { + // cannot take the buffer. Something must be wrong with the connection + errLog.Print(err) + return errBadConnNoWrite + } // command [1 byte] + data[4] = comStmtExecute // statement_id [4 bytes] + data[5] = byte(stmt.id) + data[6] = byte(stmt.id >> 8) + data[7] = byte(stmt.id >> 16) + data[8] = byte(stmt.id >> 24) // flags (0: CURSOR_TYPE_NO_CURSOR) [1 byte] + data[9] = 0x00 // iteration_count (uint32(1)) [4 bytes] + data[10] = 0x01 + data[11] = 0x00 + data[12] = 0x00 + data[13] = 0x00 if len(args) > 0 { + pos := minPktLen var nullMask []byte + if maskLen, typesLen := (len(args)+7)/8, 1+2*len(args); pos+maskLen+typesLen >= cap(data) { + // buffer has to be extended but we don't know by how much so + // we depend on append after all data with known sizes fit. + // We stop at that because we deal with a lot of columns here + // which makes the required allocation size hard to guess. + tmp := make([]byte, pos+maskLen+typesLen) + copy(tmp[:pos], data[:pos]) + data = tmp + nullMask = data[pos : pos+maskLen] + // No need to clean nullMask as make ensures that. + pos += maskLen + } else { + nullMask = data[pos : pos+maskLen] + for i := range nullMask { + nullMask[i] = 0 + } + pos += maskLen + } // newParameterBoundFlag 1 [1 byte] + data[pos] = 0x01 + pos++ // type of each parameter [len(args)*2 bytes] + paramTypes := data[pos:] + pos += len(args) * 2 // value of each parameter [n bytes] + paramValues := data[pos:pos] + valuesCap := cap(paramValues) for i, arg := range args { + // build NULL-bitmap + if arg == nil { + nullMask[i/8] |= 1 << (uint(i) & 7) + paramTypes[i+i] = byte(fieldTypeNULL) + paramTypes[i+i+1] = 0x00 + continue + } if v, ok := arg.(json.RawMessage); ok { + arg = []byte(v) + } + // cache types and values + switch v := arg.(type) { + case int64: + paramTypes[i+i] = byte(fieldTypeLongLong) + paramTypes[i+i+1] = 0x00 if cap(paramValues)-len(paramValues)-8 >= 0 { + paramValues = paramValues[:len(paramValues)+8] + binary.LittleEndian.PutUint64( + paramValues[len(paramValues)-8:], + uint64(v), ) + } else { + paramValues = append(paramValues, + uint64ToBytes(uint64(v))..., ) + } case uint64: + paramTypes[i+i] = byte(fieldTypeLongLong) + paramTypes[i+i+1] = 0x80 // type is unsigned if cap(paramValues)-len(paramValues)-8 >= 0 { + paramValues = paramValues[:len(paramValues)+8] + binary.LittleEndian.PutUint64( + paramValues[len(paramValues)-8:], + uint64(v), ) + } else { + paramValues = append(paramValues, + uint64ToBytes(uint64(v))..., ) + } case float64: + paramTypes[i+i] = byte(fieldTypeDouble) + paramTypes[i+i+1] = 0x00 if cap(paramValues)-len(paramValues)-8 >= 0 { + paramValues = paramValues[:len(paramValues)+8] + binary.LittleEndian.PutUint64( + paramValues[len(paramValues)-8:], + math.Float64bits(v), ) + } else { + paramValues = append(paramValues, + uint64ToBytes(math.Float64bits(v))..., ) + } case bool: + paramTypes[i+i] = byte(fieldTypeTiny) + paramTypes[i+i+1] = 0x00 if v { + paramValues = append(paramValues, 0x01) + } else { + paramValues = append(paramValues, 0x00) + } case []byte: + // Common case (non-nil value) first + if v != nil { + paramTypes[i+i] = byte(fieldTypeString) + paramTypes[i+i+1] = 0x00 if len(v) < longDataSize { + paramValues = appendLengthEncodedInteger(paramValues, + uint64(len(v)), ) + paramValues = append(paramValues, v...) + } else { + if err := stmt.writeCommandLongData(i, v); err != nil { + return err + } + } + continue + } // Handle []byte(nil) as a NULL value + nullMask[i/8] |= 1 << (uint(i) & 7) + paramTypes[i+i] = byte(fieldTypeNULL) + paramTypes[i+i+1] = 0x00 case string: + paramTypes[i+i] = byte(fieldTypeString) + paramTypes[i+i+1] = 0x00 if len(v) < longDataSize { + paramValues = appendLengthEncodedInteger(paramValues, + uint64(len(v)), ) + paramValues = append(paramValues, v...) + } else { + if err := stmt.writeCommandLongData(i, []byte(v)); err != nil { + return err + } + } case time.Time: + paramTypes[i+i] = byte(fieldTypeString) + paramTypes[i+i+1] = 0x00 var a [64]byte + var b = a[:0] if v.IsZero() { + b = append(b, "0000-00-00"...) + } else { + b, err = appendDateTime(b, v.In(mc.cfg.Loc)) + if err != nil { + return err + } + } paramValues = appendLengthEncodedInteger(paramValues, + uint64(len(b)), ) + paramValues = append(paramValues, b...) default: + return fmt.Errorf("cannot convert type: %T", arg) + } + } // Check if param values exceeded the available buffer + // In that case we must build the data packet with the new values buffer + if valuesCap != cap(paramValues) { + data = append(data[:pos], paramValues...) + if err = mc.buf.store(data); err != nil { + errLog.Print(err) + return errBadConnNoWrite + } + } pos += len(paramValues) + data = data[:pos] + } return mc.writePacket(data) + } func (mc *mysqlConn) discardResults() error { + for mc.status&statusMoreResultsExists != 0 { + resLen, err := mc.readResultSetHeaderPacket() + if err != nil { + return err + } + if resLen > 0 { + // columns + if err := mc.readUntilEOF(); err != nil { + return err + } + // rows + if err := mc.readUntilEOF(); err != nil { + return err + } + } + } + return nil + } // http://dev.mysql.com/doc/internals/en/binary-protocol-resultset-row.html + func (rows *binaryRows) readRow(dest []driver.Value) error { + data, err := rows.mc.readPacket() + if err != nil { + return err + } // packet indicator [1 byte] + if data[0] != iOK { + // EOF Packet + if data[0] == iEOF && len(data) == 5 { + rows.mc.status = readStatus(data[3:]) + rows.rs.done = true + if !rows.HasNextResultSet() { + rows.mc = nil + } + return io.EOF + } + mc := rows.mc + rows.mc = nil // Error otherwise + return mc.handleErrorPacket(data) + } // NULL-bitmap, [(column-count + 7 + 2) / 8 bytes] + pos := 1 + (len(dest)+7+2)>>3 + nullMask := data[1:pos] for i := range dest { + // Field is NULL + // (byte >> bit-pos) % 2 == 1 + if ((nullMask[(i+2)>>3] >> uint((i+2)&7)) & 1) == 1 { + dest[i] = nil + continue + } // Convert to byte-coded string + switch rows.rs.columns[i].fieldType { + case fieldTypeNULL: + dest[i] = nil + continue // Numeric Types + case fieldTypeTiny: + if rows.rs.columns[i].flags&flagUnsigned != 0 { + dest[i] = int64(data[pos]) + } else { + dest[i] = int64(int8(data[pos])) + } + pos++ + continue case fieldTypeShort, fieldTypeYear: + if rows.rs.columns[i].flags&flagUnsigned != 0 { + dest[i] = int64(binary.LittleEndian.Uint16(data[pos : pos+2])) + } else { + dest[i] = int64(int16(binary.LittleEndian.Uint16(data[pos : pos+2]))) + } + pos += 2 + continue case fieldTypeInt24, fieldTypeLong: + if rows.rs.columns[i].flags&flagUnsigned != 0 { + dest[i] = int64(binary.LittleEndian.Uint32(data[pos : pos+4])) + } else { + dest[i] = int64(int32(binary.LittleEndian.Uint32(data[pos : pos+4]))) + } + pos += 4 + continue case fieldTypeLongLong: + if rows.rs.columns[i].flags&flagUnsigned != 0 { + val := binary.LittleEndian.Uint64(data[pos : pos+8]) + if val > math.MaxInt64 { + dest[i] = uint64ToString(val) + } else { + dest[i] = int64(val) + } + } else { + dest[i] = int64(binary.LittleEndian.Uint64(data[pos : pos+8])) + } + pos += 8 + continue case fieldTypeFloat: + dest[i] = math.Float32frombits(binary.LittleEndian.Uint32(data[pos : pos+4])) + pos += 4 + continue case fieldTypeDouble: + dest[i] = math.Float64frombits(binary.LittleEndian.Uint64(data[pos : pos+8])) + pos += 8 + continue // Length coded Binary Strings + case fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar, + fieldTypeBit, fieldTypeEnum, fieldTypeSet, fieldTypeTinyBLOB, + fieldTypeMediumBLOB, fieldTypeLongBLOB, fieldTypeBLOB, + fieldTypeVarString, fieldTypeString, fieldTypeGeometry, fieldTypeJSON: + var isNull bool + var n int + dest[i], isNull, n, err = readLengthEncodedString(data[pos:]) + pos += n + if err == nil { + if !isNull { + continue + } else { + dest[i] = nil + continue + } + } + return err case + fieldTypeDate, fieldTypeNewDate, // Date YYYY-MM-DD - fieldTypeTime, // Time [-][H]HH:MM:SS[.fractal] + + fieldTypeTime, // Time [-][H]HH:MM:SS[.fractal] + fieldTypeTimestamp, fieldTypeDateTime: // Timestamp YYYY-MM-DD HH:MM:SS[.fractal] num, isNull, n := readLengthEncodedInteger(data[pos:]) + pos += n switch { + case isNull: + dest[i] = nil + continue + case rows.rs.columns[i].fieldType == fieldTypeTime: + // database/sql does not support an equivalent to TIME, return a string + var dstlen uint8 + switch decimals := rows.rs.columns[i].decimals; decimals { + case 0x00, 0x1f: + dstlen = 8 + case 1, 2, 3, 4, 5, 6: + dstlen = 8 + 1 + decimals + default: + return fmt.Errorf( + "protocol error, illegal decimals value %d", + rows.rs.columns[i].decimals, ) + } + dest[i], err = formatBinaryTime(data[pos:pos+int(num)], dstlen) + case rows.mc.parseTime: + dest[i], err = parseBinaryDateTime(num, data[pos:], rows.mc.cfg.Loc) + default: + var dstlen uint8 + if rows.rs.columns[i].fieldType == fieldTypeDate { + dstlen = 10 + } else { + switch decimals := rows.rs.columns[i].decimals; decimals { + case 0x00, 0x1f: + dstlen = 19 + case 1, 2, 3, 4, 5, 6: + dstlen = 19 + 1 + decimals + default: + return fmt.Errorf( + "protocol error, illegal decimals value %d", + rows.rs.columns[i].decimals, ) + } + } + dest[i], err = formatBinaryDateTime(data[pos:pos+int(num)], dstlen) + } if err == nil { + pos += int(num) + continue + } else { + return err + } // Please report if this happens! + default: + return fmt.Errorf("unknown field type %d", rows.rs.columns[i].fieldType) + } + } return nil + } diff --git a/vendor/github.com/go-sql-driver/mysql/rows.go b/vendor/github.com/go-sql-driver/mysql/rows.go index 888bdb5..a7820cd 100644 --- a/vendor/github.com/go-sql-driver/mysql/rows.go +++ b/vendor/github.com/go-sql-driver/mysql/rows.go @@ -1,9 +1,15 @@ // Go MySQL Driver - A MySQL-Driver for Go's database/sql package + // + // Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. + // + // This Source Code Form is subject to the terms of the Mozilla Public + // License, v. 2.0. If a copy of the MPL was not distributed with this file, + // You can obtain one at http://mozilla.org/MPL/2.0/. package mysql @@ -16,14 +22,18 @@ import ( ) type resultSet struct { - columns []mysqlField + columns []mysqlField + columnNames []string - done bool + + done bool } type mysqlRows struct { - mc *mysqlConn - rs resultSet + mc *mysqlConn + + rs resultSet + finish func() } @@ -36,188 +46,315 @@ type textRows struct { } func (rows *mysqlRows) Columns() []string { + if rows.rs.columnNames != nil { + return rows.rs.columnNames + } columns := make([]string, len(rows.rs.columns)) + if rows.mc != nil && rows.mc.cfg.ColumnsWithAlias { + for i := range columns { + if tableName := rows.rs.columns[i].tableName; len(tableName) > 0 { + columns[i] = tableName + "." + rows.rs.columns[i].name + } else { + columns[i] = rows.rs.columns[i].name + } + } + } else { + for i := range columns { + columns[i] = rows.rs.columns[i].name + } + } rows.rs.columnNames = columns + return columns + } func (rows *mysqlRows) ColumnTypeDatabaseTypeName(i int) string { + return rows.rs.columns[i].typeDatabaseName() + } // func (rows *mysqlRows) ColumnTypeLength(i int) (length int64, ok bool) { + // return int64(rows.rs.columns[i].length), true + // } func (rows *mysqlRows) ColumnTypeNullable(i int) (nullable, ok bool) { + return rows.rs.columns[i].flags&flagNotNULL == 0, true + } func (rows *mysqlRows) ColumnTypePrecisionScale(i int) (int64, int64, bool) { + column := rows.rs.columns[i] + decimals := int64(column.decimals) switch column.fieldType { + case fieldTypeDecimal, fieldTypeNewDecimal: + if decimals > 0 { + return int64(column.length) - 2, decimals, true + } + return int64(column.length) - 1, decimals, true + case fieldTypeTimestamp, fieldTypeDateTime, fieldTypeTime: + return decimals, decimals, true + case fieldTypeFloat, fieldTypeDouble: + if decimals == 0x1f { + return math.MaxInt64, math.MaxInt64, true + } + return math.MaxInt64, decimals, true + } return 0, 0, false + } func (rows *mysqlRows) ColumnTypeScanType(i int) reflect.Type { + return rows.rs.columns[i].scanType() + } func (rows *mysqlRows) Close() (err error) { + if f := rows.finish; f != nil { + f() + rows.finish = nil + } mc := rows.mc + if mc == nil { + return nil + } + if err := mc.error(); err != nil { + return err + } // flip the buffer for this connection if we need to drain it. + // note that for a successful query (i.e. one where rows.next() + // has been called until it returns false), `rows.mc` will be nil + // by the time the user calls `(*Rows).Close`, so we won't reach this + // see: https://github.com/golang/go/commit/651ddbdb5056ded455f47f9c494c67b389622a47 + mc.buf.flip() // Remove unread packets from stream + if !rows.rs.done { + err = mc.readUntilEOF() + } + if err == nil { + if err = mc.discardResults(); err != nil { + return err + } + } rows.mc = nil + return err + } func (rows *mysqlRows) HasNextResultSet() (b bool) { + if rows.mc == nil { + return false + } + return rows.mc.status&statusMoreResultsExists != 0 + } func (rows *mysqlRows) nextResultSet() (int, error) { + if rows.mc == nil { + return 0, io.EOF + } + if err := rows.mc.error(); err != nil { + return 0, err + } // Remove unread packets from stream + if !rows.rs.done { + if err := rows.mc.readUntilEOF(); err != nil { + return 0, err + } + rows.rs.done = true + } if !rows.HasNextResultSet() { + rows.mc = nil + return 0, io.EOF + } + rows.rs = resultSet{} + return rows.mc.readResultSetHeaderPacket() + } func (rows *mysqlRows) nextNotEmptyResultSet() (int, error) { + for { + resLen, err := rows.nextResultSet() + if err != nil { + return 0, err + } if resLen > 0 { + return resLen, nil + } rows.rs.done = true + } + } func (rows *binaryRows) NextResultSet() error { + resLen, err := rows.nextNotEmptyResultSet() + if err != nil { + return err + } rows.rs.columns, err = rows.mc.readColumns(resLen) + return err + } func (rows *binaryRows) Next(dest []driver.Value) error { + if mc := rows.mc; mc != nil { + if err := mc.error(); err != nil { + return err + } // Fetch next row from stream + return rows.readRow(dest) + } + return io.EOF + } func (rows *textRows) NextResultSet() (err error) { + resLen, err := rows.nextNotEmptyResultSet() + if err != nil { + return err + } rows.rs.columns, err = rows.mc.readColumns(resLen) + return err + } func (rows *textRows) Next(dest []driver.Value) error { + if mc := rows.mc; mc != nil { + if err := mc.error(); err != nil { + return err + } // Fetch next row from stream + return rows.readRow(dest) + } + return io.EOF + } diff --git a/vendor/github.com/go-sql-driver/mysql/statement.go b/vendor/github.com/go-sql-driver/mysql/statement.go index 18a3ae4..7f48608 100644 --- a/vendor/github.com/go-sql-driver/mysql/statement.go +++ b/vendor/github.com/go-sql-driver/mysql/statement.go @@ -1,9 +1,15 @@ // Go MySQL Driver - A MySQL-Driver for Go's database/sql package + // + // Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. + // + // This Source Code Form is subject to the terms of the Mozilla Public + // License, v. 2.0. If a copy of the MPL was not distributed with this file, + // You can obtain one at http://mozilla.org/MPL/2.0/. package mysql @@ -17,122 +23,194 @@ import ( ) type mysqlStmt struct { - mc *mysqlConn - id uint32 + mc *mysqlConn + + id uint32 + paramCount int } func (stmt *mysqlStmt) Close() error { + if stmt.mc == nil || stmt.mc.closed.IsSet() { + // driver.Stmt.Close can be called more than once, thus this function + // has to be idempotent. + // See also Issue #450 and golang/go#16019. + //errLog.Print(ErrInvalidConn) + return driver.ErrBadConn + } err := stmt.mc.writeCommandPacketUint32(comStmtClose, stmt.id) + stmt.mc = nil + return err + } func (stmt *mysqlStmt) NumInput() int { + return stmt.paramCount + } func (stmt *mysqlStmt) ColumnConverter(idx int) driver.ValueConverter { + return converter{} + } func (stmt *mysqlStmt) CheckNamedValue(nv *driver.NamedValue) (err error) { + nv.Value, err = converter{}.ConvertValue(nv.Value) + return + } func (stmt *mysqlStmt) Exec(args []driver.Value) (driver.Result, error) { + if stmt.mc.closed.IsSet() { + errLog.Print(ErrInvalidConn) + return nil, driver.ErrBadConn + } + // Send command + err := stmt.writeExecutePacket(args) + if err != nil { + return nil, stmt.mc.markBadConn(err) + } mc := stmt.mc mc.affectedRows = 0 + mc.insertId = 0 // Read Result + resLen, err := mc.readResultSetHeaderPacket() + if err != nil { + return nil, err + } if resLen > 0 { + // Columns + if err = mc.readUntilEOF(); err != nil { + return nil, err + } // Rows + if err := mc.readUntilEOF(); err != nil { + return nil, err + } + } if err := mc.discardResults(); err != nil { + return nil, err + } return &mysqlResult{ + affectedRows: int64(mc.affectedRows), - insertId: int64(mc.insertId), + + insertId: int64(mc.insertId), }, nil + } func (stmt *mysqlStmt) Query(args []driver.Value) (driver.Rows, error) { + return stmt.query(args) + } func (stmt *mysqlStmt) query(args []driver.Value) (*binaryRows, error) { + if stmt.mc.closed.IsSet() { + errLog.Print(ErrInvalidConn) + return nil, driver.ErrBadConn + } + // Send command + err := stmt.writeExecutePacket(args) + if err != nil { + return nil, stmt.mc.markBadConn(err) + } mc := stmt.mc // Read Result + resLen, err := mc.readResultSetHeaderPacket() + if err != nil { + return nil, err + } rows := new(binaryRows) if resLen > 0 { + rows.mc = mc + rows.rs.columns, err = mc.readColumns(resLen) + } else { + rows.rs.done = true switch err := rows.NextResultSet(); err { + case nil, io.EOF: + return rows, nil + default: + return nil, err + } + } return rows, err + } var jsonType = reflect.TypeOf(json.RawMessage{}) @@ -140,81 +218,153 @@ var jsonType = reflect.TypeOf(json.RawMessage{}) type converter struct{} // ConvertValue mirrors the reference/default converter in database/sql/driver + // with _one_ exception. We support uint64 with their high bit and the default + // implementation does not. This function should be kept in sync with + // database/sql/driver defaultConverter.ConvertValue() except for that + // deliberate difference. + func (c converter) ConvertValue(v interface{}) (driver.Value, error) { + if driver.IsValue(v) { + return v, nil + } if vr, ok := v.(driver.Valuer); ok { + sv, err := callValuerValue(vr) + if err != nil { + return nil, err + } + if driver.IsValue(sv) { + return sv, nil + } + // A value returend from the Valuer interface can be "a type handled by + // a database driver's NamedValueChecker interface" so we should accept + // uint64 here as well. + if u, ok := sv.(uint64); ok { + return u, nil + } + return nil, fmt.Errorf("non-Value type %T returned from Value", sv) + } + rv := reflect.ValueOf(v) + switch rv.Kind() { + case reflect.Ptr: + // indirect pointers + if rv.IsNil() { + return nil, nil + } else { + return c.ConvertValue(rv.Elem().Interface()) + } + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return rv.Int(), nil + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return rv.Uint(), nil + case reflect.Float32, reflect.Float64: + return rv.Float(), nil + case reflect.Bool: + return rv.Bool(), nil + case reflect.Slice: + switch t := rv.Type(); { + case t == jsonType: + return v, nil + case t.Elem().Kind() == reflect.Uint8: + return rv.Bytes(), nil + default: + return nil, fmt.Errorf("unsupported type %T, a slice of %s", v, t.Elem().Kind()) + } + case reflect.String: + return rv.String(), nil + } + return nil, fmt.Errorf("unsupported type %T, a %s", v, rv.Kind()) + } var valuerReflectType = reflect.TypeOf((*driver.Valuer)(nil)).Elem() // 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. + // + // 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 is an exact copy of the same-named unexported function from the + // database/sql package. + func callValuerValue(vr driver.Valuer) (v driver.Value, err error) { + if rv := reflect.ValueOf(vr); rv.Kind() == reflect.Ptr && + rv.IsNil() && + rv.Type().Elem().Implements(valuerReflectType) { + return nil, nil + } + return vr.Value() + } diff --git a/vendor/github.com/go-sql-driver/mysql/utils.go b/vendor/github.com/go-sql-driver/mysql/utils.go index ae7be39..d5444b2 100644 --- a/vendor/github.com/go-sql-driver/mysql/utils.go +++ b/vendor/github.com/go-sql-driver/mysql/utils.go @@ -1,9 +1,15 @@ // Go MySQL Driver - A MySQL-Driver for Go's database/sql package + // + // Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. + // + // This Source Code Form is subject to the terms of the Mozilla Public + // License, v. 2.0. If a copy of the MPL was not distributed with this file, + // You can obtain one at http://mozilla.org/MPL/2.0/. package mysql @@ -24,844 +30,1480 @@ import ( ) // Registry for custom tls.Configs + var ( - tlsConfigLock sync.RWMutex + tlsConfigLock sync.RWMutex + tlsConfigRegistry map[string]*tls.Config ) // RegisterTLSConfig registers a custom tls.Config to be used with sql.Open. + // Use the key as a value in the DSN where tls=value. + // + // Note: The provided tls.Config is exclusively owned by the driver after + // registering it. + // + // rootCertPool := x509.NewCertPool() + // pem, err := ioutil.ReadFile("/path/ca-cert.pem") + // if err != nil { + // log.Fatal(err) + // } + // if ok := rootCertPool.AppendCertsFromPEM(pem); !ok { + // log.Fatal("Failed to append PEM.") + // } + // clientCert := make([]tls.Certificate, 0, 1) + // certs, err := tls.LoadX509KeyPair("/path/client-cert.pem", "/path/client-key.pem") + // if err != nil { + // log.Fatal(err) + // } + // clientCert = append(clientCert, certs) + // mysql.RegisterTLSConfig("custom", &tls.Config{ + // RootCAs: rootCertPool, + // Certificates: clientCert, + // }) + // db, err := sql.Open("mysql", "user@tcp(localhost:3306)/test?tls=custom") + func RegisterTLSConfig(key string, config *tls.Config) error { + if _, isBool := readBool(key); isBool || strings.ToLower(key) == "skip-verify" || strings.ToLower(key) == "preferred" { + return fmt.Errorf("key '%s' is reserved", key) + } tlsConfigLock.Lock() + if tlsConfigRegistry == nil { + tlsConfigRegistry = make(map[string]*tls.Config) + } tlsConfigRegistry[key] = config + tlsConfigLock.Unlock() + return nil + } // DeregisterTLSConfig removes the tls.Config associated with key. + func DeregisterTLSConfig(key string) { + tlsConfigLock.Lock() + if tlsConfigRegistry != nil { + delete(tlsConfigRegistry, key) + } + tlsConfigLock.Unlock() + } func getTLSConfigClone(key string) (config *tls.Config) { + tlsConfigLock.RLock() + if v, ok := tlsConfigRegistry[key]; ok { + config = v.Clone() + } + tlsConfigLock.RUnlock() + return + } // Returns the bool value of the input. + // The 2nd return value indicates if the input was a valid bool value + func readBool(input string) (value bool, valid bool) { + switch input { + case "1", "true", "TRUE", "True": + return true, true + case "0", "false", "FALSE", "False": + return false, true + } // Not a valid bool value + return + } /****************************************************************************** + * Time related utils * + ******************************************************************************/ func parseDateTime(b []byte, loc *time.Location) (time.Time, error) { + const base = "0000-00-00 00:00:00.000000" + switch len(b) { + case 10, 19, 21, 22, 23, 24, 25, 26: // up to "YYYY-MM-DD HH:MM:SS.MMMMMM" + if string(b) == base[:len(b)] { + return time.Time{}, nil + } year, err := parseByteYear(b) + if err != nil { + return time.Time{}, err + } + if year <= 0 { + year = 1 + } if b[4] != '-' { + return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[4]) + } m, err := parseByte2Digits(b[5], b[6]) + if err != nil { + return time.Time{}, err + } + if m <= 0 { + m = 1 + } + month := time.Month(m) if b[7] != '-' { + return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[7]) + } day, err := parseByte2Digits(b[8], b[9]) + if err != nil { + return time.Time{}, err + } + if day <= 0 { + day = 1 + } + if len(b) == 10 { + return time.Date(year, month, day, 0, 0, 0, 0, loc), nil + } if b[10] != ' ' { + return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[10]) + } hour, err := parseByte2Digits(b[11], b[12]) + if err != nil { + return time.Time{}, err + } + if b[13] != ':' { + return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[13]) + } min, err := parseByte2Digits(b[14], b[15]) + if err != nil { + return time.Time{}, err + } + if b[16] != ':' { + return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[16]) + } sec, err := parseByte2Digits(b[17], b[18]) + if err != nil { + return time.Time{}, err + } + if len(b) == 19 { + return time.Date(year, month, day, hour, min, sec, 0, loc), nil + } if b[19] != '.' { + return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[19]) + } + nsec, err := parseByteNanoSec(b[20:]) + if err != nil { + return time.Time{}, err + } + return time.Date(year, month, day, hour, min, sec, nsec, loc), nil + default: + return time.Time{}, fmt.Errorf("invalid time bytes: %s", b) + } + } func parseByteYear(b []byte) (int, error) { + year, n := 0, 1000 + for i := 0; i < 4; i++ { + v, err := bToi(b[i]) + if err != nil { + return 0, err + } + year += v * n + n = n / 10 + } + return year, nil + } func parseByte2Digits(b1, b2 byte) (int, error) { + d1, err := bToi(b1) + if err != nil { + return 0, err + } + d2, err := bToi(b2) + if err != nil { + return 0, err + } + return d1*10 + d2, nil + } func parseByteNanoSec(b []byte) (int, error) { + ns, digit := 0, 100000 // max is 6-digits + for i := 0; i < len(b); i++ { + v, err := bToi(b[i]) + if err != nil { + return 0, err + } + ns += v * digit + digit /= 10 + } + // nanoseconds has 10-digits. (needs to scale digits) + // 10 - 6 = 4, so we have to multiple 1000. + return ns * 1000, nil + } func bToi(b byte) (int, error) { + if b < '0' || b > '9' { + return 0, errors.New("not [0-9]") + } + return int(b - '0'), nil + } func parseBinaryDateTime(num uint64, data []byte, loc *time.Location) (driver.Value, error) { + switch num { + case 0: + return time.Time{}, nil + case 4: + return time.Date( + int(binary.LittleEndian.Uint16(data[:2])), // year - time.Month(data[2]), // month - int(data[3]), // day + + time.Month(data[2]), // month + + int(data[3]), // day + 0, 0, 0, 0, + loc, ), nil + case 7: + return time.Date( + int(binary.LittleEndian.Uint16(data[:2])), // year - time.Month(data[2]), // month - int(data[3]), // day - int(data[4]), // hour - int(data[5]), // minutes - int(data[6]), // seconds + + time.Month(data[2]), // month + + int(data[3]), // day + + int(data[4]), // hour + + int(data[5]), // minutes + + int(data[6]), // seconds + 0, + loc, ), nil + case 11: + return time.Date( + int(binary.LittleEndian.Uint16(data[:2])), // year - time.Month(data[2]), // month - int(data[3]), // day - int(data[4]), // hour - int(data[5]), // minutes - int(data[6]), // seconds + + time.Month(data[2]), // month + + int(data[3]), // day + + int(data[4]), // hour + + int(data[5]), // minutes + + int(data[6]), // seconds + int(binary.LittleEndian.Uint32(data[7:11]))*1000, // nanoseconds + loc, ), nil + } + return nil, fmt.Errorf("invalid DATETIME packet length %d", num) + } func appendDateTime(buf []byte, t time.Time) ([]byte, error) { + year, month, day := t.Date() + hour, min, sec := t.Clock() + nsec := t.Nanosecond() if year < 1 || year > 9999 { + return buf, errors.New("year is not in the range [1, 9999]: " + strconv.Itoa(year)) // use errors.New instead of fmt.Errorf to avoid year escape to heap + } + year100 := year / 100 + year1 := year % 100 var localBuf [len("2006-01-02T15:04:05.999999999")]byte // does not escape + localBuf[0], localBuf[1], localBuf[2], localBuf[3] = digits10[year100], digits01[year100], digits10[year1], digits01[year1] + localBuf[4] = '-' + localBuf[5], localBuf[6] = digits10[month], digits01[month] + localBuf[7] = '-' + localBuf[8], localBuf[9] = digits10[day], digits01[day] if hour == 0 && min == 0 && sec == 0 && nsec == 0 { + return append(buf, localBuf[:10]...), nil + } localBuf[10] = ' ' + localBuf[11], localBuf[12] = digits10[hour], digits01[hour] + localBuf[13] = ':' + localBuf[14], localBuf[15] = digits10[min], digits01[min] + localBuf[16] = ':' + localBuf[17], localBuf[18] = digits10[sec], digits01[sec] if nsec == 0 { + return append(buf, localBuf[:19]...), nil + } + nsec100000000 := nsec / 100000000 + nsec1000000 := (nsec / 1000000) % 100 + nsec10000 := (nsec / 10000) % 100 + nsec100 := (nsec / 100) % 100 + nsec1 := nsec % 100 + localBuf[19] = '.' // milli second + localBuf[20], localBuf[21], localBuf[22] = + digits01[nsec100000000], digits10[nsec1000000], digits01[nsec1000000] + // micro second + localBuf[23], localBuf[24], localBuf[25] = + digits10[nsec10000], digits01[nsec10000], digits10[nsec100] + // nano second + localBuf[26], localBuf[27], localBuf[28] = + digits01[nsec100], digits10[nsec1], digits01[nsec1] // trim trailing zeros + n := len(localBuf) + for n > 0 && localBuf[n-1] == '0' { + n-- + } return append(buf, localBuf[:n]...), nil + } // zeroDateTime is used in formatBinaryDateTime to avoid an allocation + // if the DATE or DATETIME has the zero value. + // It must never be changed. + // The current behavior depends on database/sql copying the result. + var zeroDateTime = []byte("0000-00-00 00:00:00.000000") const digits01 = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" + const digits10 = "0000000000111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999" func appendMicrosecs(dst, src []byte, decimals int) []byte { + if decimals <= 0 { + return dst + } + if len(src) == 0 { + return append(dst, ".000000"[:decimals+1]...) + } microsecs := binary.LittleEndian.Uint32(src[:4]) + p1 := byte(microsecs / 10000) + microsecs -= 10000 * uint32(p1) + p2 := byte(microsecs / 100) + microsecs -= 100 * uint32(p2) + p3 := byte(microsecs) switch decimals { + default: + return append(dst, '.', + digits10[p1], digits01[p1], + digits10[p2], digits01[p2], + digits10[p3], digits01[p3], ) + case 1: + return append(dst, '.', + digits10[p1], ) + case 2: + return append(dst, '.', + digits10[p1], digits01[p1], ) + case 3: + return append(dst, '.', + digits10[p1], digits01[p1], + digits10[p2], ) + case 4: + return append(dst, '.', + digits10[p1], digits01[p1], + digits10[p2], digits01[p2], ) + case 5: + return append(dst, '.', + digits10[p1], digits01[p1], + digits10[p2], digits01[p2], + digits10[p3], ) + } + } func formatBinaryDateTime(src []byte, length uint8) (driver.Value, error) { + // length expects the deterministic length of the zero value, + // negative time and 100+ hours are automatically added if needed + if len(src) == 0 { + return zeroDateTime[:length], nil + } - var dst []byte // return value + + var dst []byte // return value + var p1, p2, p3 byte // current digit pair switch length { + case 10, 19, 21, 22, 23, 24, 25, 26: + default: + t := "DATE" + if length > 10 { + t += "TIME" + } + return nil, fmt.Errorf("illegal %s length %d", t, length) + } + switch len(src) { + case 4, 7, 11: + default: + t := "DATE" + if length > 10 { + t += "TIME" + } + return nil, fmt.Errorf("illegal %s packet length %d", t, len(src)) + } + dst = make([]byte, 0, length) + // start with the date + year := binary.LittleEndian.Uint16(src[:2]) + pt := year / 100 + p1 = byte(year - 100*uint16(pt)) + p2, p3 = src[2], src[3] + dst = append(dst, + digits10[pt], digits01[pt], + digits10[p1], digits01[p1], '-', + digits10[p2], digits01[p2], '-', + digits10[p3], digits01[p3], ) + if length == 10 { + return dst, nil + } + if len(src) == 4 { + return append(dst, zeroDateTime[10:length]...), nil + } + dst = append(dst, ' ') + p1 = src[4] // hour + src = src[5:] // p1 is 2-digit hour, src is after hour + p2, p3 = src[0], src[1] + dst = append(dst, + digits10[p1], digits01[p1], ':', + digits10[p2], digits01[p2], ':', + digits10[p3], digits01[p3], ) + return appendMicrosecs(dst, src[2:], int(length)-20), nil + } func formatBinaryTime(src []byte, length uint8) (driver.Value, error) { + // length expects the deterministic length of the zero value, + // negative time and 100+ hours are automatically added if needed + if len(src) == 0 { + return zeroDateTime[11 : 11+length], nil + } + var dst []byte // return value switch length { + case - 8, // time (can be up to 10 when negative and 100+ hours) + + 8, // time (can be up to 10 when negative and 100+ hours) + 10, 11, 12, 13, 14, 15: // time with fractional seconds + default: + return nil, fmt.Errorf("illegal TIME length %d", length) + } + switch len(src) { + case 8, 12: + default: + return nil, fmt.Errorf("invalid TIME packet length %d", len(src)) + } + // +2 to enable negative time and 100+ hours + dst = make([]byte, 0, length+2) + if src[0] == 1 { + dst = append(dst, '-') + } + days := binary.LittleEndian.Uint32(src[1:5]) + hours := int64(days)*24 + int64(src[5]) if hours >= 100 { + dst = strconv.AppendInt(dst, hours, 10) + } else { + dst = append(dst, digits10[hours], digits01[hours]) + } min, sec := src[6], src[7] + dst = append(dst, ':', + digits10[min], digits01[min], ':', + digits10[sec], digits01[sec], ) + return appendMicrosecs(dst, src[8:], int(length)-9), nil + } /****************************************************************************** + * Convert from and to bytes * + ******************************************************************************/ func uint64ToBytes(n uint64) []byte { + return []byte{ + byte(n), + byte(n >> 8), + byte(n >> 16), + byte(n >> 24), + byte(n >> 32), + byte(n >> 40), + byte(n >> 48), + byte(n >> 56), } + } func uint64ToString(n uint64) []byte { + var a [20]byte + i := 20 // U+0030 = 0 + // ... + // U+0039 = 9 var q uint64 + for n >= 10 { + i-- + q = n / 10 + a[i] = uint8(n-q*10) + 0x30 + n = q + } i-- + a[i] = uint8(n) + 0x30 return a[i:] + } // treats string value as unsigned integer representation + func stringToInt(b []byte) int { + val := 0 + for i := range b { + val *= 10 + val += int(b[i] - 0x30) + } + return val + } // returns the string read as a bytes slice, wheter the value is NULL, + // the number of bytes read and an error, in case the string is longer than + // the input slice + func readLengthEncodedString(b []byte) ([]byte, bool, int, error) { + // Get length + num, isNull, n := readLengthEncodedInteger(b) + if num < 1 { + return b[n:n], isNull, n, nil + } n += int(num) // Check data length + if len(b) >= n { + return b[n-int(num) : n : n], false, n, nil + } + return nil, false, n, io.EOF + } // returns the number of bytes skipped and an error, in case the string is + // longer than the input slice + func skipLengthEncodedString(b []byte) (int, error) { + // Get length + num, _, n := readLengthEncodedInteger(b) + if num < 1 { + return n, nil + } n += int(num) // Check data length + if len(b) >= n { + return n, nil + } + return n, io.EOF + } // returns the number read, whether the value is NULL and the number of bytes read + func readLengthEncodedInteger(b []byte) (uint64, bool, int) { + // See issue #349 + if len(b) == 0 { + return 0, true, 1 + } switch b[0] { + // 251: NULL + case 0xfb: + return 0, true, 1 // 252: value of following 2 + case 0xfc: + return uint64(b[1]) | uint64(b[2])<<8, false, 3 // 253: value of following 3 + case 0xfd: + return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16, false, 4 // 254: value of following 8 + case 0xfe: + return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16 | + uint64(b[4])<<24 | uint64(b[5])<<32 | uint64(b[6])<<40 | + uint64(b[7])<<48 | uint64(b[8])<<56, + false, 9 + } // 0-250: value of first byte + return uint64(b[0]), false, 1 + } // encodes a uint64 value and appends it to the given bytes slice + func appendLengthEncodedInteger(b []byte, n uint64) []byte { + switch { + case n <= 250: + return append(b, byte(n)) case n <= 0xffff: + return append(b, 0xfc, byte(n), byte(n>>8)) case n <= 0xffffff: + return append(b, 0xfd, byte(n), byte(n>>8), byte(n>>16)) + } + return append(b, 0xfe, byte(n), byte(n>>8), byte(n>>16), byte(n>>24), + byte(n>>32), byte(n>>40), byte(n>>48), byte(n>>56)) + } // reserveBuffer checks cap(buf) and expand buffer to len(buf) + appendSize. + // If cap(buf) is not enough, reallocate new buffer. + func reserveBuffer(buf []byte, appendSize int) []byte { + newSize := len(buf) + appendSize + if cap(buf) < newSize { + // Grow buffer exponentially + newBuf := make([]byte, len(buf)*2+appendSize) + copy(newBuf, buf) + buf = newBuf + } + return buf[:newSize] + } // escapeBytesBackslash escapes []byte with backslashes (\) + // This escapes the contents of a string (provided as []byte) by adding backslashes before special + // characters, and turning others into specific escape sequences, such as + // turning newlines into \n and null bytes into \0. + // https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L823-L932 + func escapeBytesBackslash(buf, v []byte) []byte { + pos := len(buf) + buf = reserveBuffer(buf, len(v)*2) for _, c := range v { + switch c { + case '\x00': + buf[pos] = '\\' + buf[pos+1] = '0' + pos += 2 + case '\n': + buf[pos] = '\\' + buf[pos+1] = 'n' + pos += 2 + case '\r': + buf[pos] = '\\' + buf[pos+1] = 'r' + pos += 2 + case '\x1a': + buf[pos] = '\\' + buf[pos+1] = 'Z' + pos += 2 + case '\'': + buf[pos] = '\\' + buf[pos+1] = '\'' + pos += 2 + case '"': + buf[pos] = '\\' + buf[pos+1] = '"' + pos += 2 + case '\\': + buf[pos] = '\\' + buf[pos+1] = '\\' + pos += 2 + default: + buf[pos] = c + pos++ + } + } return buf[:pos] + } // escapeStringBackslash is similar to escapeBytesBackslash but for string. + func escapeStringBackslash(buf []byte, v string) []byte { + pos := len(buf) + buf = reserveBuffer(buf, len(v)*2) for i := 0; i < len(v); i++ { + c := v[i] + switch c { + case '\x00': + buf[pos] = '\\' + buf[pos+1] = '0' + pos += 2 + case '\n': + buf[pos] = '\\' + buf[pos+1] = 'n' + pos += 2 + case '\r': + buf[pos] = '\\' + buf[pos+1] = 'r' + pos += 2 + case '\x1a': + buf[pos] = '\\' + buf[pos+1] = 'Z' + pos += 2 + case '\'': + buf[pos] = '\\' + buf[pos+1] = '\'' + pos += 2 + case '"': + buf[pos] = '\\' + buf[pos+1] = '"' + pos += 2 + case '\\': + buf[pos] = '\\' + buf[pos+1] = '\\' + pos += 2 + default: + buf[pos] = c + pos++ + } + } return buf[:pos] + } // escapeBytesQuotes escapes apostrophes in []byte by doubling them up. + // This escapes the contents of a string by doubling up any apostrophes that + // it contains. This is used when the NO_BACKSLASH_ESCAPES SQL_MODE is in + // effect on the server. + // https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L963-L1038 + func escapeBytesQuotes(buf, v []byte) []byte { + pos := len(buf) + buf = reserveBuffer(buf, len(v)*2) for _, c := range v { + if c == '\'' { + buf[pos] = '\'' + buf[pos+1] = '\'' + pos += 2 + } else { + buf[pos] = c + pos++ + } + } return buf[:pos] + } // escapeStringQuotes is similar to escapeBytesQuotes but for string. + func escapeStringQuotes(buf []byte, v string) []byte { + pos := len(buf) + buf = reserveBuffer(buf, len(v)*2) for i := 0; i < len(v); i++ { + c := v[i] + if c == '\'' { + buf[pos] = '\'' + buf[pos+1] = '\'' + pos += 2 + } else { + buf[pos] = c + pos++ + } + } return buf[:pos] + } /****************************************************************************** + * Sync utils * + ******************************************************************************/ // noCopy may be embedded into structs which must not be copied + // after the first use. + // + // See https://github.com/golang/go/issues/8005#issuecomment-190753527 + // for details. + type noCopy struct{} // Lock is a no-op used by -copylocks checker from `go vet`. + func (*noCopy) Lock() {} // atomicBool is a wrapper around uint32 for usage as a boolean value with + // atomic access. + type atomicBool struct { _noCopy noCopy - value uint32 + + value uint32 } // IsSet returns whether the current boolean value is true + func (ab *atomicBool) IsSet() bool { + return atomic.LoadUint32(&ab.value) > 0 + } // Set sets the value of the bool regardless of the previous value + func (ab *atomicBool) Set(value bool) { + if value { + atomic.StoreUint32(&ab.value, 1) + } else { + atomic.StoreUint32(&ab.value, 0) + } + } // TrySet sets the value of the bool and returns whether the value changed + func (ab *atomicBool) TrySet(value bool) bool { + if value { + return atomic.SwapUint32(&ab.value, 1) == 0 + } + return atomic.SwapUint32(&ab.value, 0) > 0 + } // atomicError is a wrapper for atomically accessed error values + type atomicError struct { _noCopy noCopy - value atomic.Value + + value atomic.Value } // Set sets the error value regardless of the previous value. + // The value must not be nil + func (ae *atomicError) Set(value error) { + ae.value.Store(value) + } // Value returns the current error value + func (ae *atomicError) Value() error { + if v := ae.value.Load(); v != nil { + // this will panic if the value doesn't implement the error interface + return v.(error) + } + return nil + } func namedValueToValue(named []driver.NamedValue) ([]driver.Value, error) { + dargs := make([]driver.Value, len(named)) + for n, param := range named { + if len(param.Name) > 0 { + // TODO: support the use of Named Parameters #561 + return nil, errors.New("mysql: driver does not support the use of Named Parameters") + } + dargs[n] = param.Value + } + return dargs, nil + } func mapIsolationLevel(level driver.IsolationLevel) (string, error) { + switch sql.IsolationLevel(level) { + case sql.LevelRepeatableRead: + return "REPEATABLE READ", nil + case sql.LevelReadCommitted: + return "READ COMMITTED", nil + case sql.LevelReadUncommitted: + return "READ UNCOMMITTED", nil + case sql.LevelSerializable: + return "SERIALIZABLE", nil + default: + return "", fmt.Errorf("mysql: unsupported isolation level: %v", level) + } + } diff --git a/vendor/github.com/golang-jwt/jwt/claims.go b/vendor/github.com/golang-jwt/jwt/claims.go index f1dba3c..a2645dd 100644 --- a/vendor/github.com/golang-jwt/jwt/claims.go +++ b/vendor/github.com/golang-jwt/jwt/claims.go @@ -7,140 +7,231 @@ import ( ) // For a type to be a Claims object, it must just have a Valid method that determines + // if the token is invalid for any supported reason + type Claims interface { Valid() error } // Structured version of Claims Section, as referenced at + // https://tools.ietf.org/html/rfc7519#section-4.1 + // See examples for how to use this with your own claim types + type StandardClaims struct { - Audience string `json:"aud,omitempty"` - ExpiresAt int64 `json:"exp,omitempty"` - Id string `json:"jti,omitempty"` - IssuedAt int64 `json:"iat,omitempty"` - Issuer string `json:"iss,omitempty"` - NotBefore int64 `json:"nbf,omitempty"` - Subject string `json:"sub,omitempty"` + Audience string `json:"aud,omitempty"` + + ExpiresAt int64 `json:"exp,omitempty"` + + Id string `json:"jti,omitempty"` + + IssuedAt int64 `json:"iat,omitempty"` + + Issuer string `json:"iss,omitempty"` + + NotBefore int64 `json:"nbf,omitempty"` + + Subject string `json:"sub,omitempty"` } // Validates time based claims "exp, iat, nbf". + // There is no accounting for clock skew. + // As well, if any of the above claims are not in the token, it will still + // be considered a valid claim. + func (c StandardClaims) Valid() error { + vErr := new(ValidationError) + now := TimeFunc().Unix() // The claims below are optional, by default, so if they are set to the + // default value in Go, let's not fail the verification for them. + if !c.VerifyExpiresAt(now, false) { + delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0)) + vErr.Inner = fmt.Errorf("token is expired by %v", delta) + vErr.Errors |= ValidationErrorExpired + } if !c.VerifyIssuedAt(now, false) { + vErr.Inner = fmt.Errorf("Token used before issued") + vErr.Errors |= ValidationErrorIssuedAt + } if !c.VerifyNotBefore(now, false) { + vErr.Inner = fmt.Errorf("token is not valid yet") + vErr.Errors |= ValidationErrorNotValidYet + } if vErr.valid() { + return nil + } return vErr + } // Compares the aud claim against cmp. + // If required is false, this method will return true if the value matches or is unset + func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool { + return verifyAud([]string{c.Audience}, cmp, req) + } // Compares the exp claim against cmp. + // If required is false, this method will return true if the value matches or is unset + func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool { + return verifyExp(c.ExpiresAt, cmp, req) + } // Compares the iat claim against cmp. + // If required is false, this method will return true if the value matches or is unset + func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool { + return verifyIat(c.IssuedAt, cmp, req) + } // Compares the iss claim against cmp. + // If required is false, this method will return true if the value matches or is unset + func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool { + return verifyIss(c.Issuer, cmp, req) + } // Compares the nbf claim against cmp. + // If required is false, this method will return true if the value matches or is unset + func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool { + return verifyNbf(c.NotBefore, cmp, req) + } // ----- helpers func verifyAud(aud []string, cmp string, required bool) bool { + if len(aud) == 0 { + return !required + } + // use a var here to keep constant time compare when looping over a number of claims + result := false var stringClaims string + for _, a := range aud { + if subtle.ConstantTimeCompare([]byte(a), []byte(cmp)) != 0 { + result = true + } + stringClaims = stringClaims + a + } // case where "" is sent in one or many aud claims + if len(stringClaims) == 0 { + return !required + } return result + } func verifyExp(exp int64, now int64, required bool) bool { + if exp == 0 { + return !required + } + return now <= exp + } func verifyIat(iat int64, now int64, required bool) bool { + if iat == 0 { + return !required + } + return now >= iat + } func verifyIss(iss string, cmp string, required bool) bool { + if iss == "" { + return !required + } + if subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 { + return true + } else { + return false + } + } func verifyNbf(nbf int64, now int64, required bool) bool { + if nbf == 0 { + return !required + } + return now >= nbf + } diff --git a/vendor/github.com/golang-jwt/jwt/ecdsa.go b/vendor/github.com/golang-jwt/jwt/ecdsa.go index 15e2343..6cfc5f3 100644 --- a/vendor/github.com/golang-jwt/jwt/ecdsa.go +++ b/vendor/github.com/golang-jwt/jwt/ecdsa.go @@ -9,134 +9,216 @@ import ( ) var ( + // Sadly this is missing from crypto/ecdsa compared to crypto/rsa + ErrECDSAVerification = errors.New("crypto/ecdsa: verification error") ) // Implements the ECDSA family of signing methods signing methods + // Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification + type SigningMethodECDSA struct { - Name string - Hash crypto.Hash - KeySize int + Name string + + Hash crypto.Hash + + KeySize int + CurveBits int } // Specific instances for EC256 and company + var ( SigningMethodES256 *SigningMethodECDSA + SigningMethodES384 *SigningMethodECDSA + SigningMethodES512 *SigningMethodECDSA ) func init() { + // ES256 + SigningMethodES256 = &SigningMethodECDSA{"ES256", crypto.SHA256, 32, 256} + RegisterSigningMethod(SigningMethodES256.Alg(), func() SigningMethod { + return SigningMethodES256 + }) // ES384 + SigningMethodES384 = &SigningMethodECDSA{"ES384", crypto.SHA384, 48, 384} + RegisterSigningMethod(SigningMethodES384.Alg(), func() SigningMethod { + return SigningMethodES384 + }) // ES512 + SigningMethodES512 = &SigningMethodECDSA{"ES512", crypto.SHA512, 66, 521} + RegisterSigningMethod(SigningMethodES512.Alg(), func() SigningMethod { + return SigningMethodES512 + }) + } func (m *SigningMethodECDSA) Alg() string { + return m.Name + } // Implements the Verify method from SigningMethod + // For this verify method, key must be an ecdsa.PublicKey struct + func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error { + var err error // Decode the signature + var sig []byte + if sig, err = DecodeSegment(signature); err != nil { + return err + } // Get the key + var ecdsaKey *ecdsa.PublicKey + switch k := key.(type) { + case *ecdsa.PublicKey: + ecdsaKey = k + default: + return ErrInvalidKeyType + } if len(sig) != 2*m.KeySize { + return ErrECDSAVerification + } r := big.NewInt(0).SetBytes(sig[:m.KeySize]) + s := big.NewInt(0).SetBytes(sig[m.KeySize:]) // Create hasher + if !m.Hash.Available() { + return ErrHashUnavailable + } + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) // Verify the signature + if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus { + return nil + } return ErrECDSAVerification + } // Implements the Sign method from SigningMethod + // For this signing method, key must be an ecdsa.PrivateKey struct + func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) { + // Get the key + var ecdsaKey *ecdsa.PrivateKey + switch k := key.(type) { + case *ecdsa.PrivateKey: + ecdsaKey = k + default: + return "", ErrInvalidKeyType + } // Create the hasher + if !m.Hash.Available() { + return "", ErrHashUnavailable + } hasher := m.Hash.New() + hasher.Write([]byte(signingString)) // Sign the string and return r, s + if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil { + curveBits := ecdsaKey.Curve.Params().BitSize if m.CurveBits != curveBits { + return "", ErrInvalidKey + } keyBytes := curveBits / 8 + if curveBits%8 > 0 { + keyBytes += 1 + } // We serialize the outputs (r and s) into big-endian byte arrays + // padded with zeros on the left to make sure the sizes work out. + // Output must be 2*keyBytes long. + out := make([]byte, 2*keyBytes) + r.FillBytes(out[0:keyBytes]) // r is assigned to the first half of output. - s.FillBytes(out[keyBytes:]) // s is assigned to the second half of output. + + s.FillBytes(out[keyBytes:]) // s is assigned to the second half of output. return EncodeSegment(out), nil + } else { + return "", err + } + } diff --git a/vendor/github.com/golang-jwt/jwt/ecdsa_utils.go b/vendor/github.com/golang-jwt/jwt/ecdsa_utils.go index db9f4be..b126a25 100644 --- a/vendor/github.com/golang-jwt/jwt/ecdsa_utils.go +++ b/vendor/github.com/golang-jwt/jwt/ecdsa_utils.go @@ -8,62 +8,99 @@ import ( ) var ( - ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key") + ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key") + ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key") ) // Parse PEM encoded Elliptic Curve Private Key Structure + func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil { + if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { + return nil, err + } + } var pkey *ecdsa.PrivateKey + var ok bool + if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok { + return nil, ErrNotECPrivateKey + } return pkey, nil + } // Parse PEM encoded PKCS1 or PKCS8 public key + func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { + if cert, err := x509.ParseCertificate(block.Bytes); err == nil { + parsedKey = cert.PublicKey + } else { + return nil, err + } + } var pkey *ecdsa.PublicKey + var ok bool + if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok { + return nil, ErrNotECPublicKey + } return pkey, nil + } diff --git a/vendor/github.com/golang-jwt/jwt/ed25519.go b/vendor/github.com/golang-jwt/jwt/ed25519.go index 9c18f05..2cf9928 100644 --- a/vendor/github.com/golang-jwt/jwt/ed25519.go +++ b/vendor/github.com/golang-jwt/jwt/ed25519.go @@ -10,71 +10,111 @@ var ( ) // Implements the EdDSA family + // Expects ed25519.PrivateKey for signing and ed25519.PublicKey for verification + type SigningMethodEd25519 struct{} // Specific instance for EdDSA + var ( SigningMethodEdDSA *SigningMethodEd25519 ) func init() { + SigningMethodEdDSA = &SigningMethodEd25519{} + RegisterSigningMethod(SigningMethodEdDSA.Alg(), func() SigningMethod { + return SigningMethodEdDSA + }) + } func (m *SigningMethodEd25519) Alg() string { + return "EdDSA" + } // Implements the Verify method from SigningMethod + // For this verify method, key must be an ed25519.PublicKey + func (m *SigningMethodEd25519) Verify(signingString, signature string, key interface{}) error { + var err error + var ed25519Key ed25519.PublicKey + var ok bool if ed25519Key, ok = key.(ed25519.PublicKey); !ok { + return ErrInvalidKeyType + } if len(ed25519Key) != ed25519.PublicKeySize { + return ErrInvalidKey + } // Decode the signature + var sig []byte + if sig, err = DecodeSegment(signature); err != nil { + return err + } // Verify the signature + if !ed25519.Verify(ed25519Key, []byte(signingString), sig) { + return ErrEd25519Verification + } return nil + } // Implements the Sign method from SigningMethod + // For this signing method, key must be an ed25519.PrivateKey + func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) (string, error) { + var ed25519Key ed25519.PrivateKey + var ok bool if ed25519Key, ok = key.(ed25519.PrivateKey); !ok { + return "", ErrInvalidKeyType + } // ed25519.Sign panics if private key not equal to ed25519.PrivateKeySize + // this allows to avoid recover usage + if len(ed25519Key) != ed25519.PrivateKeySize { + return "", ErrInvalidKey + } // Sign the string and return the encoded result + sig := ed25519.Sign(ed25519Key, []byte(signingString)) + return EncodeSegment(sig), nil + } diff --git a/vendor/github.com/golang-jwt/jwt/ed25519_utils.go b/vendor/github.com/golang-jwt/jwt/ed25519_utils.go index c635727..a738a0a 100644 --- a/vendor/github.com/golang-jwt/jwt/ed25519_utils.go +++ b/vendor/github.com/golang-jwt/jwt/ed25519_utils.go @@ -10,55 +10,86 @@ import ( var ( ErrNotEdPrivateKey = errors.New("Key is not a valid Ed25519 private key") - ErrNotEdPublicKey = errors.New("Key is not a valid Ed25519 public key") + + ErrNotEdPublicKey = errors.New("Key is not a valid Ed25519 public key") ) // Parse PEM-encoded Edwards curve private key + func ParseEdPrivateKeyFromPEM(key []byte) (crypto.PrivateKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { + return nil, err + } var pkey ed25519.PrivateKey + var ok bool + if pkey, ok = parsedKey.(ed25519.PrivateKey); !ok { + return nil, ErrNotEdPrivateKey + } return pkey, nil + } // Parse PEM-encoded Edwards curve public key + func ParseEdPublicKeyFromPEM(key []byte) (crypto.PublicKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { + return nil, err + } var pkey ed25519.PublicKey + var ok bool + if pkey, ok = parsedKey.(ed25519.PublicKey); !ok { + return nil, ErrNotEdPublicKey + } return pkey, nil + } diff --git a/vendor/github.com/golang-jwt/jwt/hmac.go b/vendor/github.com/golang-jwt/jwt/hmac.go index addbe5d..0321cf8 100644 --- a/vendor/github.com/golang-jwt/jwt/hmac.go +++ b/vendor/github.com/golang-jwt/jwt/hmac.go @@ -7,89 +7,143 @@ import ( ) // Implements the HMAC-SHA family of signing methods signing methods + // Expects key type of []byte for both signing and validation + type SigningMethodHMAC struct { Name string + Hash crypto.Hash } // Specific instances for HS256 and company + var ( - SigningMethodHS256 *SigningMethodHMAC - SigningMethodHS384 *SigningMethodHMAC - SigningMethodHS512 *SigningMethodHMAC + SigningMethodHS256 *SigningMethodHMAC + + SigningMethodHS384 *SigningMethodHMAC + + SigningMethodHS512 *SigningMethodHMAC + ErrSignatureInvalid = errors.New("signature is invalid") ) func init() { + // HS256 + SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256} + RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod { + return SigningMethodHS256 + }) // HS384 + SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384} + RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod { + return SigningMethodHS384 + }) // HS512 + SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512} + RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod { + return SigningMethodHS512 + }) + } func (m *SigningMethodHMAC) Alg() string { + return m.Name + } // Verify the signature of HSXXX tokens. Returns nil if the signature is valid. + func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error { + // Verify the key is the right type + keyBytes, ok := key.([]byte) + if !ok { + return ErrInvalidKeyType + } // Decode signature, for comparison + sig, err := DecodeSegment(signature) + if err != nil { + return err + } // Can we use the specified hashing method? + if !m.Hash.Available() { + return ErrHashUnavailable + } // This signing method is symmetric, so we validate the signature + // by reproducing the signature from the signing string and key, then + // comparing that against the provided signature. + hasher := hmac.New(m.Hash.New, keyBytes) + hasher.Write([]byte(signingString)) + if !hmac.Equal(sig, hasher.Sum(nil)) { + return ErrSignatureInvalid + } // No validation errors. Signature is good. + return nil + } // Implements the Sign method from SigningMethod for this signing method. + // Key must be []byte + func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) { + if keyBytes, ok := key.([]byte); ok { + if !m.Hash.Available() { + return "", ErrHashUnavailable + } hasher := hmac.New(m.Hash.New, keyBytes) + hasher.Write([]byte(signingString)) return EncodeSegment(hasher.Sum(nil)), nil + } return "", ErrInvalidKeyType + } diff --git a/vendor/github.com/golang-jwt/jwt/map_claims.go b/vendor/github.com/golang-jwt/jwt/map_claims.go index 9fa1454..bafbbd8 100644 --- a/vendor/github.com/golang-jwt/jwt/map_claims.go +++ b/vendor/github.com/golang-jwt/jwt/map_claims.go @@ -6,114 +6,203 @@ import ( ) // Claims type that uses the map[string]interface{} for JSON decoding + // This is the default claims type if you don't supply one + type MapClaims map[string]interface{} // VerifyAudience Compares the aud claim against cmp. + // If required is false, this method will return true if the value matches or is unset + func (m MapClaims) VerifyAudience(cmp string, req bool) bool { + var aud []string + switch v := m["aud"].(type) { + case string: + aud = append(aud, v) + case []string: + aud = v + case []interface{}: + for _, a := range v { + vs, ok := a.(string) + if !ok { + return false + } + aud = append(aud, vs) + } + } + return verifyAud(aud, cmp, req) + } // Compares the exp claim against cmp. + // If required is false, this method will return true if the value matches or is unset + func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool { + exp, ok := m["exp"] + if !ok { + return !req + } + switch expType := exp.(type) { + case float64: + return verifyExp(int64(expType), cmp, req) + case json.Number: + v, _ := expType.Int64() + return verifyExp(v, cmp, req) + } + return false + } // Compares the iat claim against cmp. + // If required is false, this method will return true if the value matches or is unset + func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool { + iat, ok := m["iat"] + if !ok { + return !req + } + switch iatType := iat.(type) { + case float64: + return verifyIat(int64(iatType), cmp, req) + case json.Number: + v, _ := iatType.Int64() + return verifyIat(v, cmp, req) + } + return false + } // Compares the iss claim against cmp. + // If required is false, this method will return true if the value matches or is unset + func (m MapClaims) VerifyIssuer(cmp string, req bool) bool { + iss, _ := m["iss"].(string) + return verifyIss(iss, cmp, req) + } // Compares the nbf claim against cmp. + // If required is false, this method will return true if the value matches or is unset + func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool { + nbf, ok := m["nbf"] + if !ok { + return !req + } + switch nbfType := nbf.(type) { + case float64: + return verifyNbf(int64(nbfType), cmp, req) + case json.Number: + v, _ := nbfType.Int64() + return verifyNbf(v, cmp, req) + } + return false + } // Validates time based claims "exp, iat, nbf". + // There is no accounting for clock skew. + // As well, if any of the above claims are not in the token, it will still + // be considered a valid claim. + func (m MapClaims) Valid() error { + vErr := new(ValidationError) + now := TimeFunc().Unix() if !m.VerifyExpiresAt(now, false) { + vErr.Inner = errors.New("Token is expired") + vErr.Errors |= ValidationErrorExpired + } if !m.VerifyIssuedAt(now, false) { + vErr.Inner = errors.New("Token used before issued") + vErr.Errors |= ValidationErrorIssuedAt + } if !m.VerifyNotBefore(now, false) { + vErr.Inner = errors.New("Token is not valid yet") + vErr.Errors |= ValidationErrorNotValidYet + } if vErr.valid() { + return nil + } return vErr + } diff --git a/vendor/github.com/golang-jwt/jwt/parser.go b/vendor/github.com/golang-jwt/jwt/parser.go index d6901d9..70f0ca2 100644 --- a/vendor/github.com/golang-jwt/jwt/parser.go +++ b/vendor/github.com/golang-jwt/jwt/parser.go @@ -8,141 +8,244 @@ import ( ) type Parser struct { - ValidMethods []string // If populated, only these methods will be considered valid - UseJSONNumber bool // Use JSON Number format in JSON decoder - SkipClaimsValidation bool // Skip claims validation during token parsing + ValidMethods []string // If populated, only these methods will be considered valid + + UseJSONNumber bool // Use JSON Number format in JSON decoder + + SkipClaimsValidation bool // Skip claims validation during token parsing + } // Parse, validate, and return a token. + // keyFunc will receive the parsed token and should return the key for validating. + // If everything is kosher, err will be nil + func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { + return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) + } func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { + token, parts, err := p.ParseUnverified(tokenString, claims) + if err != nil { + return token, err + } // Verify signing method is in the required set + if p.ValidMethods != nil { + var signingMethodValid = false + var alg = token.Method.Alg() + for _, m := range p.ValidMethods { + if m == alg { + signingMethodValid = true + break + } + } + if !signingMethodValid { + // signing method is not in the listed set + return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid) + } + } // Lookup key + var key interface{} + if keyFunc == nil { + // keyFunc was not provided. short circuiting validation + return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable) + } + if key, err = keyFunc(token); err != nil { + // keyFunc returned an error + if ve, ok := err.(*ValidationError); ok { + return token, ve + } + return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable} + } vErr := &ValidationError{} // Validate Claims + if !p.SkipClaimsValidation { + if err := token.Claims.Valid(); err != nil { // If the Claims Valid returned an error, check if it is a validation error, + // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set + if e, ok := err.(*ValidationError); !ok { + vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid} + } else { + vErr = e + } + } + } // Perform validation + token.Signature = parts[2] + if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { + vErr.Inner = err + vErr.Errors |= ValidationErrorSignatureInvalid + } if vErr.valid() { + token.Valid = true + return token, nil + } return token, vErr + } // WARNING: Don't use this method unless you know what you're doing + // + // This method parses the token but doesn't validate the signature. It's only + // ever useful in cases where you know the signature is valid (because it has + // been checked previously in the stack) and you want to extract values from + // it. + func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { + parts = strings.Split(tokenString, ".") + if len(parts) != 3 { + return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) + } token = &Token{Raw: tokenString} // parse Header + var headerBytes []byte + if headerBytes, err = DecodeSegment(parts[0]); err != nil { + if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { + return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) + } + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + if err = json.Unmarshal(headerBytes, &token.Header); err != nil { + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } // parse Claims + var claimBytes []byte + token.Claims = claims if claimBytes, err = DecodeSegment(parts[1]); err != nil { + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) + if p.UseJSONNumber { + dec.UseNumber() + } + // JSON Decode. Special case for map type to avoid weird pointer behavior + if c, ok := token.Claims.(MapClaims); ok { + err = dec.Decode(&c) + } else { + err = dec.Decode(&claims) + } + // Handle decode error + if err != nil { + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } // Lookup signature method + if method, ok := token.Header["alg"].(string); ok { + if token.Method = GetSigningMethod(method); token.Method == nil { + return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) + } + } else { + return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) + } return token, parts, nil + } diff --git a/vendor/github.com/golang-jwt/jwt/rsa.go b/vendor/github.com/golang-jwt/jwt/rsa.go index e4caf1c..b63546b 100644 --- a/vendor/github.com/golang-jwt/jwt/rsa.go +++ b/vendor/github.com/golang-jwt/jwt/rsa.go @@ -7,95 +7,151 @@ import ( ) // Implements the RSA family of signing methods signing methods + // Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation + type SigningMethodRSA struct { Name string + Hash crypto.Hash } // Specific instances for RS256 and company + var ( SigningMethodRS256 *SigningMethodRSA + SigningMethodRS384 *SigningMethodRSA + SigningMethodRS512 *SigningMethodRSA ) func init() { + // RS256 + SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256} + RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod { + return SigningMethodRS256 + }) // RS384 + SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384} + RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod { + return SigningMethodRS384 + }) // RS512 + SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512} + RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod { + return SigningMethodRS512 + }) + } func (m *SigningMethodRSA) Alg() string { + return m.Name + } // Implements the Verify method from SigningMethod + // For this signing method, must be an *rsa.PublicKey structure. + func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error { + var err error // Decode the signature + var sig []byte + if sig, err = DecodeSegment(signature); err != nil { + return err + } var rsaKey *rsa.PublicKey + var ok bool if rsaKey, ok = key.(*rsa.PublicKey); !ok { + return ErrInvalidKeyType + } // Create hasher + if !m.Hash.Available() { + return ErrHashUnavailable + } + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) // Verify the signature + return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig) + } // Implements the Sign method from SigningMethod + // For this signing method, must be an *rsa.PrivateKey structure. + func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) { + var rsaKey *rsa.PrivateKey + var ok bool // Validate type of key + if rsaKey, ok = key.(*rsa.PrivateKey); !ok { + return "", ErrInvalidKey + } // Create the hasher + if !m.Hash.Available() { + return "", ErrHashUnavailable + } hasher := m.Hash.New() + hasher.Write([]byte(signingString)) // Sign the string and return the encoded bytes + if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil { + return EncodeSegment(sigBytes), nil + } else { + return "", err + } + } diff --git a/vendor/github.com/golang-jwt/jwt/rsa_pss.go b/vendor/github.com/golang-jwt/jwt/rsa_pss.go index 370c5a8..61deea4 100644 --- a/vendor/github.com/golang-jwt/jwt/rsa_pss.go +++ b/vendor/github.com/golang-jwt/jwt/rsa_pss.go @@ -10,134 +10,219 @@ import ( ) // Implements the RSAPSS family of signing methods signing methods + type SigningMethodRSAPSS struct { *SigningMethodRSA + Options *rsa.PSSOptions + // VerifyOptions is optional. If set overrides Options for rsa.VerifyPPS. + // Used to accept tokens signed with rsa.PSSSaltLengthAuto, what doesn't follow + // https://tools.ietf.org/html/rfc7518#section-3.5 but was used previously. + // See https://github.com/dgrijalva/jwt-go/issues/285#issuecomment-437451244 for details. + VerifyOptions *rsa.PSSOptions } // Specific instances for RS/PS and company. + var ( SigningMethodPS256 *SigningMethodRSAPSS + SigningMethodPS384 *SigningMethodRSAPSS + SigningMethodPS512 *SigningMethodRSAPSS ) func init() { + // PS256 + SigningMethodPS256 = &SigningMethodRSAPSS{ + SigningMethodRSA: &SigningMethodRSA{ + Name: "PS256", + Hash: crypto.SHA256, }, + Options: &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthEqualsHash, }, + VerifyOptions: &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, }, } + RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod { + return SigningMethodPS256 + }) // PS384 + SigningMethodPS384 = &SigningMethodRSAPSS{ + SigningMethodRSA: &SigningMethodRSA{ + Name: "PS384", + Hash: crypto.SHA384, }, + Options: &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthEqualsHash, }, + VerifyOptions: &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, }, } + RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod { + return SigningMethodPS384 + }) // PS512 + SigningMethodPS512 = &SigningMethodRSAPSS{ + SigningMethodRSA: &SigningMethodRSA{ + Name: "PS512", + Hash: crypto.SHA512, }, + Options: &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthEqualsHash, }, + VerifyOptions: &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, }, } + RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod { + return SigningMethodPS512 + }) + } // Implements the Verify method from SigningMethod + // For this verify method, key must be an rsa.PublicKey struct + func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error { + var err error // Decode the signature + var sig []byte + if sig, err = DecodeSegment(signature); err != nil { + return err + } var rsaKey *rsa.PublicKey + switch k := key.(type) { + case *rsa.PublicKey: + rsaKey = k + default: + return ErrInvalidKey + } // Create hasher + if !m.Hash.Available() { + return ErrHashUnavailable + } + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) opts := m.Options + if m.VerifyOptions != nil { + opts = m.VerifyOptions + } return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, opts) + } // Implements the Sign method from SigningMethod + // For this signing method, key must be an rsa.PrivateKey struct + func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) { + var rsaKey *rsa.PrivateKey switch k := key.(type) { + case *rsa.PrivateKey: + rsaKey = k + default: + return "", ErrInvalidKeyType + } // Create the hasher + if !m.Hash.Available() { + return "", ErrHashUnavailable + } hasher := m.Hash.New() + hasher.Write([]byte(signingString)) // Sign the string and return the encoded bytes + if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil { + return EncodeSegment(sigBytes), nil + } else { + return "", err + } + } diff --git a/vendor/github.com/golang-jwt/jwt/rsa_utils.go b/vendor/github.com/golang-jwt/jwt/rsa_utils.go index 14c78c2..83625ba 100644 --- a/vendor/github.com/golang-jwt/jwt/rsa_utils.go +++ b/vendor/github.com/golang-jwt/jwt/rsa_utils.go @@ -9,93 +9,148 @@ import ( var ( ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be a PEM encoded PKCS1 or PKCS8 key") - ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key") - ErrNotRSAPublicKey = errors.New("Key is not a valid RSA public key") + + ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key") + + ErrNotRSAPublicKey = errors.New("Key is not a valid RSA public key") ) // Parse PEM encoded PKCS1 or PKCS8 private key + func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } var parsedKey interface{} + if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { + if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { + return nil, err + } + } var pkey *rsa.PrivateKey + var ok bool + if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { + return nil, ErrNotRSAPrivateKey + } return pkey, nil + } // Parse PEM encoded PKCS1 or PKCS8 private key protected with password + func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } var parsedKey interface{} var blockDecrypted []byte + if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil { + return nil, err + } if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil { + if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil { + return nil, err + } + } var pkey *rsa.PrivateKey + var ok bool + if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { + return nil, ErrNotRSAPrivateKey + } return pkey, nil + } // Parse PEM encoded PKCS1 or PKCS8 public key + func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { + if cert, err := x509.ParseCertificate(block.Bytes); err == nil { + parsedKey = cert.PublicKey + } else { + return nil, err + } + } var pkey *rsa.PublicKey + var ok bool + if pkey, ok = parsedKey.(*rsa.PublicKey); !ok { + return nil, ErrNotRSAPublicKey + } return pkey, nil + } diff --git a/vendor/github.com/golang-jwt/jwt/token.go b/vendor/github.com/golang-jwt/jwt/token.go index 6b30ced..4730d78 100644 --- a/vendor/github.com/golang-jwt/jwt/token.go +++ b/vendor/github.com/golang-jwt/jwt/token.go @@ -8,97 +8,166 @@ import ( ) // TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). + // You can override it to use another time value. This is useful for testing or if your + // server uses a different time zone than your tokens. + var TimeFunc = time.Now // Parse methods use this callback function to supply + // the key for verification. The function receives the parsed, + // but unverified Token. This allows you to use properties in the + // Header of the token (such as `kid`) to identify which key to use. + type Keyfunc func(*Token) (interface{}, error) // A JWT Token. Different fields will be used depending on whether you're + // creating or parsing/verifying a token. + type Token struct { - Raw string // The raw token. Populated when you Parse a token - Method SigningMethod // The signing method used or to be used - Header map[string]interface{} // The first segment of the token - Claims Claims // The second segment of the token - Signature string // The third segment of the token. Populated when you Parse a token - Valid bool // Is the token valid? Populated when you Parse/Verify a token + Raw string // The raw token. Populated when you Parse a token + + Method SigningMethod // The signing method used or to be used + + Header map[string]interface{} // The first segment of the token + + Claims Claims // The second segment of the token + + Signature string // The third segment of the token. Populated when you Parse a token + + Valid bool // Is the token valid? Populated when you Parse/Verify a token + } // Create a new Token. Takes a signing method + func New(method SigningMethod) *Token { + return NewWithClaims(method, MapClaims{}) + } func NewWithClaims(method SigningMethod, claims Claims) *Token { + return &Token{ + Header: map[string]interface{}{ + "typ": "JWT", + "alg": method.Alg(), }, + Claims: claims, + Method: method, } + } // Get the complete, signed token + func (t *Token) SignedString(key interface{}) (string, error) { + var sig, sstr string + var err error + if sstr, err = t.SigningString(); err != nil { + return "", err + } + if sig, err = t.Method.Sign(sstr, key); err != nil { + return "", err + } + return strings.Join([]string{sstr, sig}, "."), nil + } // Generate the signing string. This is the + // most expensive part of the whole deal. Unless you + // need this for something special, just go straight for + // the SignedString. + func (t *Token) SigningString() (string, error) { + var err error + parts := make([]string, 2) + for i := range parts { + var jsonValue []byte + if i == 0 { + if jsonValue, err = json.Marshal(t.Header); err != nil { + return "", err + } + } else { + if jsonValue, err = json.Marshal(t.Claims); err != nil { + return "", err + } + } parts[i] = EncodeSegment(jsonValue) + } + return strings.Join(parts, "."), nil + } // Parse, validate, and return a token. + // keyFunc will receive the parsed token and should return the key for validating. + // If everything is kosher, err will be nil + func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { + return new(Parser).Parse(tokenString, keyFunc) + } func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { + return new(Parser).ParseWithClaims(tokenString, claims, keyFunc) + } // Encode JWT specific base64url encoding with padding stripped + func EncodeSegment(seg []byte) string { + return base64.RawURLEncoding.EncodeToString(seg) + } // Decode JWT specific base64url encoding with padding stripped + func DecodeSegment(seg string) ([]byte, error) { + return base64.RawURLEncoding.DecodeString(seg) + } diff --git a/vendor/github.com/golang-jwt/jwt/v4/claims.go b/vendor/github.com/golang-jwt/jwt/v4/claims.go index 364cec8..4083e2b 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/claims.go +++ b/vendor/github.com/golang-jwt/jwt/v4/claims.go @@ -7,263 +7,428 @@ import ( ) // Claims must just have a Valid method that determines + // if the token is invalid for any supported reason + type Claims interface { Valid() error } // RegisteredClaims are a structured version of the JWT Claims Set, + // restricted to Registered Claim Names, as referenced at + // https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 + // + // This type can be used on its own, but then additional private and + // public claims embedded in the JWT will not be parsed. The typical usecase + // therefore is to embedded this in a user-defined claim type. + // + // See examples for how to use this with your own claim types. + type RegisteredClaims struct { + // the `iss` (Issuer) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.1 + Issuer string `json:"iss,omitempty"` // the `sub` (Subject) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2 + Subject string `json:"sub,omitempty"` // the `aud` (Audience) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3 + Audience ClaimStrings `json:"aud,omitempty"` // the `exp` (Expiration Time) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4 + ExpiresAt *NumericDate `json:"exp,omitempty"` // the `nbf` (Not Before) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5 + NotBefore *NumericDate `json:"nbf,omitempty"` // the `iat` (Issued At) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.6 + IssuedAt *NumericDate `json:"iat,omitempty"` // the `jti` (JWT ID) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7 + ID string `json:"jti,omitempty"` } // Valid validates time based claims "exp, iat, nbf". + // There is no accounting for clock skew. + // As well, if any of the above claims are not in the token, it will still + // be considered a valid claim. + func (c RegisteredClaims) Valid() error { + vErr := new(ValidationError) + now := TimeFunc() // The claims below are optional, by default, so if they are set to the + // default value in Go, let's not fail the verification for them. + if !c.VerifyExpiresAt(now, false) { + delta := now.Sub(c.ExpiresAt.Time) + vErr.Inner = fmt.Errorf("%s by %s", ErrTokenExpired, delta) + vErr.Errors |= ValidationErrorExpired + } if !c.VerifyIssuedAt(now, false) { + vErr.Inner = ErrTokenUsedBeforeIssued + vErr.Errors |= ValidationErrorIssuedAt + } if !c.VerifyNotBefore(now, false) { + vErr.Inner = ErrTokenNotValidYet + vErr.Errors |= ValidationErrorNotValidYet + } if vErr.valid() { + return nil + } return vErr + } // VerifyAudience compares the aud claim against cmp. + // If required is false, this method will return true if the value matches or is unset + func (c *RegisteredClaims) VerifyAudience(cmp string, req bool) bool { + return verifyAud(c.Audience, cmp, req) + } // VerifyExpiresAt compares the exp claim against cmp (cmp < exp). + // If req is false, it will return true, if exp is unset. + func (c *RegisteredClaims) VerifyExpiresAt(cmp time.Time, req bool) bool { + if c.ExpiresAt == nil { + return verifyExp(nil, cmp, req) + } return verifyExp(&c.ExpiresAt.Time, cmp, req) + } // VerifyIssuedAt compares the iat claim against cmp (cmp >= iat). + // If req is false, it will return true, if iat is unset. + func (c *RegisteredClaims) VerifyIssuedAt(cmp time.Time, req bool) bool { + if c.IssuedAt == nil { + return verifyIat(nil, cmp, req) + } return verifyIat(&c.IssuedAt.Time, cmp, req) + } // VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). + // If req is false, it will return true, if nbf is unset. + func (c *RegisteredClaims) VerifyNotBefore(cmp time.Time, req bool) bool { + if c.NotBefore == nil { + return verifyNbf(nil, cmp, req) + } return verifyNbf(&c.NotBefore.Time, cmp, req) + } // VerifyIssuer compares the iss claim against cmp. + // If required is false, this method will return true if the value matches or is unset + func (c *RegisteredClaims) VerifyIssuer(cmp string, req bool) bool { + return verifyIss(c.Issuer, cmp, req) + } // StandardClaims are a structured version of the JWT Claims Set, as referenced at + // https://datatracker.ietf.org/doc/html/rfc7519#section-4. They do not follow the + // specification exactly, since they were based on an earlier draft of the + // specification and not updated. The main difference is that they only + // support integer-based date fields and singular audiences. This might lead to + // incompatibilities with other JWT implementations. The use of this is discouraged, instead + // the newer RegisteredClaims struct should be used. + // + // Deprecated: Use RegisteredClaims instead for a forward-compatible way to access registered claims in a struct. + type StandardClaims struct { - Audience string `json:"aud,omitempty"` - ExpiresAt int64 `json:"exp,omitempty"` - Id string `json:"jti,omitempty"` - IssuedAt int64 `json:"iat,omitempty"` - Issuer string `json:"iss,omitempty"` - NotBefore int64 `json:"nbf,omitempty"` - Subject string `json:"sub,omitempty"` + Audience string `json:"aud,omitempty"` + + ExpiresAt int64 `json:"exp,omitempty"` + + Id string `json:"jti,omitempty"` + + IssuedAt int64 `json:"iat,omitempty"` + + Issuer string `json:"iss,omitempty"` + + NotBefore int64 `json:"nbf,omitempty"` + + Subject string `json:"sub,omitempty"` } // Valid validates time based claims "exp, iat, nbf". There is no accounting for clock skew. + // As well, if any of the above claims are not in the token, it will still + // be considered a valid claim. + func (c StandardClaims) Valid() error { + vErr := new(ValidationError) + now := TimeFunc().Unix() // The claims below are optional, by default, so if they are set to the + // default value in Go, let's not fail the verification for them. + if !c.VerifyExpiresAt(now, false) { + delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0)) + vErr.Inner = fmt.Errorf("%s by %s", ErrTokenExpired, delta) + vErr.Errors |= ValidationErrorExpired + } if !c.VerifyIssuedAt(now, false) { + vErr.Inner = ErrTokenUsedBeforeIssued + vErr.Errors |= ValidationErrorIssuedAt + } if !c.VerifyNotBefore(now, false) { + vErr.Inner = ErrTokenNotValidYet + vErr.Errors |= ValidationErrorNotValidYet + } if vErr.valid() { + return nil + } return vErr + } // VerifyAudience compares the aud claim against cmp. + // If required is false, this method will return true if the value matches or is unset + func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool { + return verifyAud([]string{c.Audience}, cmp, req) + } // VerifyExpiresAt compares the exp claim against cmp (cmp < exp). + // If req is false, it will return true, if exp is unset. + func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool { + if c.ExpiresAt == 0 { + return verifyExp(nil, time.Unix(cmp, 0), req) + } t := time.Unix(c.ExpiresAt, 0) + return verifyExp(&t, time.Unix(cmp, 0), req) + } // VerifyIssuedAt compares the iat claim against cmp (cmp >= iat). + // If req is false, it will return true, if iat is unset. + func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool { + if c.IssuedAt == 0 { + return verifyIat(nil, time.Unix(cmp, 0), req) + } t := time.Unix(c.IssuedAt, 0) + return verifyIat(&t, time.Unix(cmp, 0), req) + } // VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). + // If req is false, it will return true, if nbf is unset. + func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool { + if c.NotBefore == 0 { + return verifyNbf(nil, time.Unix(cmp, 0), req) + } t := time.Unix(c.NotBefore, 0) + return verifyNbf(&t, time.Unix(cmp, 0), req) + } // VerifyIssuer compares the iss claim against cmp. + // If required is false, this method will return true if the value matches or is unset + func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool { + return verifyIss(c.Issuer, cmp, req) + } // ----- helpers func verifyAud(aud []string, cmp string, required bool) bool { + if len(aud) == 0 { + return !required + } + // use a var here to keep constant time compare when looping over a number of claims + result := false var stringClaims string + for _, a := range aud { + if subtle.ConstantTimeCompare([]byte(a), []byte(cmp)) != 0 { + result = true + } + stringClaims = stringClaims + a + } // case where "" is sent in one or many aud claims + if len(stringClaims) == 0 { + return !required + } return result + } func verifyExp(exp *time.Time, now time.Time, required bool) bool { + if exp == nil { + return !required + } + return now.Before(*exp) + } func verifyIat(iat *time.Time, now time.Time, required bool) bool { + if iat == nil { + return !required + } + return now.After(*iat) || now.Equal(*iat) + } func verifyNbf(nbf *time.Time, now time.Time, required bool) bool { + if nbf == nil { + return !required + } + return now.After(*nbf) || now.Equal(*nbf) + } func verifyIss(iss string, cmp string, required bool) bool { + if iss == "" { + return !required + } + return subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 + } diff --git a/vendor/github.com/golang-jwt/jwt/v4/ecdsa.go b/vendor/github.com/golang-jwt/jwt/v4/ecdsa.go index eac023f..11a5542 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/ecdsa.go +++ b/vendor/github.com/golang-jwt/jwt/v4/ecdsa.go @@ -9,134 +9,216 @@ import ( ) var ( + // Sadly this is missing from crypto/ecdsa compared to crypto/rsa + ErrECDSAVerification = errors.New("crypto/ecdsa: verification error") ) // SigningMethodECDSA implements the ECDSA family of signing methods. + // Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification + type SigningMethodECDSA struct { - Name string - Hash crypto.Hash - KeySize int + Name string + + Hash crypto.Hash + + KeySize int + CurveBits int } // Specific instances for EC256 and company + var ( SigningMethodES256 *SigningMethodECDSA + SigningMethodES384 *SigningMethodECDSA + SigningMethodES512 *SigningMethodECDSA ) func init() { + // ES256 + SigningMethodES256 = &SigningMethodECDSA{"ES256", crypto.SHA256, 32, 256} + RegisterSigningMethod(SigningMethodES256.Alg(), func() SigningMethod { + return SigningMethodES256 + }) // ES384 + SigningMethodES384 = &SigningMethodECDSA{"ES384", crypto.SHA384, 48, 384} + RegisterSigningMethod(SigningMethodES384.Alg(), func() SigningMethod { + return SigningMethodES384 + }) // ES512 + SigningMethodES512 = &SigningMethodECDSA{"ES512", crypto.SHA512, 66, 521} + RegisterSigningMethod(SigningMethodES512.Alg(), func() SigningMethod { + return SigningMethodES512 + }) + } func (m *SigningMethodECDSA) Alg() string { + return m.Name + } // Verify implements token verification for the SigningMethod. + // For this verify method, key must be an ecdsa.PublicKey struct + func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error { + var err error // Decode the signature + var sig []byte + if sig, err = DecodeSegment(signature); err != nil { + return err + } // Get the key + var ecdsaKey *ecdsa.PublicKey + switch k := key.(type) { + case *ecdsa.PublicKey: + ecdsaKey = k + default: + return ErrInvalidKeyType + } if len(sig) != 2*m.KeySize { + return ErrECDSAVerification + } r := big.NewInt(0).SetBytes(sig[:m.KeySize]) + s := big.NewInt(0).SetBytes(sig[m.KeySize:]) // Create hasher + if !m.Hash.Available() { + return ErrHashUnavailable + } + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) // Verify the signature + if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus { + return nil + } return ErrECDSAVerification + } // Sign implements token signing for the SigningMethod. + // For this signing method, key must be an ecdsa.PrivateKey struct + func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) { + // Get the key + var ecdsaKey *ecdsa.PrivateKey + switch k := key.(type) { + case *ecdsa.PrivateKey: + ecdsaKey = k + default: + return "", ErrInvalidKeyType + } // Create the hasher + if !m.Hash.Available() { + return "", ErrHashUnavailable + } hasher := m.Hash.New() + hasher.Write([]byte(signingString)) // Sign the string and return r, s + if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil { + curveBits := ecdsaKey.Curve.Params().BitSize if m.CurveBits != curveBits { + return "", ErrInvalidKey + } keyBytes := curveBits / 8 + if curveBits%8 > 0 { + keyBytes += 1 + } // We serialize the outputs (r and s) into big-endian byte arrays + // padded with zeros on the left to make sure the sizes work out. + // Output must be 2*keyBytes long. + out := make([]byte, 2*keyBytes) + r.FillBytes(out[0:keyBytes]) // r is assigned to the first half of output. - s.FillBytes(out[keyBytes:]) // s is assigned to the second half of output. + + s.FillBytes(out[keyBytes:]) // s is assigned to the second half of output. return EncodeSegment(out), nil + } else { + return "", err + } + } diff --git a/vendor/github.com/golang-jwt/jwt/v4/ecdsa_utils.go b/vendor/github.com/golang-jwt/jwt/v4/ecdsa_utils.go index 5700636..7254d66 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/ecdsa_utils.go +++ b/vendor/github.com/golang-jwt/jwt/v4/ecdsa_utils.go @@ -8,62 +8,99 @@ import ( ) var ( - ErrNotECPublicKey = errors.New("key is not a valid ECDSA public key") + ErrNotECPublicKey = errors.New("key is not a valid ECDSA public key") + ErrNotECPrivateKey = errors.New("key is not a valid ECDSA private key") ) // ParseECPrivateKeyFromPEM parses a PEM encoded Elliptic Curve Private Key Structure + func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil { + if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { + return nil, err + } + } var pkey *ecdsa.PrivateKey + var ok bool + if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok { + return nil, ErrNotECPrivateKey + } return pkey, nil + } // ParseECPublicKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 public key + func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { + if cert, err := x509.ParseCertificate(block.Bytes); err == nil { + parsedKey = cert.PublicKey + } else { + return nil, err + } + } var pkey *ecdsa.PublicKey + var ok bool + if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok { + return nil, ErrNotECPublicKey + } return pkey, nil + } diff --git a/vendor/github.com/golang-jwt/jwt/v4/ed25519.go b/vendor/github.com/golang-jwt/jwt/v4/ed25519.go index 24bd027..3329287 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/ed25519.go +++ b/vendor/github.com/golang-jwt/jwt/v4/ed25519.go @@ -12,73 +12,115 @@ var ( ) // SigningMethodEd25519 implements the EdDSA family. + // Expects ed25519.PrivateKey for signing and ed25519.PublicKey for verification + type SigningMethodEd25519 struct{} // Specific instance for EdDSA + var ( SigningMethodEdDSA *SigningMethodEd25519 ) func init() { + SigningMethodEdDSA = &SigningMethodEd25519{} + RegisterSigningMethod(SigningMethodEdDSA.Alg(), func() SigningMethod { + return SigningMethodEdDSA + }) + } func (m *SigningMethodEd25519) Alg() string { + return "EdDSA" + } // Verify implements token verification for the SigningMethod. + // For this verify method, key must be an ed25519.PublicKey + func (m *SigningMethodEd25519) Verify(signingString, signature string, key interface{}) error { + var err error + var ed25519Key ed25519.PublicKey + var ok bool if ed25519Key, ok = key.(ed25519.PublicKey); !ok { + return ErrInvalidKeyType + } if len(ed25519Key) != ed25519.PublicKeySize { + return ErrInvalidKey + } // Decode the signature + var sig []byte + if sig, err = DecodeSegment(signature); err != nil { + return err + } // Verify the signature + if !ed25519.Verify(ed25519Key, []byte(signingString), sig) { + return ErrEd25519Verification + } return nil + } // Sign implements token signing for the SigningMethod. + // For this signing method, key must be an ed25519.PrivateKey + func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) (string, error) { + var ed25519Key crypto.Signer + var ok bool if ed25519Key, ok = key.(crypto.Signer); !ok { + return "", ErrInvalidKeyType + } if _, ok := ed25519Key.Public().(ed25519.PublicKey); !ok { + return "", ErrInvalidKey + } // Sign the string and return the encoded result + // ed25519 performs a two-pass hash as part of its algorithm. Therefore, we need to pass a non-prehashed message into the Sign function, as indicated by crypto.Hash(0) + sig, err := ed25519Key.Sign(rand.Reader, []byte(signingString), crypto.Hash(0)) + if err != nil { + return "", err + } + return EncodeSegment(sig), nil + } diff --git a/vendor/github.com/golang-jwt/jwt/v4/ed25519_utils.go b/vendor/github.com/golang-jwt/jwt/v4/ed25519_utils.go index cdb5e68..58dcc40 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/ed25519_utils.go +++ b/vendor/github.com/golang-jwt/jwt/v4/ed25519_utils.go @@ -10,55 +10,86 @@ import ( var ( ErrNotEdPrivateKey = errors.New("key is not a valid Ed25519 private key") - ErrNotEdPublicKey = errors.New("key is not a valid Ed25519 public key") + + ErrNotEdPublicKey = errors.New("key is not a valid Ed25519 public key") ) // ParseEdPrivateKeyFromPEM parses a PEM-encoded Edwards curve private key + func ParseEdPrivateKeyFromPEM(key []byte) (crypto.PrivateKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { + return nil, err + } var pkey ed25519.PrivateKey + var ok bool + if pkey, ok = parsedKey.(ed25519.PrivateKey); !ok { + return nil, ErrNotEdPrivateKey + } return pkey, nil + } // ParseEdPublicKeyFromPEM parses a PEM-encoded Edwards curve public key + func ParseEdPublicKeyFromPEM(key []byte) (crypto.PublicKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { + return nil, err + } var pkey ed25519.PublicKey + var ok bool + if pkey, ok = parsedKey.(ed25519.PublicKey); !ok { + return nil, ErrNotEdPublicKey + } return pkey, nil + } diff --git a/vendor/github.com/golang-jwt/jwt/v4/hmac.go b/vendor/github.com/golang-jwt/jwt/v4/hmac.go index 011f68a..de246a3 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/hmac.go +++ b/vendor/github.com/golang-jwt/jwt/v4/hmac.go @@ -7,89 +7,143 @@ import ( ) // SigningMethodHMAC implements the HMAC-SHA family of signing methods. + // Expects key type of []byte for both signing and validation + type SigningMethodHMAC struct { Name string + Hash crypto.Hash } // Specific instances for HS256 and company + var ( - SigningMethodHS256 *SigningMethodHMAC - SigningMethodHS384 *SigningMethodHMAC - SigningMethodHS512 *SigningMethodHMAC + SigningMethodHS256 *SigningMethodHMAC + + SigningMethodHS384 *SigningMethodHMAC + + SigningMethodHS512 *SigningMethodHMAC + ErrSignatureInvalid = errors.New("signature is invalid") ) func init() { + // HS256 + SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256} + RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod { + return SigningMethodHS256 + }) // HS384 + SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384} + RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod { + return SigningMethodHS384 + }) // HS512 + SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512} + RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod { + return SigningMethodHS512 + }) + } func (m *SigningMethodHMAC) Alg() string { + return m.Name + } // Verify implements token verification for the SigningMethod. Returns nil if the signature is valid. + func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error { + // Verify the key is the right type + keyBytes, ok := key.([]byte) + if !ok { + return ErrInvalidKeyType + } // Decode signature, for comparison + sig, err := DecodeSegment(signature) + if err != nil { + return err + } // Can we use the specified hashing method? + if !m.Hash.Available() { + return ErrHashUnavailable + } // This signing method is symmetric, so we validate the signature + // by reproducing the signature from the signing string and key, then + // comparing that against the provided signature. + hasher := hmac.New(m.Hash.New, keyBytes) + hasher.Write([]byte(signingString)) + if !hmac.Equal(sig, hasher.Sum(nil)) { + return ErrSignatureInvalid + } // No validation errors. Signature is good. + return nil + } // Sign implements token signing for the SigningMethod. + // Key must be []byte + func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) { + if keyBytes, ok := key.([]byte); ok { + if !m.Hash.Available() { + return "", ErrHashUnavailable + } hasher := hmac.New(m.Hash.New, keyBytes) + hasher.Write([]byte(signingString)) return EncodeSegment(hasher.Sum(nil)), nil + } return "", ErrInvalidKeyType + } diff --git a/vendor/github.com/golang-jwt/jwt/v4/map_claims.go b/vendor/github.com/golang-jwt/jwt/v4/map_claims.go index 1d5c430..5529da4 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/map_claims.go +++ b/vendor/github.com/golang-jwt/jwt/v4/map_claims.go @@ -7,144 +7,233 @@ import ( ) // MapClaims is a claims type that uses the map[string]interface{} for JSON decoding. + // This is the default claims type if you don't supply one + type MapClaims map[string]interface{} // VerifyAudience Compares the aud claim against cmp. + // If required is false, this method will return true if the value matches or is unset + func (m MapClaims) VerifyAudience(cmp string, req bool) bool { + var aud []string + switch v := m["aud"].(type) { + case string: + aud = append(aud, v) + case []string: + aud = v + case []interface{}: + for _, a := range v { + vs, ok := a.(string) + if !ok { + return false + } + aud = append(aud, vs) + } + } + return verifyAud(aud, cmp, req) + } // VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). + // If req is false, it will return true, if exp is unset. + func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool { + cmpTime := time.Unix(cmp, 0) v, ok := m["exp"] + if !ok { + return !req + } switch exp := v.(type) { + case float64: + if exp == 0 { + return verifyExp(nil, cmpTime, req) + } return verifyExp(&newNumericDateFromSeconds(exp).Time, cmpTime, req) + case json.Number: + v, _ := exp.Float64() return verifyExp(&newNumericDateFromSeconds(v).Time, cmpTime, req) + } return false + } // VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). + // If req is false, it will return true, if iat is unset. + func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool { + cmpTime := time.Unix(cmp, 0) v, ok := m["iat"] + if !ok { + return !req + } switch iat := v.(type) { + case float64: + if iat == 0 { + return verifyIat(nil, cmpTime, req) + } return verifyIat(&newNumericDateFromSeconds(iat).Time, cmpTime, req) + case json.Number: + v, _ := iat.Float64() return verifyIat(&newNumericDateFromSeconds(v).Time, cmpTime, req) + } return false + } // VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). + // If req is false, it will return true, if nbf is unset. + func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool { + cmpTime := time.Unix(cmp, 0) v, ok := m["nbf"] + if !ok { + return !req + } switch nbf := v.(type) { + case float64: + if nbf == 0 { + return verifyNbf(nil, cmpTime, req) + } return verifyNbf(&newNumericDateFromSeconds(nbf).Time, cmpTime, req) + case json.Number: + v, _ := nbf.Float64() return verifyNbf(&newNumericDateFromSeconds(v).Time, cmpTime, req) + } return false + } // VerifyIssuer compares the iss claim against cmp. + // If required is false, this method will return true if the value matches or is unset + func (m MapClaims) VerifyIssuer(cmp string, req bool) bool { + iss, _ := m["iss"].(string) + return verifyIss(iss, cmp, req) + } // Valid validates time based claims "exp, iat, nbf". + // There is no accounting for clock skew. + // As well, if any of the above claims are not in the token, it will still + // be considered a valid claim. + func (m MapClaims) Valid() error { + vErr := new(ValidationError) + now := TimeFunc().Unix() if !m.VerifyExpiresAt(now, false) { + // TODO(oxisto): this should be replaced with ErrTokenExpired + vErr.Inner = errors.New("Token is expired") + vErr.Errors |= ValidationErrorExpired + } if !m.VerifyIssuedAt(now, false) { + // TODO(oxisto): this should be replaced with ErrTokenUsedBeforeIssued + vErr.Inner = errors.New("Token used before issued") + vErr.Errors |= ValidationErrorIssuedAt + } if !m.VerifyNotBefore(now, false) { + // TODO(oxisto): this should be replaced with ErrTokenNotValidYet + vErr.Inner = errors.New("Token is not valid yet") + vErr.Errors |= ValidationErrorNotValidYet + } if vErr.valid() { + return nil + } return vErr + } diff --git a/vendor/github.com/golang-jwt/jwt/v4/parser.go b/vendor/github.com/golang-jwt/jwt/v4/parser.go index c0a6f69..dffbefc 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/parser.go +++ b/vendor/github.com/golang-jwt/jwt/v4/parser.go @@ -8,170 +8,292 @@ import ( ) type Parser struct { + // If populated, only these methods will be considered valid. + // + // Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead. + ValidMethods []string // Use JSON Number format in JSON decoder. + // + // Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead. + UseJSONNumber bool // Skip claims validation during token parsing. + // + // Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead. + SkipClaimsValidation bool } // NewParser creates a new Parser with the specified options + func NewParser(options ...ParserOption) *Parser { + p := &Parser{} // loop through our parsing options and apply them + for _, option := range options { + option(p) + } return p + } // Parse parses, validates, verifies the signature and returns the parsed token. + // keyFunc will receive the parsed token and should return the key for validating. + func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { + return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) + } // ParseWithClaims parses, validates, and verifies like Parse, but supplies a default object implementing the Claims + // interface. This provides default values which can be overridden and allows a caller to use their own type, rather + // than the default MapClaims implementation of Claims. + // + // Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims), + // make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the + // proper memory for it before passing in the overall claims, otherwise you might run into a panic. + func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { + token, parts, err := p.ParseUnverified(tokenString, claims) + if err != nil { + return token, err + } // Verify signing method is in the required set + if p.ValidMethods != nil { + var signingMethodValid = false + var alg = token.Method.Alg() + for _, m := range p.ValidMethods { + if m == alg { + signingMethodValid = true + break + } + } + if !signingMethodValid { + // signing method is not in the listed set + return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid) + } + } // Lookup key + var key interface{} + if keyFunc == nil { + // keyFunc was not provided. short circuiting validation + return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable) + } + if key, err = keyFunc(token); err != nil { + // keyFunc returned an error + if ve, ok := err.(*ValidationError); ok { + return token, ve + } + return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable} + } vErr := &ValidationError{} // Validate Claims + if !p.SkipClaimsValidation { + if err := token.Claims.Valid(); err != nil { // If the Claims Valid returned an error, check if it is a validation error, + // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set + if e, ok := err.(*ValidationError); !ok { + vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid} + } else { + vErr = e + } + } + } // Perform validation + token.Signature = parts[2] + if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { + vErr.Inner = err + vErr.Errors |= ValidationErrorSignatureInvalid + } if vErr.valid() { + token.Valid = true + return token, nil + } return token, vErr + } // ParseUnverified parses the token but doesn't validate the signature. + // + // WARNING: Don't use this method unless you know what you're doing. + // + // It's only ever useful in cases where you know the signature is valid (because it has + // been checked previously in the stack) and you want to extract values from it. + func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { + parts = strings.Split(tokenString, ".") + if len(parts) != 3 { + return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) + } token = &Token{Raw: tokenString} // parse Header + var headerBytes []byte + if headerBytes, err = DecodeSegment(parts[0]); err != nil { + if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { + return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) + } + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + if err = json.Unmarshal(headerBytes, &token.Header); err != nil { + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } // parse Claims + var claimBytes []byte + token.Claims = claims if claimBytes, err = DecodeSegment(parts[1]); err != nil { + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) + if p.UseJSONNumber { + dec.UseNumber() + } + // JSON Decode. Special case for map type to avoid weird pointer behavior + if c, ok := token.Claims.(MapClaims); ok { + err = dec.Decode(&c) + } else { + err = dec.Decode(&claims) + } + // Handle decode error + if err != nil { + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } // Lookup signature method + if method, ok := token.Header["alg"].(string); ok { + if token.Method = GetSigningMethod(method); token.Method == nil { + return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) + } + } else { + return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) + } return token, parts, nil + } diff --git a/vendor/github.com/golang-jwt/jwt/v4/rsa.go b/vendor/github.com/golang-jwt/jwt/v4/rsa.go index b910b19..e062427 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/rsa.go +++ b/vendor/github.com/golang-jwt/jwt/v4/rsa.go @@ -7,95 +7,151 @@ import ( ) // SigningMethodRSA implements the RSA family of signing methods. + // Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation + type SigningMethodRSA struct { Name string + Hash crypto.Hash } // Specific instances for RS256 and company + var ( SigningMethodRS256 *SigningMethodRSA + SigningMethodRS384 *SigningMethodRSA + SigningMethodRS512 *SigningMethodRSA ) func init() { + // RS256 + SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256} + RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod { + return SigningMethodRS256 + }) // RS384 + SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384} + RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod { + return SigningMethodRS384 + }) // RS512 + SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512} + RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod { + return SigningMethodRS512 + }) + } func (m *SigningMethodRSA) Alg() string { + return m.Name + } // Verify implements token verification for the SigningMethod + // For this signing method, must be an *rsa.PublicKey structure. + func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error { + var err error // Decode the signature + var sig []byte + if sig, err = DecodeSegment(signature); err != nil { + return err + } var rsaKey *rsa.PublicKey + var ok bool if rsaKey, ok = key.(*rsa.PublicKey); !ok { + return ErrInvalidKeyType + } // Create hasher + if !m.Hash.Available() { + return ErrHashUnavailable + } + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) // Verify the signature + return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig) + } // Sign implements token signing for the SigningMethod + // For this signing method, must be an *rsa.PrivateKey structure. + func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) { + var rsaKey *rsa.PrivateKey + var ok bool // Validate type of key + if rsaKey, ok = key.(*rsa.PrivateKey); !ok { + return "", ErrInvalidKey + } // Create the hasher + if !m.Hash.Available() { + return "", ErrHashUnavailable + } hasher := m.Hash.New() + hasher.Write([]byte(signingString)) // Sign the string and return the encoded bytes + if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil { + return EncodeSegment(sigBytes), nil + } else { + return "", err + } + } diff --git a/vendor/github.com/golang-jwt/jwt/v4/rsa_pss.go b/vendor/github.com/golang-jwt/jwt/v4/rsa_pss.go index 4fd6f9e..a7a5c79 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/rsa_pss.go +++ b/vendor/github.com/golang-jwt/jwt/v4/rsa_pss.go @@ -10,134 +10,219 @@ import ( ) // SigningMethodRSAPSS implements the RSAPSS family of signing methods signing methods + type SigningMethodRSAPSS struct { *SigningMethodRSA + Options *rsa.PSSOptions + // VerifyOptions is optional. If set overrides Options for rsa.VerifyPPS. + // Used to accept tokens signed with rsa.PSSSaltLengthAuto, what doesn't follow + // https://tools.ietf.org/html/rfc7518#section-3.5 but was used previously. + // See https://github.com/dgrijalva/jwt-go/issues/285#issuecomment-437451244 for details. + VerifyOptions *rsa.PSSOptions } // Specific instances for RS/PS and company. + var ( SigningMethodPS256 *SigningMethodRSAPSS + SigningMethodPS384 *SigningMethodRSAPSS + SigningMethodPS512 *SigningMethodRSAPSS ) func init() { + // PS256 + SigningMethodPS256 = &SigningMethodRSAPSS{ + SigningMethodRSA: &SigningMethodRSA{ + Name: "PS256", + Hash: crypto.SHA256, }, + Options: &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthEqualsHash, }, + VerifyOptions: &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, }, } + RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod { + return SigningMethodPS256 + }) // PS384 + SigningMethodPS384 = &SigningMethodRSAPSS{ + SigningMethodRSA: &SigningMethodRSA{ + Name: "PS384", + Hash: crypto.SHA384, }, + Options: &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthEqualsHash, }, + VerifyOptions: &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, }, } + RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod { + return SigningMethodPS384 + }) // PS512 + SigningMethodPS512 = &SigningMethodRSAPSS{ + SigningMethodRSA: &SigningMethodRSA{ + Name: "PS512", + Hash: crypto.SHA512, }, + Options: &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthEqualsHash, }, + VerifyOptions: &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, }, } + RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod { + return SigningMethodPS512 + }) + } // Verify implements token verification for the SigningMethod. + // For this verify method, key must be an rsa.PublicKey struct + func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error { + var err error // Decode the signature + var sig []byte + if sig, err = DecodeSegment(signature); err != nil { + return err + } var rsaKey *rsa.PublicKey + switch k := key.(type) { + case *rsa.PublicKey: + rsaKey = k + default: + return ErrInvalidKey + } // Create hasher + if !m.Hash.Available() { + return ErrHashUnavailable + } + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) opts := m.Options + if m.VerifyOptions != nil { + opts = m.VerifyOptions + } return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, opts) + } // Sign implements token signing for the SigningMethod. + // For this signing method, key must be an rsa.PrivateKey struct + func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) { + var rsaKey *rsa.PrivateKey switch k := key.(type) { + case *rsa.PrivateKey: + rsaKey = k + default: + return "", ErrInvalidKeyType + } // Create the hasher + if !m.Hash.Available() { + return "", ErrHashUnavailable + } hasher := m.Hash.New() + hasher.Write([]byte(signingString)) // Sign the string and return the encoded bytes + if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil { + return EncodeSegment(sigBytes), nil + } else { + return "", err + } + } diff --git a/vendor/github.com/golang-jwt/jwt/v4/rsa_utils.go b/vendor/github.com/golang-jwt/jwt/v4/rsa_utils.go index 1966c45..d574e76 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/rsa_utils.go +++ b/vendor/github.com/golang-jwt/jwt/v4/rsa_utils.go @@ -9,97 +9,156 @@ import ( var ( ErrKeyMustBePEMEncoded = errors.New("invalid key: Key must be a PEM encoded PKCS1 or PKCS8 key") - ErrNotRSAPrivateKey = errors.New("key is not a valid RSA private key") - ErrNotRSAPublicKey = errors.New("key is not a valid RSA public key") + + ErrNotRSAPrivateKey = errors.New("key is not a valid RSA private key") + + ErrNotRSAPublicKey = errors.New("key is not a valid RSA public key") ) // ParseRSAPrivateKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 private key + func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } var parsedKey interface{} + if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { + if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { + return nil, err + } + } var pkey *rsa.PrivateKey + var ok bool + if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { + return nil, ErrNotRSAPrivateKey + } return pkey, nil + } // ParseRSAPrivateKeyFromPEMWithPassword parses a PEM encoded PKCS1 or PKCS8 private key protected with password + // + // Deprecated: This function is deprecated and should not be used anymore. It uses the deprecated x509.DecryptPEMBlock + // function, which was deprecated since RFC 1423 is regarded insecure by design. Unfortunately, there is no alternative + // in the Go standard library for now. See https://github.com/golang/go/issues/8860. + func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } var parsedKey interface{} var blockDecrypted []byte + if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil { + return nil, err + } if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil { + if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil { + return nil, err + } + } var pkey *rsa.PrivateKey + var ok bool + if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { + return nil, ErrNotRSAPrivateKey + } return pkey, nil + } // ParseRSAPublicKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 public key + func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { + if cert, err := x509.ParseCertificate(block.Bytes); err == nil { + parsedKey = cert.PublicKey + } else { + return nil, err + } + } var pkey *rsa.PublicKey + var ok bool + if pkey, ok = parsedKey.(*rsa.PublicKey); !ok { + return nil, ErrNotRSAPublicKey + } return pkey, nil + } diff --git a/vendor/github.com/golang-jwt/jwt/v4/token.go b/vendor/github.com/golang-jwt/jwt/v4/token.go index 786b275..d9e82b1 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/token.go +++ b/vendor/github.com/golang-jwt/jwt/v4/token.go @@ -8,136 +8,232 @@ import ( ) // DecodePaddingAllowed will switch the codec used for decoding JWTs respectively. Note that the JWS RFC7515 + // states that the tokens will utilize a Base64url encoding with no padding. Unfortunately, some implementations + // of JWT are producing non-standard tokens, and thus require support for decoding. Note that this is a global + // variable, and updating it will change the behavior on a package level, and is also NOT go-routine safe. + // To use the non-recommended decoding, set this boolean to `true` prior to using this package. + var DecodePaddingAllowed bool // DecodeStrict will switch the codec used for decoding JWTs into strict mode. + // In this mode, the decoder requires that trailing padding bits are zero, as described in RFC 4648 section 3.5. + // Note that this is a global variable, and updating it will change the behavior on a package level, and is also NOT go-routine safe. + // To use strict decoding, set this boolean to `true` prior to using this package. + var DecodeStrict bool // TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). + // You can override it to use another time value. This is useful for testing or if your + // server uses a different time zone than your tokens. + var TimeFunc = time.Now // Keyfunc will be used by the Parse methods as a callback function to supply + // the key for verification. The function receives the parsed, + // but unverified Token. This allows you to use properties in the + // Header of the token (such as `kid`) to identify which key to use. + type Keyfunc func(*Token) (interface{}, error) // Token represents a JWT Token. Different fields will be used depending on whether you're + // creating or parsing/verifying a token. + type Token struct { - Raw string // The raw token. Populated when you Parse a token - Method SigningMethod // The signing method used or to be used - Header map[string]interface{} // The first segment of the token - Claims Claims // The second segment of the token - Signature string // The third segment of the token. Populated when you Parse a token - Valid bool // Is the token valid? Populated when you Parse/Verify a token + Raw string // The raw token. Populated when you Parse a token + + Method SigningMethod // The signing method used or to be used + + Header map[string]interface{} // The first segment of the token + + Claims Claims // The second segment of the token + + Signature string // The third segment of the token. Populated when you Parse a token + + Valid bool // Is the token valid? Populated when you Parse/Verify a token + } // New creates a new Token with the specified signing method and an empty map of claims. + func New(method SigningMethod) *Token { + return NewWithClaims(method, MapClaims{}) + } // NewWithClaims creates a new Token with the specified signing method and claims. + func NewWithClaims(method SigningMethod, claims Claims) *Token { + return &Token{ + Header: map[string]interface{}{ + "typ": "JWT", + "alg": method.Alg(), }, + Claims: claims, + Method: method, } + } // SignedString creates and returns a complete, signed JWT. + // The token is signed using the SigningMethod specified in the token. + func (t *Token) SignedString(key interface{}) (string, error) { + var sig, sstr string + var err error + if sstr, err = t.SigningString(); err != nil { + return "", err + } + if sig, err = t.Method.Sign(sstr, key); err != nil { + return "", err + } + return strings.Join([]string{sstr, sig}, "."), nil + } // SigningString generates the signing string. This is the + // most expensive part of the whole deal. Unless you + // need this for something special, just go straight for + // the SignedString. + func (t *Token) SigningString() (string, error) { + var err error + var jsonValue []byte if jsonValue, err = json.Marshal(t.Header); err != nil { + return "", err + } + header := EncodeSegment(jsonValue) if jsonValue, err = json.Marshal(t.Claims); err != nil { + return "", err + } + claim := EncodeSegment(jsonValue) return strings.Join([]string{header, claim}, "."), nil + } // Parse parses, validates, verifies the signature and returns the parsed token. + // keyFunc will receive the parsed token and should return the cryptographic key + // for verifying the signature. + // The caller is strongly encouraged to set the WithValidMethods option to + // validate the 'alg' claim in the token matches the expected algorithm. + // For more details about the importance of validating the 'alg' claim, + // see https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/ + func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { + return NewParser(options...).Parse(tokenString, keyFunc) + } // ParseWithClaims is a shortcut for NewParser().ParseWithClaims(). + // + // Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims), + // make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the + // proper memory for it before passing in the overall claims, otherwise you might run into a panic. + func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { + return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc) + } // EncodeSegment encodes a JWT specific base64url encoding with padding stripped + // + // Deprecated: In a future release, we will demote this function to a non-exported function, since it + // should only be used internally + func EncodeSegment(seg []byte) string { + return base64.RawURLEncoding.EncodeToString(seg) + } // DecodeSegment decodes a JWT specific base64url encoding with padding stripped + // + // Deprecated: In a future release, we will demote this function to a non-exported function, since it + // should only be used internally + func DecodeSegment(seg string) ([]byte, error) { + encoding := base64.RawURLEncoding if DecodePaddingAllowed { + if l := len(seg) % 4; l > 0 { + seg += strings.Repeat("=", 4-l) + } + encoding = base64.URLEncoding + } if DecodeStrict { + encoding = encoding.Strict() + } + return encoding.DecodeString(seg) + } diff --git a/vendor/github.com/golang-jwt/jwt/v4/types.go b/vendor/github.com/golang-jwt/jwt/v4/types.go index ac8e140..30bdd5d 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/types.go +++ b/vendor/github.com/golang-jwt/jwt/v4/types.go @@ -10,136 +10,221 @@ import ( ) // TimePrecision sets the precision of times and dates within this library. + // This has an influence on the precision of times when comparing expiry or + // other related time fields. Furthermore, it is also the precision of times + // when serializing. + // + // For backwards compatibility the default precision is set to seconds, so that + // no fractional timestamps are generated. + var TimePrecision = time.Second // MarshalSingleStringAsArray modifies the behaviour of the ClaimStrings type, especially + // its MarshalJSON function. + // + // If it is set to true (the default), it will always serialize the type as an + // array of strings, even if it just contains one element, defaulting to the behaviour + // of the underlying []string. If it is set to false, it will serialize to a single + // string, if it contains one element. Otherwise, it will serialize to an array of strings. + var MarshalSingleStringAsArray = true // NumericDate represents a JSON numeric date value, as referenced at + // https://datatracker.ietf.org/doc/html/rfc7519#section-2. + type NumericDate struct { time.Time } // NewNumericDate constructs a new *NumericDate from a standard library time.Time struct. + // It will truncate the timestamp according to the precision specified in TimePrecision. + func NewNumericDate(t time.Time) *NumericDate { + return &NumericDate{t.Truncate(TimePrecision)} + } // newNumericDateFromSeconds creates a new *NumericDate out of a float64 representing a + // UNIX epoch with the float fraction representing non-integer seconds. + func newNumericDateFromSeconds(f float64) *NumericDate { + round, frac := math.Modf(f) + return NewNumericDate(time.Unix(int64(round), int64(frac*1e9))) + } // MarshalJSON is an implementation of the json.RawMessage interface and serializes the UNIX epoch + // represented in NumericDate to a byte array, using the precision specified in TimePrecision. + func (date NumericDate) MarshalJSON() (b []byte, err error) { + var prec int + if TimePrecision < time.Second { + prec = int(math.Log10(float64(time.Second) / float64(TimePrecision))) + } + truncatedDate := date.Truncate(TimePrecision) // For very large timestamps, UnixNano would overflow an int64, but this + // function requires nanosecond level precision, so we have to use the + // following technique to get round the issue: + // 1. Take the normal unix timestamp to form the whole number part of the + // output, + // 2. Take the result of the Nanosecond function, which retuns the offset + // within the second of the particular unix time instance, to form the + // decimal part of the output + // 3. Concatenate them to produce the final result + seconds := strconv.FormatInt(truncatedDate.Unix(), 10) + nanosecondsOffset := strconv.FormatFloat(float64(truncatedDate.Nanosecond())/float64(time.Second), 'f', prec, 64) output := append([]byte(seconds), []byte(nanosecondsOffset)[1:]...) return output, nil + } // UnmarshalJSON is an implementation of the json.RawMessage interface and deserializses a + // NumericDate from a JSON representation, i.e. a json.Number. This number represents an UNIX epoch + // with either integer or non-integer seconds. + func (date *NumericDate) UnmarshalJSON(b []byte) (err error) { + var ( number json.Number - f float64 + + f float64 ) if err = json.Unmarshal(b, &number); err != nil { + return fmt.Errorf("could not parse NumericData: %w", err) + } if f, err = number.Float64(); err != nil { + return fmt.Errorf("could not convert json number value to float: %w", err) + } n := newNumericDateFromSeconds(f) + *date = *n return nil + } // ClaimStrings is basically just a slice of strings, but it can be either serialized from a string array or just a string. + // This type is necessary, since the "aud" claim can either be a single string or an array. + type ClaimStrings []string func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error) { + var value interface{} if err = json.Unmarshal(data, &value); err != nil { + return err + } var aud []string switch v := value.(type) { + case string: + aud = append(aud, v) + case []string: + aud = ClaimStrings(v) + case []interface{}: + for _, vv := range v { + vs, ok := vv.(string) + if !ok { + return &json.UnsupportedTypeError{Type: reflect.TypeOf(vv)} + } + aud = append(aud, vs) + } + case nil: + return nil + default: + return &json.UnsupportedTypeError{Type: reflect.TypeOf(v)} + } *s = aud return + } func (s ClaimStrings) MarshalJSON() (b []byte, err error) { + // This handles a special case in the JWT RFC. If the string array, e.g. used by the "aud" field, + // only contains one element, it MAY be serialized as a single string. This may or may not be + // desired based on the ecosystem of other JWT library used, so we make it configurable by the + // variable MarshalSingleStringAsArray. + if len(s) == 1 && !MarshalSingleStringAsArray { + return json.Marshal(s[0]) + } return json.Marshal([]string(s)) + } diff --git a/vendor/github.com/golang-jwt/jwt/v5/ecdsa.go b/vendor/github.com/golang-jwt/jwt/v5/ecdsa.go index 4ccae2a..9e60f3e 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/ecdsa.go +++ b/vendor/github.com/golang-jwt/jwt/v5/ecdsa.go @@ -9,126 +9,204 @@ import ( ) var ( + // Sadly this is missing from crypto/ecdsa compared to crypto/rsa + ErrECDSAVerification = errors.New("crypto/ecdsa: verification error") ) // SigningMethodECDSA implements the ECDSA family of signing methods. + // Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification + type SigningMethodECDSA struct { - Name string - Hash crypto.Hash - KeySize int + Name string + + Hash crypto.Hash + + KeySize int + CurveBits int } // Specific instances for EC256 and company + var ( SigningMethodES256 *SigningMethodECDSA + SigningMethodES384 *SigningMethodECDSA + SigningMethodES512 *SigningMethodECDSA ) func init() { + // ES256 + SigningMethodES256 = &SigningMethodECDSA{"ES256", crypto.SHA256, 32, 256} + RegisterSigningMethod(SigningMethodES256.Alg(), func() SigningMethod { + return SigningMethodES256 + }) // ES384 + SigningMethodES384 = &SigningMethodECDSA{"ES384", crypto.SHA384, 48, 384} + RegisterSigningMethod(SigningMethodES384.Alg(), func() SigningMethod { + return SigningMethodES384 + }) // ES512 + SigningMethodES512 = &SigningMethodECDSA{"ES512", crypto.SHA512, 66, 521} + RegisterSigningMethod(SigningMethodES512.Alg(), func() SigningMethod { + return SigningMethodES512 + }) + } func (m *SigningMethodECDSA) Alg() string { + return m.Name + } // Verify implements token verification for the SigningMethod. + // For this verify method, key must be an ecdsa.PublicKey struct + func (m *SigningMethodECDSA) Verify(signingString string, sig []byte, key interface{}) error { + // Get the key + var ecdsaKey *ecdsa.PublicKey + switch k := key.(type) { + case *ecdsa.PublicKey: + ecdsaKey = k + default: + return ErrInvalidKeyType + } if len(sig) != 2*m.KeySize { + return ErrECDSAVerification + } r := big.NewInt(0).SetBytes(sig[:m.KeySize]) + s := big.NewInt(0).SetBytes(sig[m.KeySize:]) // Create hasher + if !m.Hash.Available() { + return ErrHashUnavailable + } + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) // Verify the signature + if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus { + return nil + } return ErrECDSAVerification + } // Sign implements token signing for the SigningMethod. + // For this signing method, key must be an ecdsa.PrivateKey struct + func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) ([]byte, error) { + // Get the key + var ecdsaKey *ecdsa.PrivateKey + switch k := key.(type) { + case *ecdsa.PrivateKey: + ecdsaKey = k + default: + return nil, ErrInvalidKeyType + } // Create the hasher + if !m.Hash.Available() { + return nil, ErrHashUnavailable + } hasher := m.Hash.New() + hasher.Write([]byte(signingString)) // Sign the string and return r, s + if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil { + curveBits := ecdsaKey.Curve.Params().BitSize if m.CurveBits != curveBits { + return nil, ErrInvalidKey + } keyBytes := curveBits / 8 + if curveBits%8 > 0 { + keyBytes += 1 + } // We serialize the outputs (r and s) into big-endian byte arrays + // padded with zeros on the left to make sure the sizes work out. + // Output must be 2*keyBytes long. + out := make([]byte, 2*keyBytes) + r.FillBytes(out[0:keyBytes]) // r is assigned to the first half of output. - s.FillBytes(out[keyBytes:]) // s is assigned to the second half of output. + + s.FillBytes(out[keyBytes:]) // s is assigned to the second half of output. return out, nil + } else { + return nil, err + } + } diff --git a/vendor/github.com/golang-jwt/jwt/v5/ecdsa_utils.go b/vendor/github.com/golang-jwt/jwt/v5/ecdsa_utils.go index 5700636..7254d66 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/ecdsa_utils.go +++ b/vendor/github.com/golang-jwt/jwt/v5/ecdsa_utils.go @@ -8,62 +8,99 @@ import ( ) var ( - ErrNotECPublicKey = errors.New("key is not a valid ECDSA public key") + ErrNotECPublicKey = errors.New("key is not a valid ECDSA public key") + ErrNotECPrivateKey = errors.New("key is not a valid ECDSA private key") ) // ParseECPrivateKeyFromPEM parses a PEM encoded Elliptic Curve Private Key Structure + func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil { + if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { + return nil, err + } + } var pkey *ecdsa.PrivateKey + var ok bool + if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok { + return nil, ErrNotECPrivateKey + } return pkey, nil + } // ParseECPublicKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 public key + func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { + if cert, err := x509.ParseCertificate(block.Bytes); err == nil { + parsedKey = cert.PublicKey + } else { + return nil, err + } + } var pkey *ecdsa.PublicKey + var ok bool + if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok { + return nil, ErrNotECPublicKey + } return pkey, nil + } diff --git a/vendor/github.com/golang-jwt/jwt/v5/ed25519.go b/vendor/github.com/golang-jwt/jwt/v5/ed25519.go index eb6bdf0..943b68c 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/ed25519.go +++ b/vendor/github.com/golang-jwt/jwt/v5/ed25519.go @@ -12,68 +12,105 @@ var ( ) // SigningMethodEd25519 implements the EdDSA family. + // Expects ed25519.PrivateKey for signing and ed25519.PublicKey for verification + type SigningMethodEd25519 struct{} // Specific instance for EdDSA + var ( SigningMethodEdDSA *SigningMethodEd25519 ) func init() { + SigningMethodEdDSA = &SigningMethodEd25519{} + RegisterSigningMethod(SigningMethodEdDSA.Alg(), func() SigningMethod { + return SigningMethodEdDSA + }) + } func (m *SigningMethodEd25519) Alg() string { + return "EdDSA" + } // Verify implements token verification for the SigningMethod. + // For this verify method, key must be an ed25519.PublicKey + func (m *SigningMethodEd25519) Verify(signingString string, sig []byte, key interface{}) error { + var ed25519Key ed25519.PublicKey + var ok bool if ed25519Key, ok = key.(ed25519.PublicKey); !ok { + return ErrInvalidKeyType + } if len(ed25519Key) != ed25519.PublicKeySize { + return ErrInvalidKey + } // Verify the signature + if !ed25519.Verify(ed25519Key, []byte(signingString), sig) { + return ErrEd25519Verification + } return nil + } // Sign implements token signing for the SigningMethod. + // For this signing method, key must be an ed25519.PrivateKey + func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) ([]byte, error) { + var ed25519Key crypto.Signer + var ok bool if ed25519Key, ok = key.(crypto.Signer); !ok { + return nil, ErrInvalidKeyType + } if _, ok := ed25519Key.Public().(ed25519.PublicKey); !ok { + return nil, ErrInvalidKey + } // Sign the string and return the result. ed25519 performs a two-pass hash + // as part of its algorithm. Therefore, we need to pass a non-prehashed + // message into the Sign function, as indicated by crypto.Hash(0) + sig, err := ed25519Key.Sign(rand.Reader, []byte(signingString), crypto.Hash(0)) + if err != nil { + return nil, err + } return sig, nil + } diff --git a/vendor/github.com/golang-jwt/jwt/v5/ed25519_utils.go b/vendor/github.com/golang-jwt/jwt/v5/ed25519_utils.go index cdb5e68..58dcc40 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/ed25519_utils.go +++ b/vendor/github.com/golang-jwt/jwt/v5/ed25519_utils.go @@ -10,55 +10,86 @@ import ( var ( ErrNotEdPrivateKey = errors.New("key is not a valid Ed25519 private key") - ErrNotEdPublicKey = errors.New("key is not a valid Ed25519 public key") + + ErrNotEdPublicKey = errors.New("key is not a valid Ed25519 public key") ) // ParseEdPrivateKeyFromPEM parses a PEM-encoded Edwards curve private key + func ParseEdPrivateKeyFromPEM(key []byte) (crypto.PrivateKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { + return nil, err + } var pkey ed25519.PrivateKey + var ok bool + if pkey, ok = parsedKey.(ed25519.PrivateKey); !ok { + return nil, ErrNotEdPrivateKey + } return pkey, nil + } // ParseEdPublicKeyFromPEM parses a PEM-encoded Edwards curve public key + func ParseEdPublicKeyFromPEM(key []byte) (crypto.PublicKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { + return nil, err + } var pkey ed25519.PublicKey + var ok bool + if pkey, ok = parsedKey.(ed25519.PublicKey); !ok { + return nil, ErrNotEdPublicKey + } return pkey, nil + } diff --git a/vendor/github.com/golang-jwt/jwt/v5/errors.go b/vendor/github.com/golang-jwt/jwt/v5/errors.go index 23bb616..53363fa 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/errors.go +++ b/vendor/github.com/golang-jwt/jwt/v5/errors.go @@ -6,44 +6,72 @@ import ( ) var ( - ErrInvalidKey = errors.New("key is invalid") - ErrInvalidKeyType = errors.New("key is of invalid type") - ErrHashUnavailable = errors.New("the requested hash function is unavailable") - ErrTokenMalformed = errors.New("token is malformed") - ErrTokenUnverifiable = errors.New("token is unverifiable") - ErrTokenSignatureInvalid = errors.New("token signature is invalid") + ErrInvalidKey = errors.New("key is invalid") + + ErrInvalidKeyType = errors.New("key is of invalid type") + + ErrHashUnavailable = errors.New("the requested hash function is unavailable") + + ErrTokenMalformed = errors.New("token is malformed") + + ErrTokenUnverifiable = errors.New("token is unverifiable") + + ErrTokenSignatureInvalid = errors.New("token signature is invalid") + ErrTokenRequiredClaimMissing = errors.New("token is missing required claim") - ErrTokenInvalidAudience = errors.New("token has invalid audience") - ErrTokenExpired = errors.New("token is expired") - ErrTokenUsedBeforeIssued = errors.New("token used before issued") - ErrTokenInvalidIssuer = errors.New("token has invalid issuer") - ErrTokenInvalidSubject = errors.New("token has invalid subject") - ErrTokenNotValidYet = errors.New("token is not valid yet") - ErrTokenInvalidId = errors.New("token has invalid id") - ErrTokenInvalidClaims = errors.New("token has invalid claims") - ErrInvalidType = errors.New("invalid type for claim") + + ErrTokenInvalidAudience = errors.New("token has invalid audience") + + ErrTokenExpired = errors.New("token is expired") + + ErrTokenUsedBeforeIssued = errors.New("token used before issued") + + ErrTokenInvalidIssuer = errors.New("token has invalid issuer") + + ErrTokenInvalidSubject = errors.New("token has invalid subject") + + ErrTokenNotValidYet = errors.New("token is not valid yet") + + ErrTokenInvalidId = errors.New("token has invalid id") + + ErrTokenInvalidClaims = errors.New("token has invalid claims") + + ErrInvalidType = errors.New("invalid type for claim") ) // joinedError is an error type that works similar to what [errors.Join] + // produces, with the exception that it has a nice error string; mainly its + // error messages are concatenated using a comma, rather than a newline. + type joinedError struct { errs []error } func (je joinedError) Error() string { + msg := []string{} + for _, err := range je.errs { + msg = append(msg, err.Error()) + } return strings.Join(msg, ", ") + } // joinErrors joins together multiple errors. Useful for scenarios where + // multiple errors next to each other occur, e.g., in claims validation. + func joinErrors(errs ...error) error { + return &joinedError{ + errs: errs, } + } diff --git a/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go b/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go index 3afb04e..bdc84ba 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go +++ b/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go @@ -9,70 +9,122 @@ import ( ) // Is implements checking for multiple errors using [errors.Is], since multiple + // error unwrapping is not possible in versions less than Go 1.20. + func (je joinedError) Is(err error) bool { + for _, e := range je.errs { + if errors.Is(e, err) { + return true + } + } return false + } // wrappedErrors is a workaround for wrapping multiple errors in environments + // where Go 1.20 is not available. It basically uses the already implemented + // functionatlity of joinedError to handle multiple errors with supplies a + // custom error message that is identical to the one we produce in Go 1.20 using + // multiple %w directives. + type wrappedErrors struct { msg string + joinedError } // Error returns the stored error string + func (we wrappedErrors) Error() string { + return we.msg + } // newError creates a new error message with a detailed error message. The + // message will be prefixed with the contents of the supplied error type. + // Additionally, more errors, that provide more context can be supplied which + // will be appended to the message. Since we cannot use of Go 1.20's possibility + // to include more than one %w formatting directive in [fmt.Errorf], we have to + // emulate that. + // + // For example, + // + // newError("no keyfunc was provided", ErrTokenUnverifiable) + // + // will produce the error string + // + // "token is unverifiable: no keyfunc was provided" + func newError(message string, err error, more ...error) error { + // We cannot wrap multiple errors here with %w, so we have to be a little + // bit creative. Basically, we are using %s instead of %w to produce the + // same error message and then throw the result into a custom error struct. + var format string + var args []any + if message != "" { + format = "%s: %s" + args = []any{err, message} + } else { + format = "%s" + args = []any{err} + } + errs := []error{err} for _, e := range more { + format += ": %s" + args = append(args, e) + errs = append(errs, e) + } err = &wrappedErrors{ - msg: fmt.Sprintf(format, args...), + + msg: fmt.Sprintf(format, args...), + joinedError: joinedError{errs: errs}, } + return err + } diff --git a/vendor/github.com/golang-jwt/jwt/v5/hmac.go b/vendor/github.com/golang-jwt/jwt/v5/hmac.go index 91b688b..a2f8da6 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/hmac.go +++ b/vendor/github.com/golang-jwt/jwt/v5/hmac.go @@ -7,98 +7,163 @@ import ( ) // SigningMethodHMAC implements the HMAC-SHA family of signing methods. + // Expects key type of []byte for both signing and validation + type SigningMethodHMAC struct { Name string + Hash crypto.Hash } // Specific instances for HS256 and company + var ( - SigningMethodHS256 *SigningMethodHMAC - SigningMethodHS384 *SigningMethodHMAC - SigningMethodHS512 *SigningMethodHMAC + SigningMethodHS256 *SigningMethodHMAC + + SigningMethodHS384 *SigningMethodHMAC + + SigningMethodHS512 *SigningMethodHMAC + ErrSignatureInvalid = errors.New("signature is invalid") ) func init() { + // HS256 + SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256} + RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod { + return SigningMethodHS256 + }) // HS384 + SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384} + RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod { + return SigningMethodHS384 + }) // HS512 + SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512} + RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod { + return SigningMethodHS512 + }) + } func (m *SigningMethodHMAC) Alg() string { + return m.Name + } // Verify implements token verification for the SigningMethod. Returns nil if + // the signature is valid. Key must be []byte. + // + // Note it is not advised to provide a []byte which was converted from a 'human + // readable' string using a subset of ASCII characters. To maximize entropy, you + // should ideally be providing a []byte key which was produced from a + // cryptographically random source, e.g. crypto/rand. Additional information + // about this, and why we intentionally are not supporting string as a key can + // be found on our usage guide + // https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types. + func (m *SigningMethodHMAC) Verify(signingString string, sig []byte, key interface{}) error { + // Verify the key is the right type + keyBytes, ok := key.([]byte) + if !ok { + return ErrInvalidKeyType + } // Can we use the specified hashing method? + if !m.Hash.Available() { + return ErrHashUnavailable + } // This signing method is symmetric, so we validate the signature + // by reproducing the signature from the signing string and key, then + // comparing that against the provided signature. + hasher := hmac.New(m.Hash.New, keyBytes) + hasher.Write([]byte(signingString)) + if !hmac.Equal(sig, hasher.Sum(nil)) { + return ErrSignatureInvalid + } // No validation errors. Signature is good. + return nil + } // Sign implements token signing for the SigningMethod. Key must be []byte. + // + // Note it is not advised to provide a []byte which was converted from a 'human + // readable' string using a subset of ASCII characters. To maximize entropy, you + // should ideally be providing a []byte key which was produced from a + // cryptographically random source, e.g. crypto/rand. Additional information + // about this, and why we intentionally are not supporting string as a key can + // be found on our usage guide https://golang-jwt.github.io/jwt/usage/signing_methods/. + func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) ([]byte, error) { + if keyBytes, ok := key.([]byte); ok { + if !m.Hash.Available() { + return nil, ErrHashUnavailable + } hasher := hmac.New(m.Hash.New, keyBytes) + hasher.Write([]byte(signingString)) return hasher.Sum(nil), nil + } return nil, ErrInvalidKeyType + } diff --git a/vendor/github.com/golang-jwt/jwt/v5/map_claims.go b/vendor/github.com/golang-jwt/jwt/v5/map_claims.go index b2b51a1..8ec52e6 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/map_claims.go +++ b/vendor/github.com/golang-jwt/jwt/v5/map_claims.go @@ -6,104 +6,171 @@ import ( ) // MapClaims is a claims type that uses the map[string]interface{} for JSON + // decoding. This is the default claims type if you don't supply one + type MapClaims map[string]interface{} // GetExpirationTime implements the Claims interface. + func (m MapClaims) GetExpirationTime() (*NumericDate, error) { + return m.parseNumericDate("exp") + } // GetNotBefore implements the Claims interface. + func (m MapClaims) GetNotBefore() (*NumericDate, error) { + return m.parseNumericDate("nbf") + } // GetIssuedAt implements the Claims interface. + func (m MapClaims) GetIssuedAt() (*NumericDate, error) { + return m.parseNumericDate("iat") + } // GetAudience implements the Claims interface. + func (m MapClaims) GetAudience() (ClaimStrings, error) { + return m.parseClaimsString("aud") + } // GetIssuer implements the Claims interface. + func (m MapClaims) GetIssuer() (string, error) { + return m.parseString("iss") + } // GetSubject implements the Claims interface. + func (m MapClaims) GetSubject() (string, error) { + return m.parseString("sub") + } // parseNumericDate tries to parse a key in the map claims type as a number + // date. This will succeed, if the underlying type is either a [float64] or a + // [json.Number]. Otherwise, nil will be returned. + func (m MapClaims) parseNumericDate(key string) (*NumericDate, error) { + v, ok := m[key] + if !ok { + return nil, nil + } switch exp := v.(type) { + case float64: + if exp == 0 { + return nil, nil + } return newNumericDateFromSeconds(exp), nil + case json.Number: + v, _ := exp.Float64() return newNumericDateFromSeconds(v), nil + } return nil, newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) + } // parseClaimsString tries to parse a key in the map claims type as a + // [ClaimsStrings] type, which can either be a string or an array of string. + func (m MapClaims) parseClaimsString(key string) (ClaimStrings, error) { + var cs []string + switch v := m[key].(type) { + case string: + cs = append(cs, v) + case []string: + cs = v + case []interface{}: + for _, a := range v { + vs, ok := a.(string) + if !ok { + return nil, newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) + } + cs = append(cs, vs) + } + } return cs, nil + } // parseString tries to parse a key in the map claims type as a [string] type. + // If the key does not exist, an empty string is returned. If the key has the + // wrong type, an error is returned. + func (m MapClaims) parseString(key string) (string, error) { + var ( - ok bool + ok bool + raw interface{} + iss string ) + raw, ok = m[key] + if !ok { + return "", nil + } iss, ok = raw.(string) + if !ok { + return "", newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) + } return iss, nil + } diff --git a/vendor/github.com/golang-jwt/jwt/v5/parser.go b/vendor/github.com/golang-jwt/jwt/v5/parser.go index f4386fb..ccdf4d4 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/parser.go +++ b/vendor/github.com/golang-jwt/jwt/v5/parser.go @@ -9,13 +9,17 @@ import ( ) type Parser struct { + // If populated, only these methods will be considered valid. + validMethods []string // Use JSON Number format in JSON decoder. + useJSONNumber bool // Skip claims validation during token parsing. + skipClaimsValidation bool validator *validator @@ -26,190 +30,328 @@ type Parser struct { } // NewParser creates a new Parser with the specified options + func NewParser(options ...ParserOption) *Parser { + p := &Parser{ + validator: &validator{}, } // Loop through our parsing options and apply them + for _, option := range options { + option(p) + } return p + } // Parse parses, validates, verifies the signature and returns the parsed token. + // keyFunc will receive the parsed token and should return the key for validating. + func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { + return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) + } // ParseWithClaims parses, validates, and verifies like Parse, but supplies a default object implementing the Claims + // interface. This provides default values which can be overridden and allows a caller to use their own type, rather + // than the default MapClaims implementation of Claims. + // + // Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims), + // make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the + // proper memory for it before passing in the overall claims, otherwise you might run into a panic. + func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { + token, parts, err := p.ParseUnverified(tokenString, claims) + if err != nil { + return token, err + } // Verify signing method is in the required set + if p.validMethods != nil { + var signingMethodValid = false + var alg = token.Method.Alg() + for _, m := range p.validMethods { + if m == alg { + signingMethodValid = true + break + } + } + if !signingMethodValid { + // signing method is not in the listed set + return token, newError(fmt.Sprintf("signing method %v is invalid", alg), ErrTokenSignatureInvalid) + } + } // Lookup key + var key interface{} + if keyFunc == nil { + // keyFunc was not provided. short circuiting validation + return token, newError("no keyfunc was provided", ErrTokenUnverifiable) + } + if key, err = keyFunc(token); err != nil { + return token, newError("error while executing keyfunc", ErrTokenUnverifiable, err) + } // Decode signature + token.Signature, err = p.DecodeSegment(parts[2]) + if err != nil { + return token, newError("could not base64 decode signature", ErrTokenMalformed, err) + } // Perform signature validation + if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { + return token, newError("", ErrTokenSignatureInvalid, err) + } // Validate Claims + if !p.skipClaimsValidation { + // Make sure we have at least a default validator + if p.validator == nil { + p.validator = newValidator() + } if err := p.validator.Validate(claims); err != nil { + return token, newError("", ErrTokenInvalidClaims, err) + } + } // No errors so far, token is valid. + token.Valid = true return token, nil + } // ParseUnverified parses the token but doesn't validate the signature. + // + // WARNING: Don't use this method unless you know what you're doing. + // + // It's only ever useful in cases where you know the signature is valid (because it has + // been checked previously in the stack) and you want to extract values from it. + func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { + parts = strings.Split(tokenString, ".") + if len(parts) != 3 { + return nil, parts, newError("token contains an invalid number of segments", ErrTokenMalformed) + } token = &Token{Raw: tokenString} // parse Header + var headerBytes []byte + if headerBytes, err = p.DecodeSegment(parts[0]); err != nil { + if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { + return token, parts, newError("tokenstring should not contain 'bearer '", ErrTokenMalformed) + } + return token, parts, newError("could not base64 decode header", ErrTokenMalformed, err) + } + if err = json.Unmarshal(headerBytes, &token.Header); err != nil { + return token, parts, newError("could not JSON decode header", ErrTokenMalformed, err) + } // parse Claims + var claimBytes []byte + token.Claims = claims if claimBytes, err = p.DecodeSegment(parts[1]); err != nil { + return token, parts, newError("could not base64 decode claim", ErrTokenMalformed, err) + } + dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) + if p.useJSONNumber { + dec.UseNumber() + } + // JSON Decode. Special case for map type to avoid weird pointer behavior + if c, ok := token.Claims.(MapClaims); ok { + err = dec.Decode(&c) + } else { + err = dec.Decode(&claims) + } + // Handle decode error + if err != nil { + return token, parts, newError("could not JSON decode claim", ErrTokenMalformed, err) + } // Lookup signature method + if method, ok := token.Header["alg"].(string); ok { + if token.Method = GetSigningMethod(method); token.Method == nil { + return token, parts, newError("signing method (alg) is unavailable", ErrTokenUnverifiable) + } + } else { + return token, parts, newError("signing method (alg) is unspecified", ErrTokenUnverifiable) + } return token, parts, nil + } // DecodeSegment decodes a JWT specific base64url encoding. This function will + // take into account whether the [Parser] is configured with additional options, + // such as [WithStrictDecoding] or [WithPaddingAllowed]. + func (p *Parser) DecodeSegment(seg string) ([]byte, error) { + encoding := base64.RawURLEncoding if p.decodePaddingAllowed { + if l := len(seg) % 4; l > 0 { + seg += strings.Repeat("=", 4-l) + } + encoding = base64.URLEncoding + } if p.decodeStrict { + encoding = encoding.Strict() + } + return encoding.DecodeString(seg) + } // Parse parses, validates, verifies the signature and returns the parsed token. + // keyFunc will receive the parsed token and should return the cryptographic key + // for verifying the signature. The caller is strongly encouraged to set the + // WithValidMethods option to validate the 'alg' claim in the token matches the + // expected algorithm. For more details about the importance of validating the + // 'alg' claim, see + // https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/ + func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { + return NewParser(options...).Parse(tokenString, keyFunc) + } // ParseWithClaims is a shortcut for NewParser().ParseWithClaims(). + // + // Note: If you provide a custom claim implementation that embeds one of the + // standard claims (such as RegisteredClaims), make sure that a) you either + // embed a non-pointer version of the claims or b) if you are using a pointer, + // allocate the proper memory for it before passing in the overall claims, + // otherwise you might run into a panic. + func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { + return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc) + } diff --git a/vendor/github.com/golang-jwt/jwt/v5/rsa.go b/vendor/github.com/golang-jwt/jwt/v5/rsa.go index daff094..5037408 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/rsa.go +++ b/vendor/github.com/golang-jwt/jwt/v5/rsa.go @@ -7,87 +7,139 @@ import ( ) // SigningMethodRSA implements the RSA family of signing methods. + // Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation + type SigningMethodRSA struct { Name string + Hash crypto.Hash } // Specific instances for RS256 and company + var ( SigningMethodRS256 *SigningMethodRSA + SigningMethodRS384 *SigningMethodRSA + SigningMethodRS512 *SigningMethodRSA ) func init() { + // RS256 + SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256} + RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod { + return SigningMethodRS256 + }) // RS384 + SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384} + RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod { + return SigningMethodRS384 + }) // RS512 + SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512} + RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod { + return SigningMethodRS512 + }) + } func (m *SigningMethodRSA) Alg() string { + return m.Name + } // Verify implements token verification for the SigningMethod + // For this signing method, must be an *rsa.PublicKey structure. + func (m *SigningMethodRSA) Verify(signingString string, sig []byte, key interface{}) error { + var rsaKey *rsa.PublicKey + var ok bool if rsaKey, ok = key.(*rsa.PublicKey); !ok { + return ErrInvalidKeyType + } // Create hasher + if !m.Hash.Available() { + return ErrHashUnavailable + } + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) // Verify the signature + return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig) + } // Sign implements token signing for the SigningMethod + // For this signing method, must be an *rsa.PrivateKey structure. + func (m *SigningMethodRSA) Sign(signingString string, key interface{}) ([]byte, error) { + var rsaKey *rsa.PrivateKey + var ok bool // Validate type of key + if rsaKey, ok = key.(*rsa.PrivateKey); !ok { + return nil, ErrInvalidKey + } // Create the hasher + if !m.Hash.Available() { + return nil, ErrHashUnavailable + } hasher := m.Hash.New() + hasher.Write([]byte(signingString)) // Sign the string and return the encoded bytes + if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil { + return sigBytes, nil + } else { + return nil, err + } + } diff --git a/vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go b/vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go index 9599f0a..b4d1ccb 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go +++ b/vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go @@ -10,126 +10,207 @@ import ( ) // SigningMethodRSAPSS implements the RSAPSS family of signing methods signing methods + type SigningMethodRSAPSS struct { *SigningMethodRSA + Options *rsa.PSSOptions + // VerifyOptions is optional. If set overrides Options for rsa.VerifyPPS. + // Used to accept tokens signed with rsa.PSSSaltLengthAuto, what doesn't follow + // https://tools.ietf.org/html/rfc7518#section-3.5 but was used previously. + // See https://github.com/dgrijalva/jwt-go/issues/285#issuecomment-437451244 for details. + VerifyOptions *rsa.PSSOptions } // Specific instances for RS/PS and company. + var ( SigningMethodPS256 *SigningMethodRSAPSS + SigningMethodPS384 *SigningMethodRSAPSS + SigningMethodPS512 *SigningMethodRSAPSS ) func init() { + // PS256 + SigningMethodPS256 = &SigningMethodRSAPSS{ + SigningMethodRSA: &SigningMethodRSA{ + Name: "PS256", + Hash: crypto.SHA256, }, + Options: &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthEqualsHash, }, + VerifyOptions: &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, }, } + RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod { + return SigningMethodPS256 + }) // PS384 + SigningMethodPS384 = &SigningMethodRSAPSS{ + SigningMethodRSA: &SigningMethodRSA{ + Name: "PS384", + Hash: crypto.SHA384, }, + Options: &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthEqualsHash, }, + VerifyOptions: &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, }, } + RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod { + return SigningMethodPS384 + }) // PS512 + SigningMethodPS512 = &SigningMethodRSAPSS{ + SigningMethodRSA: &SigningMethodRSA{ + Name: "PS512", + Hash: crypto.SHA512, }, + Options: &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthEqualsHash, }, + VerifyOptions: &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, }, } + RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod { + return SigningMethodPS512 + }) + } // Verify implements token verification for the SigningMethod. + // For this verify method, key must be an rsa.PublicKey struct + func (m *SigningMethodRSAPSS) Verify(signingString string, sig []byte, key interface{}) error { + var rsaKey *rsa.PublicKey + switch k := key.(type) { + case *rsa.PublicKey: + rsaKey = k + default: + return ErrInvalidKey + } // Create hasher + if !m.Hash.Available() { + return ErrHashUnavailable + } + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) opts := m.Options + if m.VerifyOptions != nil { + opts = m.VerifyOptions + } return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, opts) + } // Sign implements token signing for the SigningMethod. + // For this signing method, key must be an rsa.PrivateKey struct + func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) ([]byte, error) { + var rsaKey *rsa.PrivateKey switch k := key.(type) { + case *rsa.PrivateKey: + rsaKey = k + default: + return nil, ErrInvalidKeyType + } // Create the hasher + if !m.Hash.Available() { + return nil, ErrHashUnavailable + } hasher := m.Hash.New() + hasher.Write([]byte(signingString)) // Sign the string and return the encoded bytes + if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil { + return sigBytes, nil + } else { + return nil, err + } + } diff --git a/vendor/github.com/golang-jwt/jwt/v5/rsa_utils.go b/vendor/github.com/golang-jwt/jwt/v5/rsa_utils.go index b3aeebb..e1359d9 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/rsa_utils.go +++ b/vendor/github.com/golang-jwt/jwt/v5/rsa_utils.go @@ -9,99 +9,160 @@ import ( var ( ErrKeyMustBePEMEncoded = errors.New("invalid key: Key must be a PEM encoded PKCS1 or PKCS8 key") - ErrNotRSAPrivateKey = errors.New("key is not a valid RSA private key") - ErrNotRSAPublicKey = errors.New("key is not a valid RSA public key") + + ErrNotRSAPrivateKey = errors.New("key is not a valid RSA private key") + + ErrNotRSAPublicKey = errors.New("key is not a valid RSA public key") ) // ParseRSAPrivateKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 private key + func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } var parsedKey interface{} + if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { + if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { + return nil, err + } + } var pkey *rsa.PrivateKey + var ok bool + if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { + return nil, ErrNotRSAPrivateKey + } return pkey, nil + } // ParseRSAPrivateKeyFromPEMWithPassword parses a PEM encoded PKCS1 or PKCS8 private key protected with password + // + // Deprecated: This function is deprecated and should not be used anymore. It uses the deprecated x509.DecryptPEMBlock + // function, which was deprecated since RFC 1423 is regarded insecure by design. Unfortunately, there is no alternative + // in the Go standard library for now. See https://github.com/golang/go/issues/8860. + func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } var parsedKey interface{} var blockDecrypted []byte + if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil { + return nil, err + } if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil { + if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil { + return nil, err + } + } var pkey *rsa.PrivateKey + var ok bool + if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { + return nil, ErrNotRSAPrivateKey + } return pkey, nil + } // ParseRSAPublicKeyFromPEM parses a certificate or a PEM encoded PKCS1 or PKIX public key + func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { + var err error // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { + if cert, err := x509.ParseCertificate(block.Bytes); err == nil { + parsedKey = cert.PublicKey + } else { + if parsedKey, err = x509.ParsePKCS1PublicKey(block.Bytes); err != nil { + return nil, err + } + } + } var pkey *rsa.PublicKey + var ok bool + if pkey, ok = parsedKey.(*rsa.PublicKey); !ok { + return nil, ErrNotRSAPublicKey + } return pkey, nil + } diff --git a/vendor/github.com/golang-jwt/jwt/v5/token.go b/vendor/github.com/golang-jwt/jwt/v5/token.go index c8ad7c7..84a40bf 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/token.go +++ b/vendor/github.com/golang-jwt/jwt/v5/token.go @@ -6,81 +6,136 @@ import ( ) // Keyfunc will be used by the Parse methods as a callback function to supply + // the key for verification. The function receives the parsed, but unverified + // Token. This allows you to use properties in the Header of the token (such as + // `kid`) to identify which key to use. + type Keyfunc func(*Token) (interface{}, error) // Token represents a JWT Token. Different fields will be used depending on + // whether you're creating or parsing/verifying a token. + type Token struct { - Raw string // Raw contains the raw token. Populated when you [Parse] a token - Method SigningMethod // Method is the signing method used or to be used - Header map[string]interface{} // Header is the first segment of the token in decoded form - Claims Claims // Claims is the second segment of the token in decoded form - Signature []byte // Signature is the third segment of the token in decoded form. Populated when you Parse a token - Valid bool // Valid specifies if the token is valid. Populated when you Parse/Verify a token + Raw string // Raw contains the raw token. Populated when you [Parse] a token + + Method SigningMethod // Method is the signing method used or to be used + + Header map[string]interface{} // Header is the first segment of the token in decoded form + + Claims Claims // Claims is the second segment of the token in decoded form + + Signature []byte // Signature is the third segment of the token in decoded form. Populated when you Parse a token + + Valid bool // Valid specifies if the token is valid. Populated when you Parse/Verify a token + } // New creates a new [Token] with the specified signing method and an empty map + // of claims. Additional options can be specified, but are currently unused. + func New(method SigningMethod, opts ...TokenOption) *Token { + return NewWithClaims(method, MapClaims{}, opts...) + } // NewWithClaims creates a new [Token] with the specified signing method and + // claims. Additional options can be specified, but are currently unused. + func NewWithClaims(method SigningMethod, claims Claims, opts ...TokenOption) *Token { + return &Token{ + Header: map[string]interface{}{ + "typ": "JWT", + "alg": method.Alg(), }, + Claims: claims, + Method: method, } + } // SignedString creates and returns a complete, signed JWT. The token is signed + // using the SigningMethod specified in the token. Please refer to + // https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types + // for an overview of the different signing methods and their respective key + // types. + func (t *Token) SignedString(key interface{}) (string, error) { + sstr, err := t.SigningString() + if err != nil { + return "", err + } sig, err := t.Method.Sign(sstr, key) + if err != nil { + return "", err + } return sstr + "." + t.EncodeSegment(sig), nil + } // SigningString generates the signing string. This is the most expensive part + // of the whole deal. Unless you need this for something special, just go + // straight for the SignedString. + func (t *Token) SigningString() (string, error) { + h, err := json.Marshal(t.Header) + if err != nil { + return "", err + } c, err := json.Marshal(t.Claims) + if err != nil { + return "", err + } return t.EncodeSegment(h) + "." + t.EncodeSegment(c), nil + } // EncodeSegment encodes a JWT specific base64url encoding with padding + // stripped. In the future, this function might take into account a + // [TokenOption]. Therefore, this function exists as a method of [Token], rather + // than a global function. + func (*Token) EncodeSegment(seg []byte) string { + return base64.RawURLEncoding.EncodeToString(seg) + } diff --git a/vendor/github.com/golang-jwt/jwt/v5/types.go b/vendor/github.com/golang-jwt/jwt/v5/types.go index b82b388..8e25807 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/types.go +++ b/vendor/github.com/golang-jwt/jwt/v5/types.go @@ -10,141 +10,231 @@ import ( ) // TimePrecision sets the precision of times and dates within this library. This + // has an influence on the precision of times when comparing expiry or other + // related time fields. Furthermore, it is also the precision of times when + // serializing. + // + // For backwards compatibility the default precision is set to seconds, so that + // no fractional timestamps are generated. + var TimePrecision = time.Second // MarshalSingleStringAsArray modifies the behavior of the ClaimStrings type, + // especially its MarshalJSON function. + // + // If it is set to true (the default), it will always serialize the type as an + // array of strings, even if it just contains one element, defaulting to the + // behavior of the underlying []string. If it is set to false, it will serialize + // to a single string, if it contains one element. Otherwise, it will serialize + // to an array of strings. + var MarshalSingleStringAsArray = true // NumericDate represents a JSON numeric date value, as referenced at + // https://datatracker.ietf.org/doc/html/rfc7519#section-2. + type NumericDate struct { time.Time } // NewNumericDate constructs a new *NumericDate from a standard library time.Time struct. + // It will truncate the timestamp according to the precision specified in TimePrecision. + func NewNumericDate(t time.Time) *NumericDate { + return &NumericDate{t.Truncate(TimePrecision)} + } // newNumericDateFromSeconds creates a new *NumericDate out of a float64 representing a + // UNIX epoch with the float fraction representing non-integer seconds. + func newNumericDateFromSeconds(f float64) *NumericDate { + round, frac := math.Modf(f) + return NewNumericDate(time.Unix(int64(round), int64(frac*1e9))) + } // MarshalJSON is an implementation of the json.RawMessage interface and serializes the UNIX epoch + // represented in NumericDate to a byte array, using the precision specified in TimePrecision. + func (date NumericDate) MarshalJSON() (b []byte, err error) { + var prec int + if TimePrecision < time.Second { + prec = int(math.Log10(float64(time.Second) / float64(TimePrecision))) + } + truncatedDate := date.Truncate(TimePrecision) // For very large timestamps, UnixNano would overflow an int64, but this + // function requires nanosecond level precision, so we have to use the + // following technique to get round the issue: + // + // 1. Take the normal unix timestamp to form the whole number part of the + // output, + // 2. Take the result of the Nanosecond function, which returns the offset + // within the second of the particular unix time instance, to form the + // decimal part of the output + // 3. Concatenate them to produce the final result + seconds := strconv.FormatInt(truncatedDate.Unix(), 10) + nanosecondsOffset := strconv.FormatFloat(float64(truncatedDate.Nanosecond())/float64(time.Second), 'f', prec, 64) output := append([]byte(seconds), []byte(nanosecondsOffset)[1:]...) return output, nil + } // UnmarshalJSON is an implementation of the json.RawMessage interface and + // deserializes a [NumericDate] from a JSON representation, i.e. a + // [json.Number]. This number represents an UNIX epoch with either integer or + // non-integer seconds. + func (date *NumericDate) UnmarshalJSON(b []byte) (err error) { + var ( number json.Number - f float64 + + f float64 ) if err = json.Unmarshal(b, &number); err != nil { + return fmt.Errorf("could not parse NumericData: %w", err) + } if f, err = number.Float64(); err != nil { + return fmt.Errorf("could not convert json number value to float: %w", err) + } n := newNumericDateFromSeconds(f) + *date = *n return nil + } // ClaimStrings is basically just a slice of strings, but it can be either + // serialized from a string array or just a string. This type is necessary, + // since the "aud" claim can either be a single string or an array. + type ClaimStrings []string func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error) { + var value interface{} if err = json.Unmarshal(data, &value); err != nil { + return err + } var aud []string switch v := value.(type) { + case string: + aud = append(aud, v) + case []string: + aud = ClaimStrings(v) + case []interface{}: + for _, vv := range v { + vs, ok := vv.(string) + if !ok { + return &json.UnsupportedTypeError{Type: reflect.TypeOf(vv)} + } + aud = append(aud, vs) + } + case nil: + return nil + default: + return &json.UnsupportedTypeError{Type: reflect.TypeOf(v)} + } *s = aud return + } func (s ClaimStrings) MarshalJSON() (b []byte, err error) { + // This handles a special case in the JWT RFC. If the string array, e.g. + // used by the "aud" field, only contains one element, it MAY be serialized + // as a single string. This may or may not be desired based on the ecosystem + // of other JWT library used, so we make it configurable by the variable + // MarshalSingleStringAsArray. + if len(s) == 1 && !MarshalSingleStringAsArray { + return json.Marshal(s[0]) + } return json.Marshal([]string(s)) + } diff --git a/vendor/github.com/golang-jwt/jwt/v5/validator.go b/vendor/github.com/golang-jwt/jwt/v5/validator.go index 3850438..029be87 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/validator.go +++ b/vendor/github.com/golang-jwt/jwt/v5/validator.go @@ -7,295 +7,500 @@ import ( ) // ClaimsValidator is an interface that can be implemented by custom claims who + // wish to execute any additional claims validation based on + // application-specific logic. The Validate function is then executed in + // addition to the regular claims validation and any error returned is appended + // to the final validation result. + // + // type MyCustomClaims struct { + // Foo string `json:"foo"` + // jwt.RegisteredClaims + // } + // + // func (m MyCustomClaims) Validate() error { + // if m.Foo != "bar" { + // return errors.New("must be foobar") + // } + // return nil + // } + type ClaimsValidator interface { Claims + Validate() error } // validator is the core of the new Validation API. It is automatically used by + // a [Parser] during parsing and can be modified with various parser options. + // + // Note: This struct is intentionally not exported (yet) as we want to + // internally finalize its API. In the future, we might make it publicly + // available. + type validator struct { + // leeway is an optional leeway that can be provided to account for clock skew. + leeway time.Duration // timeFunc is used to supply the current time that is needed for + // validation. If unspecified, this defaults to time.Now. + timeFunc func() time.Time // verifyIat specifies whether the iat (Issued At) claim will be verified. + // According to https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 this + // only specifies the age of the token, but no validation check is + // necessary. However, if wanted, it can be checked if the iat is + // unrealistic, i.e., in the future. + verifyIat bool // expectedAud contains the audience this token expects. Supplying an empty + // string will disable aud checking. + expectedAud string // expectedIss contains the issuer this token expects. Supplying an empty + // string will disable iss checking. + expectedIss string // expectedSub contains the subject this token expects. Supplying an empty + // string will disable sub checking. + expectedSub string } // newValidator can be used to create a stand-alone validator with the supplied + // options. This validator can then be used to validate already parsed claims. + func newValidator(opts ...ParserOption) *validator { + p := NewParser(opts...) + return p.validator + } // Validate validates the given claims. It will also perform any custom + // validation if claims implements the [ClaimsValidator] interface. + func (v *validator) Validate(claims Claims) error { + var ( - now time.Time + now time.Time + errs []error = make([]error, 0, 6) - err error + + err error ) // Check, if we have a time func + if v.timeFunc != nil { + now = v.timeFunc() + } else { + now = time.Now() + } // We always need to check the expiration time, but usage of the claim + // itself is OPTIONAL. + if err = v.verifyExpiresAt(claims, now, false); err != nil { + errs = append(errs, err) + } // We always need to check not-before, but usage of the claim itself is + // OPTIONAL. + if err = v.verifyNotBefore(claims, now, false); err != nil { + errs = append(errs, err) + } // Check issued-at if the option is enabled + if v.verifyIat { + if err = v.verifyIssuedAt(claims, now, false); err != nil { + errs = append(errs, err) + } + } // If we have an expected audience, we also require the audience claim + if v.expectedAud != "" { + if err = v.verifyAudience(claims, v.expectedAud, true); err != nil { + errs = append(errs, err) + } + } // If we have an expected issuer, we also require the issuer claim + if v.expectedIss != "" { + if err = v.verifyIssuer(claims, v.expectedIss, true); err != nil { + errs = append(errs, err) + } + } // If we have an expected subject, we also require the subject claim + if v.expectedSub != "" { + if err = v.verifySubject(claims, v.expectedSub, true); err != nil { + errs = append(errs, err) + } + } // Finally, we want to give the claim itself some possibility to do some + // additional custom validation based on a custom Validate function. + cvt, ok := claims.(ClaimsValidator) + if ok { + if err := cvt.Validate(); err != nil { + errs = append(errs, err) + } + } if len(errs) == 0 { + return nil + } return joinErrors(errs...) + } // verifyExpiresAt compares the exp claim in claims against cmp. This function + // will succeed if cmp < exp. Additional leeway is taken into account. + // + // If exp is not set, it will succeed if the claim is not required, + // otherwise ErrTokenRequiredClaimMissing will be returned. + // + // Additionally, if any error occurs while retrieving the claim, e.g., when its + // the wrong type, an ErrTokenUnverifiable error will be returned. + func (v *validator) verifyExpiresAt(claims Claims, cmp time.Time, required bool) error { + exp, err := claims.GetExpirationTime() + if err != nil { + return err + } if exp == nil { + return errorIfRequired(required, "exp") + } return errorIfFalse(cmp.Before((exp.Time).Add(+v.leeway)), ErrTokenExpired) + } // verifyIssuedAt compares the iat claim in claims against cmp. This function + // will succeed if cmp >= iat. Additional leeway is taken into account. + // + // If iat is not set, it will succeed if the claim is not required, + // otherwise ErrTokenRequiredClaimMissing will be returned. + // + // Additionally, if any error occurs while retrieving the claim, e.g., when its + // the wrong type, an ErrTokenUnverifiable error will be returned. + func (v *validator) verifyIssuedAt(claims Claims, cmp time.Time, required bool) error { + iat, err := claims.GetIssuedAt() + if err != nil { + return err + } if iat == nil { + return errorIfRequired(required, "iat") + } return errorIfFalse(!cmp.Before(iat.Add(-v.leeway)), ErrTokenUsedBeforeIssued) + } // verifyNotBefore compares the nbf claim in claims against cmp. This function + // will return true if cmp >= nbf. Additional leeway is taken into account. + // + // If nbf is not set, it will succeed if the claim is not required, + // otherwise ErrTokenRequiredClaimMissing will be returned. + // + // Additionally, if any error occurs while retrieving the claim, e.g., when its + // the wrong type, an ErrTokenUnverifiable error will be returned. + func (v *validator) verifyNotBefore(claims Claims, cmp time.Time, required bool) error { + nbf, err := claims.GetNotBefore() + if err != nil { + return err + } if nbf == nil { + return errorIfRequired(required, "nbf") + } return errorIfFalse(!cmp.Before(nbf.Add(-v.leeway)), ErrTokenNotValidYet) + } // verifyAudience compares the aud claim against cmp. + // + // If aud is not set or an empty list, it will succeed if the claim is not required, + // otherwise ErrTokenRequiredClaimMissing will be returned. + // + // Additionally, if any error occurs while retrieving the claim, e.g., when its + // the wrong type, an ErrTokenUnverifiable error will be returned. + func (v *validator) verifyAudience(claims Claims, cmp string, required bool) error { + aud, err := claims.GetAudience() + if err != nil { + return err + } if len(aud) == 0 { + return errorIfRequired(required, "aud") + } // use a var here to keep constant time compare when looping over a number of claims + result := false var stringClaims string + for _, a := range aud { + if subtle.ConstantTimeCompare([]byte(a), []byte(cmp)) != 0 { + result = true + } + stringClaims = stringClaims + a + } // case where "" is sent in one or many aud claims + if stringClaims == "" { + return errorIfRequired(required, "aud") + } return errorIfFalse(result, ErrTokenInvalidAudience) + } // verifyIssuer compares the iss claim in claims against cmp. + // + // If iss is not set, it will succeed if the claim is not required, + // otherwise ErrTokenRequiredClaimMissing will be returned. + // + // Additionally, if any error occurs while retrieving the claim, e.g., when its + // the wrong type, an ErrTokenUnverifiable error will be returned. + func (v *validator) verifyIssuer(claims Claims, cmp string, required bool) error { + iss, err := claims.GetIssuer() + if err != nil { + return err + } if iss == "" { + return errorIfRequired(required, "iss") + } return errorIfFalse(iss == cmp, ErrTokenInvalidIssuer) + } // verifySubject compares the sub claim against cmp. + // + // If sub is not set, it will succeed if the claim is not required, + // otherwise ErrTokenRequiredClaimMissing will be returned. + // + // Additionally, if any error occurs while retrieving the claim, e.g., when its + // the wrong type, an ErrTokenUnverifiable error will be returned. + func (v *validator) verifySubject(claims Claims, cmp string, required bool) error { + sub, err := claims.GetSubject() + if err != nil { + return err + } if sub == "" { + return errorIfRequired(required, "sub") + } return errorIfFalse(sub == cmp, ErrTokenInvalidSubject) + } // errorIfFalse returns the error specified in err, if the value is true. + // Otherwise, nil is returned. + func errorIfFalse(value bool, err error) error { + if value { + return nil + } else { + return err + } + } // errorIfRequired returns an ErrTokenRequiredClaimMissing error if required is + // true. Otherwise, nil is returned. + func errorIfRequired(required bool, claim string) error { + if required { + return newError(fmt.Sprintf("%s claim is required", claim), ErrTokenRequiredClaimMissing) + } else { + return nil + } + } diff --git a/vendor/github.com/kavenegar/kavenegar-go/client.go b/vendor/github.com/kavenegar/kavenegar-go/client.go index 6fe34e6..24a9f8c 100644 --- a/vendor/github.com/kavenegar/kavenegar-go/client.go +++ b/vendor/github.com/kavenegar/kavenegar-go/client.go @@ -11,13 +11,17 @@ import ( const ( apiBaseURL = "https://api.kavenegar.com/" + apiVersion = "v1" - apiFormat = "json" - version = "0.1.0" + + apiFormat = "json" + + version = "0.1.0" ) type Return struct { - Status int `json:"status"` + Status int `json:"status"` + Message string `json:"message"` } @@ -27,69 +31,123 @@ type ReturnError struct { type Client struct { BaseClient *http.Client - apikey string - BaseURL *url.URL + + apikey string + + BaseURL *url.URL } func NewClient(apikey string) *Client { + baseURL, _ := url.Parse(apiBaseURL) + c := &Client{ + BaseClient: http.DefaultClient, - BaseURL: baseURL, - apikey: apikey, + + BaseURL: baseURL, + + apikey: apikey, } + return c + } func (c *Client) EndPoint(parts ...string) *url.URL { + up := []string{apiVersion, c.apikey} + up = append(up, parts...) + u, _ := url.Parse(strings.Join(up, "/")) + u.Path = fmt.Sprintf("/%s.%s", u.Path, apiFormat) + return u + } func (c *Client) Execute(urlStr string, b url.Values, v interface{}) error { + body := strings.NewReader(b.Encode()) + ul, _ := url.Parse(urlStr) + u := c.BaseURL.ResolveReference(ul) + req, _ := http.NewRequest("POST", u.String(), body) + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") + req.Header.Add("Accept", "application/json") + req.Header.Add("Accept-Charset", "utf-8") + resp, err := c.BaseClient.Do(req) + if err != nil { + if err, ok := err.(net.Error); ok { + return err + } + if resp == nil { + return &HTTPError{ - Status: http.StatusInternalServerError, + + Status: http.StatusInternalServerError, + Message: "nil api response", - Err: err, + + Err: err, } + } + return &HTTPError{ - Status: resp.StatusCode, + + Status: resp.StatusCode, + Message: resp.Status, - Err: err, + + Err: err, } + } + defer resp.Body.Close() + if 200 != resp.StatusCode { + re := new(ReturnError) + err = json.NewDecoder(resp.Body).Decode(&re) + if err != nil { + return &HTTPError{ - Status: resp.StatusCode, + + Status: resp.StatusCode, + Message: resp.Status, } + } + return &APIError{ - Status: re.Return.Status, + + Status: re.Return.Status, + Message: re.Return.Message, } + } + _ = json.NewDecoder(resp.Body).Decode(&v) + return nil + } diff --git a/vendor/github.com/kavenegar/kavenegar-go/message_countInbox.go b/vendor/github.com/kavenegar/kavenegar-go/message_countInbox.go index 54159b8..1c262bc 100644 --- a/vendor/github.com/kavenegar/kavenegar-go/message_countInbox.go +++ b/vendor/github.com/kavenegar/kavenegar-go/message_countInbox.go @@ -6,40 +6,65 @@ import ( ) // MessageCountInbox ... + type MessageCountInbox struct { Startdate int `json:"startdate"` - Enddate int `json:"enddate"` - Sumcount int `json:"sumcount"` + + Enddate int `json:"enddate"` + + Sumcount int `json:"sumcount"` } // MessageCountInboxResult ... + type MessageCountInboxResult struct { *Return `json:"return"` + Entries []MessageCountInbox `json:"entries"` } // CountInbox ... + func (message *MessageService) CountInbox(linenumber string, startdate time.Time, endate time.Time, isread bool) (MessageCountInbox, error) { v := url.Values{} + v.Set("linenumber", linenumber) + v.Set("startdate", ToUnix(startdate)) + if !endate.IsZero() { + v.Set("endate", ToUnix(startdate)) + } + //if isread != nil { + v.Set("isread", map[bool]string{true: "1", false: "0"}[isread != true]) + //} + return message.CreateCountInbox(v) + } // CreateCountInbox ... + func (message *MessageService) CreateCountInbox(v url.Values) (MessageCountInbox, error) { + u := message.client.EndPoint("sms", "countinbox") + m := new(MessageCountInboxResult) + err := message.client.Execute(u.String(), v, m) + if m.Entries == nil { + return MessageCountInbox{}, err + } + return m.Entries[0], err + } diff --git a/vendor/github.com/kavenegar/kavenegar-go/message_countPostalCode.go b/vendor/github.com/kavenegar/kavenegar-go/message_countPostalCode.go index c768fcc..24982ba 100644 --- a/vendor/github.com/kavenegar/kavenegar-go/message_countPostalCode.go +++ b/vendor/github.com/kavenegar/kavenegar-go/message_countPostalCode.go @@ -6,23 +6,35 @@ import ( ) // MessageCountPostalCode ... + type MessageCountPostalCode struct { Section string `json:"section"` - Value int `json:"value"` + + Value int `json:"value"` } // MessageCountPostalCodeResult ... + type MessageCountPostalCodeResult struct { *Return `json:"return"` + Entries []MessageCountPostalCode `json:"entries"` } // CountPostalCode ... + func (message *MessageService) CountPostalCode(postalcode int64) ([]MessageCountPostalCode, error) { + u := message.client.EndPoint("sms", "countpostalcode") + m := new(MessageCountPostalCodeResult) + v := url.Values{} + v.Set("postalcode", strconv.FormatInt(postalcode, 10)) + err := message.client.Execute(u.String(), v, m) + return m.Entries, err + } diff --git a/vendor/github.com/kavenegar/kavenegar-go/message_countoutbox.go b/vendor/github.com/kavenegar/kavenegar-go/message_countoutbox.go index cbe3988..56da7fb 100644 --- a/vendor/github.com/kavenegar/kavenegar-go/message_countoutbox.go +++ b/vendor/github.com/kavenegar/kavenegar-go/message_countoutbox.go @@ -6,36 +6,59 @@ import ( ) // MessageCountOutbox ... + type MessageCountOutbox struct { *MessageCountInbox + Sumpart int `json:"sumpart"` - Cost int `json:"cost"` + + Cost int `json:"cost"` } // MessageCountOutboxResult ... + type MessageCountOutboxResult struct { *Return `json:"return"` + Entries []MessageCountOutbox `json:"entries"` } // CountOutbox ... + func (message *MessageService) CountOutbox(startdate time.Time, endate time.Time, status MessageStatusType) (MessageCountOutbox, error) { + v := url.Values{} + v.Set("startdate", ToUnix(startdate)) + if !endate.IsZero() { + v.Set("endate", ToUnix(startdate)) + } + v.Set("status", status.String()) + return message.CreateCountOutbox(v) + } // CreateCountOutbox ... + func (message *MessageService) CreateCountOutbox(v url.Values) (MessageCountOutbox, error) { + u := message.client.EndPoint("sms", "countoutbox") + m := new(MessageCountOutboxResult) + err := message.client.Execute(u.String(), v, m) + if m.Entries == nil { + return MessageCountOutbox{}, err + } + return m.Entries[0], err + } diff --git a/vendor/github.com/kavenegar/kavenegar-go/message_latestOutbox.go b/vendor/github.com/kavenegar/kavenegar-go/message_latestOutbox.go index 35ec68e..ffaa3dc 100644 --- a/vendor/github.com/kavenegar/kavenegar-go/message_latestOutbox.go +++ b/vendor/github.com/kavenegar/kavenegar-go/message_latestOutbox.go @@ -6,24 +6,43 @@ import ( ) // LatestOutbox ... + func (message *MessageService) LatestOutbox(sender string, pagesize int) ([]Message, error) { + v := url.Values{} + v.Set("sender", sender) + v.Set("pagesize", strconv.Itoa(pagesize)) + return message.CreateLatestOutbox(v) + } // CreateLatestOutbox ... + func (message *MessageService) CreateLatestOutbox(v url.Values) ([]Message, error) { + u := message.client.EndPoint("sms", "latestoutbox") + vc := url.Values{} + if v.Get("sender") != "" { + vc.Set("sender", v.Get("sender")) + } + if v.Get("pagesize") != "" { + vc.Set("pagesize", v.Get("pagesize")) + } + m := new(MessageResult) + err := message.client.Execute(u.String(), v, m) + return m.Entries, err + } diff --git a/vendor/github.com/kavenegar/kavenegar-go/message_selectOutbox.go b/vendor/github.com/kavenegar/kavenegar-go/message_selectOutbox.go index 766765c..c6985f5 100644 --- a/vendor/github.com/kavenegar/kavenegar-go/message_selectOutbox.go +++ b/vendor/github.com/kavenegar/kavenegar-go/message_selectOutbox.go @@ -6,27 +6,43 @@ import ( ) // SelectOutbox ... + func (message *MessageService) SelectOutbox(startdate time.Time, endate time.Time, sender string) ([]Message, error) { v := url.Values{} if !startdate.IsZero() { + v.Set("startdate", ToUnix(startdate)) + } + if !endate.IsZero() { + v.Set("endate", ToUnix(endate)) + } + if v.Get("sender") != "" { + v.Set("sender", v.Get("sender")) + } return message.CreateSelectOutbox(v) + } // CreateSelectOutbox ... + func (message *MessageService) CreateSelectOutbox(v url.Values) ([]Message, error) { + u := message.client.EndPoint("sms", "selectoutbox") + m := new(MessageResult) + err := message.client.Execute(u.String(), v, m) + return m.Entries, err + } diff --git a/vendor/github.com/kavenegar/kavenegar-go/message_sendByPostalCode.go b/vendor/github.com/kavenegar/kavenegar-go/message_sendByPostalCode.go index fe537b2..ffe9015 100644 --- a/vendor/github.com/kavenegar/kavenegar-go/message_sendByPostalCode.go +++ b/vendor/github.com/kavenegar/kavenegar-go/message_sendByPostalCode.go @@ -7,23 +7,41 @@ import ( ) // SendPostalCode ... + func (m *MessageService) SendPostalCode(postalcode int64, sender string, message string, mcistartindex int, mcicount int, mtnstartindex int, mtncount int, date time.Time) ([]Message, error) { + v := url.Values{} + v.Set("postalcode", strconv.FormatInt(postalcode, 10)) + v.Set("sender", sender) + v.Set("message", message) + v.Set("mcistartind", strconv.Itoa(mcistartindex)) + v.Set("mcicount", strconv.Itoa(mcicount)) + v.Set("mtnstartind", strconv.Itoa(mtnstartindex)) + v.Set("mtncount", strconv.Itoa(mtncount)) + v.Set("date", ToUnix(date)) + return m.CreateSendPostalCode(v) + } // CreateSendPostalCode ... + func (m *MessageService) CreateSendPostalCode(v url.Values) ([]Message, error) { + u := m.client.EndPoint("sms", "sendbypostalcode") + res := new(MessageResult) + err := m.client.Execute(u.String(), v, res) + return res.Entries, err + } diff --git a/vendor/github.com/kavenegar/kavenegar-go/message_statusLocal.go b/vendor/github.com/kavenegar/kavenegar-go/message_statusLocal.go index 2b060e9..171606c 100644 --- a/vendor/github.com/kavenegar/kavenegar-go/message_statusLocal.go +++ b/vendor/github.com/kavenegar/kavenegar-go/message_statusLocal.go @@ -6,26 +6,41 @@ import ( ) // MessageStatusLocal ... + type MessageStatusLocal struct { *MessageStatus + LocalID string `json:"localid"` } // MessageStatusLocalResult ... + type MessageStatusLocalResult struct { *Return `json:"return"` + Entries []MessageStatusLocal `json:"entries"` } // StatusLocal ... + func (message *MessageService) StatusLocal(localid int64) (MessageStatusLocal, error) { + u := message.client.EndPoint("sms", "statuslocalmessageid") + m := new(MessageStatusLocalResult) + v := url.Values{} + v.Set("localid", strconv.FormatInt(localid, 10)) + err := message.client.Execute(u.String(), v, m) + if err != nil { + return MessageStatusLocal{}, err + } + return m.Entries[0], err + } diff --git a/vendor/github.com/kavenegar/kavenegar-go/utils.go b/vendor/github.com/kavenegar/kavenegar-go/utils.go index 28e96f2..01db592 100644 --- a/vendor/github.com/kavenegar/kavenegar-go/utils.go +++ b/vendor/github.com/kavenegar/kavenegar-go/utils.go @@ -11,92 +11,159 @@ import ( ) // ToString ... + func ToString(i interface{}) string { + return strings.Trim(strings.Replace(fmt.Sprint(i), " ", ",", -1), "[]") + } // ToJson ... + func ToJson(i interface{}) string { + _json, _ := json.Marshal(i) + return string(_json) + } // ToUnix ... + func ToUnix(t time.Time) string { + return strconv.FormatInt(t.Unix(), 10) + } // structToUrlValues ... + func structToURLValues(i interface{}) url.Values { + v := url.Values{} + if reflect.ValueOf(i).IsNil() { + return v + } + m := structToMapString(i) + for k, s := range m { + switch { + case len(s) == 1: + v.Set(k, s[0]) + case len(s) > 1: + for i := range s { + v.Add(k, s[i]) + } + } + } return v + } // structToMapString converts struct as map string + func structToMapString(i interface{}) map[string][]string { + ms := map[string][]string{} + iv := reflect.ValueOf(i).Elem() + tp := iv.Type() for i := 0; i < iv.NumField(); i++ { + if isMap(iv.Field(i)) { + m := iv.Field(i).Interface() + for key, value := range m.(map[string]string) { + ms[key] = []string{value} + } + } else { + k := tp.Field(i).Name + f := iv.Field(i) + ms[k] = valueToString(f) + } + } return ms + } func isMap(f reflect.Value) bool { + return reflect.TypeOf(f.Interface()).Kind() == reflect.Map + } // valueToString converts supported type of f as slice string + func valueToString(f reflect.Value) []string { + var v []string switch reflect.TypeOf(f.Interface()).Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + v = []string{strconv.FormatInt(f.Int(), 10)} + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + v = []string{strconv.FormatUint(f.Uint(), 10)} + case reflect.Float32: + v = []string{strconv.FormatFloat(f.Float(), 'f', 4, 32)} + case reflect.Float64: + v = []string{strconv.FormatFloat(f.Float(), 'f', 4, 64)} + case reflect.Bool: + v = []string{strconv.FormatBool(f.Bool())} + case reflect.Slice: + for i := 0; i < f.Len(); i++ { + if s := valueToString(f.Index(i)); len(s) == 1 { + v = append(v, s[0]) + } + } + case reflect.String: + v = []string{f.String()} + } return v + } diff --git a/vendor/github.com/knadh/koanf/getters.go b/vendor/github.com/knadh/koanf/getters.go index 1cf9201..4f66146 100644 --- a/vendor/github.com/knadh/koanf/getters.go +++ b/vendor/github.com/knadh/koanf/getters.go @@ -6,649 +6,1159 @@ import ( ) // Int64 returns the int64 value of a given key path or 0 if the path + // does not exist or if the value is not a valid int64. + func (ko *Koanf) Int64(path string) int64 { + if v := ko.Get(path); v != nil { + i, _ := toInt64(v) + return i + } + return 0 + } // MustInt64 returns the int64 value of a given key path or panics + // if the value is not set or set to default value of 0. + func (ko *Koanf) MustInt64(path string) int64 { + val := ko.Int64(path) + if val == 0 { + panic(fmt.Sprintf("invalid value: %s=%v", path, val)) + } + return val + } // Int64s returns the []int64 slice value of a given key path or an + // empty []int64 slice if the path does not exist or if the value + // is not a valid int slice. + func (ko *Koanf) Int64s(path string) []int64 { + o := ko.Get(path) + if o == nil { + return []int64{} + } var out []int64 + switch v := o.(type) { + case []int64: + return v + case []int: + out = make([]int64, 0, len(v)) + for _, vi := range v { + i, err := toInt64(vi) // On error, return as it's not a valid + // int slice. + if err != nil { + return []int64{} + } + out = append(out, i) + } + return out + case []interface{}: + out = make([]int64, 0, len(v)) + for _, vi := range v { + i, err := toInt64(vi) // On error, return as it's not a valid + // int slice. + if err != nil { + return []int64{} + } + out = append(out, i) + } + return out + } return []int64{} + } // MustInt64s returns the []int64 slice value of a given key path or panics + // if the value is not set or its default value. + func (ko *Koanf) MustInt64s(path string) []int64 { + val := ko.Int64s(path) + if len(val) == 0 { + panic(fmt.Sprintf("invalid value: %s=%v", path, val)) + } + return val + } // Int64Map returns the map[string]int64 value of a given key path + // or an empty map[string]int64 if the path does not exist or if the + // value is not a valid int64 map. + func (ko *Koanf) Int64Map(path string) map[string]int64 { + var ( out = map[string]int64{} - o = ko.Get(path) + + o = ko.Get(path) ) + if o == nil { + return out + } mp, ok := o.(map[string]interface{}) + if !ok { + return out + } out = make(map[string]int64, len(mp)) + for k, v := range mp { + switch i := v.(type) { + case int64: + out[k] = i + default: + // Attempt a conversion. + iv, err := toInt64(i) + if err != nil { + return map[string]int64{} + } + out[k] = iv + } + } + return out + } // MustInt64Map returns the map[string]int64 value of a given key path + // or panics if its not set or set to default value. + func (ko *Koanf) MustInt64Map(path string) map[string]int64 { + val := ko.Int64Map(path) + if len(val) == 0 { + panic(fmt.Sprintf("invalid value: %s=%v", path, val)) + } + return val + } // Int returns the int value of a given key path or 0 if the path + // does not exist or if the value is not a valid int. + func (ko *Koanf) Int(path string) int { + return int(ko.Int64(path)) + } // MustInt returns the int value of a given key path or panics + // or panics if its not set or set to default value of 0. + func (ko *Koanf) MustInt(path string) int { + val := ko.Int(path) + if val == 0 { + panic(fmt.Sprintf("invalid value: %s=%v", path, val)) + } + return val + } // Ints returns the []int slice value of a given key path or an + // empty []int slice if the path does not exist or if the value + // is not a valid int slice. + func (ko *Koanf) Ints(path string) []int { + o := ko.Get(path) + if o == nil { + return []int{} + } var out []int + switch v := o.(type) { + case []int: + return v + case []int64: + out = make([]int, 0, len(v)) + for _, vi := range v { + out = append(out, int(vi)) + } + return out + case []interface{}: + out = make([]int, 0, len(v)) + for _, vi := range v { + i, err := toInt64(vi) // On error, return as it's not a valid + // int slice. + if err != nil { + return []int{} + } + out = append(out, int(i)) + } + return out + } return []int{} + } // MustInts returns the []int slice value of a given key path or panics + // if the value is not set or set to default value. + func (ko *Koanf) MustInts(path string) []int { + val := ko.Ints(path) + if len(val) == 0 { + panic(fmt.Sprintf("invalid value: %s=%v", path, val)) + } + return val + } // IntMap returns the map[string]int value of a given key path + // or an empty map[string]int if the path does not exist or if the + // value is not a valid int map. + func (ko *Koanf) IntMap(path string) map[string]int { + var ( - mp = ko.Int64Map(path) + mp = ko.Int64Map(path) + out = make(map[string]int, len(mp)) ) + for k, v := range mp { + out[k] = int(v) + } + return out + } // MustIntMap returns the map[string]int value of a given key path or panics + // if the value is not set or set to default value. + func (ko *Koanf) MustIntMap(path string) map[string]int { + val := ko.IntMap(path) + if len(val) == 0 { + panic(fmt.Sprintf("invalid value: %s=%v", path, val)) + } + return val + } // Float64 returns the float64 value of a given key path or 0 if the path + // does not exist or if the value is not a valid float64. + func (ko *Koanf) Float64(path string) float64 { + if v := ko.Get(path); v != nil { + f, _ := toFloat64(v) + return f + } + return 0 + } // MustFloat64 returns the float64 value of a given key path or panics + // or panics if its not set or set to default value 0. + func (ko *Koanf) MustFloat64(path string) float64 { + val := ko.Float64(path) + if val == 0 { + panic(fmt.Sprintf("invalid value: %s=%v", path, val)) + } + return val + } // Float64s returns the []float64 slice value of a given key path or an + // empty []float64 slice if the path does not exist or if the value + // is not a valid float64 slice. + func (ko *Koanf) Float64s(path string) []float64 { + o := ko.Get(path) + if o == nil { + return []float64{} + } var out []float64 + switch v := o.(type) { + case []float64: + return v + case []interface{}: + out = make([]float64, 0, len(v)) + for _, vi := range v { + i, err := toFloat64(vi) // On error, return as it's not a valid + // int slice. + if err != nil { + return []float64{} + } + out = append(out, i) + } + return out + } return []float64{} + } // MustFloat64s returns the []Float64 slice value of a given key path or panics + // if the value is not set or set to default value. + func (ko *Koanf) MustFloat64s(path string) []float64 { + val := ko.Float64s(path) + if len(val) == 0 { + panic(fmt.Sprintf("invalid value: %s=%v", path, val)) + } + return val + } // Float64Map returns the map[string]float64 value of a given key path + // or an empty map[string]float64 if the path does not exist or if the + // value is not a valid float64 map. + func (ko *Koanf) Float64Map(path string) map[string]float64 { + var ( out = map[string]float64{} - o = ko.Get(path) + + o = ko.Get(path) ) + if o == nil { + return out + } mp, ok := o.(map[string]interface{}) + if !ok { + return out + } out = make(map[string]float64, len(mp)) + for k, v := range mp { + switch i := v.(type) { + case float64: + out[k] = i + default: + // Attempt a conversion. + iv, err := toFloat64(i) + if err != nil { + return map[string]float64{} + } + out[k] = iv + } + } + return out + } // MustFloat64Map returns the map[string]float64 value of a given key path or panics + // if the value is not set or set to default value. + func (ko *Koanf) MustFloat64Map(path string) map[string]float64 { + val := ko.Float64Map(path) + if len(val) == 0 { + panic(fmt.Sprintf("invalid value: %s=%v", path, val)) + } + return val + } // Duration returns the time.Duration value of a given key path assuming + // that the key contains a valid numeric value. + func (ko *Koanf) Duration(path string) time.Duration { + // Look for a parsable string representation first. + if v := ko.Int64(path); v != 0 { + return time.Duration(v) + } v, _ := time.ParseDuration(ko.String(path)) + return v + } // MustDuration returns the time.Duration value of a given key path or panics + // if its not set or set to default value 0. + func (ko *Koanf) MustDuration(path string) time.Duration { + val := ko.Duration(path) + if val == 0 { + panic(fmt.Sprintf("invalid value: %s=%v", path, val)) + } + return val + } // Time attempts to parse the value of a given key path and return time.Time + // representation. If the value is numeric, it is treated as a UNIX timestamp + // and if it's string, a parse is attempted with the given layout. + func (ko *Koanf) Time(path, layout string) time.Time { + // Unix timestamp? + v := ko.Int64(path) + if v != 0 { + return time.Unix(v, 0) + } // String representation. + s := ko.String(path) + if s != "" { + t, _ := time.Parse(layout, s) + return t + } return time.Time{} + } // MustTime attempts to parse the value of a given key path and return time.Time + // representation. If the value is numeric, it is treated as a UNIX timestamp + // and if it's string, a parse is attempted with the given layout. It panics if + // the parsed time is zero. + func (ko *Koanf) MustTime(path, layout string) time.Time { + val := ko.Time(path, layout) + if val.IsZero() { + panic(fmt.Sprintf("invalid value: %s=%v", path, val)) + } + return val + } // String returns the string value of a given key path or "" if the path + // does not exist or if the value is not a valid string. + func (ko *Koanf) String(path string) string { + if v := ko.Get(path); v != nil { + if i, ok := v.(string); ok { + return i + } + return fmt.Sprintf("%v", v) + } + return "" + } // MustString returns the string value of a given key path + // or panics if its not set or set to default value "". + func (ko *Koanf) MustString(path string) string { + val := ko.String(path) + if val == "" { + panic(fmt.Sprintf("invalid value: %s=%v", path, val)) + } + return val + } // Strings returns the []string slice value of a given key path or an + // empty []string slice if the path does not exist or if the value + // is not a valid string slice. + func (ko *Koanf) Strings(path string) []string { + o := ko.Get(path) + if o == nil { + return []string{} + } var out []string + switch v := o.(type) { + case []interface{}: + out = make([]string, 0, len(v)) + for _, u := range v { + if s, ok := u.(string); ok { + out = append(out, s) + } else { + out = append(out, fmt.Sprintf("%v", u)) + } + } + return out + case []string: + out := make([]string, len(v)) + copy(out[:], v[:]) + return out + } return []string{} + } // MustStrings returns the []string slice value of a given key path or panics + // if the value is not set or set to default value. + func (ko *Koanf) MustStrings(path string) []string { + val := ko.Strings(path) + if len(val) == 0 { + panic(fmt.Sprintf("invalid value: %s=%v", path, val)) + } + return val + } // StringMap returns the map[string]string value of a given key path + // or an empty map[string]string if the path does not exist or if the + // value is not a valid string map. + func (ko *Koanf) StringMap(path string) map[string]string { + var ( out = map[string]string{} - o = ko.Get(path) + + o = ko.Get(path) ) + if o == nil { + return out + } switch mp := o.(type) { + case map[string]string: + out = make(map[string]string, len(mp)) + for k, v := range mp { + out[k] = v + } + case map[string]interface{}: + out = make(map[string]string, len(mp)) + for k, v := range mp { + switch s := v.(type) { + case string: + out[k] = s + default: + // There's a non string type. Return. + return map[string]string{} + } + } + } return out + } // MustStringMap returns the map[string]string value of a given key path or panics + // if the value is not set or set to default value. + func (ko *Koanf) MustStringMap(path string) map[string]string { + val := ko.StringMap(path) + if len(val) == 0 { + panic(fmt.Sprintf("invalid value: %s=%v", path, val)) + } + return val + } // StringsMap returns the map[string][]string value of a given key path + // or an empty map[string][]string if the path does not exist or if the + // value is not a valid strings map. + func (ko *Koanf) StringsMap(path string) map[string][]string { + var ( out = map[string][]string{} - o = ko.Get(path) + + o = ko.Get(path) ) + if o == nil { + return out + } switch mp := o.(type) { + case map[string][]string: + out = make(map[string][]string, len(mp)) + for k, v := range mp { + out[k] = make([]string, 0, len(v)) + for _, s := range v { + out[k] = append(out[k], s) + } + } + case map[string][]interface{}: + out = make(map[string][]string, len(mp)) + for k, v := range mp { + for _, v := range v { + switch sv := v.(type) { + case string: + out[k] = append(out[k], sv) + default: + return map[string][]string{} + } + } + } + case map[string]interface{}: + out = make(map[string][]string, len(mp)) + for k, v := range mp { + switch s := v.(type) { + case []string: + for _, v := range s { + out[k] = append(out[k], v) + } + case []interface{}: + for _, v := range s { + switch sv := v.(type) { + case string: + out[k] = append(out[k], sv) + default: + return map[string][]string{} + } + } + default: + // There's a non []interface type. Return. + return map[string][]string{} + } + } + } return out + } // MustStringsMap returns the map[string][]string value of a given key path or panics + // if the value is not set or set to default value. + func (ko *Koanf) MustStringsMap(path string) map[string][]string { + val := ko.StringsMap(path) + if len(val) == 0 { + panic(fmt.Sprintf("invalid value: %s=%v", path, val)) + } + return val + } // Bytes returns the []byte value of a given key path or an empty + // []byte slice if the path does not exist or if the value is not a valid string. + func (ko *Koanf) Bytes(path string) []byte { + return []byte(ko.String(path)) + } // MustBytes returns the []byte value of a given key path or panics + // if the value is not set or set to default value. + func (ko *Koanf) MustBytes(path string) []byte { + val := ko.Bytes(path) + if len(val) == 0 { + panic(fmt.Sprintf("invalid value: %s=%v", path, val)) + } + return val + } // Bool returns the bool value of a given key path or false if the path + // does not exist or if the value is not a valid bool representation. + // Accepted string representations of bool are the ones supported by strconv.ParseBool. + func (ko *Koanf) Bool(path string) bool { + if v := ko.Get(path); v != nil { + b, _ := toBool(v) + return b + } + return false + } // Bools returns the []bool slice value of a given key path or an + // empty []bool slice if the path does not exist or if the value + // is not a valid bool slice. + func (ko *Koanf) Bools(path string) []bool { + o := ko.Get(path) + if o == nil { + return []bool{} + } var out []bool + switch v := o.(type) { + case []interface{}: + out = make([]bool, 0, len(v)) + for _, u := range v { + b, err := toBool(u) + if err != nil { + return nil + } + out = append(out, b) + } + return out + case []bool: + return out + } + return nil + } // MustBools returns the []bool value of a given key path or panics + // if the value is not set or set to default value. + func (ko *Koanf) MustBools(path string) []bool { + val := ko.Bools(path) + if len(val) == 0 { + panic(fmt.Sprintf("invalid value: %s=%v", path, val)) + } + return val + } // BoolMap returns the map[string]bool value of a given key path + // or an empty map[string]bool if the path does not exist or if the + // value is not a valid bool map. + func (ko *Koanf) BoolMap(path string) map[string]bool { + var ( out = map[string]bool{} - o = ko.Get(path) + + o = ko.Get(path) ) + if o == nil { + return out + } mp, ok := o.(map[string]interface{}) + if !ok { + return out + } + out = make(map[string]bool, len(mp)) + for k, v := range mp { + switch i := v.(type) { + case bool: + out[k] = i + default: + // Attempt a conversion. + b, err := toBool(i) + if err != nil { + return map[string]bool{} + } + out[k] = b + } + } return out + } // MustBoolMap returns the map[string]bool value of a given key path or panics + // if the value is not set or set to default value. + func (ko *Koanf) MustBoolMap(path string) map[string]bool { + val := ko.BoolMap(path) + if len(val) == 0 { + panic(fmt.Sprintf("invalid value: %s=%v", path, val)) + } + return val + } diff --git a/vendor/github.com/knadh/koanf/koanf.go b/vendor/github.com/knadh/koanf/koanf.go index aa514e3..86e8453 100644 --- a/vendor/github.com/knadh/koanf/koanf.go +++ b/vendor/github.com/knadh/koanf/koanf.go @@ -12,502 +12,860 @@ import ( ) // Koanf is the configuration apparatus. + type Koanf struct { - confMap map[string]interface{} + confMap map[string]interface{} + confMapFlat map[string]interface{} - keyMap KeyMap - conf Conf + + keyMap KeyMap + + conf Conf } // Conf is the Koanf configuration. + type Conf struct { + // Delim is the delimiter to use + // when specifying config key paths, for instance a . for `parent.child.key` + // or a / for `parent/child/key`. + Delim string // StrictMerge makes the merging behavior strict. + // Meaning when loading two files that have the same key, + // the first loaded file will define the desired type, and if the second file loads + // a different type will cause an error. + StrictMerge bool } // KeyMap represents a map of flattened delimited keys and the non-delimited + // parts as their slices. For nested keys, the map holds all levels of path combinations. + // For example, the nested structure `parent -> child -> key` will produce the map: + // parent.child.key => [parent, child, key] + // parent.child => [parent, child] + // parent => [parent] + type KeyMap map[string][]string // UnmarshalConf represents configuration options used by + // Unmarshal() to unmarshal conf maps into arbitrary structs. + type UnmarshalConf struct { + // Tag is the struct field tag to unmarshal. + // `koanf` is used if left empty. + Tag string // If this is set to true, instead of unmarshalling nested structures + // based on the key path, keys are taken literally to unmarshal into + // a flat struct. For example: + // ``` + // type MyStuff struct { + // Child1Name string `koanf:"parent1.child1.name"` + // Child2Name string `koanf:"parent2.child2.name"` + // Type string `koanf:"json"` + // } + // ``` - FlatPaths bool + + FlatPaths bool + DecoderConfig *mapstructure.DecoderConfig } // New returns a new instance of Koanf. delim is the delimiter to use + // when specifying config key paths, for instance a . for `parent.child.key` + // or a / for `parent/child/key`. + func New(delim string) *Koanf { + return NewWithConf(Conf{ - Delim: delim, + + Delim: delim, + StrictMerge: false, }) + } // NewWithConf returns a new instance of Koanf based on the Conf. + func NewWithConf(conf Conf) *Koanf { + return &Koanf{ - confMap: make(map[string]interface{}), + + confMap: make(map[string]interface{}), + confMapFlat: make(map[string]interface{}), - keyMap: make(KeyMap), - conf: conf, + + keyMap: make(KeyMap), + + conf: conf, } + } // Load takes a Provider that either provides a parsed config map[string]interface{} + // in which case pa (Parser) can be nil, or raw bytes to be parsed, where a Parser + // can be provided to parse. Additionally, options can be passed which modify the + // load behavior, such as passing a custom merge function. + func (ko *Koanf) Load(p Provider, pa Parser, opts ...Option) error { + var ( - mp map[string]interface{} + mp map[string]interface{} + err error ) if p == nil { + return fmt.Errorf("load received a nil provider") + } // No Parser is given. Call the Provider's Read() method to get + // the config map. + if pa == nil { + mp, err = p.Read() + if err != nil { + return err + } + } else { + // There's a Parser. Get raw bytes from the Provider to parse. + b, err := p.ReadBytes() + if err != nil { + return err + } + mp, err = pa.Unmarshal(b) + if err != nil { + return err + } + } return ko.merge(mp, newOptions(opts)) + } // Keys returns the slice of all flattened keys in the loaded configuration + // sorted alphabetically. + func (ko *Koanf) Keys() []string { + out := make([]string, 0, len(ko.confMapFlat)) + for k := range ko.confMapFlat { + out = append(out, k) + } + sort.Strings(out) + return out + } // KeyMap returns a map of flattened keys and the individual parts of the + // key as slices. eg: "parent.child.key" => ["parent", "child", "key"] + func (ko *Koanf) KeyMap() KeyMap { + out := make(KeyMap, len(ko.keyMap)) + for key, parts := range ko.keyMap { + out[key] = make([]string, len(parts)) + copy(out[key][:], parts[:]) + } + return out + } // All returns a map of all flattened key paths and their values. + // Note that it uses maps.Copy to create a copy that uses + // json.Marshal which changes the numeric types to float64. + func (ko *Koanf) All() map[string]interface{} { + return maps.Copy(ko.confMapFlat) + } // Raw returns a copy of the full raw conf map. + // Note that it uses maps.Copy to create a copy that uses + // json.Marshal which changes the numeric types to float64. + func (ko *Koanf) Raw() map[string]interface{} { + return maps.Copy(ko.confMap) + } // Sprint returns a key -> value string representation + // of the config map with keys sorted alphabetically. + func (ko *Koanf) Sprint() string { + b := bytes.Buffer{} + for _, k := range ko.Keys() { + b.Write([]byte(fmt.Sprintf("%s -> %v\n", k, ko.confMapFlat[k]))) + } + return b.String() + } // Print prints a key -> value string representation + // of the config map with keys sorted alphabetically. + func (ko *Koanf) Print() { + fmt.Print(ko.Sprint()) + } // Cut cuts the config map at a given key path into a sub map and + // returns a new Koanf instance with the cut config map loaded. + // For instance, if the loaded config has a path that looks like + // parent.child.sub.a.b, `Cut("parent.child")` returns a new Koanf + // instance with the config map `sub.a.b` where everything above + // `parent.child` are cut out. + func (ko *Koanf) Cut(path string) *Koanf { + out := make(map[string]interface{}) // Cut only makes sense if the requested key path is a map. + if v, ok := ko.Get(path).(map[string]interface{}); ok { + out = v + } n := New(ko.conf.Delim) + _ = n.merge(out, new(options)) + return n + } // Copy returns a copy of the Koanf instance. + func (ko *Koanf) Copy() *Koanf { + return ko.Cut("") + } // Merge merges the config map of a given Koanf instance into + // the current instance. + func (ko *Koanf) Merge(in *Koanf) error { + return ko.merge(in.Raw(), new(options)) + } // MergeAt merges the config map of a given Koanf instance into + // the current instance as a sub map, at the given key path. + // If all or part of the key path is missing, it will be created. + // If the key path is `""`, this is equivalent to Merge. + func (ko *Koanf) MergeAt(in *Koanf, path string) error { + // No path. Merge the two config maps. + if path == "" { + return ko.Merge(in) + } // Unflatten the config map with the given key path. + n := maps.Unflatten(map[string]interface{}{ + path: in.Raw(), }, ko.conf.Delim) return ko.merge(n, new(options)) + } // Set sets the value at a specific key. + func (ko *Koanf) Set(key string, val interface{}) error { + // Unflatten the config map with the given key path. + n := maps.Unflatten(map[string]interface{}{ + key: val, }, ko.conf.Delim) return ko.merge(n, new(options)) + } // Marshal takes a Parser implementation and marshals the config map into bytes, + // for example, to TOML or JSON bytes. + func (ko *Koanf) Marshal(p Parser) ([]byte, error) { + return p.Marshal(ko.Raw()) + } // Unmarshal unmarshals a given key path into the given struct using + // the mapstructure lib. If no path is specified, the whole map is unmarshalled. + // `koanf` is the struct field tag used to match field names. To customize, + // use UnmarshalWithConf(). It uses the mitchellh/mapstructure package. + func (ko *Koanf) Unmarshal(path string, o interface{}) error { + return ko.UnmarshalWithConf(path, o, UnmarshalConf{}) + } // UnmarshalWithConf is like Unmarshal but takes configuration params in UnmarshalConf. + // See mitchellh/mapstructure's DecoderConfig for advanced customization + // of the unmarshal behaviour. + func (ko *Koanf) UnmarshalWithConf(path string, o interface{}, c UnmarshalConf) error { + if c.DecoderConfig == nil { + c.DecoderConfig = &mapstructure.DecoderConfig{ + DecodeHook: mapstructure.ComposeDecodeHookFunc( + mapstructure.StringToTimeDurationHookFunc(), + mapstructure.StringToSliceHookFunc(","), + mapstructure.TextUnmarshallerHookFunc()), - Metadata: nil, - Result: o, + + Metadata: nil, + + Result: o, + WeaklyTypedInput: true, } + } if c.Tag == "" { + c.DecoderConfig.TagName = "koanf" + } else { + c.DecoderConfig.TagName = c.Tag + } d, err := mapstructure.NewDecoder(c.DecoderConfig) + if err != nil { + return err + } // Unmarshal using flat key paths. + mp := ko.Get(path) + if c.FlatPaths { + if f, ok := mp.(map[string]interface{}); ok { + fmp, _ := maps.Flatten(f, nil, ko.conf.Delim) + mp = fmp + } + } return d.Decode(mp) + } // Delete removes all nested values from a given path. + // Clears all keys/values if no path is specified. + // Every empty, key on the path, is recursively deleted. + func (ko *Koanf) Delete(path string) { + // No path. Erase the entire map. + if path == "" { + ko.confMap = make(map[string]interface{}) + ko.confMapFlat = make(map[string]interface{}) + ko.keyMap = make(KeyMap) + return + } // Does the path exist? + p, ok := ko.keyMap[path] + if !ok { + return + } + maps.Delete(ko.confMap, p) // Update the flattened version as well. + ko.confMapFlat, ko.keyMap = maps.Flatten(ko.confMap, nil, ko.conf.Delim) + ko.keyMap = populateKeyParts(ko.keyMap, ko.conf.Delim) + } // Get returns the raw, uncast interface{} value of a given key path + // in the config map. If the key path does not exist, nil is returned. + func (ko *Koanf) Get(path string) interface{} { + // No path. Return the whole conf map. + if path == "" { + return ko.Raw() + } // Does the path exist? + p, ok := ko.keyMap[path] + if !ok { + return nil + } + res := maps.Search(ko.confMap, p) // Non-reference types are okay to return directly. + // Other types are "copied" with maps.Copy or json.Marshal + // that change the numeric types to float64. switch v := res.(type) { + case int, int8, int16, int32, int64, float32, float64, string, bool: + return v + case map[string]interface{}: + return maps.Copy(v) + } out, _ := copystructure.Copy(&res) + if ptrOut, ok := out.(*interface{}); ok { + return *ptrOut + } + return out + } // Slices returns a list of Koanf instances constructed out of a + // []map[string]interface{} interface at the given path. + func (ko *Koanf) Slices(path string) []*Koanf { + out := []*Koanf{} + if path == "" { + return out + } // Does the path exist? + sl, ok := ko.Get(path).([]interface{}) + if !ok { + return out + } for _, s := range sl { + mp, ok := s.(map[string]interface{}) + if !ok { + continue + } k := New(ko.conf.Delim) + _ = k.merge(mp, new(options)) + out = append(out, k) + } return out + } // Exists returns true if the given key path exists in the conf map. + func (ko *Koanf) Exists(path string) bool { + _, ok := ko.keyMap[path] + return ok + } // MapKeys returns a sorted string list of keys in a map addressed by the + // given path. If the path is not a map, an empty string slice is + // returned. + func (ko *Koanf) MapKeys(path string) []string { + var ( out = []string{} - o = ko.Get(path) + + o = ko.Get(path) ) + if o == nil { + return out + } mp, ok := o.(map[string]interface{}) + if !ok { + return out + } + out = make([]string, 0, len(mp)) + for k := range mp { + out = append(out, k) + } + sort.Strings(out) + return out + } // Delim returns delimiter in used by this instance of Koanf. + func (ko *Koanf) Delim() string { + return ko.conf.Delim + } func (ko *Koanf) merge(c map[string]interface{}, opts *options) error { + maps.IntfaceKeysToStrings(c) + if opts.merge != nil { + if err := opts.merge(c, ko.confMap); err != nil { + return err + } + } else if ko.conf.StrictMerge { + if err := maps.MergeStrict(c, ko.confMap); err != nil { + return err + } + } else { + maps.Merge(c, ko.confMap) + } // Maintain a flattened version as well. + ko.confMapFlat, ko.keyMap = maps.Flatten(ko.confMap, nil, ko.conf.Delim) + ko.keyMap = populateKeyParts(ko.keyMap, ko.conf.Delim) return nil + } // toInt64 takes an interface value and if it is an integer type, + // converts and returns int64. If it's any other type, + // forces it to a string and attempts to an strconv.Atoi + // to get an integer out. + func toInt64(v interface{}) (int64, error) { + switch i := v.(type) { + case int: + return int64(i), nil + case int8: + return int64(i), nil + case int16: + return int64(i), nil + case int32: + return int64(i), nil + case int64: + return i, nil + } // Force it to a string and try to convert. + f, err := strconv.ParseFloat(fmt.Sprintf("%v", v), 64) + if err != nil { + return 0, err + } return int64(f), nil + } // toInt64 takes a `v interface{}` value and if it is a float type, + // converts and returns a `float64`. If it's any other type, forces it to a + // string and attempts to get a float out using `strconv.ParseFloat`. + func toFloat64(v interface{}) (float64, error) { + switch i := v.(type) { + case float32: + return float64(i), nil + case float64: + return i, nil + } // Force it to a string and try to convert. + f, err := strconv.ParseFloat(fmt.Sprintf("%v", v), 64) + if err != nil { + return f, err + } return f, nil + } // toBool takes an interface value and if it is a bool type, + // returns it. If it's any other type, forces it to a string and attempts + // to parse it as a bool using strconv.ParseBool. + func toBool(v interface{}) (bool, error) { + if b, ok := v.(bool); ok { + return b, nil + } // Force it to a string and try to convert. + b, err := strconv.ParseBool(fmt.Sprintf("%v", v)) + if err != nil { + return b, err + } + return b, nil + } // populateKeyParts iterates a key map and generates all possible + // traversal paths. For instance, `parent.child.key` generates + // `parent`, and `parent.child`. + func populateKeyParts(m KeyMap, delim string) KeyMap { + out := make(KeyMap, len(m)) // The size of the result is at very least same to KeyMap + for _, parts := range m { + // parts is a slice of [parent, child, key] + var nk string for i := range parts { + if i == 0 { + // On first iteration only use first part + nk = parts[i] + } else { + // If nk already contains a part (e.g. `parent`) append delim + `child` + nk += delim + parts[i] + } + if _, ok := out[nk]; ok { + continue + } + out[nk] = make([]string, i+1) + copy(out[nk][:], parts[0:i+1]) + } + } + return out + } diff --git a/vendor/github.com/knadh/koanf/maps/maps.go b/vendor/github.com/knadh/koanf/maps/maps.go index cad1068..da648b1 100644 --- a/vendor/github.com/knadh/koanf/maps/maps.go +++ b/vendor/github.com/knadh/koanf/maps/maps.go @@ -1,6 +1,9 @@ // Package maps provides reusable functions for manipulating nested + // map[string]interface{} maps are common unmarshal products from + // various serializers such as json, yaml etc. + package maps import ( @@ -12,284 +15,517 @@ import ( ) // Flatten takes a map[string]interface{} and traverses it and flattens + // nested children into keys delimited by delim. + // + // It's important to note that all nested maps should be + // map[string]interface{} and not map[interface{}]interface{}. + // Use IntfaceKeysToStrings() to convert if necessary. + // + // eg: `{ "parent": { "child": 123 }}` becomes `{ "parent.child": 123 }` + // In addition, it keeps track of and returns a map of the delimited keypaths with + // a slice of key parts, for eg: { "parent.child": ["parent", "child"] }. This + // parts list is used to remember the key path's original structure to + // unflatten later. + func Flatten(m map[string]interface{}, keys []string, delim string) (map[string]interface{}, map[string][]string) { + var ( - out = make(map[string]interface{}) + out = make(map[string]interface{}) + keyMap = make(map[string][]string) ) flatten(m, keys, delim, out, keyMap) + return out, keyMap + } func flatten(m map[string]interface{}, keys []string, delim string, out map[string]interface{}, keyMap map[string][]string) { + for key, val := range m { + // Copy the incoming key paths into a fresh list + // and append the current key in the iteration. + kp := make([]string, 0, len(keys)+1) + kp = append(kp, keys...) + kp = append(kp, key) switch cur := val.(type) { + case map[string]interface{}: + // Empty map. + if len(cur) == 0 { + newKey := strings.Join(kp, delim) + out[newKey] = val + keyMap[newKey] = kp + continue + } // It's a nested map. Flatten it recursively. + flatten(cur, kp, delim, out, keyMap) + default: + newKey := strings.Join(kp, delim) + out[newKey] = val + keyMap[newKey] = kp + } + } + } // Unflatten takes a flattened key:value map (non-nested with delimited keys) + // and returns a nested map where the keys are split into hierarchies by the given + // delimiter. For instance, `parent.child.key: 1` to `{parent: {child: {key: 1}}}` + // + // It's important to note that all nested maps should be + // map[string]interface{} and not map[interface{}]interface{}. + // Use IntfaceKeysToStrings() to convert if necessary. + func Unflatten(m map[string]interface{}, delim string) map[string]interface{} { + out := make(map[string]interface{}) // Iterate through the flat conf map. + for k, v := range m { + var ( keys = strings.Split(k, delim) + next = out ) // Iterate through key parts, for eg:, parent.child.key + // will be ["parent", "child", "key"] + for _, k := range keys[:len(keys)-1] { + sub, ok := next[k] + if !ok { + // If the key does not exist in the map, create it. + sub = make(map[string]interface{}) + next[k] = sub + } + if n, ok := sub.(map[string]interface{}); ok { + next = n + } + } // Assign the value. + next[keys[len(keys)-1]] = v + } + return out + } // Merge recursively merges map a into b (left to right), mutating + // and expanding map b. Note that there's no copying involved, so + // map b will retain references to map a. + // + // It's important to note that all nested maps should be + // map[string]interface{} and not map[interface{}]interface{}. + // Use IntfaceKeysToStrings() to convert if necessary. + func Merge(a, b map[string]interface{}) { + for key, val := range a { + // Does the key exist in the target map? + // If no, add it and move on. + bVal, ok := b[key] + if !ok { + b[key] = val + continue + } // If the incoming val is not a map, do a direct merge. + if _, ok := val.(map[string]interface{}); !ok { + b[key] = val + continue + } // The source key and target keys are both maps. Merge them. + switch v := bVal.(type) { + case map[string]interface{}: + Merge(val.(map[string]interface{}), v) + default: + b[key] = val + } + } + } // MergeStrict recursively merges map a into b (left to right), mutating + // and expanding map b. Note that there's no copying involved, so + // map b will retain references to map a. + // If an equal key in either of the maps has a different value type, it will return the first error. + // + // It's important to note that all nested maps should be + // map[string]interface{} and not map[interface{}]interface{}. + // Use IntfaceKeysToStrings() to convert if necessary. + func MergeStrict(a, b map[string]interface{}) error { + return mergeStrict(a, b, "") + } func mergeStrict(a, b map[string]interface{}, fullKey string) error { + for key, val := range a { + // Does the key exist in the target map? + // If no, add it and move on. + bVal, ok := b[key] + if !ok { + b[key] = val + continue + } newFullKey := key + if fullKey != "" { + newFullKey = fmt.Sprintf("%v.%v", fullKey, key) + } // If the incoming val is not a map, do a direct merge between the same types. + if _, ok := val.(map[string]interface{}); !ok { + if reflect.TypeOf(b[key]) == reflect.TypeOf(val) { + b[key] = val + } else { + return fmt.Errorf("incorrect types at key %v, type %T != %T", fullKey, b[key], val) + } + continue + } // The source key and target keys are both maps. Merge them. + switch v := bVal.(type) { + case map[string]interface{}: + return mergeStrict(val.(map[string]interface{}), v, newFullKey) + default: + b[key] = val + } + } + return nil + } // Delete removes the entry present at a given path, from the map. The path + // is the key map slice, for eg:, parent.child.key -> [parent child key]. + // Any empty, nested map on the path, is recursively deleted. + // + // It's important to note that all nested maps should be + // map[string]interface{} and not map[interface{}]interface{}. + // Use IntfaceKeysToStrings() to convert if necessary. + func Delete(mp map[string]interface{}, path []string) { + next, ok := mp[path[0]] + if ok { + if len(path) == 1 { + delete(mp, path[0]) + return + } + switch nval := next.(type) { + case map[string]interface{}: + Delete(nval, path[1:]) + // Delete map if it has no keys. + if len(nval) == 0 { + delete(mp, path[0]) + } + } + } + } // Search recursively searches a map for a given path. The path is + // the key map slice, for eg:, parent.child.key -> [parent child key]. + // + // It's important to note that all nested maps should be + // map[string]interface{} and not map[interface{}]interface{}. + // Use IntfaceKeysToStrings() to convert if necessary. + func Search(mp map[string]interface{}, path []string) interface{} { + next, ok := mp[path[0]] + if ok { + if len(path) == 1 { + return next + } + switch m := next.(type) { + case map[string]interface{}: + return Search(m, path[1:]) + default: + return nil + } // + // It's important to note that all nested maps should be + // map[string]interface{} and not map[interface{}]interface{}. + // Use IntfaceKeysToStrings() to convert if necessary. + } + return nil + } // Copy returns a deep copy of a conf map. + // + // It's important to note that all nested maps should be + // map[string]interface{} and not map[interface{}]interface{}. + // Use IntfaceKeysToStrings() to convert if necessary. + func Copy(mp map[string]interface{}) map[string]interface{} { + out, _ := copystructure.Copy(&mp) + if res, ok := out.(*map[string]interface{}); ok { + return *res + } + return map[string]interface{}{} + } // IntfaceKeysToStrings recursively converts map[interface{}]interface{} to + // map[string]interface{}. Some parses such as YAML unmarshal return this. + func IntfaceKeysToStrings(mp map[string]interface{}) { + for key, val := range mp { + switch cur := val.(type) { + case map[interface{}]interface{}: + x := make(map[string]interface{}) + for k, v := range cur { + x[fmt.Sprintf("%v", k)] = v + } + mp[key] = x + IntfaceKeysToStrings(x) + case []interface{}: + for i, v := range cur { + switch sub := v.(type) { + case map[interface{}]interface{}: + x := make(map[string]interface{}) + for k, v := range sub { + x[fmt.Sprintf("%v", k)] = v + } + cur[i] = x + IntfaceKeysToStrings(x) + case map[string]interface{}: + IntfaceKeysToStrings(sub) + } + } + case map[string]interface{}: + IntfaceKeysToStrings(cur) + } + } + } // StringSliceToLookupMap takes a slice of strings and returns a lookup map + // with the slice values as keys with true values. + func StringSliceToLookupMap(s []string) map[string]bool { + mp := make(map[string]bool, len(s)) + for _, v := range s { + mp[v] = true + } + return mp + } // Int64SliceToLookupMap takes a slice of int64s and returns a lookup map + // with the slice values as keys with true values. + func Int64SliceToLookupMap(s []int64) map[int64]bool { + mp := make(map[int64]bool, len(s)) + for _, v := range s { + mp[v] = true + } + return mp + } diff --git a/vendor/github.com/knadh/koanf/providers/env/env.go b/vendor/github.com/knadh/koanf/providers/env/env.go index 5ec252b..3988ba2 100644 --- a/vendor/github.com/knadh/koanf/providers/env/env.go +++ b/vendor/github.com/knadh/koanf/providers/env/env.go @@ -1,5 +1,7 @@ // Package env implements a koanf.Provider that reads environment + // variables as conf maps. + package env import ( @@ -11,88 +13,153 @@ import ( ) // Env implements an environment variables provider. + type Env struct { prefix string - delim string - cb func(key string, value string) (string, interface{}) + + delim string + + cb func(key string, value string) (string, interface{}) } // Provider returns an environment variables provider that returns + // a nested map[string]interface{} of environment variable where the + // nesting hierarchy of keys is defined by delim. For instance, the + // delim "." will convert the key `parent.child.key: 1` + // to `{parent: {child: {key: 1}}}`. + // + // If prefix is specified (case-sensitive), only the env vars with + // the prefix are captured. cb is an optional callback that takes + // a string and returns a string (the env variable name) in case + // transformations have to be applied, for instance, to lowercase + // everything, strip prefixes and replace _ with . etc. + // If the callback returns an empty string, the variable will be + // ignored. + func Provider(prefix, delim string, cb func(s string) string) *Env { + e := &Env{ + prefix: prefix, - delim: delim, + + delim: delim, } + if cb != nil { + e.cb = func(key string, value string) (string, interface{}) { + return cb(key), value + } + } + return e + } // ProviderWithValue works exactly the same as Provider except the callback + // takes a (key, value) with the variable name and value and allows you + // to modify both. This is useful for cases where you may want to return + // other types like a string slice instead of just a string. + func ProviderWithValue(prefix, delim string, cb func(key string, value string) (string, interface{})) *Env { + return &Env{ + prefix: prefix, - delim: delim, - cb: cb, + + delim: delim, + + cb: cb, } + } // ReadBytes is not supported by the env provider. + func (e *Env) ReadBytes() ([]byte, error) { + return nil, errors.New("env provider does not support this method") + } // Read reads all available environment variables into a key:value map + // and returns it. + func (e *Env) Read() (map[string]interface{}, error) { + // Collect the environment variable keys. + var keys []string + for _, k := range os.Environ() { + if e.prefix != "" { + if strings.HasPrefix(k, e.prefix) { + keys = append(keys, k) + } + } else { + keys = append(keys, k) + } + } mp := make(map[string]interface{}) + for _, k := range keys { + parts := strings.SplitN(k, "=", 2) // If there's a transformation callback, + // run it through every key/value. + if e.cb != nil { + key, value := e.cb(parts[0], parts[1]) + // If the callback blanked the key, it should be omitted + if key == "" { + continue + } + mp[key] = value + } else { + mp[parts[0]] = parts[1] + } } return maps.Unflatten(mp, e.delim), nil + } diff --git a/vendor/github.com/knadh/koanf/providers/file/file.go b/vendor/github.com/knadh/koanf/providers/file/file.go index 7378e28..8d064d8 100644 --- a/vendor/github.com/knadh/koanf/providers/file/file.go +++ b/vendor/github.com/knadh/koanf/providers/file/file.go @@ -1,6 +1,9 @@ // Package file implements a koanf.Provider that reads raw bytes + // from files on disk to be used with a koanf.Parser to parse + // into conf maps. + package file import ( @@ -14,115 +17,185 @@ import ( ) // File implements a File provider. + type File struct { path string } // Provider returns a file provider. + func Provider(path string) *File { + return &File{path: filepath.Clean(path)} + } // ReadBytes reads the contents of a file on disk and returns the bytes. + func (f *File) ReadBytes() ([]byte, error) { + return ioutil.ReadFile(f.path) + } // Read is not supported by the file provider. + func (f *File) Read() (map[string]interface{}, error) { + return nil, errors.New("file provider does not support this method") + } // Watch watches the file and triggers a callback when it changes. It is a + // blocking function that internally spawns a goroutine to watch for changes. + func (f *File) Watch(cb func(event interface{}, err error)) error { + // Resolve symlinks and save the original path so that changes to symlinks + // can be detected. + realPath, err := filepath.EvalSymlinks(f.path) + if err != nil { + return err + } + realPath = filepath.Clean(realPath) // Although only a single file is being watched, fsnotify has to watch + // the whole parent directory to pick up all events such as symlink changes. + fDir, _ := filepath.Split(f.path) w, err := fsnotify.NewWatcher() + if err != nil { + return err + } var ( - lastEvent string + lastEvent string + lastEventTime time.Time ) go func() { + loop: + for { + select { + case event, ok := <-w.Events: + if !ok { + cb(nil, errors.New("fsnotify watch channel closed")) + break loop + } // Use a simple timer to buffer events as certain events fire + // multiple times on some platforms. + if event.String() == lastEvent && time.Since(lastEventTime) < time.Millisecond*5 { + continue + } + lastEvent = event.String() + lastEventTime = time.Now() evFile := filepath.Clean(event.Name) // Since the event is triggered on a directory, is this + // one on the file being watched? + if evFile != realPath && evFile != f.path { + continue + } // The file was removed. + if event.Op&fsnotify.Remove != 0 { + cb(nil, fmt.Errorf("file %s was removed", event.Name)) + break loop + } // Resolve symlink to get the real path, in case the symlink's + // target has changed. + curPath, err := filepath.EvalSymlinks(f.path) + if err != nil { + cb(nil, err) + break loop + } + realPath = filepath.Clean(curPath) // Finally, we only care about create and write. + if event.Op&(fsnotify.Write|fsnotify.Create) == 0 { + continue + } // Trigger event. + cb(nil, nil) // There's an error. + case err, ok := <-w.Errors: + if !ok { + cb(nil, errors.New("fsnotify err channel closed")) + break loop + } // Pass the error to the callback. + cb(nil, err) + break loop + } + } w.Close() + }() // Watch the directory for changes. + return w.Add(fDir) + } diff --git a/vendor/github.com/knadh/koanf/providers/structs/structs.go b/vendor/github.com/knadh/koanf/providers/structs/structs.go index 7508b62..8aa9380 100644 --- a/vendor/github.com/knadh/koanf/providers/structs/structs.go +++ b/vendor/github.com/knadh/koanf/providers/structs/structs.go @@ -1,5 +1,7 @@ // Package structs implements a koanf.Provider that takes a struct and tag + // and returns a nested config map (using fatih/structs) to provide it to koanf. + package structs import ( @@ -10,39 +12,59 @@ import ( ) // Structs implements a structs provider. + type Structs struct { - s interface{} - tag string + s interface{} + + tag string + delim string } // Provider returns a provider that takes a takes a struct and a struct tag + // and uses structs to parse and provide it to koanf. + func Provider(s interface{}, tag string) *Structs { + return &Structs{s: s, tag: tag} + } // ProviderWithDelim returns a provider that takes a takes a struct and a struct tag + // along with a delim and uses structs to parse and provide it to koanf. + func ProviderWithDelim(s interface{}, tag, delim string) *Structs { + return &Structs{s: s, tag: tag, delim: delim} + } // ReadBytes is not supported by the structs provider. + func (s *Structs) ReadBytes() ([]byte, error) { + return nil, errors.New("structs provider does not support this method") + } // Read reads the struct and returns a nested config map. + func (s *Structs) Read() (map[string]interface{}, error) { + ns := structs.New(s.s) + ns.TagName = s.tag out := ns.Map() if s.delim != "" { + out = maps.Unflatten(out, s.delim) + } return out, nil + } diff --git a/vendor/github.com/labstack/gommon/bytes/bytes.go b/vendor/github.com/labstack/gommon/bytes/bytes.go index b07e31c..9e1ba73 100644 --- a/vendor/github.com/labstack/gommon/bytes/bytes.go +++ b/vendor/github.com/labstack/gommon/bytes/bytes.go @@ -8,209 +8,364 @@ import ( ) type ( + // Bytes struct + Bytes struct{} ) // binary units (IEC 60027) + const ( _ = 1.0 << (10 * iota) // ignore first value by assigning to blank identifier + KiB + MiB + GiB + TiB + PiB + EiB ) // decimal units (SI international system of units) + const ( KB = 1000 + MB = KB * 1000 + GB = MB * 1000 + TB = GB * 1000 + PB = TB * 1000 + EB = PB * 1000 ) var ( - patternBinary = regexp.MustCompile(`(?i)^(-?\d+(?:\.\d+)?)\s?([KMGTPE]iB?)$`) + patternBinary = regexp.MustCompile(`(?i)^(-?\d+(?:\.\d+)?)\s?([KMGTPE]iB?)$`) + patternDecimal = regexp.MustCompile(`(?i)^(-?\d+(?:\.\d+)?)\s?([KMGTPE]B?|B?)$`) - global = New() + + global = New() ) // New creates a Bytes instance. + func New() *Bytes { + return &Bytes{} + } // Format formats bytes integer to human readable string according to IEC 60027. + // For example, 31323 bytes will return 30.59KB. + func (b *Bytes) Format(value int64) string { + return b.FormatBinary(value) + } // FormatBinary formats bytes integer to human readable string according to IEC 60027. + // For example, 31323 bytes will return 30.59KB. + func (*Bytes) FormatBinary(value int64) string { + multiple := "" + val := float64(value) switch { + case value >= EiB: + val /= EiB + multiple = "EiB" + case value >= PiB: + val /= PiB + multiple = "PiB" + case value >= TiB: + val /= TiB + multiple = "TiB" + case value >= GiB: + val /= GiB + multiple = "GiB" + case value >= MiB: + val /= MiB + multiple = "MiB" + case value >= KiB: + val /= KiB + multiple = "KiB" + case value == 0: + return "0" + default: + return strconv.FormatInt(value, 10) + "B" + } return fmt.Sprintf("%.2f%s", val, multiple) + } // FormatDecimal formats bytes integer to human readable string according to SI international system of units. + // For example, 31323 bytes will return 31.32KB. + func (*Bytes) FormatDecimal(value int64) string { + multiple := "" + val := float64(value) switch { + case value >= EB: + val /= EB + multiple = "EB" + case value >= PB: + val /= PB + multiple = "PB" + case value >= TB: + val /= TB + multiple = "TB" + case value >= GB: + val /= GB + multiple = "GB" + case value >= MB: + val /= MB + multiple = "MB" + case value >= KB: + val /= KB + multiple = "KB" + case value == 0: + return "0" + default: + return strconv.FormatInt(value, 10) + "B" + } return fmt.Sprintf("%.2f%s", val, multiple) + } // Parse parses human readable bytes string to bytes integer. + // For example, 6GiB (6Gi is also valid) will return 6442450944, and + // 6GB (6G is also valid) will return 6000000000. + func (b *Bytes) Parse(value string) (int64, error) { i, err := b.ParseBinary(value) + if err == nil { + return i, err + } return b.ParseDecimal(value) + } // ParseBinary parses human readable bytes string to bytes integer. + // For example, 6GiB (6Gi is also valid) will return 6442450944. + func (*Bytes) ParseBinary(value string) (i int64, err error) { + parts := patternBinary.FindStringSubmatch(value) + if len(parts) < 3 { + return 0, fmt.Errorf("error parsing value=%s", value) + } + bytesString := parts[1] + multiple := strings.ToUpper(parts[2]) + bytes, err := strconv.ParseFloat(bytesString, 64) + if err != nil { + return + } switch multiple { + case "KI", "KIB": + return int64(bytes * KiB), nil + case "MI", "MIB": + return int64(bytes * MiB), nil + case "GI", "GIB": + return int64(bytes * GiB), nil + case "TI", "TIB": + return int64(bytes * TiB), nil + case "PI", "PIB": + return int64(bytes * PiB), nil + case "EI", "EIB": + return int64(bytes * EiB), nil + default: + return int64(bytes), nil + } + } // ParseDecimal parses human readable bytes string to bytes integer. + // For example, 6GB (6G is also valid) will return 6000000000. + func (*Bytes) ParseDecimal(value string) (i int64, err error) { + parts := patternDecimal.FindStringSubmatch(value) + if len(parts) < 3 { + return 0, fmt.Errorf("error parsing value=%s", value) + } + bytesString := parts[1] + multiple := strings.ToUpper(parts[2]) + bytes, err := strconv.ParseFloat(bytesString, 64) + if err != nil { + return + } switch multiple { + case "K", "KB": + return int64(bytes * KB), nil + case "M", "MB": + return int64(bytes * MB), nil + case "G", "GB": + return int64(bytes * GB), nil + case "T", "TB": + return int64(bytes * TB), nil + case "P", "PB": + return int64(bytes * PB), nil + case "E", "EB": + return int64(bytes * EB), nil + default: + return int64(bytes), nil + } + } // Format wraps global Bytes's Format function. + func Format(value int64) string { + return global.Format(value) + } // FormatBinary wraps global Bytes's FormatBinary function. + func FormatBinary(value int64) string { + return global.FormatBinary(value) + } // FormatDecimal wraps global Bytes's FormatDecimal function. + func FormatDecimal(value int64) string { + return global.FormatDecimal(value) + } // Parse wraps global Bytes's Parse function. + func Parse(value string) (int64, error) { + return global.Parse(value) + } diff --git a/vendor/github.com/labstack/gommon/color/color.go b/vendor/github.com/labstack/gommon/color/color.go index 4131dcf..3ed3867 100644 --- a/vendor/github.com/labstack/gommon/color/color.go +++ b/vendor/github.com/labstack/gommon/color/color.go @@ -15,393 +15,628 @@ type ( ) // Color styles + const ( + // Blk Black text style + Blk = "30" + // Rd red text style + Rd = "31" + // Grn green text style + Grn = "32" + // Yel yellow text style + Yel = "33" + // Blu blue text style + Blu = "34" + // Mgn magenta text style + Mgn = "35" + // Cyn cyan text style + Cyn = "36" + // Wht white text style + Wht = "37" + // Gry grey text style + Gry = "90" // BlkBg black background style + BlkBg = "40" + // RdBg red background style + RdBg = "41" + // GrnBg green background style + GrnBg = "42" + // YelBg yellow background style + YelBg = "43" + // BluBg blue background style + BluBg = "44" + // MgnBg magenta background style + MgnBg = "45" + // CynBg cyan background style + CynBg = "46" + // WhtBg white background style + WhtBg = "47" // R reset emphasis style + R = "0" + // B bold emphasis style + B = "1" + // D dim emphasis style + D = "2" + // I italic emphasis style + I = "3" + // U underline emphasis style + U = "4" + // In inverse emphasis style + In = "7" + // H hidden emphasis style + H = "8" + // S strikeout emphasis style + S = "9" ) var ( - black = outer(Blk) - red = outer(Rd) - green = outer(Grn) - yellow = outer(Yel) - blue = outer(Blu) + black = outer(Blk) + + red = outer(Rd) + + green = outer(Grn) + + yellow = outer(Yel) + + blue = outer(Blu) + magenta = outer(Mgn) - cyan = outer(Cyn) - white = outer(Wht) - grey = outer(Gry) - blackBg = outer(BlkBg) - redBg = outer(RdBg) - greenBg = outer(GrnBg) - yellowBg = outer(YelBg) - blueBg = outer(BluBg) + cyan = outer(Cyn) + + white = outer(Wht) + + grey = outer(Gry) + + blackBg = outer(BlkBg) + + redBg = outer(RdBg) + + greenBg = outer(GrnBg) + + yellowBg = outer(YelBg) + + blueBg = outer(BluBg) + magentaBg = outer(MgnBg) - cyanBg = outer(CynBg) - whiteBg = outer(WhtBg) - reset = outer(R) - bold = outer(B) - dim = outer(D) - italic = outer(I) + cyanBg = outer(CynBg) + + whiteBg = outer(WhtBg) + + reset = outer(R) + + bold = outer(B) + + dim = outer(D) + + italic = outer(I) + underline = outer(U) - inverse = outer(In) - hidden = outer(H) + + inverse = outer(In) + + hidden = outer(H) + strikeout = outer(S) global = New() ) func outer(n string) inner { + return func(msg interface{}, styles []string, c *Color) string { + // TODO: Drop fmt to boost performance? + if c.disabled { + return fmt.Sprintf("%v", msg) + } b := new(bytes.Buffer) + b.WriteString("\x1b[") + b.WriteString(n) + for _, s := range styles { + b.WriteString(";") + b.WriteString(s) + } + b.WriteString("m") + return fmt.Sprintf("%s%v\x1b[0m", b.String(), msg) + } + } type ( Color struct { - output io.Writer + output io.Writer + disabled bool } ) // New creates a Color instance. + func New() (c *Color) { + c = new(Color) + c.SetOutput(colorable.NewColorableStdout()) + return + } // Output returns the output. + func (c *Color) Output() io.Writer { + return c.output + } // SetOutput sets the output. + func (c *Color) SetOutput(w io.Writer) { + c.output = w + if w, ok := w.(*os.File); !ok || !isatty.IsTerminal(w.Fd()) { + c.disabled = true + } + } // Disable disables the colors and styles. + func (c *Color) Disable() { + c.disabled = true + } // Enable enables the colors and styles. + func (c *Color) Enable() { + c.disabled = false + } // Print is analogous to `fmt.Print` with termial detection. + func (c *Color) Print(args ...interface{}) { + fmt.Fprint(c.output, args...) + } // Println is analogous to `fmt.Println` with termial detection. + func (c *Color) Println(args ...interface{}) { + fmt.Fprintln(c.output, args...) + } // Printf is analogous to `fmt.Printf` with termial detection. + func (c *Color) Printf(format string, args ...interface{}) { + fmt.Fprintf(c.output, format, args...) + } func (c *Color) Black(msg interface{}, styles ...string) string { + return black(msg, styles, c) + } func (c *Color) Red(msg interface{}, styles ...string) string { + return red(msg, styles, c) + } func (c *Color) Green(msg interface{}, styles ...string) string { + return green(msg, styles, c) + } func (c *Color) Yellow(msg interface{}, styles ...string) string { + return yellow(msg, styles, c) + } func (c *Color) Blue(msg interface{}, styles ...string) string { + return blue(msg, styles, c) + } func (c *Color) Magenta(msg interface{}, styles ...string) string { + return magenta(msg, styles, c) + } func (c *Color) Cyan(msg interface{}, styles ...string) string { + return cyan(msg, styles, c) + } func (c *Color) White(msg interface{}, styles ...string) string { + return white(msg, styles, c) + } func (c *Color) Grey(msg interface{}, styles ...string) string { + return grey(msg, styles, c) + } func (c *Color) BlackBg(msg interface{}, styles ...string) string { + return blackBg(msg, styles, c) + } func (c *Color) RedBg(msg interface{}, styles ...string) string { + return redBg(msg, styles, c) + } func (c *Color) GreenBg(msg interface{}, styles ...string) string { + return greenBg(msg, styles, c) + } func (c *Color) YellowBg(msg interface{}, styles ...string) string { + return yellowBg(msg, styles, c) + } func (c *Color) BlueBg(msg interface{}, styles ...string) string { + return blueBg(msg, styles, c) + } func (c *Color) MagentaBg(msg interface{}, styles ...string) string { + return magentaBg(msg, styles, c) + } func (c *Color) CyanBg(msg interface{}, styles ...string) string { + return cyanBg(msg, styles, c) + } func (c *Color) WhiteBg(msg interface{}, styles ...string) string { + return whiteBg(msg, styles, c) + } func (c *Color) Reset(msg interface{}, styles ...string) string { + return reset(msg, styles, c) + } func (c *Color) Bold(msg interface{}, styles ...string) string { + return bold(msg, styles, c) + } func (c *Color) Dim(msg interface{}, styles ...string) string { + return dim(msg, styles, c) + } func (c *Color) Italic(msg interface{}, styles ...string) string { + return italic(msg, styles, c) + } func (c *Color) Underline(msg interface{}, styles ...string) string { + return underline(msg, styles, c) + } func (c *Color) Inverse(msg interface{}, styles ...string) string { + return inverse(msg, styles, c) + } func (c *Color) Hidden(msg interface{}, styles ...string) string { + return hidden(msg, styles, c) + } func (c *Color) Strikeout(msg interface{}, styles ...string) string { + return strikeout(msg, styles, c) + } // Output returns the output. + func Output() io.Writer { + return global.output + } // SetOutput sets the output. + func SetOutput(w io.Writer) { + global.SetOutput(w) + } func Disable() { + global.Disable() + } func Enable() { + global.Enable() + } // Print is analogous to `fmt.Print` with termial detection. + func Print(args ...interface{}) { + global.Print(args...) + } // Println is analogous to `fmt.Println` with termial detection. + func Println(args ...interface{}) { + global.Println(args...) + } // Printf is analogous to `fmt.Printf` with termial detection. + func Printf(format string, args ...interface{}) { + global.Printf(format, args...) + } func Black(msg interface{}, styles ...string) string { + return global.Black(msg, styles...) + } func Red(msg interface{}, styles ...string) string { + return global.Red(msg, styles...) + } func Green(msg interface{}, styles ...string) string { + return global.Green(msg, styles...) + } func Yellow(msg interface{}, styles ...string) string { + return global.Yellow(msg, styles...) + } func Blue(msg interface{}, styles ...string) string { + return global.Blue(msg, styles...) + } func Magenta(msg interface{}, styles ...string) string { + return global.Magenta(msg, styles...) + } func Cyan(msg interface{}, styles ...string) string { + return global.Cyan(msg, styles...) + } func White(msg interface{}, styles ...string) string { + return global.White(msg, styles...) + } func Grey(msg interface{}, styles ...string) string { + return global.Grey(msg, styles...) + } func BlackBg(msg interface{}, styles ...string) string { + return global.BlackBg(msg, styles...) + } func RedBg(msg interface{}, styles ...string) string { + return global.RedBg(msg, styles...) + } func GreenBg(msg interface{}, styles ...string) string { + return global.GreenBg(msg, styles...) + } func YellowBg(msg interface{}, styles ...string) string { + return global.YellowBg(msg, styles...) + } func BlueBg(msg interface{}, styles ...string) string { + return global.BlueBg(msg, styles...) + } func MagentaBg(msg interface{}, styles ...string) string { + return global.MagentaBg(msg, styles...) + } func CyanBg(msg interface{}, styles ...string) string { + return global.CyanBg(msg, styles...) + } func WhiteBg(msg interface{}, styles ...string) string { + return global.WhiteBg(msg, styles...) + } func Reset(msg interface{}, styles ...string) string { + return global.Reset(msg, styles...) + } func Bold(msg interface{}, styles ...string) string { + return global.Bold(msg, styles...) + } func Dim(msg interface{}, styles ...string) string { + return global.Dim(msg, styles...) + } func Italic(msg interface{}, styles ...string) string { + return global.Italic(msg, styles...) + } func Underline(msg interface{}, styles ...string) string { + return global.Underline(msg, styles...) + } func Inverse(msg interface{}, styles ...string) string { + return global.Inverse(msg, styles...) + } func Hidden(msg interface{}, styles ...string) string { + return global.Hidden(msg, styles...) + } func Strikeout(msg interface{}, styles ...string) string { + return global.Strikeout(msg, styles...) + } diff --git a/vendor/github.com/labstack/gommon/log/color.go b/vendor/github.com/labstack/gommon/log/color.go index 84fa274..acfe4d8 100644 --- a/vendor/github.com/labstack/gommon/log/color.go +++ b/vendor/github.com/labstack/gommon/log/color.go @@ -10,5 +10,7 @@ import ( ) func output() io.Writer { + return colorable.NewColorableStdout() + } diff --git a/vendor/github.com/labstack/gommon/log/log.go b/vendor/github.com/labstack/gommon/log/log.go index e840be3..d18b67a 100644 --- a/vendor/github.com/labstack/gommon/log/log.go +++ b/vendor/github.com/labstack/gommon/log/log.go @@ -20,15 +20,23 @@ import ( type ( Logger struct { - prefix string - level uint32 - skip int - output io.Writer - template *fasttemplate.Template - levels []string - color *color.Color + prefix string + + level uint32 + + skip int + + output io.Writer + + template *fasttemplate.Template + + levels []string + + color *color.Color + bufferPool sync.Pool - mutex sync.Mutex + + mutex sync.Mutex } Lvl uint8 @@ -38,380 +46,611 @@ type ( const ( DEBUG Lvl = iota + 1 + INFO + WARN + ERROR + OFF + panicLevel + fatalLevel ) var ( - global = New("-") + global = New("-") + defaultHeader = `{"time":"${time_rfc3339_nano}","level":"${level}","prefix":"${prefix}",` + + `"file":"${short_file}","line":"${line}"}` ) func init() { + global.skip = 3 + } func New(prefix string) (l *Logger) { + l = &Logger{ - level: uint32(INFO), - skip: 2, - prefix: prefix, + + level: uint32(INFO), + + skip: 2, + + prefix: prefix, + template: l.newTemplate(defaultHeader), - color: color.New(), + + color: color.New(), + bufferPool: sync.Pool{ + New: func() interface{} { + return bytes.NewBuffer(make([]byte, 256)) + }, }, } + l.initLevels() + l.SetOutput(output()) + return + } func (l *Logger) initLevels() { + l.levels = []string{ + "-", + l.color.Blue("DEBUG"), + l.color.Green("INFO"), + l.color.Yellow("WARN"), + l.color.Red("ERROR"), + "", + l.color.Yellow("PANIC", color.U), + l.color.Red("FATAL", color.U), } + } func (l *Logger) newTemplate(format string) *fasttemplate.Template { + return fasttemplate.New(format, "${", "}") + } func (l *Logger) DisableColor() { + l.color.Disable() + l.initLevels() + } func (l *Logger) EnableColor() { + l.color.Enable() + l.initLevels() + } func (l *Logger) Prefix() string { + return l.prefix + } func (l *Logger) SetPrefix(p string) { + l.prefix = p + } func (l *Logger) Level() Lvl { + return Lvl(atomic.LoadUint32(&l.level)) + } func (l *Logger) SetLevel(level Lvl) { + atomic.StoreUint32(&l.level, uint32(level)) + } func (l *Logger) Output() io.Writer { + return l.output + } func (l *Logger) SetOutput(w io.Writer) { + l.output = w + if w, ok := w.(*os.File); !ok || !isatty.IsTerminal(w.Fd()) { + l.DisableColor() + } + } func (l *Logger) Color() *color.Color { + return l.color + } func (l *Logger) SetHeader(h string) { + l.template = l.newTemplate(h) + } func (l *Logger) Print(i ...interface{}) { + l.log(0, "", i...) + // fmt.Fprintln(l.output, i...) + } func (l *Logger) Printf(format string, args ...interface{}) { + l.log(0, format, args...) + } func (l *Logger) Printj(j JSON) { + l.log(0, "json", j) + } func (l *Logger) Debug(i ...interface{}) { + l.log(DEBUG, "", i...) + } func (l *Logger) Debugf(format string, args ...interface{}) { + l.log(DEBUG, format, args...) + } func (l *Logger) Debugj(j JSON) { + l.log(DEBUG, "json", j) + } func (l *Logger) Info(i ...interface{}) { + l.log(INFO, "", i...) + } func (l *Logger) Infof(format string, args ...interface{}) { + l.log(INFO, format, args...) + } func (l *Logger) Infoj(j JSON) { + l.log(INFO, "json", j) + } func (l *Logger) Warn(i ...interface{}) { + l.log(WARN, "", i...) + } func (l *Logger) Warnf(format string, args ...interface{}) { + l.log(WARN, format, args...) + } func (l *Logger) Warnj(j JSON) { + l.log(WARN, "json", j) + } func (l *Logger) Error(i ...interface{}) { + l.log(ERROR, "", i...) + } func (l *Logger) Errorf(format string, args ...interface{}) { + l.log(ERROR, format, args...) + } func (l *Logger) Errorj(j JSON) { + l.log(ERROR, "json", j) + } func (l *Logger) Fatal(i ...interface{}) { + l.log(fatalLevel, "", i...) + os.Exit(1) + } func (l *Logger) Fatalf(format string, args ...interface{}) { + l.log(fatalLevel, format, args...) + os.Exit(1) + } func (l *Logger) Fatalj(j JSON) { + l.log(fatalLevel, "json", j) + os.Exit(1) + } func (l *Logger) Panic(i ...interface{}) { + l.log(panicLevel, "", i...) + panic(fmt.Sprint(i...)) + } func (l *Logger) Panicf(format string, args ...interface{}) { + l.log(panicLevel, format, args...) + panic(fmt.Sprintf(format, args...)) + } func (l *Logger) Panicj(j JSON) { + l.log(panicLevel, "json", j) + panic(j) + } func DisableColor() { + global.DisableColor() + } func EnableColor() { + global.EnableColor() + } func Prefix() string { + return global.Prefix() + } func SetPrefix(p string) { + global.SetPrefix(p) + } func Level() Lvl { + return global.Level() + } func SetLevel(level Lvl) { + global.SetLevel(level) + } func Output() io.Writer { + return global.Output() + } func SetOutput(w io.Writer) { + global.SetOutput(w) + } func SetHeader(h string) { + global.SetHeader(h) + } func Print(i ...interface{}) { + global.Print(i...) + } func Printf(format string, args ...interface{}) { + global.Printf(format, args...) + } func Printj(j JSON) { + global.Printj(j) + } func Debug(i ...interface{}) { + global.Debug(i...) + } func Debugf(format string, args ...interface{}) { + global.Debugf(format, args...) + } func Debugj(j JSON) { + global.Debugj(j) + } func Info(i ...interface{}) { + global.Info(i...) + } func Infof(format string, args ...interface{}) { + global.Infof(format, args...) + } func Infoj(j JSON) { + global.Infoj(j) + } func Warn(i ...interface{}) { + global.Warn(i...) + } func Warnf(format string, args ...interface{}) { + global.Warnf(format, args...) + } func Warnj(j JSON) { + global.Warnj(j) + } func Error(i ...interface{}) { + global.Error(i...) + } func Errorf(format string, args ...interface{}) { + global.Errorf(format, args...) + } func Errorj(j JSON) { + global.Errorj(j) + } func Fatal(i ...interface{}) { + global.Fatal(i...) + } func Fatalf(format string, args ...interface{}) { + global.Fatalf(format, args...) + } func Fatalj(j JSON) { + global.Fatalj(j) + } func Panic(i ...interface{}) { + global.Panic(i...) + } func Panicf(format string, args ...interface{}) { + global.Panicf(format, args...) + } func Panicj(j JSON) { + global.Panicj(j) + } func (l *Logger) log(level Lvl, format string, args ...interface{}) { + if level >= l.Level() || level == 0 { + buf := l.bufferPool.Get().(*bytes.Buffer) + buf.Reset() + defer l.bufferPool.Put(buf) + _, file, line, _ := runtime.Caller(l.skip) + message := "" if format == "" { + message = fmt.Sprint(args...) + } else if format == "json" { + b, err := json.Marshal(args[0]) + if err != nil { + panic(err) + } + message = string(b) + } else { + message = fmt.Sprintf(format, args...) + } _, err := l.template.ExecuteFunc(buf, func(w io.Writer, tag string) (int, error) { + switch tag { + case "time_rfc3339": + return w.Write([]byte(time.Now().Format(time.RFC3339))) + case "time_rfc3339_nano": + return w.Write([]byte(time.Now().Format(time.RFC3339Nano))) + case "level": + return w.Write([]byte(l.levels[level])) + case "prefix": + return w.Write([]byte(l.prefix)) + case "long_file": + return w.Write([]byte(file)) + case "short_file": + return w.Write([]byte(path.Base(file))) + case "line": + return w.Write([]byte(strconv.Itoa(line))) + } + return 0, nil + }) if err == nil { + s := buf.String() + i := buf.Len() - 1 + if i >= 0 && s[i] == '}' { + // JSON header + buf.Truncate(i) + buf.WriteByte(',') + if format == "json" { + buf.WriteString(message[1:]) + } else { + buf.WriteString(`"message":`) + buf.WriteString(strconv.Quote(message)) + buf.WriteString(`}`) + } + } else { + // Text header + if len(s) > 0 { + buf.WriteByte(' ') + } + buf.WriteString(message) + } + buf.WriteByte('\n') + l.mutex.Lock() + defer l.mutex.Unlock() + l.output.Write(buf.Bytes()) + } + } + } diff --git a/vendor/github.com/labstack/gommon/log/white.go b/vendor/github.com/labstack/gommon/log/white.go index cf0c27c..89a9d31 100644 --- a/vendor/github.com/labstack/gommon/log/white.go +++ b/vendor/github.com/labstack/gommon/log/white.go @@ -9,5 +9,7 @@ import ( ) func output() io.Writer { + return os.Stdout + } diff --git a/vendor/github.com/mailru/easyjson/buffer/pool.go b/vendor/github.com/mailru/easyjson/buffer/pool.go index 598a54a..b728a52 100644 --- a/vendor/github.com/mailru/easyjson/buffer/pool.go +++ b/vendor/github.com/mailru/easyjson/buffer/pool.go @@ -1,5 +1,7 @@ // Package buffer implements a buffer for serialization, consisting of a chain of []byte-s to + // reduce copying and to allow reuse of individual chunks. + package buffer import ( @@ -9,270 +11,446 @@ import ( ) // PoolConfig contains configuration for the allocation and reuse strategy. + type PoolConfig struct { - StartSize int // Minimum chunk size that is allocated. + StartSize int // Minimum chunk size that is allocated. + PooledSize int // Minimum chunk size that is reused, reusing chunks too small will result in overhead. - MaxSize int // Maximum chunk size that will be allocated. + + MaxSize int // Maximum chunk size that will be allocated. + } var config = PoolConfig{ - StartSize: 128, + + StartSize: 128, + PooledSize: 512, - MaxSize: 32768, + + MaxSize: 32768, } // Reuse pool: chunk size -> pool. + var buffers = map[int]*sync.Pool{} func initBuffers() { + for l := config.PooledSize; l <= config.MaxSize; l *= 2 { + buffers[l] = new(sync.Pool) + } + } func init() { + initBuffers() + } // Init sets up a non-default pooling and allocation strategy. Should be run before serialization is done. + func Init(cfg PoolConfig) { + config = cfg + initBuffers() + } // putBuf puts a chunk to reuse pool if it can be reused. + func putBuf(buf []byte) { + size := cap(buf) + if size < config.PooledSize { + return + } + if c := buffers[size]; c != nil { + c.Put(buf[:0]) + } + } // getBuf gets a chunk from reuse pool or creates a new one if reuse failed. + func getBuf(size int) []byte { + if size >= config.PooledSize { + if c := buffers[size]; c != nil { + v := c.Get() + if v != nil { + return v.([]byte) + } + } + } + return make([]byte, 0, size) + } // Buffer is a buffer optimized for serialization without extra copying. + type Buffer struct { // Buf is the current chunk that can be used for serialization. + Buf []byte toPool []byte - bufs [][]byte + + bufs [][]byte } // EnsureSpace makes sure that the current chunk contains at least s free bytes, + // possibly creating a new chunk. + func (b *Buffer) EnsureSpace(s int) { + if cap(b.Buf)-len(b.Buf) < s { + b.ensureSpaceSlow(s) + } + } func (b *Buffer) ensureSpaceSlow(s int) { + l := len(b.Buf) + if l > 0 { + if cap(b.toPool) != cap(b.Buf) { + // Chunk was reallocated, toPool can be pooled. + putBuf(b.toPool) + } + if cap(b.bufs) == 0 { + b.bufs = make([][]byte, 0, 8) + } + b.bufs = append(b.bufs, b.Buf) + l = cap(b.toPool) * 2 + } else { + l = config.StartSize + } if l > config.MaxSize { + l = config.MaxSize + } + b.Buf = getBuf(l) + b.toPool = b.Buf + } // AppendByte appends a single byte to buffer. + func (b *Buffer) AppendByte(data byte) { + b.EnsureSpace(1) + b.Buf = append(b.Buf, data) + } // AppendBytes appends a byte slice to buffer. + func (b *Buffer) AppendBytes(data []byte) { + if len(data) <= cap(b.Buf)-len(b.Buf) { + b.Buf = append(b.Buf, data...) // fast path + } else { + b.appendBytesSlow(data) + } + } func (b *Buffer) appendBytesSlow(data []byte) { + for len(data) > 0 { + b.EnsureSpace(1) sz := cap(b.Buf) - len(b.Buf) + if sz > len(data) { + sz = len(data) + } b.Buf = append(b.Buf, data[:sz]...) + data = data[sz:] + } + } // AppendString appends a string to buffer. + func (b *Buffer) AppendString(data string) { + if len(data) <= cap(b.Buf)-len(b.Buf) { + b.Buf = append(b.Buf, data...) // fast path + } else { + b.appendStringSlow(data) + } + } func (b *Buffer) appendStringSlow(data string) { + for len(data) > 0 { + b.EnsureSpace(1) sz := cap(b.Buf) - len(b.Buf) + if sz > len(data) { + sz = len(data) + } b.Buf = append(b.Buf, data[:sz]...) + data = data[sz:] + } + } // Size computes the size of a buffer by adding sizes of every chunk. + func (b *Buffer) Size() int { + size := len(b.Buf) + for _, buf := range b.bufs { + size += len(buf) + } + return size + } // DumpTo outputs the contents of a buffer to a writer and resets the buffer. + func (b *Buffer) DumpTo(w io.Writer) (written int, err error) { + bufs := net.Buffers(b.bufs) + if len(b.Buf) > 0 { + bufs = append(bufs, b.Buf) + } + n, err := bufs.WriteTo(w) for _, buf := range b.bufs { + putBuf(buf) + } + putBuf(b.toPool) b.bufs = nil + b.Buf = nil + b.toPool = nil return int(n), err + } // BuildBytes creates a single byte slice with all the contents of the buffer. Data is + // copied if it does not fit in a single chunk. You can optionally provide one byte + // slice as argument that it will try to reuse. + func (b *Buffer) BuildBytes(reuse ...[]byte) []byte { + if len(b.bufs) == 0 { + ret := b.Buf + b.toPool = nil + b.Buf = nil + return ret + } var ret []byte + size := b.Size() // If we got a buffer as argument and it is big enough, reuse it. + if len(reuse) == 1 && cap(reuse[0]) >= size { + ret = reuse[0][:0] + } else { + ret = make([]byte, 0, size) + } + for _, buf := range b.bufs { + ret = append(ret, buf...) + putBuf(buf) + } ret = append(ret, b.Buf...) + putBuf(b.toPool) b.bufs = nil + b.toPool = nil + b.Buf = nil return ret + } type readCloser struct { offset int - bufs [][]byte + + bufs [][]byte } func (r *readCloser) Read(p []byte) (n int, err error) { + for _, buf := range r.bufs { + // Copy as much as we can. + x := copy(p[n:], buf[r.offset:]) + n += x // Increment how much we filled. // Did we empty the whole buffer? + if r.offset+x == len(buf) { + // On to the next buffer. + r.offset = 0 + r.bufs = r.bufs[1:] // We can release this buffer. + putBuf(buf) + } else { + r.offset += x + } if n == len(p) { + break + } + } + // No buffers left or nothing read? + if len(r.bufs) == 0 { + err = io.EOF + } + return + } func (r *readCloser) Close() error { + // Release all remaining buffers. + for _, buf := range r.bufs { + putBuf(buf) + } + // In case Close gets called multiple times. + r.bufs = nil return nil + } // ReadCloser creates an io.ReadCloser with all the contents of the buffer. + func (b *Buffer) ReadCloser() io.ReadCloser { + ret := &readCloser{0, append(b.bufs, b.Buf)} b.bufs = nil + b.toPool = nil + b.Buf = nil return ret + } diff --git a/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go b/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go index 87f7fb7..f6215f8 100644 --- a/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go +++ b/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go @@ -1,5 +1,7 @@ // This file will only be included to the build if neither + // easyjson_nounsafe nor appengine build tag is set. See README notes + // for more details. //go:build !easyjson_nounsafe && !appengine @@ -13,12 +15,21 @@ import ( ) // bytesToStr creates a string pointing at the slice to avoid copying. + // + // Warning: the string returned by the function should be used with care, as the whole input data + // chunk may be either blocked from being freed by GC because of a single string or the buffer.Data + // may be garbage-collected even when the string exists. + func bytesToStr(data []byte) string { + h := (*reflect.SliceHeader)(unsafe.Pointer(&data)) + shdr := reflect.StringHeader{Data: h.Data, Len: h.Len} + return *(*string)(unsafe.Pointer(&shdr)) + } diff --git a/vendor/github.com/mailru/easyjson/jlexer/lexer.go b/vendor/github.com/mailru/easyjson/jlexer/lexer.go index b5f5e26..12a9b76 100644 --- a/vendor/github.com/mailru/easyjson/jlexer/lexer.go +++ b/vendor/github.com/mailru/easyjson/jlexer/lexer.go @@ -1,7 +1,11 @@ // Package jlexer contains a JSON lexer implementation. + // + // It is expected that it is mostly used with generated parser code, so the interface is tuned + // for a parser that knows what kind of data is expected. + package jlexer import ( @@ -20,1225 +24,2123 @@ import ( ) // tokenKind determines type of a token. + type tokenKind byte const ( - tokenUndef tokenKind = iota // No token. - tokenDelim // Delimiter: one of '{', '}', '[' or ']'. - tokenString // A string literal, e.g. "abc\u1234" - tokenNumber // Number literal, e.g. 1.5e5 - tokenBool // Boolean literal: true or false. - tokenNull // null keyword. + tokenUndef tokenKind = iota // No token. + + tokenDelim // Delimiter: one of '{', '}', '[' or ']'. + + tokenString // A string literal, e.g. "abc\u1234" + + tokenNumber // Number literal, e.g. 1.5e5 + + tokenBool // Boolean literal: true or false. + + tokenNull // null keyword. + ) // token describes a single token: type, position in the input and value. + type token struct { kind tokenKind // Type of a token. - boolValue bool // Value if a boolean literal token. - byteValueCloned bool // true if byteValue was allocated and does not refer to original json body - byteValue []byte // Raw value of a token. - delimValue byte + boolValue bool // Value if a boolean literal token. + + byteValueCloned bool // true if byteValue was allocated and does not refer to original json body + + byteValue []byte // Raw value of a token. + + delimValue byte } // Lexer is a JSON lexer: it iterates over JSON tokens in a byte slice. + type Lexer struct { Data []byte // Input data given to the lexer. - start int // Start of the current token. - pos int // Current unscanned position in the input stream. + start int // Start of the current token. + + pos int // Current unscanned position in the input stream. + token token // Last scanned token, if token.kind != tokenUndef. firstElement bool // Whether current element is the first in array or an object. - wantSep byte // A comma or a colon character, which need to occur before a token. - UseMultipleErrors bool // If we want to use multiple errors. - fatalError error // Fatal error occurred during lexing. It is usually a syntax error. - multipleErrors []*LexerError // Semantic errors occurred during lexing. Marshalling will be continued after finding this errors. + wantSep byte // A comma or a colon character, which need to occur before a token. + + UseMultipleErrors bool // If we want to use multiple errors. + + fatalError error // Fatal error occurred during lexing. It is usually a syntax error. + + multipleErrors []*LexerError // Semantic errors occurred during lexing. Marshalling will be continued after finding this errors. + } // FetchToken scans the input for the next token. + func (r *Lexer) FetchToken() { + r.token.kind = tokenUndef + r.start = r.pos // Check if r.Data has r.pos element + // If it doesn't, it mean corrupted input data + if len(r.Data) < r.pos { + r.errParse("Unexpected end of data") + return + } + // Determine the type of a token by skipping whitespace and reading the + // first character. + for _, c := range r.Data[r.pos:] { + switch c { + case ':', ',': + if r.wantSep == c { + r.pos++ + r.start++ + r.wantSep = 0 + } else { + r.errSyntax() + } case ' ', '\t', '\r', '\n': + r.pos++ + r.start++ case '"': + if r.wantSep != 0 { + r.errSyntax() + } r.token.kind = tokenString + r.fetchString() + return case '{', '[': + if r.wantSep != 0 { + r.errSyntax() + } + r.firstElement = true + r.token.kind = tokenDelim + r.token.delimValue = r.Data[r.pos] + r.pos++ + return case '}', ']': + if !r.firstElement && (r.wantSep != ',') { + r.errSyntax() + } + r.wantSep = 0 + r.token.kind = tokenDelim + r.token.delimValue = r.Data[r.pos] + r.pos++ + return case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-': + if r.wantSep != 0 { + r.errSyntax() + } + r.token.kind = tokenNumber + r.fetchNumber() + return case 'n': + if r.wantSep != 0 { + r.errSyntax() + } r.token.kind = tokenNull + r.fetchNull() + return case 't': + if r.wantSep != 0 { + r.errSyntax() + } r.token.kind = tokenBool + r.token.boolValue = true + r.fetchTrue() + return case 'f': + if r.wantSep != 0 { + r.errSyntax() + } r.token.kind = tokenBool + r.token.boolValue = false + r.fetchFalse() + return default: + r.errSyntax() + return + } + } + r.fatalError = io.EOF + return + } // isTokenEnd returns true if the char can follow a non-delimiter token + func isTokenEnd(c byte) bool { + return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '[' || c == ']' || c == '{' || c == '}' || c == ',' || c == ':' + } // fetchNull fetches and checks remaining bytes of null keyword. + func (r *Lexer) fetchNull() { + r.pos += 4 + if r.pos > len(r.Data) || + r.Data[r.pos-3] != 'u' || + r.Data[r.pos-2] != 'l' || + r.Data[r.pos-1] != 'l' || + (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { r.pos -= 4 + r.errSyntax() + } + } // fetchTrue fetches and checks remaining bytes of true keyword. + func (r *Lexer) fetchTrue() { + r.pos += 4 + if r.pos > len(r.Data) || + r.Data[r.pos-3] != 'r' || + r.Data[r.pos-2] != 'u' || + r.Data[r.pos-1] != 'e' || + (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { r.pos -= 4 + r.errSyntax() + } + } // fetchFalse fetches and checks remaining bytes of false keyword. + func (r *Lexer) fetchFalse() { + r.pos += 5 + if r.pos > len(r.Data) || + r.Data[r.pos-4] != 'a' || + r.Data[r.pos-3] != 'l' || + r.Data[r.pos-2] != 's' || + r.Data[r.pos-1] != 'e' || + (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { r.pos -= 5 + r.errSyntax() + } + } // fetchNumber scans a number literal token. + func (r *Lexer) fetchNumber() { + hasE := false + afterE := false + hasDot := false r.pos++ + for i, c := range r.Data[r.pos:] { + switch { + case c >= '0' && c <= '9': + afterE = false + case c == '.' && !hasDot: + hasDot = true + case (c == 'e' || c == 'E') && !hasE: + hasE = true + hasDot = true + afterE = true + case (c == '+' || c == '-') && afterE: + afterE = false + default: + r.pos += i + if !isTokenEnd(c) { + r.errSyntax() + } else { + r.token.byteValue = r.Data[r.start:r.pos] + } + return + } + } r.pos = len(r.Data) + r.token.byteValue = r.Data[r.start:] + } // findStringLen tries to scan into the string literal for ending quote char to determine required size. + // The size will be exact if no escapes are present and may be inexact if there are escaped chars. + func findStringLen(data []byte) (isValid bool, length int) { + for { + idx := bytes.IndexByte(data, '"') + if idx == -1 { + return false, len(data) + } + if idx == 0 || (idx > 0 && data[idx-1] != '\\') { + return true, length + idx + } // count \\\\\\\ sequences. even number of slashes means quote is not really escaped + cnt := 1 + for idx-cnt-1 >= 0 && data[idx-cnt-1] == '\\' { + cnt++ + } + if cnt%2 == 0 { + return true, length + idx + } length += idx + 1 + data = data[idx+1:] + } + } // unescapeStringToken performs unescaping of string token. + // if no escaping is needed, original string is returned, otherwise - a new one allocated + func (r *Lexer) unescapeStringToken() (err error) { + data := r.token.byteValue + var unescapedData []byte for { + i := bytes.IndexByte(data, '\\') + if i == -1 { + break + } escapedRune, escapedBytes, err := decodeEscape(data[i:]) + if err != nil { + r.errParse(err.Error()) + return err + } if unescapedData == nil { + unescapedData = make([]byte, 0, len(r.token.byteValue)) + } var d [4]byte + s := utf8.EncodeRune(d[:], escapedRune) + unescapedData = append(unescapedData, data[:i]...) + unescapedData = append(unescapedData, d[:s]...) data = data[i+escapedBytes:] + } if unescapedData != nil { + r.token.byteValue = append(unescapedData, data...) + r.token.byteValueCloned = true + } + return + } // getu4 decodes \uXXXX from the beginning of s, returning the hex value, + // or it returns -1. + func getu4(s []byte) rune { + if len(s) < 6 || s[0] != '\\' || s[1] != 'u' { + return -1 + } + var val rune + for i := 2; i < len(s) && i < 6; i++ { + var v byte + c := s[i] + switch c { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + v = c - '0' + case 'a', 'b', 'c', 'd', 'e', 'f': + v = c - 'a' + 10 + case 'A', 'B', 'C', 'D', 'E', 'F': + v = c - 'A' + 10 + default: + return -1 + } val <<= 4 + val |= rune(v) + } + return val + } // decodeEscape processes a single escape sequence and returns number of bytes processed. + func decodeEscape(data []byte) (decoded rune, bytesProcessed int, err error) { + if len(data) < 2 { + return 0, 0, errors.New("incorrect escape symbol \\ at the end of token") + } c := data[1] + switch c { + case '"', '/', '\\': + return rune(c), 2, nil + case 'b': + return '\b', 2, nil + case 'f': + return '\f', 2, nil + case 'n': + return '\n', 2, nil + case 'r': + return '\r', 2, nil + case 't': + return '\t', 2, nil + case 'u': + rr := getu4(data) + if rr < 0 { + return 0, 0, errors.New("incorrectly escaped \\uXXXX sequence") + } read := 6 + if utf16.IsSurrogate(rr) { + rr1 := getu4(data[read:]) + if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar { + read += 6 + rr = dec + } else { + rr = unicode.ReplacementChar + } + } + return rr, read, nil + } return 0, 0, errors.New("incorrectly escaped bytes") + } // fetchString scans a string literal token. + func (r *Lexer) fetchString() { + r.pos++ + data := r.Data[r.pos:] isValid, length := findStringLen(data) + if !isValid { + r.pos += length + r.errParse("unterminated string literal") + return + } + r.token.byteValue = data[:length] + r.pos += length + 1 // skip closing '"' as well + } // scanToken scans the next token if no token is currently available in the lexer. + func (r *Lexer) scanToken() { + if r.token.kind != tokenUndef || r.fatalError != nil { + return + } r.FetchToken() + } // consume resets the current token to allow scanning the next one. + func (r *Lexer) consume() { + r.token.kind = tokenUndef + r.token.byteValueCloned = false + r.token.delimValue = 0 + } // Ok returns true if no error (including io.EOF) was encountered during scanning. + func (r *Lexer) Ok() bool { + return r.fatalError == nil + } const maxErrorContextLen = 13 func (r *Lexer) errParse(what string) { + if r.fatalError == nil { + var str string + if len(r.Data)-r.pos <= maxErrorContextLen { + str = string(r.Data) + } else { + str = string(r.Data[r.pos:r.pos+maxErrorContextLen-3]) + "..." + } + r.fatalError = &LexerError{ + Reason: what, + Offset: r.pos, - Data: str, + + Data: str, } + } + } func (r *Lexer) errSyntax() { + r.errParse("syntax error") + } func (r *Lexer) errInvalidToken(expected string) { + if r.fatalError != nil { + return + } + if r.UseMultipleErrors { + r.pos = r.start + r.consume() + r.SkipRecursive() + switch expected { + case "[": + r.token.delimValue = ']' + r.token.kind = tokenDelim + case "{": + r.token.delimValue = '}' + r.token.kind = tokenDelim + } + r.addNonfatalError(&LexerError{ + Reason: fmt.Sprintf("expected %s", expected), + Offset: r.start, - Data: string(r.Data[r.start:r.pos]), + + Data: string(r.Data[r.start:r.pos]), }) + return + } var str string + if len(r.token.byteValue) <= maxErrorContextLen { + str = string(r.token.byteValue) + } else { + str = string(r.token.byteValue[:maxErrorContextLen-3]) + "..." + } + r.fatalError = &LexerError{ + Reason: fmt.Sprintf("expected %s", expected), + Offset: r.pos, - Data: str, + + Data: str, } + } func (r *Lexer) GetPos() int { + return r.pos + } // Delim consumes a token and verifies that it is the given delimiter. + func (r *Lexer) Delim(c byte) { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } if !r.Ok() || r.token.delimValue != c { + r.consume() // errInvalidToken can change token if UseMultipleErrors is enabled. + r.errInvalidToken(string([]byte{c})) + } else { + r.consume() + } + } // IsDelim returns true if there was no scanning error and next token is the given delimiter. + func (r *Lexer) IsDelim(c byte) bool { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + return !r.Ok() || r.token.delimValue == c + } // Null verifies that the next token is null and consumes it. + func (r *Lexer) Null() { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() || r.token.kind != tokenNull { + r.errInvalidToken("null") + } + r.consume() + } // IsNull returns true if the next token is a null keyword. + func (r *Lexer) IsNull() bool { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + return r.Ok() && r.token.kind == tokenNull + } // Skip skips a single token. + func (r *Lexer) Skip() { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + r.consume() + } // SkipRecursive skips next array or object completely, or just skips a single token if not + // an array/object. + // + // Note: no syntax validation is performed on the skipped data. + func (r *Lexer) SkipRecursive() { + r.scanToken() + var start, end byte + startPos := r.start switch r.token.delimValue { + case '{': + start, end = '{', '}' + case '[': + start, end = '[', ']' + default: + r.consume() + return + } r.consume() level := 1 + inQuotes := false + wasEscape := false for i, c := range r.Data[r.pos:] { + switch { + case c == start && !inQuotes: + level++ + case c == end && !inQuotes: + level-- + if level == 0 { + r.pos += i + 1 + if !json.Valid(r.Data[startPos:r.pos]) { + r.pos = len(r.Data) + r.fatalError = &LexerError{ + Reason: "skipped array/object json value is invalid", + Offset: r.pos, - Data: string(r.Data[r.pos:]), + + Data: string(r.Data[r.pos:]), } + } + return + } + case c == '\\' && inQuotes: + wasEscape = !wasEscape + continue + case c == '"' && inQuotes: + inQuotes = wasEscape + case c == '"': + inQuotes = true + } + wasEscape = false + } + r.pos = len(r.Data) + r.fatalError = &LexerError{ + Reason: "EOF reached while skipping array/object or token", + Offset: r.pos, - Data: string(r.Data[r.pos:]), + + Data: string(r.Data[r.pos:]), } + } // Raw fetches the next item recursively as a data slice + func (r *Lexer) Raw() []byte { + r.SkipRecursive() + if !r.Ok() { + return nil + } + return r.Data[r.start:r.pos] + } // IsStart returns whether the lexer is positioned at the start + // of an input string. + func (r *Lexer) IsStart() bool { + return r.pos == 0 + } // Consumed reads all remaining bytes from the input, publishing an error if + // there is anything but whitespace remaining. + func (r *Lexer) Consumed() { + if r.pos > len(r.Data) || !r.Ok() { + return + } for _, c := range r.Data[r.pos:] { + if c != ' ' && c != '\t' && c != '\r' && c != '\n' { + r.AddError(&LexerError{ + Reason: "invalid character '" + string(c) + "' after top-level value", + Offset: r.pos, - Data: string(r.Data[r.pos:]), + + Data: string(r.Data[r.pos:]), }) + return + } r.pos++ + r.start++ + } + } func (r *Lexer) unsafeString(skipUnescape bool) (string, []byte) { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() || r.token.kind != tokenString { + r.errInvalidToken("string") + return "", nil + } + if !skipUnescape { + if err := r.unescapeStringToken(); err != nil { + r.errInvalidToken("string") + return "", nil + } + } bytes := r.token.byteValue + ret := bytesToStr(r.token.byteValue) + r.consume() + return ret, bytes + } // UnsafeString returns the string value if the token is a string literal. + // + // Warning: returned string may point to the input buffer, so the string should not outlive + // the input buffer. Intended pattern of usage is as an argument to a switch statement. + func (r *Lexer) UnsafeString() string { + ret, _ := r.unsafeString(false) + return ret + } // UnsafeBytes returns the byte slice if the token is a string literal. + func (r *Lexer) UnsafeBytes() []byte { + _, ret := r.unsafeString(false) + return ret + } // UnsafeFieldName returns current member name string token + func (r *Lexer) UnsafeFieldName(skipUnescape bool) string { + ret, _ := r.unsafeString(skipUnescape) + return ret + } // String reads a string literal. + func (r *Lexer) String() string { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() || r.token.kind != tokenString { + r.errInvalidToken("string") + return "" + } + if err := r.unescapeStringToken(); err != nil { + r.errInvalidToken("string") + return "" + } + var ret string + if r.token.byteValueCloned { + ret = bytesToStr(r.token.byteValue) + } else { + ret = string(r.token.byteValue) + } + r.consume() + return ret + } // StringIntern reads a string literal, and performs string interning on it. + func (r *Lexer) StringIntern() string { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() || r.token.kind != tokenString { + r.errInvalidToken("string") + return "" + } + if err := r.unescapeStringToken(); err != nil { + r.errInvalidToken("string") + return "" + } + ret := intern.Bytes(r.token.byteValue) + r.consume() + return ret + } // Bytes reads a string literal and base64 decodes it into a byte slice. + func (r *Lexer) Bytes() []byte { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() || r.token.kind != tokenString { + r.errInvalidToken("string") + return nil + } + if err := r.unescapeStringToken(); err != nil { + r.errInvalidToken("string") + return nil + } + ret := make([]byte, base64.StdEncoding.DecodedLen(len(r.token.byteValue))) + n, err := base64.StdEncoding.Decode(ret, r.token.byteValue) + if err != nil { + r.fatalError = &LexerError{ + Reason: err.Error(), } + return nil + } r.consume() + return ret[:n] + } // Bool reads a true or false boolean keyword. + func (r *Lexer) Bool() bool { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() || r.token.kind != tokenBool { + r.errInvalidToken("bool") + return false + } + ret := r.token.boolValue + r.consume() + return ret + } func (r *Lexer) number() string { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() || r.token.kind != tokenNumber { + r.errInvalidToken("number") + return "" + } + ret := bytesToStr(r.token.byteValue) + r.consume() + return ret + } func (r *Lexer) Uint8() uint8 { + s := r.number() + if !r.Ok() { + return 0 + } n, err := strconv.ParseUint(s, 10, 8) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), - Data: s, + + Data: s, }) + } + return uint8(n) + } func (r *Lexer) Uint16() uint16 { + s := r.number() + if !r.Ok() { + return 0 + } n, err := strconv.ParseUint(s, 10, 16) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), - Data: s, + + Data: s, }) + } + return uint16(n) + } func (r *Lexer) Uint32() uint32 { + s := r.number() + if !r.Ok() { + return 0 + } n, err := strconv.ParseUint(s, 10, 32) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), - Data: s, + + Data: s, }) + } + return uint32(n) + } func (r *Lexer) Uint64() uint64 { + s := r.number() + if !r.Ok() { + return 0 + } n, err := strconv.ParseUint(s, 10, 64) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), - Data: s, + + Data: s, }) + } + return n + } func (r *Lexer) Uint() uint { + return uint(r.Uint64()) + } func (r *Lexer) Int8() int8 { + s := r.number() + if !r.Ok() { + return 0 + } n, err := strconv.ParseInt(s, 10, 8) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), - Data: s, + + Data: s, }) + } + return int8(n) + } func (r *Lexer) Int16() int16 { + s := r.number() + if !r.Ok() { + return 0 + } n, err := strconv.ParseInt(s, 10, 16) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), - Data: s, + + Data: s, }) + } + return int16(n) + } func (r *Lexer) Int32() int32 { + s := r.number() + if !r.Ok() { + return 0 + } n, err := strconv.ParseInt(s, 10, 32) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), - Data: s, + + Data: s, }) + } + return int32(n) + } func (r *Lexer) Int64() int64 { + s := r.number() + if !r.Ok() { + return 0 + } n, err := strconv.ParseInt(s, 10, 64) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), - Data: s, + + Data: s, }) + } + return n + } func (r *Lexer) Int() int { + return int(r.Int64()) + } func (r *Lexer) Uint8Str() uint8 { + s, b := r.unsafeString(false) + if !r.Ok() { + return 0 + } n, err := strconv.ParseUint(s, 10, 8) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), - Data: string(b), + + Data: string(b), }) + } + return uint8(n) + } func (r *Lexer) Uint16Str() uint16 { + s, b := r.unsafeString(false) + if !r.Ok() { + return 0 + } n, err := strconv.ParseUint(s, 10, 16) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), - Data: string(b), + + Data: string(b), }) + } + return uint16(n) + } func (r *Lexer) Uint32Str() uint32 { + s, b := r.unsafeString(false) + if !r.Ok() { + return 0 + } n, err := strconv.ParseUint(s, 10, 32) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), - Data: string(b), + + Data: string(b), }) + } + return uint32(n) + } func (r *Lexer) Uint64Str() uint64 { + s, b := r.unsafeString(false) + if !r.Ok() { + return 0 + } n, err := strconv.ParseUint(s, 10, 64) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), - Data: string(b), + + Data: string(b), }) + } + return n + } func (r *Lexer) UintStr() uint { + return uint(r.Uint64Str()) + } func (r *Lexer) UintptrStr() uintptr { + return uintptr(r.Uint64Str()) + } func (r *Lexer) Int8Str() int8 { + s, b := r.unsafeString(false) + if !r.Ok() { + return 0 + } n, err := strconv.ParseInt(s, 10, 8) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), - Data: string(b), + + Data: string(b), }) + } + return int8(n) + } func (r *Lexer) Int16Str() int16 { + s, b := r.unsafeString(false) + if !r.Ok() { + return 0 + } n, err := strconv.ParseInt(s, 10, 16) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), - Data: string(b), + + Data: string(b), }) + } + return int16(n) + } func (r *Lexer) Int32Str() int32 { + s, b := r.unsafeString(false) + if !r.Ok() { + return 0 + } n, err := strconv.ParseInt(s, 10, 32) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), - Data: string(b), + + Data: string(b), }) + } + return int32(n) + } func (r *Lexer) Int64Str() int64 { + s, b := r.unsafeString(false) + if !r.Ok() { + return 0 + } n, err := strconv.ParseInt(s, 10, 64) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), - Data: string(b), + + Data: string(b), }) + } + return n + } func (r *Lexer) IntStr() int { + return int(r.Int64Str()) + } func (r *Lexer) Float32() float32 { + s := r.number() + if !r.Ok() { + return 0 + } n, err := strconv.ParseFloat(s, 32) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), - Data: s, + + Data: s, }) + } + return float32(n) + } func (r *Lexer) Float32Str() float32 { + s, b := r.unsafeString(false) + if !r.Ok() { + return 0 + } + n, err := strconv.ParseFloat(s, 32) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), - Data: string(b), + + Data: string(b), }) + } + return float32(n) + } func (r *Lexer) Float64() float64 { + s := r.number() + if !r.Ok() { + return 0 + } n, err := strconv.ParseFloat(s, 64) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), - Data: s, + + Data: s, }) + } + return n + } func (r *Lexer) Float64Str() float64 { + s, b := r.unsafeString(false) + if !r.Ok() { + return 0 + } + n, err := strconv.ParseFloat(s, 64) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), - Data: string(b), + + Data: string(b), }) + } + return n + } func (r *Lexer) Error() error { + return r.fatalError + } func (r *Lexer) AddError(e error) { + if r.fatalError == nil { + r.fatalError = e + } + } func (r *Lexer) AddNonFatalError(e error) { + r.addNonfatalError(&LexerError{ + Offset: r.start, - Data: string(r.Data[r.start:r.pos]), + + Data: string(r.Data[r.start:r.pos]), + Reason: e.Error(), }) + } func (r *Lexer) addNonfatalError(err *LexerError) { + if r.UseMultipleErrors { + // We don't want to add errors with the same offset. + if len(r.multipleErrors) != 0 && r.multipleErrors[len(r.multipleErrors)-1].Offset == err.Offset { + return + } + r.multipleErrors = append(r.multipleErrors, err) + return + } + r.fatalError = err + } func (r *Lexer) GetNonFatalErrors() []*LexerError { + return r.multipleErrors + } // JsonNumber fetches and json.Number from 'encoding/json' package. + // Both int, float or string, contains them are valid values + func (r *Lexer) JsonNumber() json.Number { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() { + r.errInvalidToken("json.Number") + return json.Number("") + } switch r.token.kind { + case tokenString: + return json.Number(r.String()) + case tokenNumber: + return json.Number(r.Raw()) + case tokenNull: + r.Null() + return json.Number("") + default: + r.errSyntax() + return json.Number("") + } + } // Interface fetches an interface{} analogous to the 'encoding/json' package. + func (r *Lexer) Interface() interface{} { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } if !r.Ok() { + return nil + } + switch r.token.kind { + case tokenString: + return r.String() + case tokenNumber: + return r.Float64() + case tokenBool: + return r.Bool() + case tokenNull: + r.Null() + return nil + } if r.token.delimValue == '{' { + r.consume() ret := map[string]interface{}{} + for !r.IsDelim('}') { + key := r.String() + r.WantColon() + ret[key] = r.Interface() + r.WantComma() + } + r.Delim('}') if r.Ok() { + return ret + } else { + return nil + } + } else if r.token.delimValue == '[' { + r.consume() ret := []interface{}{} + for !r.IsDelim(']') { + ret = append(ret, r.Interface()) + r.WantComma() + } + r.Delim(']') if r.Ok() { + return ret + } else { + return nil + } + } + r.errSyntax() + return nil + } // WantComma requires a comma to be present before fetching next token. + func (r *Lexer) WantComma() { + r.wantSep = ',' + r.firstElement = false + } // WantColon requires a colon to be present before fetching next token. + func (r *Lexer) WantColon() { + r.wantSep = ':' + r.firstElement = false + } diff --git a/vendor/github.com/mailru/easyjson/jwriter/writer.go b/vendor/github.com/mailru/easyjson/jwriter/writer.go index 2c5b201..257efb6 100644 --- a/vendor/github.com/mailru/easyjson/jwriter/writer.go +++ b/vendor/github.com/mailru/easyjson/jwriter/writer.go @@ -1,4 +1,5 @@ // Package jwriter contains a JSON writer. + package jwriter import ( @@ -10,396 +11,648 @@ import ( ) // Flags describe various encoding options. The behavior may be actually implemented in the encoder, but + // Flags field in Writer is used to set and pass them around. + type Flags int const ( - NilMapAsEmpty Flags = 1 << iota // Encode nil map as '{}' rather than 'null'. - NilSliceAsEmpty // Encode nil slice as '[]' rather than 'null'. + NilMapAsEmpty Flags = 1 << iota // Encode nil map as '{}' rather than 'null'. + + NilSliceAsEmpty // Encode nil slice as '[]' rather than 'null'. + ) // Writer is a JSON writer. + type Writer struct { Flags Flags - Error error - Buffer buffer.Buffer + Error error + + Buffer buffer.Buffer + NoEscapeHTML bool } // Size returns the size of the data that was written out. + func (w *Writer) Size() int { + return w.Buffer.Size() + } // DumpTo outputs the data to given io.Writer, resetting the buffer. + func (w *Writer) DumpTo(out io.Writer) (written int, err error) { + return w.Buffer.DumpTo(out) + } // BuildBytes returns writer data as a single byte slice. You can optionally provide one byte slice + // as argument that it will try to reuse. + func (w *Writer) BuildBytes(reuse ...[]byte) ([]byte, error) { + if w.Error != nil { + return nil, w.Error + } return w.Buffer.BuildBytes(reuse...), nil + } // ReadCloser returns an io.ReadCloser that can be used to read the data. + // ReadCloser also resets the buffer. + func (w *Writer) ReadCloser() (io.ReadCloser, error) { + if w.Error != nil { + return nil, w.Error + } return w.Buffer.ReadCloser(), nil + } // RawByte appends raw binary data to the buffer. + func (w *Writer) RawByte(c byte) { + w.Buffer.AppendByte(c) + } // RawByte appends raw binary data to the buffer. + func (w *Writer) RawString(s string) { + w.Buffer.AppendString(s) + } // Raw appends raw binary data to the buffer or sets the error if it is given. Useful for + // calling with results of MarshalJSON-like functions. + func (w *Writer) Raw(data []byte, err error) { + switch { + case w.Error != nil: + return + case err != nil: + w.Error = err + case len(data) > 0: + w.Buffer.AppendBytes(data) + default: + w.RawString("null") + } + } // RawText encloses raw binary data in quotes and appends in to the buffer. + // Useful for calling with results of MarshalText-like functions. + func (w *Writer) RawText(data []byte, err error) { + switch { + case w.Error != nil: + return + case err != nil: + w.Error = err + case len(data) > 0: + w.String(string(data)) + default: + w.RawString("null") + } + } // Base64Bytes appends data to the buffer after base64 encoding it + func (w *Writer) Base64Bytes(data []byte) { + if data == nil { + w.Buffer.AppendString("null") + return + } + w.Buffer.AppendByte('"') + w.base64(data) + w.Buffer.AppendByte('"') + } func (w *Writer) Uint8(n uint8) { + w.Buffer.EnsureSpace(3) + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) + } func (w *Writer) Uint16(n uint16) { + w.Buffer.EnsureSpace(5) + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) + } func (w *Writer) Uint32(n uint32) { + w.Buffer.EnsureSpace(10) + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) + } func (w *Writer) Uint(n uint) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) + } func (w *Writer) Uint64(n uint64) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, n, 10) + } func (w *Writer) Int8(n int8) { + w.Buffer.EnsureSpace(4) + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) + } func (w *Writer) Int16(n int16) { + w.Buffer.EnsureSpace(6) + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) + } func (w *Writer) Int32(n int32) { + w.Buffer.EnsureSpace(11) + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) + } func (w *Writer) Int(n int) { + w.Buffer.EnsureSpace(21) + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) + } func (w *Writer) Int64(n int64) { + w.Buffer.EnsureSpace(21) + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, n, 10) + } func (w *Writer) Uint8Str(n uint8) { + w.Buffer.EnsureSpace(3) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + } func (w *Writer) Uint16Str(n uint16) { + w.Buffer.EnsureSpace(5) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + } func (w *Writer) Uint32Str(n uint32) { + w.Buffer.EnsureSpace(10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + } func (w *Writer) UintStr(n uint) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + } func (w *Writer) Uint64Str(n uint64) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, n, 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + } func (w *Writer) UintptrStr(n uintptr) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + } func (w *Writer) Int8Str(n int8) { + w.Buffer.EnsureSpace(4) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + } func (w *Writer) Int16Str(n int16) { + w.Buffer.EnsureSpace(6) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + } func (w *Writer) Int32Str(n int32) { + w.Buffer.EnsureSpace(11) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + } func (w *Writer) IntStr(n int) { + w.Buffer.EnsureSpace(21) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + } func (w *Writer) Int64Str(n int64) { + w.Buffer.EnsureSpace(21) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, n, 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + } func (w *Writer) Float32(n float32) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 32) + } func (w *Writer) Float32Str(n float32) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 32) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + } func (w *Writer) Float64(n float64) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, n, 'g', -1, 64) + } func (w *Writer) Float64Str(n float64) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 64) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + } func (w *Writer) Bool(v bool) { + w.Buffer.EnsureSpace(5) + if v { + w.Buffer.Buf = append(w.Buffer.Buf, "true"...) + } else { + w.Buffer.Buf = append(w.Buffer.Buf, "false"...) + } + } const chars = "0123456789abcdef" func getTable(falseValues ...int) [128]bool { + table := [128]bool{} for i := 0; i < 128; i++ { + table[i] = true + } for _, v := range falseValues { + table[v] = false + } return table + } var ( - htmlEscapeTable = getTable(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, '"', '&', '<', '>', '\\') + htmlEscapeTable = getTable(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, '"', '&', '<', '>', '\\') + htmlNoEscapeTable = getTable(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, '"', '\\') ) func (w *Writer) String(s string) { + w.Buffer.AppendByte('"') // Portions of the string that contain no escapes are appended as + // byte slices. p := 0 // last non-escape symbol escapeTable := &htmlEscapeTable + if w.NoEscapeHTML { + escapeTable = &htmlNoEscapeTable + } for i := 0; i < len(s); { + c := s[i] if c < utf8.RuneSelf { + if escapeTable[c] { + // single-width character, no escaping is required + i++ + continue + } w.Buffer.AppendString(s[p:i]) + switch c { + case '\t': + w.Buffer.AppendString(`\t`) + case '\r': + w.Buffer.AppendString(`\r`) + case '\n': + w.Buffer.AppendString(`\n`) + case '\\': + w.Buffer.AppendString(`\\`) + case '"': + w.Buffer.AppendString(`\"`) + default: + w.Buffer.AppendString(`\u00`) + w.Buffer.AppendByte(chars[c>>4]) + w.Buffer.AppendByte(chars[c&0xf]) + } i++ + p = i + continue + } // broken utf + runeValue, runeWidth := utf8.DecodeRuneInString(s[i:]) + if runeValue == utf8.RuneError && runeWidth == 1 { + w.Buffer.AppendString(s[p:i]) + w.Buffer.AppendString(`\ufffd`) + i++ + p = i + continue + } // jsonp stuff - tab separator and line separator + if runeValue == '\u2028' || runeValue == '\u2029' { + w.Buffer.AppendString(s[p:i]) + w.Buffer.AppendString(`\u202`) + w.Buffer.AppendByte(chars[runeValue&0xf]) + i += runeWidth + p = i + continue + } + i += runeWidth + } + w.Buffer.AppendString(s[p:]) + w.Buffer.AppendByte('"') + } const encode = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + const padChar = '=' func (w *Writer) base64(in []byte) { if len(in) == 0 { + return + } w.Buffer.EnsureSpace(((len(in)-1)/3 + 1) * 4) si := 0 + n := (len(in) / 3) * 3 for si < n { + // Convert 3x 8bit source bytes into 4 bytes + val := uint(in[si+0])<<16 | uint(in[si+1])<<8 | uint(in[si+2]) w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>18&0x3F], encode[val>>12&0x3F], encode[val>>6&0x3F], encode[val&0x3F]) si += 3 + } remain := len(in) - si + if remain == 0 { + return + } // Add the remaining small block + val := uint(in[si+0]) << 16 + if remain == 2 { + val |= uint(in[si+1]) << 8 + } w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>18&0x3F], encode[val>>12&0x3F]) switch remain { + case 2: + w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>6&0x3F], byte(padChar)) + case 1: + w.Buffer.Buf = append(w.Buffer.Buf, byte(padChar), byte(padChar)) + } + } diff --git a/vendor/github.com/mattn/go-colorable/colorable_appengine.go b/vendor/github.com/mattn/go-colorable/colorable_appengine.go index 416d1bb..9ed546c 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_appengine.go +++ b/vendor/github.com/mattn/go-colorable/colorable_appengine.go @@ -11,28 +11,45 @@ import ( ) // NewColorable returns new instance of Writer which handles escape sequence. + func NewColorable(file *os.File) io.Writer { + if file == nil { + panic("nil passed instead of *os.File to NewColorable()") + } return file + } // NewColorableStdout returns new instance of Writer which handles escape sequence for stdout. + func NewColorableStdout() io.Writer { + return os.Stdout + } // NewColorableStderr returns new instance of Writer which handles escape sequence for stderr. + func NewColorableStderr() io.Writer { + return os.Stderr + } // EnableColorsStdout enable colors if possible. + func EnableColorsStdout(enabled *bool) func() { + if enabled != nil { + *enabled = true + } + return func() {} + } diff --git a/vendor/github.com/mattn/go-colorable/colorable_others.go b/vendor/github.com/mattn/go-colorable/colorable_others.go index 766d946..1a732f0 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_others.go +++ b/vendor/github.com/mattn/go-colorable/colorable_others.go @@ -11,28 +11,45 @@ import ( ) // NewColorable returns new instance of Writer which handles escape sequence. + func NewColorable(file *os.File) io.Writer { + if file == nil { + panic("nil passed instead of *os.File to NewColorable()") + } return file + } // NewColorableStdout returns new instance of Writer which handles escape sequence for stdout. + func NewColorableStdout() io.Writer { + return os.Stdout + } // NewColorableStderr returns new instance of Writer which handles escape sequence for stderr. + func NewColorableStderr() io.Writer { + return os.Stderr + } // EnableColorsStdout enable colors if possible. + func EnableColorsStdout(enabled *bool) func() { + if enabled != nil { + *enabled = true + } + return func() {} + } diff --git a/vendor/github.com/mattn/go-colorable/colorable_windows.go b/vendor/github.com/mattn/go-colorable/colorable_windows.go index 1846ad5..f8f3c90 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_windows.go +++ b/vendor/github.com/mattn/go-colorable/colorable_windows.go @@ -18,23 +18,34 @@ import ( ) const ( - foregroundBlue = 0x1 - foregroundGreen = 0x2 - foregroundRed = 0x4 + foregroundBlue = 0x1 + + foregroundGreen = 0x2 + + foregroundRed = 0x4 + foregroundIntensity = 0x8 - foregroundMask = (foregroundRed | foregroundBlue | foregroundGreen | foregroundIntensity) - backgroundBlue = 0x10 - backgroundGreen = 0x20 - backgroundRed = 0x40 + + foregroundMask = (foregroundRed | foregroundBlue | foregroundGreen | foregroundIntensity) + + backgroundBlue = 0x10 + + backgroundGreen = 0x20 + + backgroundRed = 0x40 + backgroundIntensity = 0x80 - backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity) + + backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity) + commonLvbUnderscore = 0x8000 cENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x4 ) const ( - genericRead = 0x80000000 + genericRead = 0x80000000 + genericWrite = 0x40000000 ) @@ -43,885 +54,1698 @@ const ( ) type wchar uint16 + type short int16 + type dword uint32 + type word uint16 type coord struct { x short + y short } type smallRect struct { - left short - top short - right short + left short + + top short + + right short + bottom short } type consoleScreenBufferInfo struct { - size coord - cursorPosition coord - attributes word - window smallRect + size coord + + cursorPosition coord + + attributes word + + window smallRect + maximumWindowSize coord } type consoleCursorInfo struct { - size dword + size dword + visible int32 } var ( - kernel32 = syscall.NewLazyDLL("kernel32.dll") + kernel32 = syscall.NewLazyDLL("kernel32.dll") + procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo") - procSetConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute") - procSetConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition") + + procSetConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute") + + procSetConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition") + procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW") + procFillConsoleOutputAttribute = kernel32.NewProc("FillConsoleOutputAttribute") - procGetConsoleCursorInfo = kernel32.NewProc("GetConsoleCursorInfo") - procSetConsoleCursorInfo = kernel32.NewProc("SetConsoleCursorInfo") - procSetConsoleTitle = kernel32.NewProc("SetConsoleTitleW") - procGetConsoleMode = kernel32.NewProc("GetConsoleMode") - procSetConsoleMode = kernel32.NewProc("SetConsoleMode") - procCreateConsoleScreenBuffer = kernel32.NewProc("CreateConsoleScreenBuffer") + + procGetConsoleCursorInfo = kernel32.NewProc("GetConsoleCursorInfo") + + procSetConsoleCursorInfo = kernel32.NewProc("SetConsoleCursorInfo") + + procSetConsoleTitle = kernel32.NewProc("SetConsoleTitleW") + + procGetConsoleMode = kernel32.NewProc("GetConsoleMode") + + procSetConsoleMode = kernel32.NewProc("SetConsoleMode") + + procCreateConsoleScreenBuffer = kernel32.NewProc("CreateConsoleScreenBuffer") ) // Writer provides colorable Writer to the console + type Writer struct { - out io.Writer - handle syscall.Handle + out io.Writer + + handle syscall.Handle + althandle syscall.Handle - oldattr word - oldpos coord - rest bytes.Buffer - mutex sync.Mutex + + oldattr word + + oldpos coord + + rest bytes.Buffer + + mutex sync.Mutex } // NewColorable returns new instance of Writer which handles escape sequence from File. + func NewColorable(file *os.File) io.Writer { + if file == nil { + panic("nil passed instead of *os.File to NewColorable()") + } if isatty.IsTerminal(file.Fd()) { + var mode uint32 + if r, _, _ := procGetConsoleMode.Call(file.Fd(), uintptr(unsafe.Pointer(&mode))); r != 0 && mode&cENABLE_VIRTUAL_TERMINAL_PROCESSING != 0 { + return file + } + var csbi consoleScreenBufferInfo + handle := syscall.Handle(file.Fd()) + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + return &Writer{out: file, handle: handle, oldattr: csbi.attributes, oldpos: coord{0, 0}} + } + return file + } // NewColorableStdout returns new instance of Writer which handles escape sequence for stdout. + func NewColorableStdout() io.Writer { + return NewColorable(os.Stdout) + } // NewColorableStderr returns new instance of Writer which handles escape sequence for stderr. + func NewColorableStderr() io.Writer { + return NewColorable(os.Stderr) + } var color256 = map[int]int{ - 0: 0x000000, - 1: 0x800000, - 2: 0x008000, - 3: 0x808000, - 4: 0x000080, - 5: 0x800080, - 6: 0x008080, - 7: 0xc0c0c0, - 8: 0x808080, - 9: 0xff0000, - 10: 0x00ff00, - 11: 0xffff00, - 12: 0x0000ff, - 13: 0xff00ff, - 14: 0x00ffff, - 15: 0xffffff, - 16: 0x000000, - 17: 0x00005f, - 18: 0x000087, - 19: 0x0000af, - 20: 0x0000d7, - 21: 0x0000ff, - 22: 0x005f00, - 23: 0x005f5f, - 24: 0x005f87, - 25: 0x005faf, - 26: 0x005fd7, - 27: 0x005fff, - 28: 0x008700, - 29: 0x00875f, - 30: 0x008787, - 31: 0x0087af, - 32: 0x0087d7, - 33: 0x0087ff, - 34: 0x00af00, - 35: 0x00af5f, - 36: 0x00af87, - 37: 0x00afaf, - 38: 0x00afd7, - 39: 0x00afff, - 40: 0x00d700, - 41: 0x00d75f, - 42: 0x00d787, - 43: 0x00d7af, - 44: 0x00d7d7, - 45: 0x00d7ff, - 46: 0x00ff00, - 47: 0x00ff5f, - 48: 0x00ff87, - 49: 0x00ffaf, - 50: 0x00ffd7, - 51: 0x00ffff, - 52: 0x5f0000, - 53: 0x5f005f, - 54: 0x5f0087, - 55: 0x5f00af, - 56: 0x5f00d7, - 57: 0x5f00ff, - 58: 0x5f5f00, - 59: 0x5f5f5f, - 60: 0x5f5f87, - 61: 0x5f5faf, - 62: 0x5f5fd7, - 63: 0x5f5fff, - 64: 0x5f8700, - 65: 0x5f875f, - 66: 0x5f8787, - 67: 0x5f87af, - 68: 0x5f87d7, - 69: 0x5f87ff, - 70: 0x5faf00, - 71: 0x5faf5f, - 72: 0x5faf87, - 73: 0x5fafaf, - 74: 0x5fafd7, - 75: 0x5fafff, - 76: 0x5fd700, - 77: 0x5fd75f, - 78: 0x5fd787, - 79: 0x5fd7af, - 80: 0x5fd7d7, - 81: 0x5fd7ff, - 82: 0x5fff00, - 83: 0x5fff5f, - 84: 0x5fff87, - 85: 0x5fffaf, - 86: 0x5fffd7, - 87: 0x5fffff, - 88: 0x870000, - 89: 0x87005f, - 90: 0x870087, - 91: 0x8700af, - 92: 0x8700d7, - 93: 0x8700ff, - 94: 0x875f00, - 95: 0x875f5f, - 96: 0x875f87, - 97: 0x875faf, - 98: 0x875fd7, - 99: 0x875fff, + + 0: 0x000000, + + 1: 0x800000, + + 2: 0x008000, + + 3: 0x808000, + + 4: 0x000080, + + 5: 0x800080, + + 6: 0x008080, + + 7: 0xc0c0c0, + + 8: 0x808080, + + 9: 0xff0000, + + 10: 0x00ff00, + + 11: 0xffff00, + + 12: 0x0000ff, + + 13: 0xff00ff, + + 14: 0x00ffff, + + 15: 0xffffff, + + 16: 0x000000, + + 17: 0x00005f, + + 18: 0x000087, + + 19: 0x0000af, + + 20: 0x0000d7, + + 21: 0x0000ff, + + 22: 0x005f00, + + 23: 0x005f5f, + + 24: 0x005f87, + + 25: 0x005faf, + + 26: 0x005fd7, + + 27: 0x005fff, + + 28: 0x008700, + + 29: 0x00875f, + + 30: 0x008787, + + 31: 0x0087af, + + 32: 0x0087d7, + + 33: 0x0087ff, + + 34: 0x00af00, + + 35: 0x00af5f, + + 36: 0x00af87, + + 37: 0x00afaf, + + 38: 0x00afd7, + + 39: 0x00afff, + + 40: 0x00d700, + + 41: 0x00d75f, + + 42: 0x00d787, + + 43: 0x00d7af, + + 44: 0x00d7d7, + + 45: 0x00d7ff, + + 46: 0x00ff00, + + 47: 0x00ff5f, + + 48: 0x00ff87, + + 49: 0x00ffaf, + + 50: 0x00ffd7, + + 51: 0x00ffff, + + 52: 0x5f0000, + + 53: 0x5f005f, + + 54: 0x5f0087, + + 55: 0x5f00af, + + 56: 0x5f00d7, + + 57: 0x5f00ff, + + 58: 0x5f5f00, + + 59: 0x5f5f5f, + + 60: 0x5f5f87, + + 61: 0x5f5faf, + + 62: 0x5f5fd7, + + 63: 0x5f5fff, + + 64: 0x5f8700, + + 65: 0x5f875f, + + 66: 0x5f8787, + + 67: 0x5f87af, + + 68: 0x5f87d7, + + 69: 0x5f87ff, + + 70: 0x5faf00, + + 71: 0x5faf5f, + + 72: 0x5faf87, + + 73: 0x5fafaf, + + 74: 0x5fafd7, + + 75: 0x5fafff, + + 76: 0x5fd700, + + 77: 0x5fd75f, + + 78: 0x5fd787, + + 79: 0x5fd7af, + + 80: 0x5fd7d7, + + 81: 0x5fd7ff, + + 82: 0x5fff00, + + 83: 0x5fff5f, + + 84: 0x5fff87, + + 85: 0x5fffaf, + + 86: 0x5fffd7, + + 87: 0x5fffff, + + 88: 0x870000, + + 89: 0x87005f, + + 90: 0x870087, + + 91: 0x8700af, + + 92: 0x8700d7, + + 93: 0x8700ff, + + 94: 0x875f00, + + 95: 0x875f5f, + + 96: 0x875f87, + + 97: 0x875faf, + + 98: 0x875fd7, + + 99: 0x875fff, + 100: 0x878700, + 101: 0x87875f, + 102: 0x878787, + 103: 0x8787af, + 104: 0x8787d7, + 105: 0x8787ff, + 106: 0x87af00, + 107: 0x87af5f, + 108: 0x87af87, + 109: 0x87afaf, + 110: 0x87afd7, + 111: 0x87afff, + 112: 0x87d700, + 113: 0x87d75f, + 114: 0x87d787, + 115: 0x87d7af, + 116: 0x87d7d7, + 117: 0x87d7ff, + 118: 0x87ff00, + 119: 0x87ff5f, + 120: 0x87ff87, + 121: 0x87ffaf, + 122: 0x87ffd7, + 123: 0x87ffff, + 124: 0xaf0000, + 125: 0xaf005f, + 126: 0xaf0087, + 127: 0xaf00af, + 128: 0xaf00d7, + 129: 0xaf00ff, + 130: 0xaf5f00, + 131: 0xaf5f5f, + 132: 0xaf5f87, + 133: 0xaf5faf, + 134: 0xaf5fd7, + 135: 0xaf5fff, + 136: 0xaf8700, + 137: 0xaf875f, + 138: 0xaf8787, + 139: 0xaf87af, + 140: 0xaf87d7, + 141: 0xaf87ff, + 142: 0xafaf00, + 143: 0xafaf5f, + 144: 0xafaf87, + 145: 0xafafaf, + 146: 0xafafd7, + 147: 0xafafff, + 148: 0xafd700, + 149: 0xafd75f, + 150: 0xafd787, + 151: 0xafd7af, + 152: 0xafd7d7, + 153: 0xafd7ff, + 154: 0xafff00, + 155: 0xafff5f, + 156: 0xafff87, + 157: 0xafffaf, + 158: 0xafffd7, + 159: 0xafffff, + 160: 0xd70000, + 161: 0xd7005f, + 162: 0xd70087, + 163: 0xd700af, + 164: 0xd700d7, + 165: 0xd700ff, + 166: 0xd75f00, + 167: 0xd75f5f, + 168: 0xd75f87, + 169: 0xd75faf, + 170: 0xd75fd7, + 171: 0xd75fff, + 172: 0xd78700, + 173: 0xd7875f, + 174: 0xd78787, + 175: 0xd787af, + 176: 0xd787d7, + 177: 0xd787ff, + 178: 0xd7af00, + 179: 0xd7af5f, + 180: 0xd7af87, + 181: 0xd7afaf, + 182: 0xd7afd7, + 183: 0xd7afff, + 184: 0xd7d700, + 185: 0xd7d75f, + 186: 0xd7d787, + 187: 0xd7d7af, + 188: 0xd7d7d7, + 189: 0xd7d7ff, + 190: 0xd7ff00, + 191: 0xd7ff5f, + 192: 0xd7ff87, + 193: 0xd7ffaf, + 194: 0xd7ffd7, + 195: 0xd7ffff, + 196: 0xff0000, + 197: 0xff005f, + 198: 0xff0087, + 199: 0xff00af, + 200: 0xff00d7, + 201: 0xff00ff, + 202: 0xff5f00, + 203: 0xff5f5f, + 204: 0xff5f87, + 205: 0xff5faf, + 206: 0xff5fd7, + 207: 0xff5fff, + 208: 0xff8700, + 209: 0xff875f, + 210: 0xff8787, + 211: 0xff87af, + 212: 0xff87d7, + 213: 0xff87ff, + 214: 0xffaf00, + 215: 0xffaf5f, + 216: 0xffaf87, + 217: 0xffafaf, + 218: 0xffafd7, + 219: 0xffafff, + 220: 0xffd700, + 221: 0xffd75f, + 222: 0xffd787, + 223: 0xffd7af, + 224: 0xffd7d7, + 225: 0xffd7ff, + 226: 0xffff00, + 227: 0xffff5f, + 228: 0xffff87, + 229: 0xffffaf, + 230: 0xffffd7, + 231: 0xffffff, + 232: 0x080808, + 233: 0x121212, + 234: 0x1c1c1c, + 235: 0x262626, + 236: 0x303030, + 237: 0x3a3a3a, + 238: 0x444444, + 239: 0x4e4e4e, + 240: 0x585858, + 241: 0x626262, + 242: 0x6c6c6c, + 243: 0x767676, + 244: 0x808080, + 245: 0x8a8a8a, + 246: 0x949494, + 247: 0x9e9e9e, + 248: 0xa8a8a8, + 249: 0xb2b2b2, + 250: 0xbcbcbc, + 251: 0xc6c6c6, + 252: 0xd0d0d0, + 253: 0xdadada, + 254: 0xe4e4e4, + 255: 0xeeeeee, } // `\033]0;TITLESTR\007` + func doTitleSequence(er *bytes.Reader) error { + var c byte + var err error c, err = er.ReadByte() + if err != nil { + return err + } + if c != '0' && c != '2' { + return nil + } + c, err = er.ReadByte() + if err != nil { + return err + } + if c != ';' { + return nil + } + title := make([]byte, 0, 80) + for { + c, err = er.ReadByte() + if err != nil { + return err + } + if c == 0x07 || c == '\n' { + break + } + title = append(title, c) + } + if len(title) > 0 { + title8, err := syscall.UTF16PtrFromString(string(title)) + if err == nil { + procSetConsoleTitle.Call(uintptr(unsafe.Pointer(title8))) + } + } + return nil + } // returns Atoi(s) unless s == "" in which case it returns def + func atoiWithDefault(s string, def int) (int, error) { + if s == "" { + return def, nil + } + return strconv.Atoi(s) + } // Write writes data on console + func (w *Writer) Write(data []byte) (n int, err error) { + w.mutex.Lock() + defer w.mutex.Unlock() + var csbi consoleScreenBufferInfo + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) handle := w.handle var er *bytes.Reader + if w.rest.Len() > 0 { + var rest bytes.Buffer + w.rest.WriteTo(&rest) + w.rest.Reset() + rest.Write(data) + er = bytes.NewReader(rest.Bytes()) + } else { + er = bytes.NewReader(data) + } + var plaintext bytes.Buffer + loop: + for { + c1, err := er.ReadByte() + if err != nil { + plaintext.WriteTo(w.out) + break loop + } + if c1 != 0x1b { + plaintext.WriteByte(c1) + continue + } + _, err = plaintext.WriteTo(w.out) + if err != nil { + break loop + } + c2, err := er.ReadByte() + if err != nil { + break loop + } switch c2 { + case '>': + continue + case ']': + w.rest.WriteByte(c1) + w.rest.WriteByte(c2) + er.WriteTo(&w.rest) + if bytes.IndexByte(w.rest.Bytes(), 0x07) == -1 { + break loop + } + er = bytes.NewReader(w.rest.Bytes()[2:]) + err := doTitleSequence(er) + if err != nil { + break loop + } + w.rest.Reset() + continue + // https://github.com/mattn/go-colorable/issues/27 + case '7': + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + w.oldpos = csbi.cursorPosition + continue + case '8': + procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&w.oldpos))) + continue + case 0x5b: + // execute part after switch + default: + continue + } w.rest.WriteByte(c1) + w.rest.WriteByte(c2) + er.WriteTo(&w.rest) var buf bytes.Buffer + var m byte + for i, c := range w.rest.Bytes()[2:] { + if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { + m = c + er = bytes.NewReader(w.rest.Bytes()[2+i+1:]) + w.rest.Reset() + break + } + buf.Write([]byte(string(c))) + } + if m == 0 { + break loop + } switch m { + case 'A': + n, err = atoiWithDefault(buf.String(), 1) + if err != nil { + continue + } + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.y -= short(n) + procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'B': + n, err = atoiWithDefault(buf.String(), 1) + if err != nil { + continue + } + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.y += short(n) + procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'C': + n, err = atoiWithDefault(buf.String(), 1) + if err != nil { + continue + } + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.x += short(n) + procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'D': + n, err = atoiWithDefault(buf.String(), 1) + if err != nil { + continue + } + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.x -= short(n) + if csbi.cursorPosition.x < 0 { + csbi.cursorPosition.x = 0 + } + procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'E': + n, err = strconv.Atoi(buf.String()) + if err != nil { + continue + } + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.x = 0 + csbi.cursorPosition.y += short(n) + procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'F': + n, err = strconv.Atoi(buf.String()) + if err != nil { + continue + } + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.x = 0 + csbi.cursorPosition.y -= short(n) + procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'G': + n, err = strconv.Atoi(buf.String()) + if err != nil { + continue + } + if n < 1 { + n = 1 + } + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.x = short(n - 1) + procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'H', 'f': + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + if buf.Len() > 0 { + token := strings.Split(buf.String(), ";") + switch len(token) { + case 1: + n1, err := strconv.Atoi(token[0]) + if err != nil { + continue + } + csbi.cursorPosition.y = short(n1 - 1) + case 2: + n1, err := strconv.Atoi(token[0]) + if err != nil { + continue + } + n2, err := strconv.Atoi(token[1]) + if err != nil { + continue + } + csbi.cursorPosition.x = short(n2 - 1) + csbi.cursorPosition.y = short(n1 - 1) + } + } else { + csbi.cursorPosition.y = 0 + } + procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'J': + n := 0 + if buf.Len() > 0 { + n, err = strconv.Atoi(buf.String()) + if err != nil { + continue + } + } + var count, written dword + var cursor coord + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + switch n { + case 0: + cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} + count = dword(csbi.size.x) - dword(csbi.cursorPosition.x) + dword(csbi.size.y-csbi.cursorPosition.y)*dword(csbi.size.x) + case 1: + cursor = coord{x: csbi.window.left, y: csbi.window.top} + count = dword(csbi.size.x) - dword(csbi.cursorPosition.x) + dword(csbi.window.top-csbi.cursorPosition.y)*dword(csbi.size.x) + case 2: + cursor = coord{x: csbi.window.left, y: csbi.window.top} + count = dword(csbi.size.x) - dword(csbi.cursorPosition.x) + dword(csbi.size.y-csbi.cursorPosition.y)*dword(csbi.size.x) + } + procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + case 'K': + n := 0 + if buf.Len() > 0 { + n, err = strconv.Atoi(buf.String()) + if err != nil { + continue + } + } + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + var cursor coord + var count, written dword + switch n { + case 0: + cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} + count = dword(csbi.size.x - csbi.cursorPosition.x) + case 1: + cursor = coord{x: csbi.window.left, y: csbi.cursorPosition.y} + count = dword(csbi.size.x - csbi.cursorPosition.x) + case 2: + cursor = coord{x: csbi.window.left, y: csbi.cursorPosition.y} + count = dword(csbi.size.x) + } + procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + case 'X': + n := 0 + if buf.Len() > 0 { + n, err = strconv.Atoi(buf.String()) + if err != nil { + continue + } + } + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + var cursor coord + var written dword + cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} + procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(n), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(n), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + case 'm': + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + attr := csbi.attributes + cs := buf.String() + if cs == "" { + procSetConsoleTextAttribute.Call(uintptr(handle), uintptr(w.oldattr)) + continue + } + token := strings.Split(cs, ";") + for i := 0; i < len(token); i++ { + ns := token[i] + if n, err = strconv.Atoi(ns); err == nil { + switch { + case n == 0 || n == 100: + attr = w.oldattr + case n == 4: + attr |= commonLvbUnderscore + case (1 <= n && n <= 3) || n == 5: + attr |= foregroundIntensity + case n == 7 || n == 27: + attr = + (attr &^ (foregroundMask | backgroundMask)) | + ((attr & foregroundMask) << 4) | + ((attr & backgroundMask) >> 4) + case n == 22: + attr &^= foregroundIntensity + case n == 24: + attr &^= commonLvbUnderscore + case 30 <= n && n <= 37: + attr &= backgroundMask + if (n-30)&1 != 0 { + attr |= foregroundRed + } + if (n-30)&2 != 0 { + attr |= foregroundGreen + } + if (n-30)&4 != 0 { + attr |= foregroundBlue + } + case n == 38: // set foreground color. + if i < len(token)-2 && (token[i+1] == "5" || token[i+1] == "05") { + if n256, err := strconv.Atoi(token[i+2]); err == nil { + if n256foreAttr == nil { + n256setup() + } + attr &= backgroundMask + attr |= n256foreAttr[n256%len(n256foreAttr)] + i += 2 + } + } else if len(token) == 5 && token[i+1] == "2" { + var r, g, b int + r, _ = strconv.Atoi(token[i+2]) + g, _ = strconv.Atoi(token[i+3]) + b, _ = strconv.Atoi(token[i+4]) + i += 4 + if r > 127 { + attr |= foregroundRed + } + if g > 127 { + attr |= foregroundGreen + } + if b > 127 { + attr |= foregroundBlue + } + } else { + attr = attr & (w.oldattr & backgroundMask) + } + case n == 39: // reset foreground color. + attr &= backgroundMask + attr |= w.oldattr & foregroundMask + case 40 <= n && n <= 47: + attr &= foregroundMask + if (n-40)&1 != 0 { + attr |= backgroundRed + } + if (n-40)&2 != 0 { + attr |= backgroundGreen + } + if (n-40)&4 != 0 { + attr |= backgroundBlue + } + case n == 48: // set background color. + if i < len(token)-2 && token[i+1] == "5" { + if n256, err := strconv.Atoi(token[i+2]); err == nil { + if n256backAttr == nil { + n256setup() + } + attr &= foregroundMask + attr |= n256backAttr[n256%len(n256backAttr)] + i += 2 + } + } else if len(token) == 5 && token[i+1] == "2" { + var r, g, b int + r, _ = strconv.Atoi(token[i+2]) + g, _ = strconv.Atoi(token[i+3]) + b, _ = strconv.Atoi(token[i+4]) + i += 4 + if r > 127 { + attr |= backgroundRed + } + if g > 127 { + attr |= backgroundGreen + } + if b > 127 { + attr |= backgroundBlue + } + } else { + attr = attr & (w.oldattr & foregroundMask) + } + case n == 49: // reset foreground color. + attr &= foregroundMask + attr |= w.oldattr & backgroundMask + case 90 <= n && n <= 97: + attr = (attr & backgroundMask) + attr |= foregroundIntensity + if (n-90)&1 != 0 { + attr |= foregroundRed + } + if (n-90)&2 != 0 { + attr |= foregroundGreen + } + if (n-90)&4 != 0 { + attr |= foregroundBlue + } + case 100 <= n && n <= 107: + attr = (attr & foregroundMask) + attr |= backgroundIntensity + if (n-100)&1 != 0 { + attr |= backgroundRed + } + if (n-100)&2 != 0 { + attr |= backgroundGreen + } + if (n-100)&4 != 0 { + attr |= backgroundBlue + } + } + procSetConsoleTextAttribute.Call(uintptr(handle), uintptr(attr)) + } + } + case 'h': + var ci consoleCursorInfo + cs := buf.String() + if cs == "5>" { + procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + ci.visible = 0 + procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + } else if cs == "?25" { + procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + ci.visible = 1 + procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + } else if cs == "?1049" { + if w.althandle == 0 { + h, _, _ := procCreateConsoleScreenBuffer.Call(uintptr(genericRead|genericWrite), 0, 0, uintptr(consoleTextmodeBuffer), 0, 0) + w.althandle = syscall.Handle(h) + if w.althandle != 0 { + handle = w.althandle + } + } + } + case 'l': + var ci consoleCursorInfo + cs := buf.String() + if cs == "5>" { + procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + ci.visible = 1 + procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + } else if cs == "?25" { + procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + ci.visible = 0 + procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + } else if cs == "?1049" { + if w.althandle != 0 { + syscall.CloseHandle(w.althandle) + w.althandle = 0 + handle = w.handle + } + } + case 's': + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + w.oldpos = csbi.cursorPosition + case 'u': + procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&w.oldpos))) + } + } return len(data), nil + } type consoleColor struct { - rgb int - red bool - green bool - blue bool + rgb int + + red bool + + green bool + + blue bool + intensity bool } func (c consoleColor) foregroundAttr() (attr word) { + if c.red { + attr |= foregroundRed + } + if c.green { + attr |= foregroundGreen + } + if c.blue { + attr |= foregroundBlue + } + if c.intensity { + attr |= foregroundIntensity + } + return + } func (c consoleColor) backgroundAttr() (attr word) { + if c.red { + attr |= backgroundRed + } + if c.green { + attr |= backgroundGreen + } + if c.blue { + attr |= backgroundBlue + } + if c.intensity { + attr |= backgroundIntensity + } + return + } var color16 = []consoleColor{ + {0x000000, false, false, false, false}, + {0x000080, false, false, true, false}, + {0x008000, false, true, false, false}, + {0x008080, false, true, true, false}, + {0x800000, true, false, false, false}, + {0x800080, true, false, true, false}, + {0x808000, true, true, false, false}, + {0xc0c0c0, true, true, true, false}, + {0x808080, false, false, false, true}, + {0x0000ff, false, false, true, true}, + {0x00ff00, false, true, false, true}, + {0x00ffff, false, true, true, true}, + {0xff0000, true, false, false, true}, + {0xff00ff, true, false, true, true}, + {0xffff00, true, true, false, true}, + {0xffffff, true, true, true, true}, } @@ -930,118 +1754,217 @@ type hsv struct { } func (a hsv) dist(b hsv) float32 { + dh := a.h - b.h + switch { + case dh > 0.5: + dh = 1 - dh + case dh < -0.5: + dh = -1 - dh + } + ds := a.s - b.s + dv := a.v - b.v + return float32(math.Sqrt(float64(dh*dh + ds*ds + dv*dv))) + } func toHSV(rgb int) hsv { + r, g, b := float32((rgb&0xFF0000)>>16)/256.0, + float32((rgb&0x00FF00)>>8)/256.0, + float32(rgb&0x0000FF)/256.0 + min, max := minmax3f(r, g, b) + h := max - min + if h > 0 { + if max == r { + h = (g - b) / h + if h < 0 { + h += 6 + } + } else if max == g { + h = 2 + (b-r)/h + } else { + h = 4 + (r-g)/h + } + } + h /= 6.0 + s := max - min + if max != 0 { + s /= max + } + v := max + return hsv{h: h, s: s, v: v} + } type hsvTable []hsv func toHSVTable(rgbTable []consoleColor) hsvTable { + t := make(hsvTable, len(rgbTable)) + for i, c := range rgbTable { + t[i] = toHSV(c.rgb) + } + return t + } func (t hsvTable) find(rgb int) consoleColor { + hsv := toHSV(rgb) + n := 7 + l := float32(5.0) + for i, p := range t { + d := hsv.dist(p) + if d < l { + l, n = d, i + } + } + return color16[n] + } func minmax3f(a, b, c float32) (min, max float32) { + if a < b { + if b < c { + return a, c + } else if a < c { + return a, b + } else { + return c, b + } + } else { + if a < c { + return b, c + } else if b < c { + return b, a + } else { + return c, a + } + } + } var n256foreAttr []word + var n256backAttr []word func n256setup() { + n256foreAttr = make([]word, 256) + n256backAttr = make([]word, 256) + t := toHSVTable(color16) + for i, rgb := range color256 { + c := t.find(rgb) + n256foreAttr[i] = c.foregroundAttr() + n256backAttr[i] = c.backgroundAttr() + } + } // EnableColorsStdout enable colors if possible. + func EnableColorsStdout(enabled *bool) func() { + var mode uint32 + h := os.Stdout.Fd() + if r, _, _ := procGetConsoleMode.Call(h, uintptr(unsafe.Pointer(&mode))); r != 0 { + if r, _, _ = procSetConsoleMode.Call(h, uintptr(mode|cENABLE_VIRTUAL_TERMINAL_PROCESSING)); r != 0 { + if enabled != nil { + *enabled = true + } + return func() { + procSetConsoleMode.Call(h, uintptr(mode)) + } + } + } + if enabled != nil { + *enabled = true + } + return func() {} + } diff --git a/vendor/github.com/mattn/go-colorable/noncolorable.go b/vendor/github.com/mattn/go-colorable/noncolorable.go index 05d6f74..9ad8700 100644 --- a/vendor/github.com/mattn/go-colorable/noncolorable.go +++ b/vendor/github.com/mattn/go-colorable/noncolorable.go @@ -6,52 +6,91 @@ import ( ) // NonColorable holds writer but removes escape sequence. + type NonColorable struct { out io.Writer } // NewNonColorable returns new instance of Writer which removes escape sequence from Writer. + func NewNonColorable(w io.Writer) io.Writer { + return &NonColorable{out: w} + } // Write writes data on console + func (w *NonColorable) Write(data []byte) (n int, err error) { + er := bytes.NewReader(data) + var plaintext bytes.Buffer + loop: + for { + c1, err := er.ReadByte() + if err != nil { + plaintext.WriteTo(w.out) + break loop + } + if c1 != 0x1b { + plaintext.WriteByte(c1) + continue + } + _, err = plaintext.WriteTo(w.out) + if err != nil { + break loop + } + c2, err := er.ReadByte() + if err != nil { + break loop + } + if c2 != 0x5b { + continue + } for { + c, err := er.ReadByte() + if err != nil { + break loop + } + if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { + break + } + } + } return len(data), nil + } diff --git a/vendor/github.com/mattn/go-isatty/isatty_windows.go b/vendor/github.com/mattn/go-isatty/isatty_windows.go index 367adab..a866759 100644 --- a/vendor/github.com/mattn/go-isatty/isatty_windows.go +++ b/vendor/github.com/mattn/go-isatty/isatty_windows.go @@ -13,114 +13,190 @@ import ( const ( objectNameInfo uintptr = 1 - fileNameInfo = 2 - fileTypePipe = 3 + + fileNameInfo = 2 + + fileTypePipe = 3 ) var ( - kernel32 = syscall.NewLazyDLL("kernel32.dll") - ntdll = syscall.NewLazyDLL("ntdll.dll") - procGetConsoleMode = kernel32.NewProc("GetConsoleMode") + kernel32 = syscall.NewLazyDLL("kernel32.dll") + + ntdll = syscall.NewLazyDLL("ntdll.dll") + + procGetConsoleMode = kernel32.NewProc("GetConsoleMode") + procGetFileInformationByHandleEx = kernel32.NewProc("GetFileInformationByHandleEx") - procGetFileType = kernel32.NewProc("GetFileType") - procNtQueryObject = ntdll.NewProc("NtQueryObject") + + procGetFileType = kernel32.NewProc("GetFileType") + + procNtQueryObject = ntdll.NewProc("NtQueryObject") ) func init() { + // Check if GetFileInformationByHandleEx is available. + if procGetFileInformationByHandleEx.Find() != nil { + procGetFileInformationByHandleEx = nil + } + } // IsTerminal return true if the file descriptor is terminal. + func IsTerminal(fd uintptr) bool { + var st uint32 + r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0) + return r != 0 && e == 0 + } // Check pipe name is used for cygwin/msys2 pty. + // Cygwin/MSYS2 PTY has a name like: + // + // \{cygwin,msys}-XXXXXXXXXXXXXXXX-ptyN-{from,to}-master + func isCygwinPipeName(name string) bool { + token := strings.Split(name, "-") + if len(token) < 5 { + return false + } if token[0] != `\msys` && + token[0] != `\cygwin` && + token[0] != `\Device\NamedPipe\msys` && + token[0] != `\Device\NamedPipe\cygwin` { + return false + } if token[1] == "" { + return false + } if !strings.HasPrefix(token[2], "pty") { + return false + } if token[3] != `from` && token[3] != `to` { + return false + } if token[4] != "master" { + return false + } return true + } // getFileNameByHandle use the undocomented ntdll NtQueryObject to get file full name from file handler + // since GetFileInformationByHandleEx is not available under windows Vista and still some old fashion + // guys are using Windows XP, this is a workaround for those guys, it will also work on system from + // Windows vista to 10 + // see https://stackoverflow.com/a/18792477 for details + func getFileNameByHandle(fd uintptr) (string, error) { + if procNtQueryObject == nil { + return "", errors.New("ntdll.dll: NtQueryObject not supported") + } var buf [4 + syscall.MAX_PATH]uint16 + var result int + r, _, e := syscall.Syscall6(procNtQueryObject.Addr(), 5, + fd, objectNameInfo, uintptr(unsafe.Pointer(&buf)), uintptr(2*len(buf)), uintptr(unsafe.Pointer(&result)), 0) + if r != 0 { + return "", e + } + return string(utf16.Decode(buf[4 : 4+buf[0]/2])), nil + } // IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 + // terminal. + func IsCygwinTerminal(fd uintptr) bool { + if procGetFileInformationByHandleEx == nil { + name, err := getFileNameByHandle(fd) + if err != nil { + return false + } + return isCygwinPipeName(name) + } // Cygwin/msys's pty is a pipe. + ft, _, e := syscall.Syscall(procGetFileType.Addr(), 1, fd, 0, 0) + if ft != fileTypePipe || e != 0 { + return false + } var buf [2 + syscall.MAX_PATH]uint16 + r, _, e := syscall.Syscall6(procGetFileInformationByHandleEx.Addr(), + 4, fd, fileNameInfo, uintptr(unsafe.Pointer(&buf)), + uintptr(len(buf)*2), 0, 0) + if r == 0 || e != 0 { + return false + } l := *(*uint32)(unsafe.Pointer(&buf)) + return isCygwinPipeName(string(utf16.Decode(buf[2 : 2+l/2]))) + } diff --git a/vendor/github.com/mitchellh/copystructure/copier_time.go b/vendor/github.com/mitchellh/copystructure/copier_time.go index db6a6aa..9101bba 100644 --- a/vendor/github.com/mitchellh/copystructure/copier_time.go +++ b/vendor/github.com/mitchellh/copystructure/copier_time.go @@ -6,10 +6,15 @@ import ( ) func init() { + Copiers[reflect.TypeOf(time.Time{})] = timeCopier + } func timeCopier(v interface{}) (interface{}, error) { + // Just... copy it. + return v.(time.Time), nil + } diff --git a/vendor/github.com/mitchellh/copystructure/copystructure.go b/vendor/github.com/mitchellh/copystructure/copystructure.go index bf4b5df..27ef928 100644 --- a/vendor/github.com/mitchellh/copystructure/copystructure.go +++ b/vendor/github.com/mitchellh/copystructure/copystructure.go @@ -11,565 +11,938 @@ import ( const tagKey = "copy" // Copy returns a deep copy of v. + // + // Copy is unable to copy unexported fields in a struct (lowercase field names). + // Unexported fields can't be reflected by the Go runtime and therefore + // copystructure can't perform any data copies. + // + // For structs, copy behavior can be controlled with struct tags. For example: + // + // struct { + // Name string + // Data *bytes.Buffer `copy:"shallow"` + // } + // + // The available tag values are: + // + // - "ignore" - The field will be ignored, effectively resulting in it being + // assigned the zero value in the copy. + // + // - "shallow" - The field will be be shallow copied. This means that references + // values such as pointers, maps, slices, etc. will be directly assigned + // versus deep copied. + func Copy(v interface{}) (interface{}, error) { + return Config{}.Copy(v) + } // CopierFunc is a function that knows how to deep copy a specific type. + // Register these globally with the Copiers variable. + type CopierFunc func(interface{}) (interface{}, error) // Copiers is a map of types that behave specially when they are copied. + // If a type is found in this map while deep copying, this function + // will be called to copy it instead of attempting to copy all fields. + // + // The key should be the type, obtained using: reflect.TypeOf(value with type). + // + // It is unsafe to write to this map after Copies have started. If you + // are writing to this map while also copying, wrap all modifications to + // this map as well as to Copy in a mutex. + var Copiers map[reflect.Type]CopierFunc = make(map[reflect.Type]CopierFunc) // ShallowCopiers is a map of pointer types that behave specially + // when they are copied. If a type is found in this map while deep + // copying, the pointer value will be shallow copied and not walked + // into. + // + // The key should be the type, obtained using: reflect.TypeOf(value + // with type). + // + // It is unsafe to write to this map after Copies have started. If you + // are writing to this map while also copying, wrap all modifications to + // this map as well as to Copy in a mutex. + var ShallowCopiers map[reflect.Type]struct{} = make(map[reflect.Type]struct{}) // Must is a helper that wraps a call to a function returning + // (interface{}, error) and panics if the error is non-nil. It is intended + // for use in variable initializations and should only be used when a copy + // error should be a crashing case. + func Must(v interface{}, err error) interface{} { + if err != nil { + panic("copy error: " + err.Error()) + } return v + } var errPointerRequired = errors.New("Copy argument must be a pointer when Lock is true") type Config struct { + // Lock any types that are a sync.Locker and are not a mutex while copying. + // If there is an RLocker method, use that to get the sync.Locker. + Lock bool // Copiers is a map of types associated with a CopierFunc. Use the global + // Copiers map if this is nil. + Copiers map[reflect.Type]CopierFunc // ShallowCopiers is a map of pointer types that when they are + // shallow copied no matter where they are encountered. Use the + // global ShallowCopiers if this is nil. + ShallowCopiers map[reflect.Type]struct{} } func (c Config) Copy(v interface{}) (interface{}, error) { + if c.Lock && reflect.ValueOf(v).Kind() != reflect.Ptr { + return nil, errPointerRequired + } w := new(walker) + if c.Lock { + w.useLocks = true + } if c.Copiers == nil { + c.Copiers = Copiers + } + w.copiers = c.Copiers if c.ShallowCopiers == nil { + c.ShallowCopiers = ShallowCopiers + } + w.shallowCopiers = c.ShallowCopiers err := reflectwalk.Walk(v, w) + if err != nil { + return nil, err + } // Get the result. If the result is nil, then we want to turn it + // into a typed nil if we can. + result := w.Result + if result == nil { + val := reflect.ValueOf(v) + result = reflect.Indirect(reflect.New(val.Type())).Interface() + } return result, nil + } // Return the key used to index interfaces types we've seen. Store the number + // of pointers in the upper 32bits, and the depth in the lower 32bits. This is + // easy to calculate, easy to match a key with our current depth, and we don't + // need to deal with initializing and cleaning up nested maps or slices. + func ifaceKey(pointers, depth int) uint64 { + return uint64(pointers)<<32 | uint64(depth) + } type walker struct { Result interface{} - copiers map[reflect.Type]CopierFunc + copiers map[reflect.Type]CopierFunc + shallowCopiers map[reflect.Type]struct{} - depth int - ignoreDepth int - vals []reflect.Value - cs []reflect.Value + + depth int + + ignoreDepth int + + vals []reflect.Value + + cs []reflect.Value // This stores the number of pointers we've walked over, indexed by depth. + ps []int // If an interface is indirected by a pointer, we need to know the type of + // interface to create when creating the new value. Store the interface + // types here, indexed by both the walk depth and the number of pointers + // already seen at that depth. Use ifaceKey to calculate the proper uint64 + // value. + ifaceTypes map[uint64]reflect.Type // any locks we've taken, indexed by depth + locks []sync.Locker + // take locks while walking the structure + useLocks bool } func (w *walker) Enter(l reflectwalk.Location) error { + w.depth++ // ensure we have enough elements to index via w.depth + for w.depth >= len(w.locks) { + w.locks = append(w.locks, nil) + } for len(w.ps) < w.depth+1 { + w.ps = append(w.ps, 0) + } return nil + } func (w *walker) Exit(l reflectwalk.Location) error { + locker := w.locks[w.depth] + w.locks[w.depth] = nil + if locker != nil { + defer locker.Unlock() + } // clear out pointers and interfaces as we exit the stack + w.ps[w.depth] = 0 for k := range w.ifaceTypes { + mask := uint64(^uint32(0)) + if k&mask == uint64(w.depth) { + delete(w.ifaceTypes, k) + } + } w.depth-- + if w.ignoreDepth > w.depth { + w.ignoreDepth = 0 + } if w.ignoring() { + return nil + } switch l { + case reflectwalk.Array: + fallthrough + case reflectwalk.Map: + fallthrough + case reflectwalk.Slice: + w.replacePointerMaybe() // Pop map off our container + w.cs = w.cs[:len(w.cs)-1] + case reflectwalk.MapValue: + // Pop off the key and value + mv := w.valPop() + mk := w.valPop() + m := w.cs[len(w.cs)-1] // If mv is the zero value, SetMapIndex deletes the key form the map, + // or in this case never adds it. We need to create a properly typed + // zero value so that this key can be set. + if !mv.IsValid() { + mv = reflect.Zero(m.Elem().Type().Elem()) + } + m.Elem().SetMapIndex(mk, mv) + case reflectwalk.ArrayElem: + // Pop off the value and the index and set it on the array + v := w.valPop() + i := w.valPop().Interface().(int) + if v.IsValid() { + a := w.cs[len(w.cs)-1] + ae := a.Elem().Index(i) // storing array as pointer on stack - so need Elem() call + if ae.CanSet() { + ae.Set(v) + } + } + case reflectwalk.SliceElem: + // Pop off the value and the index and set it on the slice + v := w.valPop() + i := w.valPop().Interface().(int) + if v.IsValid() { + s := w.cs[len(w.cs)-1] + se := s.Elem().Index(i) + if se.CanSet() { + se.Set(v) + } + } + case reflectwalk.Struct: + w.replacePointerMaybe() // Remove the struct from the container stack + w.cs = w.cs[:len(w.cs)-1] + case reflectwalk.StructField: + // Pop off the value and the field + v := w.valPop() + f := w.valPop().Interface().(reflect.StructField) + if v.IsValid() { + s := w.cs[len(w.cs)-1] + sf := reflect.Indirect(s).FieldByName(f.Name) if sf.CanSet() { + sf.Set(v) + } + } + case reflectwalk.WalkLoc: + // Clear out the slices for GC + w.cs = nil + w.vals = nil + } return nil + } func (w *walker) Map(m reflect.Value) error { + if w.ignoring() { + return nil + } + w.lock(m) // Create the map. If the map itself is nil, then just make a nil map + var newMap reflect.Value + if m.IsNil() { + newMap = reflect.New(m.Type()) + } else { + newMap = wrapPtr(reflect.MakeMap(m.Type())) + } w.cs = append(w.cs, newMap) + w.valPush(newMap) + return nil + } func (w *walker) MapElem(m, k, v reflect.Value) error { + return nil + } func (w *walker) PointerEnter(v bool) error { + if v { + w.ps[w.depth]++ + } + return nil + } func (w *walker) PointerExit(v bool) error { + if v { + w.ps[w.depth]-- + } + return nil + } func (w *walker) Pointer(v reflect.Value) error { + if _, ok := w.shallowCopiers[v.Type()]; ok { + // Shallow copy this value. Use the same logic as primitive, then + // return skip. + if err := w.Primitive(v); err != nil { + return err + } return reflectwalk.SkipEntry + } return nil + } func (w *walker) Interface(v reflect.Value) error { + if !v.IsValid() { + return nil + } + if w.ifaceTypes == nil { + w.ifaceTypes = make(map[uint64]reflect.Type) + } w.ifaceTypes[ifaceKey(w.ps[w.depth], w.depth)] = v.Type() + return nil + } func (w *walker) Primitive(v reflect.Value) error { + if w.ignoring() { + return nil + } + w.lock(v) // IsValid verifies the v is non-zero and CanInterface verifies + // that we're allowed to read this value (unexported fields). + var newV reflect.Value + if v.IsValid() && v.CanInterface() { + newV = reflect.New(v.Type()) + newV.Elem().Set(v) + } w.valPush(newV) + w.replacePointerMaybe() + return nil + } func (w *walker) Slice(s reflect.Value) error { + if w.ignoring() { + return nil + } + w.lock(s) var newS reflect.Value + if s.IsNil() { + newS = reflect.New(s.Type()) + } else { + newS = wrapPtr(reflect.MakeSlice(s.Type(), s.Len(), s.Cap())) + } w.cs = append(w.cs, newS) + w.valPush(newS) + return nil + } func (w *walker) SliceElem(i int, elem reflect.Value) error { + if w.ignoring() { + return nil + } // We don't write the slice here because elem might still be + // arbitrarily complex. Just record the index and continue on. + w.valPush(reflect.ValueOf(i)) return nil + } func (w *walker) Array(a reflect.Value) error { + if w.ignoring() { + return nil + } + w.lock(a) newA := reflect.New(a.Type()) w.cs = append(w.cs, newA) + w.valPush(newA) + return nil + } func (w *walker) ArrayElem(i int, elem reflect.Value) error { + if w.ignoring() { + return nil + } // We don't write the array here because elem might still be + // arbitrarily complex. Just record the index and continue on. + w.valPush(reflect.ValueOf(i)) return nil + } func (w *walker) Struct(s reflect.Value) error { + if w.ignoring() { + return nil + } + w.lock(s) var v reflect.Value + if c, ok := w.copiers[s.Type()]; ok { + // We have a Copier for this struct, so we use that copier to + // get the copy, and we ignore anything deeper than this. + w.ignoreDepth = w.depth dup, err := c(s.Interface()) + if err != nil { + return err + } // We need to put a pointer to the value on the value stack, + // so allocate a new pointer and set it. + v = reflect.New(s.Type()) + reflect.Indirect(v).Set(reflect.ValueOf(dup)) + } else { + // No copier, we copy ourselves and allow reflectwalk to guide + // us deeper into the structure for copying. + v = reflect.New(s.Type()) + } // Push the value onto the value stack for setting the struct field, + // and add the struct itself to the containers stack in case we walk + // deeper so that its own fields can be modified. + w.valPush(v) + w.cs = append(w.cs, v) return nil + } func (w *walker) StructField(f reflect.StructField, v reflect.Value) error { + if w.ignoring() { + return nil + } // If PkgPath is non-empty, this is a private (unexported) field. + // We do not set this unexported since the Go runtime doesn't allow us. + if f.PkgPath != "" { + return reflectwalk.SkipEntry + } switch f.Tag.Get(tagKey) { + case "shallow": + // If we're shallow copying then assign the value directly to the + // struct and skip the entry. + if v.IsValid() { + s := w.cs[len(w.cs)-1] + sf := reflect.Indirect(s).FieldByName(f.Name) + if sf.CanSet() { + sf.Set(v) + } + } return reflectwalk.SkipEntry case "ignore": + // Do nothing + return reflectwalk.SkipEntry + } // Push the field onto the stack, we'll handle it when we exit + // the struct field in Exit... + w.valPush(reflect.ValueOf(f)) return nil + } // ignore causes the walker to ignore any more values until we exit this on + func (w *walker) ignore() { + w.ignoreDepth = w.depth + } func (w *walker) ignoring() bool { + return w.ignoreDepth > 0 && w.depth >= w.ignoreDepth + } func (w *walker) pointerPeek() bool { + return w.ps[w.depth] > 0 + } func (w *walker) valPop() reflect.Value { + result := w.vals[len(w.vals)-1] + w.vals = w.vals[:len(w.vals)-1] // If we're out of values, that means we popped everything off. In + // this case, we reset the result so the next pushed value becomes + // the result. + if len(w.vals) == 0 { + w.Result = nil + } return result + } func (w *walker) valPush(v reflect.Value) { + w.vals = append(w.vals, v) // If we haven't set the result yet, then this is the result since + // it is the first (outermost) value we're seeing. + if w.Result == nil && v.IsValid() { + w.Result = v.Interface() + } + } func (w *walker) replacePointerMaybe() { + // Determine the last pointer value. If it is NOT a pointer, then + // we need to push that onto the stack. + if !w.pointerPeek() { + w.valPush(reflect.Indirect(w.valPop())) + return + } v := w.valPop() // If the expected type is a pointer to an interface of any depth, + // such as *interface{}, **interface{}, etc., then we need to convert + // the value "v" from *CONCRETE to *interface{} so types match for + // Set. + // + // Example if v is type *Foo where Foo is a struct, v would become + // *interface{} instead. This only happens if we have an interface expectation + // at this depth. + // + // For more info, see GH-16 + if iType, ok := w.ifaceTypes[ifaceKey(w.ps[w.depth], w.depth)]; ok && iType.Kind() == reflect.Interface { - y := reflect.New(iType) // Create *interface{} + + y := reflect.New(iType) // Create *interface{} + y.Elem().Set(reflect.Indirect(v)) // Assign "Foo" to interface{} (dereferenced) - v = y // v is now typed *interface{} (where *v = Foo) + + v = y // v is now typed *interface{} (where *v = Foo) + } for i := 1; i < w.ps[w.depth]; i++ { + if iType, ok := w.ifaceTypes[ifaceKey(w.ps[w.depth]-i, w.depth)]; ok { + iface := reflect.New(iType).Elem() + iface.Set(v) + v = iface + } p := reflect.New(v.Type()) + p.Elem().Set(v) + v = p + } w.valPush(v) + } // if this value is a Locker, lock it and add it to the locks slice + func (w *walker) lock(v reflect.Value) { + if !w.useLocks { + return + } if !v.IsValid() || !v.CanInterface() { + return + } type rlocker interface { @@ -579,52 +952,93 @@ func (w *walker) lock(v reflect.Value) { var locker sync.Locker // We can't call Interface() on a value directly, since that requires + // a copy. This is OK, since the pointer to a value which is a sync.Locker + // is also a sync.Locker. + if v.Kind() == reflect.Ptr { + switch l := v.Interface().(type) { + case rlocker: + // don't lock a mutex directly + if _, ok := l.(*sync.RWMutex); !ok { + locker = l.RLocker() + } + case sync.Locker: + locker = l + } + } else if v.CanAddr() { + switch l := v.Addr().Interface().(type) { + case rlocker: + // don't lock a mutex directly + if _, ok := l.(*sync.RWMutex); !ok { + locker = l.RLocker() + } + case sync.Locker: + locker = l + } + } // still no callable locker + if locker == nil { + return + } // don't lock a mutex directly + switch locker.(type) { + case *sync.Mutex, *sync.RWMutex: + return + } locker.Lock() + w.locks[w.depth] = locker + } // wrapPtr is a helper that takes v and always make it *v. copystructure + // stores things internally as pointers until the last moment before unwrapping + func wrapPtr(v reflect.Value) reflect.Value { + if !v.IsValid() { + return v + } + vPtr := reflect.New(v.Type()) + vPtr.Elem().Set(v) + return vPtr + } diff --git a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go index 3a754ca..1f5cd6f 100644 --- a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go +++ b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go @@ -12,268 +12,471 @@ import ( ) // typedDecodeHook takes a raw DecodeHookFunc (an interface{}) and turns + // it into the proper DecodeHookFunc type, such as DecodeHookFuncType. + func typedDecodeHook(h DecodeHookFunc) DecodeHookFunc { + // Create variables here so we can reference them with the reflect pkg + var f1 DecodeHookFuncType + var f2 DecodeHookFuncKind + var f3 DecodeHookFuncValue // Fill in the variables into this interface and the rest is done + // automatically using the reflect package. + potential := []interface{}{f1, f2, f3} v := reflect.ValueOf(h) + vt := v.Type() + for _, raw := range potential { + pt := reflect.ValueOf(raw).Type() + if vt.ConvertibleTo(pt) { + return v.Convert(pt).Interface() + } + } return nil + } // DecodeHookExec executes the given decode hook. This should be used + // since it'll naturally degrade to the older backwards compatible DecodeHookFunc + // that took reflect.Kind instead of reflect.Type. + func DecodeHookExec( + raw DecodeHookFunc, + from reflect.Value, to reflect.Value) (interface{}, error) { switch f := typedDecodeHook(raw).(type) { + case DecodeHookFuncType: + return f(from.Type(), to.Type(), from.Interface()) + case DecodeHookFuncKind: + return f(from.Kind(), to.Kind(), from.Interface()) + case DecodeHookFuncValue: + return f(from, to) + default: + return nil, errors.New("invalid decode hook signature") + } + } // ComposeDecodeHookFunc creates a single DecodeHookFunc that + // automatically composes multiple DecodeHookFuncs. + // + // The composed funcs are called in order, with the result of the + // previous transformation. + func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc { + return func(f reflect.Value, t reflect.Value) (interface{}, error) { + var err error + data := f.Interface() newFrom := f + for _, f1 := range fs { + data, err = DecodeHookExec(f1, newFrom, t) + if err != nil { + return nil, err + } + newFrom = reflect.ValueOf(data) + } return data, nil + } + } // OrComposeDecodeHookFunc executes all input hook functions until one of them returns no error. In that case its value is returned. + // If all hooks return an error, OrComposeDecodeHookFunc returns an error concatenating all error messages. + func OrComposeDecodeHookFunc(ff ...DecodeHookFunc) DecodeHookFunc { + return func(a, b reflect.Value) (interface{}, error) { + var allErrs string + var out interface{} + var err error for _, f := range ff { + out, err = DecodeHookExec(f, a, b) + if err != nil { + allErrs += err.Error() + "\n" + continue + } return out, nil + } return nil, errors.New(allErrs) + } + } // StringToSliceHookFunc returns a DecodeHookFunc that converts + // string to []string by splitting on the given sep. + func StringToSliceHookFunc(sep string) DecodeHookFunc { + return func( + f reflect.Kind, + t reflect.Kind, + data interface{}) (interface{}, error) { + if f != reflect.String || t != reflect.Slice { + return data, nil + } raw := data.(string) + if raw == "" { + return []string{}, nil + } return strings.Split(raw, sep), nil + } + } // StringToTimeDurationHookFunc returns a DecodeHookFunc that converts + // strings to time.Duration. + func StringToTimeDurationHookFunc() DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(time.Duration(5)) { + return data, nil + } // Convert it by parsing + return time.ParseDuration(data.(string)) + } + } // StringToIPHookFunc returns a DecodeHookFunc that converts + // strings to net.IP + func StringToIPHookFunc() DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(net.IP{}) { + return data, nil + } // Convert it by parsing + ip := net.ParseIP(data.(string)) + if ip == nil { + return net.IP{}, fmt.Errorf("failed parsing ip %v", data) + } return ip, nil + } + } // StringToIPNetHookFunc returns a DecodeHookFunc that converts + // strings to net.IPNet + func StringToIPNetHookFunc() DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(net.IPNet{}) { + return data, nil + } // Convert it by parsing + _, net, err := net.ParseCIDR(data.(string)) + return net, err + } + } // StringToTimeHookFunc returns a DecodeHookFunc that converts + // strings to time.Time. + func StringToTimeHookFunc(layout string) DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(time.Time{}) { + return data, nil + } // Convert it by parsing + return time.Parse(layout, data.(string)) + } + } // WeaklyTypedHook is a DecodeHookFunc which adds support for weak typing to + // the decoder. + // + // Note that this is significantly different from the WeaklyTypedInput option + // of the DecoderConfig. + func WeaklyTypedHook( + f reflect.Kind, + t reflect.Kind, + data interface{}) (interface{}, error) { + dataVal := reflect.ValueOf(data) + switch t { + case reflect.String: + switch f { + case reflect.Bool: + if dataVal.Bool() { + return "1", nil + } + return "0", nil + case reflect.Float32: + return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil + case reflect.Int: + return strconv.FormatInt(dataVal.Int(), 10), nil + case reflect.Slice: + dataType := dataVal.Type() + elemKind := dataType.Elem().Kind() + if elemKind == reflect.Uint8 { + return string(dataVal.Interface().([]uint8)), nil + } + case reflect.Uint: + return strconv.FormatUint(dataVal.Uint(), 10), nil + } + } return data, nil + } func RecursiveStructToMapHookFunc() DecodeHookFunc { + return func(f reflect.Value, t reflect.Value) (interface{}, error) { + if f.Kind() != reflect.Struct { + return f.Interface(), nil + } var i interface{} = struct{}{} + if t.Type() != reflect.TypeOf(&i).Elem() { + return f.Interface(), nil + } m := make(map[string]interface{}) + t.Set(reflect.ValueOf(m)) return f.Interface(), nil + } + } // TextUnmarshallerHookFunc returns a DecodeHookFunc that applies + // strings to the UnmarshalText function, when the target type + // implements the encoding.TextUnmarshaler interface + func TextUnmarshallerHookFunc() DecodeHookFuncType { + return func( + f reflect.Type, + t reflect.Type, + data interface{}) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + result := reflect.New(t).Interface() + unmarshaller, ok := result.(encoding.TextUnmarshaler) + if !ok { + return data, nil + } + if err := unmarshaller.UnmarshalText([]byte(data.(string))); err != nil { + return nil, err + } + return result, nil + } + } diff --git a/vendor/github.com/mitchellh/mapstructure/error.go b/vendor/github.com/mitchellh/mapstructure/error.go index 47a99e5..a6c325c 100644 --- a/vendor/github.com/mitchellh/mapstructure/error.go +++ b/vendor/github.com/mitchellh/mapstructure/error.go @@ -8,43 +8,69 @@ import ( ) // Error implements the error interface and can represents multiple + // errors that occur in the course of a single decode. + type Error struct { Errors []string } func (e *Error) Error() string { + points := make([]string, len(e.Errors)) + for i, err := range e.Errors { + points[i] = fmt.Sprintf("* %s", err) + } sort.Strings(points) + return fmt.Sprintf( + "%d error(s) decoding:\n\n%s", + len(e.Errors), strings.Join(points, "\n")) + } // WrappedErrors implements the errwrap.Wrapper interface to make this + // return value more useful with the errwrap and go-multierror libraries. + func (e *Error) WrappedErrors() []error { + if e == nil { + return nil + } result := make([]error, len(e.Errors)) + for i, e := range e.Errors { + result[i] = errors.New(e) + } return result + } func appendErrors(errors []string, err error) []string { + switch e := err.(type) { + case *Error: + return append(errors, e.Errors...) + default: + return append(errors, e.Error()) + } + } diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure.go b/vendor/github.com/mitchellh/mapstructure/mapstructure.go index fadccc4..bb7cb44 100644 --- a/vendor/github.com/mitchellh/mapstructure/mapstructure.go +++ b/vendor/github.com/mitchellh/mapstructure/mapstructure.go @@ -1,161 +1,319 @@ // Package mapstructure exposes functionality to convert one arbitrary + // Go type into another, typically to convert a map[string]interface{} + // into a native Go structure. + // + // The Go structure can be arbitrarily complex, containing slices, + // other structs, etc. and the decoder will properly decode nested + // maps and so on into the proper structures in the native Go struct. + // See the examples to see what the decoder is capable of. + // + // The simplest function to start with is Decode. + // + // # Field Tags + // + // When decoding to a struct, mapstructure will use the field name by + // default to perform the mapping. For example, if a struct has a field + // "Username" then mapstructure will look for a key in the source value + // of "username" (case insensitive). + // + // type User struct { + // Username string + // } + // + // You can change the behavior of mapstructure by using struct tags. + // The default struct tag that mapstructure looks for is "mapstructure" + // but you can customize it using DecoderConfig. + // + // # Renaming Fields + // + // To rename the key that mapstructure looks for, use the "mapstructure" + // tag and set a value directly. For example, to change the "username" example + // above to "user": + // + // type User struct { + // Username string `mapstructure:"user"` + // } + // + // # Embedded Structs and Squashing + // + // Embedded structs are treated as if they're another field with that name. + // By default, the two structs below are equivalent when decoding with + // mapstructure: + // + // type Person struct { + // Name string + // } + // + // type Friend struct { + // Person + // } + // + // type Friend struct { + // Person Person + // } + // + // This would require an input that looks like below: + // + // map[string]interface{}{ + // "person": map[string]interface{}{"name": "alice"}, + // } + // + // If your "person" value is NOT nested, then you can append ",squash" to + // your tag value and mapstructure will treat it as if the embedded struct + // were part of the struct directly. Example: + // + // type Friend struct { + // Person `mapstructure:",squash"` + // } + // + // Now the following input would be accepted: + // + // map[string]interface{}{ + // "name": "alice", + // } + // + // When decoding from a struct to a map, the squash tag squashes the struct + // fields into a single map. Using the example structs from above: + // + // Friend{Person: Person{Name: "alice"}} + // + // Will be decoded into a map: + // + // map[string]interface{}{ + // "name": "alice", + // } + // + // DecoderConfig has a field that changes the behavior of mapstructure + // to always squash embedded structs. + // + // # Remainder Values + // + // If there are any unmapped keys in the source value, mapstructure by + // default will silently ignore them. You can error by setting ErrorUnused + // in DecoderConfig. If you're using Metadata you can also maintain a slice + // of the unused keys. + // + // You can also use the ",remain" suffix on your tag to collect all unused + // values in a map. The field with this tag MUST be a map type and should + // probably be a "map[string]interface{}" or "map[interface{}]interface{}". + // See example below: + // + // type Friend struct { + // Name string + // Other map[string]interface{} `mapstructure:",remain"` + // } + // + // Given the input below, Other would be populated with the other + // values that weren't used (everything but "name"): + // + // map[string]interface{}{ + // "name": "bob", + // "address": "123 Maple St.", + // } + // + // # Omit Empty Values + // + // When decoding from a struct to any other value, you may use the + // ",omitempty" suffix on your tag to omit that value if it equates to + // the zero value. The zero value of all types is specified in the Go + // specification. + // + // For example, the zero type of a numeric type is zero ("0"). If the struct + // field value is zero and a numeric type, the field is empty, and it won't + // be encoded into the destination type. + // + // type Source struct { + // Age int `mapstructure:",omitempty"` + // } + // + // # Unexported fields + // + // Since unexported (private) struct fields cannot be set outside the package + // where they are defined, the decoder will simply skip them. + // + // For this output type definition: + // + // type Exported struct { + // private string // this unexported field will be skipped + // Public string + // } + // + // Using this map as input: + // + // map[string]interface{}{ + // "private": "I will be ignored", + // "Public": "I made it through!", + // } + // + // The following struct will be decoded: + // + // type Exported struct { + // private: "" // field is left with an empty string (zero value) + // Public: "I made it through!" + // } + // + // # Other Configuration + // + // mapstructure is highly configurable. See the DecoderConfig struct + // for other features and options that are supported. + package mapstructure import ( @@ -169,1372 +327,2322 @@ import ( ) // DecodeHookFunc is the callback function that can be used for + // data transformations. See "DecodeHook" in the DecoderConfig + // struct. + // + // The type must be one of DecodeHookFuncType, DecodeHookFuncKind, or + // DecodeHookFuncValue. + // Values are a superset of Types (Values can return types), and Types are a + // superset of Kinds (Types can return Kinds) and are generally a richer thing + // to use, but Kinds are simpler if you only need those. + // + // The reason DecodeHookFunc is multi-typed is for backwards compatibility: + // we started with Kinds and then realized Types were the better solution, + // but have a promise to not break backwards compat so we now support + // both. + type DecodeHookFunc interface{} // DecodeHookFuncType is a DecodeHookFunc which has complete information about + // the source and target types. + type DecodeHookFuncType func(reflect.Type, reflect.Type, interface{}) (interface{}, error) // DecodeHookFuncKind is a DecodeHookFunc which knows only the Kinds of the + // source and target types. + type DecodeHookFuncKind func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error) // DecodeHookFuncValue is a DecodeHookFunc which has complete access to both the source and target + // values. + type DecodeHookFuncValue func(from reflect.Value, to reflect.Value) (interface{}, error) // DecoderConfig is the configuration that is used to create a new decoder + // and allows customization of various aspects of decoding. + type DecoderConfig struct { + // DecodeHook, if set, will be called before any decoding and any + // type conversion (if WeaklyTypedInput is on). This lets you modify + // the values before they're set down onto the resulting struct. The + // DecodeHook is called for every map and value in the input. This means + // that if a struct has embedded fields with squash tags the decode hook + // is called only once with all of the input data, not once for each + // embedded struct. + // + // If an error is returned, the entire decode will fail with that error. + DecodeHook DecodeHookFunc // If ErrorUnused is true, then it is an error for there to exist + // keys in the original map that were unused in the decoding process + // (extra keys). + ErrorUnused bool // If ErrorUnset is true, then it is an error for there to exist + // fields in the result that were not set in the decoding process + // (extra fields). This only applies to decoding to a struct. This + // will affect all nested structs as well. + ErrorUnset bool // ZeroFields, if set to true, will zero fields before writing them. + // For example, a map will be emptied before decoded values are put in + // it. If this is false, a map will be merged. + ZeroFields bool // If WeaklyTypedInput is true, the decoder will make the following + // "weak" conversions: + // + // - bools to string (true = "1", false = "0") + // - numbers to string (base 10) + // - bools to int/uint (true = 1, false = 0) + // - strings to int/uint (base implied by prefix) + // - int to bool (true if value != 0) + // - string to bool (accepts: 1, t, T, TRUE, true, True, 0, f, F, + // FALSE, false, False. Anything else is an error) + // - empty array = empty map and vice versa + // - negative numbers to overflowed uint values (base 10) + // - slice of maps to a merged map + // - single values are converted to slices if required. Each + // element is weakly decoded. For example: "4" can become []int{4} + // if the target type is an int slice. + // + WeaklyTypedInput bool // Squash will squash embedded structs. A squash tag may also be + // added to an individual struct field using a tag. For example: + // + // type Parent struct { + // Child `mapstructure:",squash"` + // } + Squash bool // Metadata is the struct that will contain extra metadata about + // the decoding. If this is nil, then no metadata will be tracked. + Metadata *Metadata // Result is a pointer to the struct that will contain the decoded + // value. + Result interface{} // The tag name that mapstructure reads for field names. This + // defaults to "mapstructure" + TagName string // IgnoreUntaggedFields ignores all struct fields without explicit + // TagName, comparable to `mapstructure:"-"` as default behaviour. + IgnoreUntaggedFields bool // MatchName is the function used to match the map key to the struct + // field name or tag. Defaults to `strings.EqualFold`. This can be used + // to implement case-sensitive tag values, support snake casing, etc. + MatchName func(mapKey, fieldName string) bool } // A Decoder takes a raw interface value and turns it into structured + // data, keeping track of rich error information along the way in case + // anything goes wrong. Unlike the basic top-level Decode method, you can + // more finely control how the Decoder behaves using the DecoderConfig + // structure. The top-level Decode method is just a convenience that sets + // up the most basic Decoder. + type Decoder struct { config *DecoderConfig } // Metadata contains information about decoding a structure that + // is tedious or difficult to get otherwise. + type Metadata struct { + // Keys are the keys of the structure which were successfully decoded + Keys []string // Unused is a slice of keys that were found in the raw value but + // weren't decoded since there was no matching field in the result interface + Unused []string // Unset is a slice of field names that were found in the result interface + // but weren't set in the decoding process since there was no matching value + // in the input + Unset []string } // Decode takes an input structure and uses reflection to translate it to + // the output structure. output must be a pointer to a map or struct. + func Decode(input interface{}, output interface{}) error { + config := &DecoderConfig{ + Metadata: nil, - Result: output, + + Result: output, } decoder, err := NewDecoder(config) + if err != nil { + return err + } return decoder.Decode(input) + } // WeakDecode is the same as Decode but is shorthand to enable + // WeaklyTypedInput. See DecoderConfig for more info. + func WeakDecode(input, output interface{}) error { + config := &DecoderConfig{ - Metadata: nil, - Result: output, + + Metadata: nil, + + Result: output, + WeaklyTypedInput: true, } decoder, err := NewDecoder(config) + if err != nil { + return err + } return decoder.Decode(input) + } // DecodeMetadata is the same as Decode, but is shorthand to + // enable metadata collection. See DecoderConfig for more info. + func DecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error { + config := &DecoderConfig{ + Metadata: metadata, - Result: output, + + Result: output, } decoder, err := NewDecoder(config) + if err != nil { + return err + } return decoder.Decode(input) + } // WeakDecodeMetadata is the same as Decode, but is shorthand to + // enable both WeaklyTypedInput and metadata collection. See + // DecoderConfig for more info. + func WeakDecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error { + config := &DecoderConfig{ - Metadata: metadata, - Result: output, + + Metadata: metadata, + + Result: output, + WeaklyTypedInput: true, } decoder, err := NewDecoder(config) + if err != nil { + return err + } return decoder.Decode(input) + } // NewDecoder returns a new decoder for the given configuration. Once + // a decoder has been returned, the same configuration must not be used + // again. + func NewDecoder(config *DecoderConfig) (*Decoder, error) { + val := reflect.ValueOf(config.Result) + if val.Kind() != reflect.Ptr { + return nil, errors.New("result must be a pointer") + } val = val.Elem() + if !val.CanAddr() { + return nil, errors.New("result must be addressable (a pointer)") + } if config.Metadata != nil { + if config.Metadata.Keys == nil { + config.Metadata.Keys = make([]string, 0) + } if config.Metadata.Unused == nil { + config.Metadata.Unused = make([]string, 0) + } if config.Metadata.Unset == nil { + config.Metadata.Unset = make([]string, 0) + } + } if config.TagName == "" { + config.TagName = "mapstructure" + } if config.MatchName == nil { + config.MatchName = strings.EqualFold + } result := &Decoder{ + config: config, } return result, nil + } // Decode decodes the given raw interface to the target pointer specified + // by the configuration. + func (d *Decoder) Decode(input interface{}) error { + return d.decode("", input, reflect.ValueOf(d.config.Result).Elem()) + } // Decodes an unknown data type into a specific reflection value. + func (d *Decoder) decode(name string, input interface{}, outVal reflect.Value) error { + var inputVal reflect.Value + if input != nil { + inputVal = reflect.ValueOf(input) // We need to check here if input is a typed nil. Typed nils won't + // match the "input == nil" below so we check that here. + if inputVal.Kind() == reflect.Ptr && inputVal.IsNil() { + input = nil + } + } if input == nil { + // If the data is nil, then we don't set anything, unless ZeroFields is set + // to true. + if d.config.ZeroFields { + outVal.Set(reflect.Zero(outVal.Type())) if d.config.Metadata != nil && name != "" { + d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) + } + } + return nil + } if !inputVal.IsValid() { + // If the input value is invalid, then we just set the value + // to be the zero value. + outVal.Set(reflect.Zero(outVal.Type())) + if d.config.Metadata != nil && name != "" { + d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) + } + return nil + } if d.config.DecodeHook != nil { + // We have a DecodeHook, so let's pre-process the input. + var err error + input, err = DecodeHookExec(d.config.DecodeHook, inputVal, outVal) + if err != nil { + return fmt.Errorf("error decoding '%s': %s", name, err) + } + } var err error + outputKind := getKind(outVal) + addMetaKey := true + switch outputKind { + case reflect.Bool: + err = d.decodeBool(name, input, outVal) + case reflect.Interface: + err = d.decodeBasic(name, input, outVal) + case reflect.String: + err = d.decodeString(name, input, outVal) + case reflect.Int: + err = d.decodeInt(name, input, outVal) + case reflect.Uint: + err = d.decodeUint(name, input, outVal) + case reflect.Float32: + err = d.decodeFloat(name, input, outVal) + case reflect.Struct: + err = d.decodeStruct(name, input, outVal) + case reflect.Map: + err = d.decodeMap(name, input, outVal) + case reflect.Ptr: + addMetaKey, err = d.decodePtr(name, input, outVal) + case reflect.Slice: + err = d.decodeSlice(name, input, outVal) + case reflect.Array: + err = d.decodeArray(name, input, outVal) + case reflect.Func: + err = d.decodeFunc(name, input, outVal) + default: + // If we reached this point then we weren't able to decode it + return fmt.Errorf("%s: unsupported type: %s", name, outputKind) + } // If we reached here, then we successfully decoded SOMETHING, so + // mark the key as used if we're tracking metainput. + if addMetaKey && d.config.Metadata != nil && name != "" { + d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) + } return err + } // This decodes a basic type (bool, int, string, etc.) and sets the + // value to "data" of that type. + func (d *Decoder) decodeBasic(name string, data interface{}, val reflect.Value) error { + if val.IsValid() && val.Elem().IsValid() { + elem := val.Elem() // If we can't address this element, then its not writable. Instead, + // we make a copy of the value (which is a pointer and therefore + // writable), decode into that, and replace the whole value. + copied := false + if !elem.CanAddr() { + copied = true // Make *T + copy := reflect.New(elem.Type()) // *T = elem + copy.Elem().Set(elem) // Set elem so we decode into it + elem = copy + } // Decode. If we have an error then return. We also return right + // away if we're not a copy because that means we decoded directly. + if err := d.decode(name, data, elem); err != nil || !copied { + return err + } // If we're a copy, we need to set te final result + val.Set(elem.Elem()) + return nil + } dataVal := reflect.ValueOf(data) // If the input data is a pointer, and the assigned type is the dereference + // of that exact pointer, then indirect it so that we can assign it. + // Example: *string to string + if dataVal.Kind() == reflect.Ptr && dataVal.Type().Elem() == val.Type() { + dataVal = reflect.Indirect(dataVal) + } if !dataVal.IsValid() { + dataVal = reflect.Zero(val.Type()) + } dataValType := dataVal.Type() + if !dataValType.AssignableTo(val.Type()) { + return fmt.Errorf( + "'%s' expected type '%s', got '%s'", + name, val.Type(), dataValType) + } val.Set(dataVal) + return nil + } func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataKind := getKind(dataVal) converted := true + switch { + case dataKind == reflect.String: + val.SetString(dataVal.String()) + case dataKind == reflect.Bool && d.config.WeaklyTypedInput: + if dataVal.Bool() { + val.SetString("1") + } else { + val.SetString("0") + } + case dataKind == reflect.Int && d.config.WeaklyTypedInput: + val.SetString(strconv.FormatInt(dataVal.Int(), 10)) + case dataKind == reflect.Uint && d.config.WeaklyTypedInput: + val.SetString(strconv.FormatUint(dataVal.Uint(), 10)) + case dataKind == reflect.Float32 && d.config.WeaklyTypedInput: + val.SetString(strconv.FormatFloat(dataVal.Float(), 'f', -1, 64)) + case dataKind == reflect.Slice && d.config.WeaklyTypedInput, + dataKind == reflect.Array && d.config.WeaklyTypedInput: + dataType := dataVal.Type() + elemKind := dataType.Elem().Kind() + switch elemKind { + case reflect.Uint8: + var uints []uint8 + if dataKind == reflect.Array { + uints = make([]uint8, dataVal.Len(), dataVal.Len()) + for i := range uints { + uints[i] = dataVal.Index(i).Interface().(uint8) + } + } else { + uints = dataVal.Interface().([]uint8) + } + val.SetString(string(uints)) + default: + converted = false + } + default: + converted = false + } if !converted { + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", + name, val.Type(), dataVal.Type(), data) + } return nil + } func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataKind := getKind(dataVal) + dataType := dataVal.Type() switch { + case dataKind == reflect.Int: + val.SetInt(dataVal.Int()) + case dataKind == reflect.Uint: + val.SetInt(int64(dataVal.Uint())) + case dataKind == reflect.Float32: + val.SetInt(int64(dataVal.Float())) + case dataKind == reflect.Bool && d.config.WeaklyTypedInput: + if dataVal.Bool() { + val.SetInt(1) + } else { + val.SetInt(0) + } + case dataKind == reflect.String && d.config.WeaklyTypedInput: + str := dataVal.String() + if str == "" { + str = "0" + } i, err := strconv.ParseInt(str, 0, val.Type().Bits()) + if err == nil { + val.SetInt(i) + } else { + return fmt.Errorf("cannot parse '%s' as int: %s", name, err) + } + case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": + jn := data.(json.Number) + i, err := jn.Int64() + if err != nil { + return fmt.Errorf( + "error decoding json.Number into %s: %s", name, err) + } + val.SetInt(i) + default: + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", + name, val.Type(), dataVal.Type(), data) + } return nil + } func (d *Decoder) decodeUint(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataKind := getKind(dataVal) + dataType := dataVal.Type() switch { + case dataKind == reflect.Int: + i := dataVal.Int() + if i < 0 && !d.config.WeaklyTypedInput { + return fmt.Errorf("cannot parse '%s', %d overflows uint", + name, i) + } + val.SetUint(uint64(i)) + case dataKind == reflect.Uint: + val.SetUint(dataVal.Uint()) + case dataKind == reflect.Float32: + f := dataVal.Float() + if f < 0 && !d.config.WeaklyTypedInput { + return fmt.Errorf("cannot parse '%s', %f overflows uint", + name, f) + } + val.SetUint(uint64(f)) + case dataKind == reflect.Bool && d.config.WeaklyTypedInput: + if dataVal.Bool() { + val.SetUint(1) + } else { + val.SetUint(0) + } + case dataKind == reflect.String && d.config.WeaklyTypedInput: + str := dataVal.String() + if str == "" { + str = "0" + } i, err := strconv.ParseUint(str, 0, val.Type().Bits()) + if err == nil { + val.SetUint(i) + } else { + return fmt.Errorf("cannot parse '%s' as uint: %s", name, err) + } + case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": + jn := data.(json.Number) + i, err := strconv.ParseUint(string(jn), 0, 64) + if err != nil { + return fmt.Errorf( + "error decoding json.Number into %s: %s", name, err) + } + val.SetUint(i) + default: + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", + name, val.Type(), dataVal.Type(), data) + } return nil + } func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataKind := getKind(dataVal) switch { + case dataKind == reflect.Bool: + val.SetBool(dataVal.Bool()) + case dataKind == reflect.Int && d.config.WeaklyTypedInput: + val.SetBool(dataVal.Int() != 0) + case dataKind == reflect.Uint && d.config.WeaklyTypedInput: + val.SetBool(dataVal.Uint() != 0) + case dataKind == reflect.Float32 && d.config.WeaklyTypedInput: + val.SetBool(dataVal.Float() != 0) + case dataKind == reflect.String && d.config.WeaklyTypedInput: + b, err := strconv.ParseBool(dataVal.String()) + if err == nil { + val.SetBool(b) + } else if dataVal.String() == "" { + val.SetBool(false) + } else { + return fmt.Errorf("cannot parse '%s' as bool: %s", name, err) + } + default: + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", + name, val.Type(), dataVal.Type(), data) + } return nil + } func (d *Decoder) decodeFloat(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataKind := getKind(dataVal) + dataType := dataVal.Type() switch { + case dataKind == reflect.Int: + val.SetFloat(float64(dataVal.Int())) + case dataKind == reflect.Uint: + val.SetFloat(float64(dataVal.Uint())) + case dataKind == reflect.Float32: + val.SetFloat(dataVal.Float()) + case dataKind == reflect.Bool && d.config.WeaklyTypedInput: + if dataVal.Bool() { + val.SetFloat(1) + } else { + val.SetFloat(0) + } + case dataKind == reflect.String && d.config.WeaklyTypedInput: + str := dataVal.String() + if str == "" { + str = "0" + } f, err := strconv.ParseFloat(str, val.Type().Bits()) + if err == nil { + val.SetFloat(f) + } else { + return fmt.Errorf("cannot parse '%s' as float: %s", name, err) + } + case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": + jn := data.(json.Number) + i, err := jn.Float64() + if err != nil { + return fmt.Errorf( + "error decoding json.Number into %s: %s", name, err) + } + val.SetFloat(i) + default: + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", + name, val.Type(), dataVal.Type(), data) + } return nil + } func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) error { + valType := val.Type() + valKeyType := valType.Key() + valElemType := valType.Elem() // By default we overwrite keys in the current map + valMap := val // If the map is nil or we're purposely zeroing fields, make a new map + if valMap.IsNil() || d.config.ZeroFields { + // Make a new map to hold our result + mapType := reflect.MapOf(valKeyType, valElemType) + valMap = reflect.MakeMap(mapType) + } // Check input type and based on the input type jump to the proper func + dataVal := reflect.Indirect(reflect.ValueOf(data)) + switch dataVal.Kind() { + case reflect.Map: + return d.decodeMapFromMap(name, dataVal, val, valMap) case reflect.Struct: + return d.decodeMapFromStruct(name, dataVal, val, valMap) case reflect.Array, reflect.Slice: + if d.config.WeaklyTypedInput { + return d.decodeMapFromSlice(name, dataVal, val, valMap) + } fallthrough default: + return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind()) + } + } func (d *Decoder) decodeMapFromSlice(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { + // Special case for BC reasons (covered by tests) + if dataVal.Len() == 0 { + val.Set(valMap) + return nil + } for i := 0; i < dataVal.Len(); i++ { + err := d.decode( + name+"["+strconv.Itoa(i)+"]", + dataVal.Index(i).Interface(), val) + if err != nil { + return err + } + } return nil + } func (d *Decoder) decodeMapFromMap(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { + valType := val.Type() + valKeyType := valType.Key() + valElemType := valType.Elem() // Accumulate errors + errors := make([]string, 0) // If the input data is empty, then we just match what the input data is. + if dataVal.Len() == 0 { + if dataVal.IsNil() { + if !val.IsNil() { + val.Set(dataVal) + } + } else { + // Set to empty allocated value + val.Set(valMap) + } return nil + } for _, k := range dataVal.MapKeys() { + fieldName := name + "[" + k.String() + "]" // First decode the key into the proper type + currentKey := reflect.Indirect(reflect.New(valKeyType)) + if err := d.decode(fieldName, k.Interface(), currentKey); err != nil { + errors = appendErrors(errors, err) + continue + } // Next decode the data into the proper type + v := dataVal.MapIndex(k).Interface() + currentVal := reflect.Indirect(reflect.New(valElemType)) + if err := d.decode(fieldName, v, currentVal); err != nil { + errors = appendErrors(errors, err) + continue + } valMap.SetMapIndex(currentKey, currentVal) + } // Set the built up map to the value + val.Set(valMap) // If we had errors, return those + if len(errors) > 0 { + return &Error{errors} + } return nil + } func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { + typ := dataVal.Type() + for i := 0; i < typ.NumField(); i++ { + // Get the StructField first since this is a cheap operation. If the + // field is unexported, then ignore it. + f := typ.Field(i) + if f.PkgPath != "" { + continue + } // Next get the actual value of this field and verify it is assignable + // to the map value. + v := dataVal.Field(i) + if !v.Type().AssignableTo(valMap.Type().Elem()) { + return fmt.Errorf("cannot assign type '%s' to map value field of type '%s'", v.Type(), valMap.Type().Elem()) + } tagValue := f.Tag.Get(d.config.TagName) + keyName := f.Name if tagValue == "" && d.config.IgnoreUntaggedFields { + continue + } // If Squash is set in the config, we squash the field down. + squash := d.config.Squash && v.Kind() == reflect.Struct && f.Anonymous v = dereferencePtrToStructIfNeeded(v, d.config.TagName) // Determine the name of the key in the map + if index := strings.Index(tagValue, ","); index != -1 { + if tagValue[:index] == "-" { + continue + } + // If "omitempty" is specified in the tag, it ignores empty values. + if strings.Index(tagValue[index+1:], "omitempty") != -1 && isEmptyValue(v) { + continue + } // If "squash" is specified in the tag, we squash the field down. + squash = squash || strings.Index(tagValue[index+1:], "squash") != -1 + if squash { + // When squashing, the embedded type can be a pointer to a struct. + if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct { + v = v.Elem() + } // The final type must be a struct + if v.Kind() != reflect.Struct { + return fmt.Errorf("cannot squash non-struct type '%s'", v.Type()) + } + } + if keyNameTagValue := tagValue[:index]; keyNameTagValue != "" { + keyName = keyNameTagValue + } + } else if len(tagValue) > 0 { + if tagValue == "-" { + continue + } + keyName = tagValue + } switch v.Kind() { + // this is an embedded struct, so handle it differently + case reflect.Struct: + x := reflect.New(v.Type()) + x.Elem().Set(v) vType := valMap.Type() + vKeyType := vType.Key() + vElemType := vType.Elem() + mType := reflect.MapOf(vKeyType, vElemType) + vMap := reflect.MakeMap(mType) // Creating a pointer to a map so that other methods can completely + // overwrite the map if need be (looking at you decodeMapFromMap). The + // indirection allows the underlying map to be settable (CanSet() == true) + // where as reflect.MakeMap returns an unsettable map. + addrVal := reflect.New(vMap.Type()) + reflect.Indirect(addrVal).Set(vMap) err := d.decode(keyName, x.Interface(), reflect.Indirect(addrVal)) + if err != nil { + return err + } // the underlying map may have been completely overwritten so pull + // it indirectly out of the enclosing value. + vMap = reflect.Indirect(addrVal) if squash { + for _, k := range vMap.MapKeys() { + valMap.SetMapIndex(k, vMap.MapIndex(k)) + } + } else { + valMap.SetMapIndex(reflect.ValueOf(keyName), vMap) + } default: + valMap.SetMapIndex(reflect.ValueOf(keyName), v) + } + } if val.CanAddr() { + val.Set(valMap) + } return nil + } func (d *Decoder) decodePtr(name string, data interface{}, val reflect.Value) (bool, error) { + // If the input data is nil, then we want to just set the output + // pointer to be nil as well. + isNil := data == nil + if !isNil { + switch v := reflect.Indirect(reflect.ValueOf(data)); v.Kind() { + case reflect.Chan, + reflect.Func, + reflect.Interface, + reflect.Map, + reflect.Ptr, + reflect.Slice: + isNil = v.IsNil() + } + } + if isNil { + if !val.IsNil() && val.CanSet() { + nilValue := reflect.New(val.Type()).Elem() + val.Set(nilValue) + } return true, nil + } // Create an element of the concrete (non pointer) type and decode + // into that. Then set the value of the pointer to this type. + valType := val.Type() + valElemType := valType.Elem() + if val.CanSet() { + realVal := val + if realVal.IsNil() || d.config.ZeroFields { + realVal = reflect.New(valElemType) + } if err := d.decode(name, data, reflect.Indirect(realVal)); err != nil { + return false, err + } val.Set(realVal) + } else { + if err := d.decode(name, data, reflect.Indirect(val)); err != nil { + return false, err + } + } + return false, nil + } func (d *Decoder) decodeFunc(name string, data interface{}, val reflect.Value) error { + // Create an element of the concrete (non pointer) type and decode + // into that. Then set the value of the pointer to this type. + dataVal := reflect.Indirect(reflect.ValueOf(data)) + if val.Type() != dataVal.Type() { + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", + name, val.Type(), dataVal.Type(), data) + } + val.Set(dataVal) + return nil + } func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataValKind := dataVal.Kind() + valType := val.Type() + valElemType := valType.Elem() + sliceType := reflect.SliceOf(valElemType) // If we have a non array/slice type then we first attempt to convert. + if dataValKind != reflect.Array && dataValKind != reflect.Slice { + if d.config.WeaklyTypedInput { + switch { + // Slice and array we use the normal logic + case dataValKind == reflect.Slice, dataValKind == reflect.Array: + break // Empty maps turn into empty slices + case dataValKind == reflect.Map: + if dataVal.Len() == 0 { + val.Set(reflect.MakeSlice(sliceType, 0, 0)) + return nil + } + // Create slice of maps of other sizes + return d.decodeSlice(name, []interface{}{data}, val) case dataValKind == reflect.String && valElemType.Kind() == reflect.Uint8: + return d.decodeSlice(name, []byte(dataVal.String()), val) // All other types we try to convert to the slice type + // and "lift" it into it. i.e. a string becomes a string slice. + default: + // Just re-try this function with data as a slice. + return d.decodeSlice(name, []interface{}{data}, val) + } + } return fmt.Errorf( + "'%s': source data must be an array or slice, got %s", name, dataValKind) + } // If the input value is nil, then don't allocate since empty != nil + if dataValKind != reflect.Array && dataVal.IsNil() { + return nil + } valSlice := val + if valSlice.IsNil() || d.config.ZeroFields { + // Make a new slice to hold our result, same size as the original data. + valSlice = reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len()) + } // Accumulate any errors + errors := make([]string, 0) for i := 0; i < dataVal.Len(); i++ { + currentData := dataVal.Index(i).Interface() + for valSlice.Len() <= i { + valSlice = reflect.Append(valSlice, reflect.Zero(valElemType)) + } + currentField := valSlice.Index(i) fieldName := name + "[" + strconv.Itoa(i) + "]" + if err := d.decode(fieldName, currentData, currentField); err != nil { + errors = appendErrors(errors, err) + } + } // Finally, set the value to the slice we built up + val.Set(valSlice) // If there were errors, we return those + if len(errors) > 0 { + return &Error{errors} + } return nil + } func (d *Decoder) decodeArray(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataValKind := dataVal.Kind() + valType := val.Type() + valElemType := valType.Elem() + arrayType := reflect.ArrayOf(valType.Len(), valElemType) valArray := val if valArray.Interface() == reflect.Zero(valArray.Type()).Interface() || d.config.ZeroFields { + // Check input type + if dataValKind != reflect.Array && dataValKind != reflect.Slice { + if d.config.WeaklyTypedInput { + switch { + // Empty maps turn into empty arrays + case dataValKind == reflect.Map: + if dataVal.Len() == 0 { + val.Set(reflect.Zero(arrayType)) + return nil + } // All other types we try to convert to the array type + // and "lift" it into it. i.e. a string becomes a string array. + default: + // Just re-try this function with data as a slice. + return d.decodeArray(name, []interface{}{data}, val) + } + } return fmt.Errorf( + "'%s': source data must be an array or slice, got %s", name, dataValKind) } + if dataVal.Len() > arrayType.Len() { + return fmt.Errorf( + "'%s': expected source data to have length less or equal to %d, got %d", name, arrayType.Len(), dataVal.Len()) } // Make a new array to hold our result, same size as the original data. + valArray = reflect.New(arrayType).Elem() + } // Accumulate any errors + errors := make([]string, 0) for i := 0; i < dataVal.Len(); i++ { + currentData := dataVal.Index(i).Interface() + currentField := valArray.Index(i) fieldName := name + "[" + strconv.Itoa(i) + "]" + if err := d.decode(fieldName, currentData, currentField); err != nil { + errors = appendErrors(errors, err) + } + } // Finally, set the value to the array we built up + val.Set(valArray) // If there were errors, we return those + if len(errors) > 0 { + return &Error{errors} + } return nil + } func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) // If the type of the value to write to and the data match directly, + // then we just set it directly instead of recursing into the structure. + if dataVal.Type() == val.Type() { + val.Set(dataVal) + return nil + } dataValKind := dataVal.Kind() + switch dataValKind { + case reflect.Map: + return d.decodeStructFromMap(name, dataVal, val) case reflect.Struct: + // Not the most efficient way to do this but we can optimize later if + // we want to. To convert from struct to struct we go to map first + // as an intermediary. // Make a new map to hold our result + mapType := reflect.TypeOf((map[string]interface{})(nil)) + mval := reflect.MakeMap(mapType) // Creating a pointer to a map so that other methods can completely + // overwrite the map if need be (looking at you decodeMapFromMap). The + // indirection allows the underlying map to be settable (CanSet() == true) + // where as reflect.MakeMap returns an unsettable map. + addrVal := reflect.New(mval.Type()) reflect.Indirect(addrVal).Set(mval) + if err := d.decodeMapFromStruct(name, dataVal, reflect.Indirect(addrVal), mval); err != nil { + return err + } result := d.decodeStructFromMap(name, reflect.Indirect(addrVal), val) + return result default: + return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind()) + } + } func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) error { + dataValType := dataVal.Type() + if kind := dataValType.Key().Kind(); kind != reflect.String && kind != reflect.Interface { + return fmt.Errorf( + "'%s' needs a map with string keys, has '%s' keys", + name, dataValType.Key().Kind()) + } dataValKeys := make(map[reflect.Value]struct{}) + dataValKeysUnused := make(map[interface{}]struct{}) + for _, dataValKey := range dataVal.MapKeys() { + dataValKeys[dataValKey] = struct{}{} + dataValKeysUnused[dataValKey.Interface()] = struct{}{} + } targetValKeysUnused := make(map[interface{}]struct{}) + errors := make([]string, 0) // This slice will keep track of all the structs we'll be decoding. + // There can be more than one struct if there are embedded structs + // that are squashed. + structs := make([]reflect.Value, 1, 5) + structs[0] = val // Compile the list of all the fields that we're going to be decoding + // from all the structs. + type field struct { field reflect.StructField - val reflect.Value + + val reflect.Value } // remainField is set to a valid field set with the "remain" tag if + // we are keeping track of remaining values. + var remainField *field fields := []field{} + for len(structs) > 0 { + structVal := structs[0] + structs = structs[1:] structType := structVal.Type() for i := 0; i < structType.NumField(); i++ { + fieldType := structType.Field(i) + fieldVal := structVal.Field(i) + if fieldVal.Kind() == reflect.Ptr && fieldVal.Elem().Kind() == reflect.Struct { + // Handle embedded struct pointers as embedded structs. + fieldVal = fieldVal.Elem() + } // If "squash" is specified in the tag, we squash the field down. + squash := d.config.Squash && fieldVal.Kind() == reflect.Struct && fieldType.Anonymous + remain := false // We always parse the tags cause we're looking for other tags too + tagParts := strings.Split(fieldType.Tag.Get(d.config.TagName), ",") + for _, tag := range tagParts[1:] { + if tag == "squash" { + squash = true + break + } if tag == "remain" { + remain = true + break + } + } if squash { + if fieldVal.Kind() != reflect.Struct { + errors = appendErrors(errors, + fmt.Errorf("%s: unsupported type for squash: %s", fieldType.Name, fieldVal.Kind())) + } else { + structs = append(structs, fieldVal) + } + continue + } // Build our field + if remain { + remainField = &field{fieldType, fieldVal} + } else { + // Normal struct field, store it away + fields = append(fields, field{fieldType, fieldVal}) + } + } + } // for fieldType, field := range fields { + for _, f := range fields { + field, fieldValue := f.field, f.val + fieldName := field.Name tagValue := field.Tag.Get(d.config.TagName) + tagValue = strings.SplitN(tagValue, ",", 2)[0] + if tagValue != "" { + fieldName = tagValue + } rawMapKey := reflect.ValueOf(fieldName) + rawMapVal := dataVal.MapIndex(rawMapKey) + if !rawMapVal.IsValid() { + // Do a slower search by iterating over each key and + // doing case-insensitive search. + for dataValKey := range dataValKeys { + mK, ok := dataValKey.Interface().(string) + if !ok { + // Not a string key + continue + } if d.config.MatchName(mK, fieldName) { + rawMapKey = dataValKey + rawMapVal = dataVal.MapIndex(dataValKey) + break + } + } if !rawMapVal.IsValid() { + // There was no matching key in the map for the value in + // the struct. Remember it for potential errors and metadata. + targetValKeysUnused[fieldName] = struct{}{} + continue + } + } if !fieldValue.IsValid() { + // This should never happen + panic("field is not valid") + } // If we can't set the field, then it is unexported or something, + // and we just continue onwards. + if !fieldValue.CanSet() { + continue + } // Delete the key we're using from the unused map so we stop tracking + delete(dataValKeysUnused, rawMapKey.Interface()) // If the name is empty string, then we're at the root, and we + // don't dot-join the fields. + if name != "" { + fieldName = name + "." + fieldName + } if err := d.decode(fieldName, rawMapVal.Interface(), fieldValue); err != nil { + errors = appendErrors(errors, err) + } + } // If we have a "remain"-tagged field and we have unused keys then + // we put the unused keys directly into the remain field. + if remainField != nil && len(dataValKeysUnused) > 0 { + // Build a map of only the unused values + remain := map[interface{}]interface{}{} + for key := range dataValKeysUnused { + remain[key] = dataVal.MapIndex(reflect.ValueOf(key)).Interface() + } // Decode it as-if we were just decoding this map onto our map. + if err := d.decodeMap(name, remain, remainField.val); err != nil { + errors = appendErrors(errors, err) + } // Set the map to nil so we have none so that the next check will + // not error (ErrorUnused) + dataValKeysUnused = nil + } if d.config.ErrorUnused && len(dataValKeysUnused) > 0 { + keys := make([]string, 0, len(dataValKeysUnused)) + for rawKey := range dataValKeysUnused { + keys = append(keys, rawKey.(string)) + } + sort.Strings(keys) err := fmt.Errorf("'%s' has invalid keys: %s", name, strings.Join(keys, ", ")) + errors = appendErrors(errors, err) + } if d.config.ErrorUnset && len(targetValKeysUnused) > 0 { + keys := make([]string, 0, len(targetValKeysUnused)) + for rawKey := range targetValKeysUnused { + keys = append(keys, rawKey.(string)) + } + sort.Strings(keys) err := fmt.Errorf("'%s' has unset fields: %s", name, strings.Join(keys, ", ")) + errors = appendErrors(errors, err) + } if len(errors) > 0 { + return &Error{errors} + } // Add the unused keys to the list of unused keys if we're tracking metadata + if d.config.Metadata != nil { + for rawKey := range dataValKeysUnused { + key := rawKey.(string) + if name != "" { + key = name + "." + key + } d.config.Metadata.Unused = append(d.config.Metadata.Unused, key) + } + for rawKey := range targetValKeysUnused { + key := rawKey.(string) + if name != "" { + key = name + "." + key + } d.config.Metadata.Unset = append(d.config.Metadata.Unset, key) + } + } return nil + } func isEmptyValue(v reflect.Value) bool { + switch getKind(v) { + case reflect.Array, reflect.Map, reflect.Slice, reflect.String: + return v.Len() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Interface, reflect.Ptr: + return v.IsNil() + } + return false + } func getKind(val reflect.Value) reflect.Kind { + kind := val.Kind() switch { + case kind >= reflect.Int && kind <= reflect.Int64: + return reflect.Int + case kind >= reflect.Uint && kind <= reflect.Uint64: + return reflect.Uint + case kind >= reflect.Float32 && kind <= reflect.Float64: + return reflect.Float32 + default: + return kind + } + } func isStructTypeConvertibleToMap(typ reflect.Type, checkMapstructureTags bool, tagName string) bool { + for i := 0; i < typ.NumField(); i++ { + f := typ.Field(i) + if f.PkgPath == "" && !checkMapstructureTags { // check for unexported fields + return true + } + if checkMapstructureTags && f.Tag.Get(tagName) != "" { // check for mapstructure tags inside + return true + } + } + return false + } func dereferencePtrToStructIfNeeded(v reflect.Value, tagName string) reflect.Value { + if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct { + return v + } + deref := v.Elem() + derefT := deref.Type() + if isStructTypeConvertibleToMap(derefT, true, tagName) { + return deref + } + return v + } diff --git a/vendor/github.com/mitchellh/reflectwalk/reflectwalk.go b/vendor/github.com/mitchellh/reflectwalk/reflectwalk.go index 2f7a976..6f36fdc 100644 --- a/vendor/github.com/mitchellh/reflectwalk/reflectwalk.go +++ b/vendor/github.com/mitchellh/reflectwalk/reflectwalk.go @@ -1,7 +1,11 @@ // reflectwalk is a package that allows you to "walk" complex structures + // similar to how you may "walk" a filesystem: visiting every element one + // by one and calling callback functions allowing you to handle and manipulate + // those elements. + package reflectwalk import ( @@ -10,410 +14,663 @@ import ( ) // PrimitiveWalker implementations are able to handle primitive values + // within complex structures. Primitive values are numbers, strings, + // booleans, funcs, chans. + // + // These primitive values are often members of more complex + // structures (slices, maps, etc.) that are walkable by other interfaces. + type PrimitiveWalker interface { Primitive(reflect.Value) error } // InterfaceWalker implementations are able to handle interface values as they + // are encountered during the walk. + type InterfaceWalker interface { Interface(reflect.Value) error } // MapWalker implementations are able to handle individual elements + // found within a map structure. + type MapWalker interface { Map(m reflect.Value) error + MapElem(m, k, v reflect.Value) error } // SliceWalker implementations are able to handle slice elements found + // within complex structures. + type SliceWalker interface { Slice(reflect.Value) error + SliceElem(int, reflect.Value) error } // ArrayWalker implementations are able to handle array elements found + // within complex structures. + type ArrayWalker interface { Array(reflect.Value) error + ArrayElem(int, reflect.Value) error } // StructWalker is an interface that has methods that are called for + // structs when a Walk is done. + type StructWalker interface { Struct(reflect.Value) error + StructField(reflect.StructField, reflect.Value) error } // EnterExitWalker implementations are notified before and after + // they walk deeper into complex structures (into struct fields, + // into slice elements, etc.) + type EnterExitWalker interface { Enter(Location) error + Exit(Location) error } // PointerWalker implementations are notified when the value they're + // walking is a pointer or not. Pointer is called for _every_ value whether + // it is a pointer or not. + type PointerWalker interface { PointerEnter(bool) error + PointerExit(bool) error } // PointerValueWalker implementations are notified with the value of + // a particular pointer when a pointer is walked. Pointer is called + // right before PointerEnter. + type PointerValueWalker interface { Pointer(reflect.Value) error } // SkipEntry can be returned from walk functions to skip walking + // the value of this field. This is only valid in the following functions: + // + // - Struct: skips all fields from being walked + // - StructField: skips walking the struct value + var SkipEntry = errors.New("skip this entry") // Walk takes an arbitrary value and an interface and traverses the + // value, calling callbacks on the interface if they are supported. + // The interface should implement one or more of the walker interfaces + // in this package, such as PrimitiveWalker, StructWalker, etc. + func Walk(data, walker interface{}) (err error) { + v := reflect.ValueOf(data) + ew, ok := walker.(EnterExitWalker) + if ok { + err = ew.Enter(WalkLoc) + } if err == nil { + err = walk(v, walker) + } if ok && err == nil { + err = ew.Exit(WalkLoc) + } return + } func walk(v reflect.Value, w interface{}) (err error) { + // Determine if we're receiving a pointer and if so notify the walker. + // The logic here is convoluted but very important (tests will fail if + // almost any part is changed). I will try to explain here. + // + // First, we check if the value is an interface, if so, we really need + // to check the interface's VALUE to see whether it is a pointer. + // + // Check whether the value is then a pointer. If so, then set pointer + // to true to notify the user. + // + // If we still have a pointer or an interface after the indirections, then + // we unwrap another level + // + // At this time, we also set "v" to be the dereferenced value. This is + // because once we've unwrapped the pointer we want to use that value. + pointer := false + pointerV := v for { + if pointerV.Kind() == reflect.Interface { + if iw, ok := w.(InterfaceWalker); ok { + if err = iw.Interface(pointerV); err != nil { + return + } + } pointerV = pointerV.Elem() + } if pointerV.Kind() == reflect.Ptr { + if pw, ok := w.(PointerValueWalker); ok { + if err = pw.Pointer(pointerV); err != nil { + if err == SkipEntry { + // Skip the rest of this entry but clear the error + return nil + } return + } + } pointer = true + v = reflect.Indirect(pointerV) + } + if pw, ok := w.(PointerWalker); ok { + if err = pw.PointerEnter(pointer); err != nil { + return + } defer func(pointer bool) { + if err != nil { + return + } err = pw.PointerExit(pointer) + }(pointer) + } if pointer { + pointerV = v + } + pointer = false // If we still have a pointer or interface we have to indirect another level. + switch pointerV.Kind() { + case reflect.Ptr, reflect.Interface: + continue + } + break + } // We preserve the original value here because if it is an interface + // type, we want to pass that directly into the walkPrimitive, so that + // we can set it. + originalV := v + if v.Kind() == reflect.Interface { + v = v.Elem() + } k := v.Kind() + if k >= reflect.Int && k <= reflect.Complex128 { + k = reflect.Int + } switch k { + // Primitives + case reflect.Bool, reflect.Chan, reflect.Func, reflect.Int, reflect.String, reflect.Invalid: + err = walkPrimitive(originalV, w) + return + case reflect.Map: + err = walkMap(v, w) + return + case reflect.Slice: + err = walkSlice(v, w) + return + case reflect.Struct: + err = walkStruct(v, w) + return + case reflect.Array: + err = walkArray(v, w) + return + default: + panic("unsupported type: " + k.String()) + } + } func walkMap(v reflect.Value, w interface{}) error { + ew, ewok := w.(EnterExitWalker) + if ewok { + ew.Enter(Map) + } if mw, ok := w.(MapWalker); ok { + if err := mw.Map(v); err != nil { + return err + } + } for _, k := range v.MapKeys() { + kv := v.MapIndex(k) if mw, ok := w.(MapWalker); ok { + if err := mw.MapElem(v, k, kv); err != nil { + return err + } + } ew, ok := w.(EnterExitWalker) + if ok { + ew.Enter(MapKey) + } if err := walk(k, w); err != nil { + return err + } if ok { + ew.Exit(MapKey) + ew.Enter(MapValue) + } // get the map value again as it may have changed in the MapElem call + if err := walk(v.MapIndex(k), w); err != nil { + return err + } if ok { + ew.Exit(MapValue) + } + } if ewok { + ew.Exit(Map) + } return nil + } func walkPrimitive(v reflect.Value, w interface{}) error { + if pw, ok := w.(PrimitiveWalker); ok { + return pw.Primitive(v) + } return nil + } func walkSlice(v reflect.Value, w interface{}) (err error) { + ew, ok := w.(EnterExitWalker) + if ok { + ew.Enter(Slice) + } if sw, ok := w.(SliceWalker); ok { + if err := sw.Slice(v); err != nil { + return err + } + } for i := 0; i < v.Len(); i++ { + elem := v.Index(i) if sw, ok := w.(SliceWalker); ok { + if err := sw.SliceElem(i, elem); err != nil { + return err + } + } ew, ok := w.(EnterExitWalker) + if ok { + ew.Enter(SliceElem) + } if err := walk(elem, w); err != nil { + return err + } if ok { + ew.Exit(SliceElem) + } + } ew, ok = w.(EnterExitWalker) + if ok { + ew.Exit(Slice) + } return nil + } func walkArray(v reflect.Value, w interface{}) (err error) { + ew, ok := w.(EnterExitWalker) + if ok { + ew.Enter(Array) + } if aw, ok := w.(ArrayWalker); ok { + if err := aw.Array(v); err != nil { + return err + } + } for i := 0; i < v.Len(); i++ { + elem := v.Index(i) if aw, ok := w.(ArrayWalker); ok { + if err := aw.ArrayElem(i, elem); err != nil { + return err + } + } ew, ok := w.(EnterExitWalker) + if ok { + ew.Enter(ArrayElem) + } if err := walk(elem, w); err != nil { + return err + } if ok { + ew.Exit(ArrayElem) + } + } ew, ok = w.(EnterExitWalker) + if ok { + ew.Exit(Array) + } return nil + } func walkStruct(v reflect.Value, w interface{}) (err error) { + ew, ewok := w.(EnterExitWalker) + if ewok { + ew.Enter(Struct) + } skip := false + if sw, ok := w.(StructWalker); ok { + err = sw.Struct(v) + if err == SkipEntry { + skip = true + err = nil + } + if err != nil { + return + } + } if !skip { + vt := v.Type() + for i := 0; i < vt.NumField(); i++ { + sf := vt.Field(i) + f := v.FieldByIndex([]int{i}) if sw, ok := w.(StructWalker); ok { + err = sw.StructField(sf, f) // SkipEntry just pretends this field doesn't even exist + if err == SkipEntry { + continue + } if err != nil { + return + } + } ew, ok := w.(EnterExitWalker) + if ok { + ew.Enter(StructField) + } err = walk(f, w) + if err != nil { + return + } if ok { + ew.Exit(StructField) + } + } + } if ewok { + ew.Exit(Struct) + } return nil + } diff --git a/vendor/github.com/pmezard/go-difflib/difflib/difflib.go b/vendor/github.com/pmezard/go-difflib/difflib/difflib.go index 2a73737..e7237eb 100644 --- a/vendor/github.com/pmezard/go-difflib/difflib/difflib.go +++ b/vendor/github.com/pmezard/go-difflib/difflib/difflib.go @@ -1,18 +1,33 @@ // Package difflib is a partial port of Python difflib module. + // + // It provides tools to compare sequences of strings and generate textual diffs. + // + // The following class and functions have been ported: + // + // - SequenceMatcher + // + // - unified_diff + // + // - context_diff + // + // Getting unified diffs was the main goal of the port. Keep in mind this code + // is mostly suitable to output text differences in a human friendly way, there + // are no guarantees generated diffs are consumable by patch(1). + package difflib import ( @@ -24,752 +39,1399 @@ import ( ) func min(a, b int) int { + if a < b { + return a + } + return b + } func max(a, b int) int { + if a > b { + return a + } + return b + } func calculateRatio(matches, length int) float64 { + if length > 0 { + return 2.0 * float64(matches) / float64(length) + } + return 1.0 + } type Match struct { - A int - B int + A int + + B int + Size int } type OpCode struct { Tag byte - I1 int - I2 int - J1 int - J2 int + + I1 int + + I2 int + + J1 int + + J2 int } // SequenceMatcher compares sequence of strings. The basic + // algorithm predates, and is a little fancier than, an algorithm + // published in the late 1980's by Ratcliff and Obershelp under the + // hyperbolic name "gestalt pattern matching". The basic idea is to find + // the longest contiguous matching subsequence that contains no "junk" + // elements (R-O doesn't address junk). The same idea is then applied + // recursively to the pieces of the sequences to the left and to the right + // of the matching subsequence. This does not yield minimal edit + // sequences, but does tend to yield matches that "look right" to people. + // + // SequenceMatcher tries to compute a "human-friendly diff" between two + // sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the + // longest *contiguous* & junk-free matching subsequence. That's what + // catches peoples' eyes. The Windows(tm) windiff has another interesting + // notion, pairing up elements that appear uniquely in each sequence. + // That, and the method here, appear to yield more intuitive difference + // reports than does diff. This method appears to be the least vulnerable + // to synching up on blocks of "junk lines", though (like blank lines in + // ordinary text files, or maybe "

" lines in HTML files). That may be + // because this is the only method of the 3 that has a *concept* of + // "junk" . + // + // Timing: Basic R-O is cubic time worst case and quadratic time expected + // case. SequenceMatcher is quadratic time for the worst case and has + // expected-case behavior dependent in a complicated way on how many + // elements the sequences have in common; best case time is linear. + type SequenceMatcher struct { - a []string - b []string - b2j map[string][]int - IsJunk func(string) bool - autoJunk bool - bJunk map[string]struct{} + a []string + + b []string + + b2j map[string][]int + + IsJunk func(string) bool + + autoJunk bool + + bJunk map[string]struct{} + matchingBlocks []Match - fullBCount map[string]int - bPopular map[string]struct{} - opCodes []OpCode + + fullBCount map[string]int + + bPopular map[string]struct{} + + opCodes []OpCode } func NewMatcher(a, b []string) *SequenceMatcher { + m := SequenceMatcher{autoJunk: true} + m.SetSeqs(a, b) + return &m + } func NewMatcherWithJunk(a, b []string, autoJunk bool, + isJunk func(string) bool) *SequenceMatcher { m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk} + m.SetSeqs(a, b) + return &m + } // Set two sequences to be compared. + func (m *SequenceMatcher) SetSeqs(a, b []string) { + m.SetSeq1(a) + m.SetSeq2(b) + } // Set the first sequence to be compared. The second sequence to be compared is + // not changed. + // + // SequenceMatcher computes and caches detailed information about the second + // sequence, so if you want to compare one sequence S against many sequences, + // use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the other + // sequences. + // + // See also SetSeqs() and SetSeq2(). + func (m *SequenceMatcher) SetSeq1(a []string) { + if &a == &m.a { + return + } + m.a = a + m.matchingBlocks = nil + m.opCodes = nil + } // Set the second sequence to be compared. The first sequence to be compared is + // not changed. + func (m *SequenceMatcher) SetSeq2(b []string) { + if &b == &m.b { + return + } + m.b = b + m.matchingBlocks = nil + m.opCodes = nil + m.fullBCount = nil + m.chainB() + } func (m *SequenceMatcher) chainB() { + // Populate line -> index mapping + b2j := map[string][]int{} + for i, s := range m.b { + indices := b2j[s] + indices = append(indices, i) + b2j[s] = indices + } // Purge junk elements + m.bJunk = map[string]struct{}{} + if m.IsJunk != nil { + junk := m.bJunk + for s, _ := range b2j { + if m.IsJunk(s) { + junk[s] = struct{}{} + } + } + for s, _ := range junk { + delete(b2j, s) + } + } // Purge remaining popular elements + popular := map[string]struct{}{} + n := len(m.b) + if m.autoJunk && n >= 200 { + ntest := n/100 + 1 + for s, indices := range b2j { + if len(indices) > ntest { + popular[s] = struct{}{} + } + } + for s, _ := range popular { + delete(b2j, s) + } + } + m.bPopular = popular + m.b2j = b2j + } func (m *SequenceMatcher) isBJunk(s string) bool { + _, ok := m.bJunk[s] + return ok + } // Find longest matching block in a[alo:ahi] and b[blo:bhi]. + // + // If IsJunk is not defined: + // + // Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where + // + // alo <= i <= i+k <= ahi + // blo <= j <= j+k <= bhi + // + // and for all (i',j',k') meeting those conditions, + // + // k >= k' + // i <= i' + // and if i == i', j <= j' + // + // In other words, of all maximal matching blocks, return one that + // starts earliest in a, and of all those maximal matching blocks that + // start earliest in a, return the one that starts earliest in b. + // + // If IsJunk is defined, first the longest matching block is + // determined as above, but with the additional restriction that no + // junk element appears in the block. Then that block is extended as + // far as possible by matching (only) junk elements on both sides. So + // the resulting block never matches on junk except as identical junk + // happens to be adjacent to an "interesting" match. + // + // If no blocks match, return (alo, blo, 0). + func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match { + // CAUTION: stripping common prefix or suffix would be incorrect. + // E.g., + // ab + // acab + // Longest matching block is "ab", but if common prefix is + // stripped, it's "a" (tied with "b"). UNIX(tm) diff does so + // strip, so ends up claiming that ab is changed to acab by + // inserting "ca" in the middle. That's minimal but unintuitive: + // "it's obvious" that someone inserted "ac" at the front. + // Windiff ends up at the same place as diff, but by pairing up + // the unique 'b's and then matching the first two 'a's. + besti, bestj, bestsize := alo, blo, 0 // find longest junk-free match + // during an iteration of the loop, j2len[j] = length of longest + // junk-free match ending with a[i-1] and b[j] + j2len := map[int]int{} + for i := alo; i != ahi; i++ { + // look at all instances of a[i] in b; note that because + // b2j has no junk keys, the loop is skipped if a[i] is junk + newj2len := map[int]int{} + for _, j := range m.b2j[m.a[i]] { + // a[i] matches b[j] + if j < blo { + continue + } + if j >= bhi { + break + } + k := j2len[j-1] + 1 + newj2len[j] = k + if k > bestsize { + besti, bestj, bestsize = i-k+1, j-k+1, k + } + } + j2len = newj2len + } // Extend the best by non-junk elements on each end. In particular, + // "popular" non-junk elements aren't in b2j, which greatly speeds + // the inner loop above, but also means "the best" match so far + // doesn't contain any junk *or* popular non-junk elements. + for besti > alo && bestj > blo && !m.isBJunk(m.b[bestj-1]) && + m.a[besti-1] == m.b[bestj-1] { + besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 + } + for besti+bestsize < ahi && bestj+bestsize < bhi && + !m.isBJunk(m.b[bestj+bestsize]) && + m.a[besti+bestsize] == m.b[bestj+bestsize] { + bestsize += 1 + } // Now that we have a wholly interesting match (albeit possibly + // empty!), we may as well suck up the matching junk on each + // side of it too. Can't think of a good reason not to, and it + // saves post-processing the (possibly considerable) expense of + // figuring out what to do with it. In the case of an empty + // interesting match, this is clearly the right thing to do, + // because no other kind of match is possible in the regions. + for besti > alo && bestj > blo && m.isBJunk(m.b[bestj-1]) && + m.a[besti-1] == m.b[bestj-1] { + besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 + } + for besti+bestsize < ahi && bestj+bestsize < bhi && + m.isBJunk(m.b[bestj+bestsize]) && + m.a[besti+bestsize] == m.b[bestj+bestsize] { + bestsize += 1 + } return Match{A: besti, B: bestj, Size: bestsize} + } // Return list of triples describing matching subsequences. + // + // Each triple is of the form (i, j, n), and means that + // a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in + // i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are + // adjacent triples in the list, and the second is not the last triple in the + // list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe + // adjacent equal blocks. + // + // The last triple is a dummy, (len(a), len(b), 0), and is the only + // triple with n==0. + func (m *SequenceMatcher) GetMatchingBlocks() []Match { + if m.matchingBlocks != nil { + return m.matchingBlocks + } var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match + matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match { + match := m.findLongestMatch(alo, ahi, blo, bhi) + i, j, k := match.A, match.B, match.Size + if match.Size > 0 { + if alo < i && blo < j { + matched = matchBlocks(alo, i, blo, j, matched) + } + matched = append(matched, match) + if i+k < ahi && j+k < bhi { + matched = matchBlocks(i+k, ahi, j+k, bhi, matched) + } + } + return matched + } + matched := matchBlocks(0, len(m.a), 0, len(m.b), nil) // It's possible that we have adjacent equal blocks in the + // matching_blocks list now. + nonAdjacent := []Match{} + i1, j1, k1 := 0, 0, 0 + for _, b := range matched { + // Is this block adjacent to i1, j1, k1? + i2, j2, k2 := b.A, b.B, b.Size + if i1+k1 == i2 && j1+k1 == j2 { + // Yes, so collapse them -- this just increases the length of + // the first block by the length of the second, and the first + // block so lengthened remains the block to compare against. + k1 += k2 + } else { + // Not adjacent. Remember the first block (k1==0 means it's + // the dummy we started with), and make the second block the + // new block to compare against. + if k1 > 0 { + nonAdjacent = append(nonAdjacent, Match{i1, j1, k1}) + } + i1, j1, k1 = i2, j2, k2 + } + } + if k1 > 0 { + nonAdjacent = append(nonAdjacent, Match{i1, j1, k1}) + } nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0}) + m.matchingBlocks = nonAdjacent + return m.matchingBlocks + } // Return list of 5-tuples describing how to turn a into b. + // + // Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple + // has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the + // tuple preceding it, and likewise for j1 == the previous j2. + // + // The tags are characters, with these meanings: + // + // 'r' (replace): a[i1:i2] should be replaced by b[j1:j2] + // + // 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case. + // + // 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case. + // + // 'e' (equal): a[i1:i2] == b[j1:j2] + func (m *SequenceMatcher) GetOpCodes() []OpCode { + if m.opCodes != nil { + return m.opCodes + } + i, j := 0, 0 + matching := m.GetMatchingBlocks() + opCodes := make([]OpCode, 0, len(matching)) + for _, m := range matching { + // invariant: we've pumped out correct diffs to change + // a[:i] into b[:j], and the next matching block is + // a[ai:ai+size] == b[bj:bj+size]. So we need to pump + // out a diff to change a[i:ai] into b[j:bj], pump out + // the matching block, and move (i,j) beyond the match + ai, bj, size := m.A, m.B, m.Size + tag := byte(0) + if i < ai && j < bj { + tag = 'r' + } else if i < ai { + tag = 'd' + } else if j < bj { + tag = 'i' + } + if tag > 0 { + opCodes = append(opCodes, OpCode{tag, i, ai, j, bj}) + } + i, j = ai+size, bj+size + // the list of matching blocks is terminated by a + // sentinel with size 0 + if size > 0 { + opCodes = append(opCodes, OpCode{'e', ai, i, bj, j}) + } + } + m.opCodes = opCodes + return m.opCodes + } // Isolate change clusters by eliminating ranges with no changes. + // + // Return a generator of groups with up to n lines of context. + // Each group is in the same format as returned by GetOpCodes(). + func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode { + if n < 0 { + n = 3 + } + codes := m.GetOpCodes() + if len(codes) == 0 { + codes = []OpCode{OpCode{'e', 0, 1, 0, 1}} + } + // Fixup leading and trailing groups if they show no changes. + if codes[0].Tag == 'e' { + c := codes[0] + i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 + codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2} + } + if codes[len(codes)-1].Tag == 'e' { + c := codes[len(codes)-1] + i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 + codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)} + } + nn := n + n + groups := [][]OpCode{} + group := []OpCode{} + for _, c := range codes { + i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 + // End the current group and start a new one whenever + // there is a large range with no changes. + if c.Tag == 'e' && i2-i1 > nn { + group = append(group, OpCode{c.Tag, i1, min(i2, i1+n), + j1, min(j2, j1+n)}) + groups = append(groups, group) + group = []OpCode{} + i1, j1 = max(i1, i2-n), max(j1, j2-n) + } + group = append(group, OpCode{c.Tag, i1, i2, j1, j2}) + } + if len(group) > 0 && !(len(group) == 1 && group[0].Tag == 'e') { + groups = append(groups, group) + } + return groups + } // Return a measure of the sequences' similarity (float in [0,1]). + // + // Where T is the total number of elements in both sequences, and + // M is the number of matches, this is 2.0*M / T. + // Note that this is 1 if the sequences are identical, and 0 if + // they have nothing in common. + // + // .Ratio() is expensive to compute if you haven't already computed + // .GetMatchingBlocks() or .GetOpCodes(), in which case you may + // want to try .QuickRatio() or .RealQuickRation() first to get an + // upper bound. + func (m *SequenceMatcher) Ratio() float64 { + matches := 0 + for _, m := range m.GetMatchingBlocks() { + matches += m.Size + } + return calculateRatio(matches, len(m.a)+len(m.b)) + } // Return an upper bound on ratio() relatively quickly. + // + // This isn't defined beyond that it is an upper bound on .Ratio(), and + // is faster to compute. + func (m *SequenceMatcher) QuickRatio() float64 { + // viewing a and b as multisets, set matches to the cardinality + // of their intersection; this counts the number of matches + // without regard to order, so is clearly an upper bound + if m.fullBCount == nil { + m.fullBCount = map[string]int{} + for _, s := range m.b { + m.fullBCount[s] = m.fullBCount[s] + 1 + } + } // avail[x] is the number of times x appears in 'b' less the + // number of times we've seen it in 'a' so far ... kinda + avail := map[string]int{} + matches := 0 + for _, s := range m.a { + n, ok := avail[s] + if !ok { + n = m.fullBCount[s] + } + avail[s] = n - 1 + if n > 0 { + matches += 1 + } + } + return calculateRatio(matches, len(m.a)+len(m.b)) + } // Return an upper bound on ratio() very quickly. + // + // This isn't defined beyond that it is an upper bound on .Ratio(), and + // is faster to compute than either .Ratio() or .QuickRatio(). + func (m *SequenceMatcher) RealQuickRatio() float64 { + la, lb := len(m.a), len(m.b) + return calculateRatio(min(la, lb), la+lb) + } // Convert range to the "ed" format + func formatRangeUnified(start, stop int) string { + // Per the diff spec at http://www.unix.org/single_unix_specification/ + beginning := start + 1 // lines start numbering with one + length := stop - start + if length == 1 { + return fmt.Sprintf("%d", beginning) + } + if length == 0 { + beginning -= 1 // empty ranges begin at line just before the range + } + return fmt.Sprintf("%d,%d", beginning, length) + } // Unified diff parameters + type UnifiedDiff struct { - A []string // First sequence lines - FromFile string // First file name - FromDate string // First file time - B []string // Second sequence lines - ToFile string // Second file name - ToDate string // Second file time - Eol string // Headers end of line, defaults to LF - Context int // Number of context lines + A []string // First sequence lines + + FromFile string // First file name + + FromDate string // First file time + + B []string // Second sequence lines + + ToFile string // Second file name + + ToDate string // Second file time + + Eol string // Headers end of line, defaults to LF + + Context int // Number of context lines + } // Compare two sequences of lines; generate the delta as a unified diff. + // + // Unified diffs are a compact way of showing line changes and a few + // lines of context. The number of context lines is set by 'n' which + // defaults to three. + // + // By default, the diff control lines (those with ---, +++, or @@) are + // created with a trailing newline. This is helpful so that inputs + // created from file.readlines() result in diffs that are suitable for + // file.writelines() since both the inputs and outputs have trailing + // newlines. + // + // For inputs that do not have trailing newlines, set the lineterm + // argument to "" so that the output will be uniformly newline free. + // + // The unidiff format normally has a header for filenames and modification + // times. Any or all of these may be specified using strings for + // 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. + // The modification times are normally expressed in the ISO 8601 format. + func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error { + buf := bufio.NewWriter(writer) + defer buf.Flush() + wf := func(format string, args ...interface{}) error { + _, err := buf.WriteString(fmt.Sprintf(format, args...)) + return err + } + ws := func(s string) error { + _, err := buf.WriteString(s) + return err + } if len(diff.Eol) == 0 { + diff.Eol = "\n" + } started := false + m := NewMatcher(diff.A, diff.B) + for _, g := range m.GetGroupedOpCodes(diff.Context) { + if !started { + started = true + fromDate := "" + if len(diff.FromDate) > 0 { + fromDate = "\t" + diff.FromDate + } + toDate := "" + if len(diff.ToDate) > 0 { + toDate = "\t" + diff.ToDate + } + if diff.FromFile != "" || diff.ToFile != "" { + err := wf("--- %s%s%s", diff.FromFile, fromDate, diff.Eol) + if err != nil { + return err + } + err = wf("+++ %s%s%s", diff.ToFile, toDate, diff.Eol) + if err != nil { + return err + } + } + } + first, last := g[0], g[len(g)-1] + range1 := formatRangeUnified(first.I1, last.I2) + range2 := formatRangeUnified(first.J1, last.J2) + if err := wf("@@ -%s +%s @@%s", range1, range2, diff.Eol); err != nil { + return err + } + for _, c := range g { + i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 + if c.Tag == 'e' { + for _, line := range diff.A[i1:i2] { + if err := ws(" " + line); err != nil { + return err + } + } + continue + } + if c.Tag == 'r' || c.Tag == 'd' { + for _, line := range diff.A[i1:i2] { + if err := ws("-" + line); err != nil { + return err + } + } + } + if c.Tag == 'r' || c.Tag == 'i' { + for _, line := range diff.B[j1:j2] { + if err := ws("+" + line); err != nil { + return err + } + } + } + } + } + return nil + } // Like WriteUnifiedDiff but returns the diff a string. + func GetUnifiedDiffString(diff UnifiedDiff) (string, error) { + w := &bytes.Buffer{} + err := WriteUnifiedDiff(w, diff) + return string(w.Bytes()), err + } // Convert range to the "ed" format. + func formatRangeContext(start, stop int) string { + // Per the diff spec at http://www.unix.org/single_unix_specification/ + beginning := start + 1 // lines start numbering with one + length := stop - start + if length == 0 { + beginning -= 1 // empty ranges begin at line just before the range + } + if length <= 1 { + return fmt.Sprintf("%d", beginning) + } + return fmt.Sprintf("%d,%d", beginning, beginning+length-1) + } type ContextDiff UnifiedDiff // Compare two sequences of lines; generate the delta as a context diff. + // + // Context diffs are a compact way of showing line changes and a few + // lines of context. The number of context lines is set by diff.Context + // which defaults to three. + // + // By default, the diff control lines (those with *** or ---) are + // created with a trailing newline. + // + // For inputs that do not have trailing newlines, set the diff.Eol + // argument to "" so that the output will be uniformly newline free. + // + // The context diff format normally has a header for filenames and + // modification times. Any or all of these may be specified using + // strings for diff.FromFile, diff.ToFile, diff.FromDate, diff.ToDate. + // The modification times are normally expressed in the ISO 8601 format. + // If not specified, the strings default to blanks. + func WriteContextDiff(writer io.Writer, diff ContextDiff) error { + buf := bufio.NewWriter(writer) + defer buf.Flush() + var diffErr error + wf := func(format string, args ...interface{}) { + _, err := buf.WriteString(fmt.Sprintf(format, args...)) + if diffErr == nil && err != nil { + diffErr = err + } + } + ws := func(s string) { + _, err := buf.WriteString(s) + if diffErr == nil && err != nil { + diffErr = err + } + } if len(diff.Eol) == 0 { + diff.Eol = "\n" + } prefix := map[byte]string{ + 'i': "+ ", + 'd': "- ", + 'r': "! ", + 'e': " ", } started := false + m := NewMatcher(diff.A, diff.B) + for _, g := range m.GetGroupedOpCodes(diff.Context) { + if !started { + started = true + fromDate := "" + if len(diff.FromDate) > 0 { + fromDate = "\t" + diff.FromDate + } + toDate := "" + if len(diff.ToDate) > 0 { + toDate = "\t" + diff.ToDate + } + if diff.FromFile != "" || diff.ToFile != "" { + wf("*** %s%s%s", diff.FromFile, fromDate, diff.Eol) + wf("--- %s%s%s", diff.ToFile, toDate, diff.Eol) + } + } first, last := g[0], g[len(g)-1] + ws("***************" + diff.Eol) range1 := formatRangeContext(first.I1, last.I2) + wf("*** %s ****%s", range1, diff.Eol) + for _, c := range g { + if c.Tag == 'r' || c.Tag == 'd' { + for _, cc := range g { + if cc.Tag == 'i' { + continue + } + for _, line := range diff.A[cc.I1:cc.I2] { + ws(prefix[cc.Tag] + line) + } + } + break + } + } range2 := formatRangeContext(first.J1, last.J2) + wf("--- %s ----%s", range2, diff.Eol) + for _, c := range g { + if c.Tag == 'r' || c.Tag == 'i' { + for _, cc := range g { + if cc.Tag == 'd' { + continue + } + for _, line := range diff.B[cc.J1:cc.J2] { + ws(prefix[cc.Tag] + line) + } + } + break + } + } + } + return diffErr + } // Like WriteContextDiff but returns the diff a string. + func GetContextDiffString(diff ContextDiff) (string, error) { + w := &bytes.Buffer{} + err := WriteContextDiff(w, diff) + return string(w.Bytes()), err + } // Split a string on "\n" while preserving them. The output can be used + // as input for UnifiedDiff and ContextDiff structures. + func SplitLines(s string) []string { + lines := strings.SplitAfter(s, "\n") + lines[len(lines)-1] += "\n" + return lines + } diff --git a/vendor/github.com/redis/go-redis/v9/command.go b/vendor/github.com/redis/go-redis/v9/command.go index 06ed86e..f60a943 100644 --- a/vendor/github.com/redis/go-redis/v9/command.go +++ b/vendor/github.com/redis/go-redis/v9/command.go @@ -18,113 +18,181 @@ import ( ) type Cmder interface { + // command name. + // e.g. "set k v ex 10" -> "set", "cluster info" -> "cluster". + Name() string // full command name. + // e.g. "set k v ex 10" -> "set", "cluster info" -> "cluster info". + FullName() string // all args of the command. + // e.g. "set k v ex 10" -> "[set k v ex 10]". + Args() []interface{} // format request and response string. + // e.g. "set k v ex 10" -> "set k v ex 10: OK", "get k" -> "get k: v". + String() string stringArg(int) string + firstKeyPos() int8 + SetFirstKeyPos(int8) readTimeout() *time.Duration + readReply(rd *proto.Reader) error SetErr(error) + Err() error } func setCmdsErr(cmds []Cmder, e error) { + for _, cmd := range cmds { + if cmd.Err() == nil { + cmd.SetErr(e) + } + } + } func cmdsFirstErr(cmds []Cmder) error { + for _, cmd := range cmds { + if err := cmd.Err(); err != nil { + return err + } + } + return nil + } func writeCmds(wr *proto.Writer, cmds []Cmder) error { + for _, cmd := range cmds { + if err := writeCmd(wr, cmd); err != nil { + return err + } + } + return nil + } func writeCmd(wr *proto.Writer, cmd Cmder) error { + return wr.WriteArgs(cmd.Args()) + } func cmdFirstKeyPos(cmd Cmder) int { + if pos := cmd.firstKeyPos(); pos != 0 { + return int(pos) + } switch cmd.Name() { + case "eval", "evalsha", "eval_ro", "evalsha_ro": + if cmd.stringArg(2) != "0" { + return 3 + } return 0 + case "publish": + return 1 + case "memory": + // https://github.com/redis/redis/issues/7493 + if cmd.stringArg(1) == "usage" { + return 2 + } + } + return 1 + } func cmdString(cmd Cmder, val interface{}) string { + b := make([]byte, 0, 64) for i, arg := range cmd.Args() { + if i > 0 { + b = append(b, ' ') + } + b = internal.AppendArg(b, arg) + } if err := cmd.Err(); err != nil { + b = append(b, ": "...) + b = append(b, err.Error()...) + } else if val != nil { + b = append(b, ": "...) + b = internal.AppendArg(b, val) + } return util.BytesToString(b) + } //------------------------------------------------------------------------------ type baseCmd struct { - ctx context.Context - args []interface{} - err error + ctx context.Context + + args []interface{} + + err error + keyPos int8 _readTimeout *time.Duration @@ -133,68 +201,113 @@ type baseCmd struct { var _ Cmder = (*Cmd)(nil) func (cmd *baseCmd) Name() string { + if len(cmd.args) == 0 { + return "" + } + // Cmd name must be lower cased. + return internal.ToLower(cmd.stringArg(0)) + } func (cmd *baseCmd) FullName() string { + switch name := cmd.Name(); name { + case "cluster", "command": + if len(cmd.args) == 1 { + return name + } + if s2, ok := cmd.args[1].(string); ok { + return name + " " + s2 + } + return name + default: + return name + } + } func (cmd *baseCmd) Args() []interface{} { + return cmd.args + } func (cmd *baseCmd) stringArg(pos int) string { + if pos < 0 || pos >= len(cmd.args) { + return "" + } + arg := cmd.args[pos] + switch v := arg.(type) { + case string: + return v + default: + // TODO: consider using appendArg + return fmt.Sprint(v) + } + } func (cmd *baseCmd) firstKeyPos() int8 { + return cmd.keyPos + } func (cmd *baseCmd) SetFirstKeyPos(keyPos int8) { + cmd.keyPos = keyPos + } func (cmd *baseCmd) SetErr(e error) { + cmd.err = e + } func (cmd *baseCmd) Err() error { + return cmd.err + } func (cmd *baseCmd) readTimeout() *time.Duration { + return cmd._readTimeout + } func (cmd *baseCmd) setReadTimeout(d time.Duration) { + cmd._readTimeout = &d + } //------------------------------------------------------------------------------ @@ -206,280 +319,491 @@ type Cmd struct { } func NewCmd(ctx context.Context, args ...interface{}) *Cmd { + return &Cmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *Cmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *Cmd) SetVal(val interface{}) { + cmd.val = val + } func (cmd *Cmd) Val() interface{} { + return cmd.val + } func (cmd *Cmd) Result() (interface{}, error) { + return cmd.val, cmd.err + } func (cmd *Cmd) Text() (string, error) { + if cmd.err != nil { + return "", cmd.err + } + return toString(cmd.val) + } func toString(val interface{}) (string, error) { + switch val := val.(type) { + case string: + return val, nil + default: + err := fmt.Errorf("redis: unexpected type=%T for String", val) + return "", err + } + } func (cmd *Cmd) Int() (int, error) { + if cmd.err != nil { + return 0, cmd.err + } + switch val := cmd.val.(type) { + case int64: + return int(val), nil + case string: + return strconv.Atoi(val) + default: + err := fmt.Errorf("redis: unexpected type=%T for Int", val) + return 0, err + } + } func (cmd *Cmd) Int64() (int64, error) { + if cmd.err != nil { + return 0, cmd.err + } + return toInt64(cmd.val) + } func toInt64(val interface{}) (int64, error) { + switch val := val.(type) { + case int64: + return val, nil + case string: + return strconv.ParseInt(val, 10, 64) + default: + err := fmt.Errorf("redis: unexpected type=%T for Int64", val) + return 0, err + } + } func (cmd *Cmd) Uint64() (uint64, error) { + if cmd.err != nil { + return 0, cmd.err + } + return toUint64(cmd.val) + } func toUint64(val interface{}) (uint64, error) { + switch val := val.(type) { + case int64: + return uint64(val), nil + case string: + return strconv.ParseUint(val, 10, 64) + default: + err := fmt.Errorf("redis: unexpected type=%T for Uint64", val) + return 0, err + } + } func (cmd *Cmd) Float32() (float32, error) { + if cmd.err != nil { + return 0, cmd.err + } + return toFloat32(cmd.val) + } func toFloat32(val interface{}) (float32, error) { + switch val := val.(type) { + case int64: + return float32(val), nil + case string: + f, err := strconv.ParseFloat(val, 32) + if err != nil { + return 0, err + } + return float32(f), nil + default: + err := fmt.Errorf("redis: unexpected type=%T for Float32", val) + return 0, err + } + } func (cmd *Cmd) Float64() (float64, error) { + if cmd.err != nil { + return 0, cmd.err + } + return toFloat64(cmd.val) + } func toFloat64(val interface{}) (float64, error) { + switch val := val.(type) { + case int64: + return float64(val), nil + case string: + return strconv.ParseFloat(val, 64) + default: + err := fmt.Errorf("redis: unexpected type=%T for Float64", val) + return 0, err + } + } func (cmd *Cmd) Bool() (bool, error) { + if cmd.err != nil { + return false, cmd.err + } + return toBool(cmd.val) + } func toBool(val interface{}) (bool, error) { + switch val := val.(type) { + case bool: + return val, nil + case int64: + return val != 0, nil + case string: + return strconv.ParseBool(val) + default: + err := fmt.Errorf("redis: unexpected type=%T for Bool", val) + return false, err + } + } func (cmd *Cmd) Slice() ([]interface{}, error) { + if cmd.err != nil { + return nil, cmd.err + } + switch val := cmd.val.(type) { + case []interface{}: + return val, nil + default: + return nil, fmt.Errorf("redis: unexpected type=%T for Slice", val) + } + } func (cmd *Cmd) StringSlice() ([]string, error) { + slice, err := cmd.Slice() + if err != nil { + return nil, err + } ss := make([]string, len(slice)) + for i, iface := range slice { + val, err := toString(iface) + if err != nil { + return nil, err + } + ss[i] = val + } + return ss, nil + } func (cmd *Cmd) Int64Slice() ([]int64, error) { + slice, err := cmd.Slice() + if err != nil { + return nil, err + } nums := make([]int64, len(slice)) + for i, iface := range slice { + val, err := toInt64(iface) + if err != nil { + return nil, err + } + nums[i] = val + } + return nums, nil + } func (cmd *Cmd) Uint64Slice() ([]uint64, error) { + slice, err := cmd.Slice() + if err != nil { + return nil, err + } nums := make([]uint64, len(slice)) + for i, iface := range slice { + val, err := toUint64(iface) + if err != nil { + return nil, err + } + nums[i] = val + } + return nums, nil + } func (cmd *Cmd) Float32Slice() ([]float32, error) { + slice, err := cmd.Slice() + if err != nil { + return nil, err + } floats := make([]float32, len(slice)) + for i, iface := range slice { + val, err := toFloat32(iface) + if err != nil { + return nil, err + } + floats[i] = val + } + return floats, nil + } func (cmd *Cmd) Float64Slice() ([]float64, error) { + slice, err := cmd.Slice() + if err != nil { + return nil, err + } floats := make([]float64, len(slice)) + for i, iface := range slice { + val, err := toFloat64(iface) + if err != nil { + return nil, err + } + floats[i] = val + } + return floats, nil + } func (cmd *Cmd) BoolSlice() ([]bool, error) { + slice, err := cmd.Slice() + if err != nil { + return nil, err + } bools := make([]bool, len(slice)) + for i, iface := range slice { + val, err := toBool(iface) + if err != nil { + return nil, err + } + bools[i] = val + } + return bools, nil + } func (cmd *Cmd) readReply(rd *proto.Reader) (err error) { + cmd.val, err = rd.ReadReply() + return err + } //------------------------------------------------------------------------------ @@ -493,53 +817,83 @@ type SliceCmd struct { var _ Cmder = (*SliceCmd)(nil) func NewSliceCmd(ctx context.Context, args ...interface{}) *SliceCmd { + return &SliceCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *SliceCmd) SetVal(val []interface{}) { + cmd.val = val + } func (cmd *SliceCmd) Val() []interface{} { + return cmd.val + } func (cmd *SliceCmd) Result() ([]interface{}, error) { + return cmd.val, cmd.err + } func (cmd *SliceCmd) String() string { + return cmdString(cmd, cmd.val) + } // Scan scans the results from the map into a destination struct. The map keys + // are matched in the Redis struct fields by the `redis:"field"` tag. + func (cmd *SliceCmd) Scan(dst interface{}) error { + if cmd.err != nil { + return cmd.err + } // Pass the list of keys and values. + // Skip the first two args for: HMGET key + var args []interface{} + if cmd.args[0] == "hmget" { + args = cmd.args[2:] + } else { + // Otherwise, it's: MGET field field ... + args = cmd.args[1:] + } return hscan.Scan(dst, args, cmd.val) + } func (cmd *SliceCmd) readReply(rd *proto.Reader) (err error) { + cmd.val, err = rd.ReadSlice() + return err + } //------------------------------------------------------------------------------ @@ -553,33 +907,49 @@ type StatusCmd struct { var _ Cmder = (*StatusCmd)(nil) func NewStatusCmd(ctx context.Context, args ...interface{}) *StatusCmd { + return &StatusCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *StatusCmd) SetVal(val string) { + cmd.val = val + } func (cmd *StatusCmd) Val() string { + return cmd.val + } func (cmd *StatusCmd) Result() (string, error) { + return cmd.val, cmd.err + } func (cmd *StatusCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *StatusCmd) readReply(rd *proto.Reader) (err error) { + cmd.val, err = rd.ReadString() + return err + } //------------------------------------------------------------------------------ @@ -593,37 +963,55 @@ type IntCmd struct { var _ Cmder = (*IntCmd)(nil) func NewIntCmd(ctx context.Context, args ...interface{}) *IntCmd { + return &IntCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *IntCmd) SetVal(val int64) { + cmd.val = val + } func (cmd *IntCmd) Val() int64 { + return cmd.val + } func (cmd *IntCmd) Result() (int64, error) { + return cmd.val, cmd.err + } func (cmd *IntCmd) Uint64() (uint64, error) { + return uint64(cmd.val), cmd.err + } func (cmd *IntCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *IntCmd) readReply(rd *proto.Reader) (err error) { + cmd.val, err = rd.ReadInt() + return err + } //------------------------------------------------------------------------------ @@ -637,42 +1025,67 @@ type IntSliceCmd struct { var _ Cmder = (*IntSliceCmd)(nil) func NewIntSliceCmd(ctx context.Context, args ...interface{}) *IntSliceCmd { + return &IntSliceCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *IntSliceCmd) SetVal(val []int64) { + cmd.val = val + } func (cmd *IntSliceCmd) Val() []int64 { + return cmd.val + } func (cmd *IntSliceCmd) Result() ([]int64, error) { + return cmd.val, cmd.err + } func (cmd *IntSliceCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *IntSliceCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } + cmd.val = make([]int64, n) + for i := 0; i < len(cmd.val); i++ { + if cmd.val[i], err = rd.ReadInt(); err != nil { + return err + } + } + return nil + } //------------------------------------------------------------------------------ @@ -680,52 +1093,81 @@ func (cmd *IntSliceCmd) readReply(rd *proto.Reader) error { type DurationCmd struct { baseCmd - val time.Duration + val time.Duration + precision time.Duration } var _ Cmder = (*DurationCmd)(nil) func NewDurationCmd(ctx context.Context, precision time.Duration, args ...interface{}) *DurationCmd { + return &DurationCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, + precision: precision, } + } func (cmd *DurationCmd) SetVal(val time.Duration) { + cmd.val = val + } func (cmd *DurationCmd) Val() time.Duration { + return cmd.val + } func (cmd *DurationCmd) Result() (time.Duration, error) { + return cmd.val, cmd.err + } func (cmd *DurationCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *DurationCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadInt() + if err != nil { + return err + } + switch n { + // -2 if the key does not exist + // -1 if the key exists but has no associated expire + case -2, -1: + cmd.val = time.Duration(n) + default: + cmd.val = time.Duration(n) * cmd.precision + } + return nil + } //------------------------------------------------------------------------------ @@ -739,44 +1181,71 @@ type TimeCmd struct { var _ Cmder = (*TimeCmd)(nil) func NewTimeCmd(ctx context.Context, args ...interface{}) *TimeCmd { + return &TimeCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *TimeCmd) SetVal(val time.Time) { + cmd.val = val + } func (cmd *TimeCmd) Val() time.Time { + return cmd.val + } func (cmd *TimeCmd) Result() (time.Time, error) { + return cmd.val, cmd.err + } func (cmd *TimeCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *TimeCmd) readReply(rd *proto.Reader) error { + if err := rd.ReadFixedArrayLen(2); err != nil { + return err + } + second, err := rd.ReadInt() + if err != nil { + return err + } + microsecond, err := rd.ReadInt() + if err != nil { + return err + } + cmd.val = time.Unix(second, microsecond*1000) + return nil + } //------------------------------------------------------------------------------ @@ -790,40 +1259,61 @@ type BoolCmd struct { var _ Cmder = (*BoolCmd)(nil) func NewBoolCmd(ctx context.Context, args ...interface{}) *BoolCmd { + return &BoolCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *BoolCmd) SetVal(val bool) { + cmd.val = val + } func (cmd *BoolCmd) Val() bool { + return cmd.val + } func (cmd *BoolCmd) Result() (bool, error) { + return cmd.val, cmd.err + } func (cmd *BoolCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *BoolCmd) readReply(rd *proto.Reader) (err error) { + cmd.val, err = rd.ReadBool() // `SET key value NX` returns nil when key already exists. But + // `SETNX key value` returns bool (0/1). So convert nil to bool. + if err == Nil { + cmd.val = false + err = nil + } + return err + } //------------------------------------------------------------------------------ @@ -837,97 +1327,159 @@ type StringCmd struct { var _ Cmder = (*StringCmd)(nil) func NewStringCmd(ctx context.Context, args ...interface{}) *StringCmd { + return &StringCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *StringCmd) SetVal(val string) { + cmd.val = val + } func (cmd *StringCmd) Val() string { + return cmd.val + } func (cmd *StringCmd) Result() (string, error) { + return cmd.val, cmd.err + } func (cmd *StringCmd) Bytes() ([]byte, error) { + return util.StringToBytes(cmd.val), cmd.err + } func (cmd *StringCmd) Bool() (bool, error) { + if cmd.err != nil { + return false, cmd.err + } + return strconv.ParseBool(cmd.val) + } func (cmd *StringCmd) Int() (int, error) { + if cmd.err != nil { + return 0, cmd.err + } + return strconv.Atoi(cmd.Val()) + } func (cmd *StringCmd) Int64() (int64, error) { + if cmd.err != nil { + return 0, cmd.err + } + return strconv.ParseInt(cmd.Val(), 10, 64) + } func (cmd *StringCmd) Uint64() (uint64, error) { + if cmd.err != nil { + return 0, cmd.err + } + return strconv.ParseUint(cmd.Val(), 10, 64) + } func (cmd *StringCmd) Float32() (float32, error) { + if cmd.err != nil { + return 0, cmd.err + } + f, err := strconv.ParseFloat(cmd.Val(), 32) + if err != nil { + return 0, err + } + return float32(f), nil + } func (cmd *StringCmd) Float64() (float64, error) { + if cmd.err != nil { + return 0, cmd.err + } + return strconv.ParseFloat(cmd.Val(), 64) + } func (cmd *StringCmd) Time() (time.Time, error) { + if cmd.err != nil { + return time.Time{}, cmd.err + } + return time.Parse(time.RFC3339Nano, cmd.Val()) + } func (cmd *StringCmd) Scan(val interface{}) error { + if cmd.err != nil { + return cmd.err + } + return proto.Scan([]byte(cmd.val), val) + } func (cmd *StringCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *StringCmd) readReply(rd *proto.Reader) (err error) { + cmd.val, err = rd.ReadString() + return err + } //------------------------------------------------------------------------------ @@ -941,33 +1493,49 @@ type FloatCmd struct { var _ Cmder = (*FloatCmd)(nil) func NewFloatCmd(ctx context.Context, args ...interface{}) *FloatCmd { + return &FloatCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *FloatCmd) SetVal(val float64) { + cmd.val = val + } func (cmd *FloatCmd) Val() float64 { + return cmd.val + } func (cmd *FloatCmd) Result() (float64, error) { + return cmd.val, cmd.err + } func (cmd *FloatCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *FloatCmd) readReply(rd *proto.Reader) (err error) { + cmd.val, err = rd.ReadFloat() + return err + } //------------------------------------------------------------------------------ @@ -981,48 +1549,77 @@ type FloatSliceCmd struct { var _ Cmder = (*FloatSliceCmd)(nil) func NewFloatSliceCmd(ctx context.Context, args ...interface{}) *FloatSliceCmd { + return &FloatSliceCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *FloatSliceCmd) SetVal(val []float64) { + cmd.val = val + } func (cmd *FloatSliceCmd) Val() []float64 { + return cmd.val + } func (cmd *FloatSliceCmd) Result() ([]float64, error) { + return cmd.val, cmd.err + } func (cmd *FloatSliceCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *FloatSliceCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } cmd.val = make([]float64, n) + for i := 0; i < len(cmd.val); i++ { + switch num, err := rd.ReadFloat(); { + case err == Nil: + cmd.val[i] = 0 + case err != nil: + return err + default: + cmd.val[i] = num + } + } + return nil + } //------------------------------------------------------------------------------ @@ -1036,57 +1633,90 @@ type StringSliceCmd struct { var _ Cmder = (*StringSliceCmd)(nil) func NewStringSliceCmd(ctx context.Context, args ...interface{}) *StringSliceCmd { + return &StringSliceCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *StringSliceCmd) SetVal(val []string) { + cmd.val = val + } func (cmd *StringSliceCmd) Val() []string { + return cmd.val + } func (cmd *StringSliceCmd) Result() ([]string, error) { + return cmd.val, cmd.err + } func (cmd *StringSliceCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *StringSliceCmd) ScanSlice(container interface{}) error { + return proto.ScanSlice(cmd.Val(), container) + } func (cmd *StringSliceCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } + cmd.val = make([]string, n) + for i := 0; i < len(cmd.val); i++ { + switch s, err := rd.ReadString(); { + case err == Nil: + cmd.val[i] = "" + case err != nil: + return err + default: + cmd.val[i] = s + } + } + return nil + } //------------------------------------------------------------------------------ type KeyValue struct { - Key string + Key string + Value string } @@ -1099,82 +1729,133 @@ type KeyValueSliceCmd struct { var _ Cmder = (*KeyValueSliceCmd)(nil) func NewKeyValueSliceCmd(ctx context.Context, args ...interface{}) *KeyValueSliceCmd { + return &KeyValueSliceCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *KeyValueSliceCmd) SetVal(val []KeyValue) { + cmd.val = val + } func (cmd *KeyValueSliceCmd) Val() []KeyValue { + return cmd.val + } func (cmd *KeyValueSliceCmd) Result() ([]KeyValue, error) { + return cmd.val, cmd.err + } func (cmd *KeyValueSliceCmd) String() string { + return cmdString(cmd, cmd.val) + } // Many commands will respond to two formats: + // 1. 1) "one" + // 2. (double) 1 + // 2. 1) "two" + // 2. (double) 2 + // + // OR: + // 1. "two" + // 2. (double) 2 + // 3. "one" + // 4. (double) 1 + func (cmd *KeyValueSliceCmd) readReply(rd *proto.Reader) error { // nolint:dupl + n, err := rd.ReadArrayLen() + if err != nil { + return err + } // If the n is 0, can't continue reading. + if n == 0 { + cmd.val = make([]KeyValue, 0) + return nil + } typ, err := rd.PeekReplyType() + if err != nil { + return err + } + array := typ == proto.RespArray if array { + cmd.val = make([]KeyValue, n) + } else { + cmd.val = make([]KeyValue, n/2) + } for i := 0; i < len(cmd.val); i++ { + if array { + if err = rd.ReadFixedArrayLen(2); err != nil { + return err + } + } if cmd.val[i].Key, err = rd.ReadString(); err != nil { + return err + } if cmd.val[i].Value, err = rd.ReadString(); err != nil { + return err + } + } return nil + } //------------------------------------------------------------------------------ @@ -1188,42 +1869,67 @@ type BoolSliceCmd struct { var _ Cmder = (*BoolSliceCmd)(nil) func NewBoolSliceCmd(ctx context.Context, args ...interface{}) *BoolSliceCmd { + return &BoolSliceCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *BoolSliceCmd) SetVal(val []bool) { + cmd.val = val + } func (cmd *BoolSliceCmd) Val() []bool { + return cmd.val + } func (cmd *BoolSliceCmd) Result() ([]bool, error) { + return cmd.val, cmd.err + } func (cmd *BoolSliceCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *BoolSliceCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } + cmd.val = make([]bool, n) + for i := 0; i < len(cmd.val); i++ { + if cmd.val[i], err = rd.ReadBool(); err != nil { + return err + } + } + return nil + } //------------------------------------------------------------------------------ @@ -1237,72 +1943,113 @@ type MapStringStringCmd struct { var _ Cmder = (*MapStringStringCmd)(nil) func NewMapStringStringCmd(ctx context.Context, args ...interface{}) *MapStringStringCmd { + return &MapStringStringCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *MapStringStringCmd) Val() map[string]string { + return cmd.val + } func (cmd *MapStringStringCmd) SetVal(val map[string]string) { + cmd.val = val + } func (cmd *MapStringStringCmd) Result() (map[string]string, error) { + return cmd.val, cmd.err + } func (cmd *MapStringStringCmd) String() string { + return cmdString(cmd, cmd.val) + } // Scan scans the results from the map into a destination struct. The map keys + // are matched in the Redis struct fields by the `redis:"field"` tag. + func (cmd *MapStringStringCmd) Scan(dest interface{}) error { + if cmd.err != nil { + return cmd.err + } strct, err := hscan.Struct(dest) + if err != nil { + return err + } for k, v := range cmd.val { + if err := strct.Scan(k, v); err != nil { + return err + } + } return nil + } func (cmd *MapStringStringCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadMapLen() + if err != nil { + return err + } cmd.val = make(map[string]string, n) + for i := 0; i < n; i++ { + key, err := rd.ReadString() + if err != nil { + return err + } value, err := rd.ReadString() + if err != nil { + return err + } cmd.val[key] = value + } + return nil + } //------------------------------------------------------------------------------ @@ -1316,109 +2063,177 @@ type MapStringIntCmd struct { var _ Cmder = (*MapStringIntCmd)(nil) func NewMapStringIntCmd(ctx context.Context, args ...interface{}) *MapStringIntCmd { + return &MapStringIntCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *MapStringIntCmd) SetVal(val map[string]int64) { + cmd.val = val + } func (cmd *MapStringIntCmd) Val() map[string]int64 { + return cmd.val + } func (cmd *MapStringIntCmd) Result() (map[string]int64, error) { + return cmd.val, cmd.err + } func (cmd *MapStringIntCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *MapStringIntCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadMapLen() + if err != nil { + return err + } cmd.val = make(map[string]int64, n) + for i := 0; i < n; i++ { + key, err := rd.ReadString() + if err != nil { + return err + } nn, err := rd.ReadInt() + if err != nil { + return err + } + cmd.val[key] = nn + } + return nil + } // ------------------------------------------------------------------------------ + type MapStringSliceInterfaceCmd struct { baseCmd + val map[string][]interface{} } func NewMapStringSliceInterfaceCmd(ctx context.Context, args ...interface{}) *MapStringSliceInterfaceCmd { + return &MapStringSliceInterfaceCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *MapStringSliceInterfaceCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *MapStringSliceInterfaceCmd) SetVal(val map[string][]interface{}) { + cmd.val = val + } func (cmd *MapStringSliceInterfaceCmd) Result() (map[string][]interface{}, error) { + return cmd.val, cmd.err + } func (cmd *MapStringSliceInterfaceCmd) Val() map[string][]interface{} { + return cmd.val + } func (cmd *MapStringSliceInterfaceCmd) readReply(rd *proto.Reader) (err error) { + n, err := rd.ReadMapLen() + if err != nil { + return err + } + cmd.val = make(map[string][]interface{}, n) + for i := 0; i < n; i++ { + k, err := rd.ReadString() + if err != nil { + return err + } + nn, err := rd.ReadArrayLen() + if err != nil { + return err + } + cmd.val[k] = make([]interface{}, nn) + for j := 0; j < nn; j++ { + value, err := rd.ReadReply() + if err != nil { + return err + } + cmd.val[k][j] = value + } + } return nil + } //------------------------------------------------------------------------------ @@ -1432,51 +2247,78 @@ type StringStructMapCmd struct { var _ Cmder = (*StringStructMapCmd)(nil) func NewStringStructMapCmd(ctx context.Context, args ...interface{}) *StringStructMapCmd { + return &StringStructMapCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *StringStructMapCmd) SetVal(val map[string]struct{}) { + cmd.val = val + } func (cmd *StringStructMapCmd) Val() map[string]struct{} { + return cmd.val + } func (cmd *StringStructMapCmd) Result() (map[string]struct{}, error) { + return cmd.val, cmd.err + } func (cmd *StringStructMapCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *StringStructMapCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } cmd.val = make(map[string]struct{}, n) + for i := 0; i < n; i++ { + key, err := rd.ReadString() + if err != nil { + return err + } + cmd.val[key] = struct{}{} + } + return nil + } //------------------------------------------------------------------------------ type XMessage struct { - ID string + ID string + Values map[string]interface{} } @@ -1489,100 +2331,157 @@ type XMessageSliceCmd struct { var _ Cmder = (*XMessageSliceCmd)(nil) func NewXMessageSliceCmd(ctx context.Context, args ...interface{}) *XMessageSliceCmd { + return &XMessageSliceCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *XMessageSliceCmd) SetVal(val []XMessage) { + cmd.val = val + } func (cmd *XMessageSliceCmd) Val() []XMessage { + return cmd.val + } func (cmd *XMessageSliceCmd) Result() ([]XMessage, error) { + return cmd.val, cmd.err + } func (cmd *XMessageSliceCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *XMessageSliceCmd) readReply(rd *proto.Reader) (err error) { + cmd.val, err = readXMessageSlice(rd) + return err + } func readXMessageSlice(rd *proto.Reader) ([]XMessage, error) { + n, err := rd.ReadArrayLen() + if err != nil { + return nil, err + } msgs := make([]XMessage, n) + for i := 0; i < len(msgs); i++ { + if msgs[i], err = readXMessage(rd); err != nil { + return nil, err + } + } + return msgs, nil + } func readXMessage(rd *proto.Reader) (XMessage, error) { + if err := rd.ReadFixedArrayLen(2); err != nil { + return XMessage{}, err + } id, err := rd.ReadString() + if err != nil { + return XMessage{}, err + } v, err := stringInterfaceMapParser(rd) + if err != nil { + if err != proto.Nil { + return XMessage{}, err + } + } return XMessage{ - ID: id, + + ID: id, + Values: v, }, nil + } func stringInterfaceMapParser(rd *proto.Reader) (map[string]interface{}, error) { + n, err := rd.ReadMapLen() + if err != nil { + return nil, err + } m := make(map[string]interface{}, n) + for i := 0; i < n; i++ { + key, err := rd.ReadString() + if err != nil { + return nil, err + } value, err := rd.ReadString() + if err != nil { + return nil, err + } m[key] = value + } + return m, nil + } //------------------------------------------------------------------------------ type XStream struct { - Stream string + Stream string + Messages []XMessage } @@ -1595,218 +2494,343 @@ type XStreamSliceCmd struct { var _ Cmder = (*XStreamSliceCmd)(nil) func NewXStreamSliceCmd(ctx context.Context, args ...interface{}) *XStreamSliceCmd { + return &XStreamSliceCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *XStreamSliceCmd) SetVal(val []XStream) { + cmd.val = val + } func (cmd *XStreamSliceCmd) Val() []XStream { + return cmd.val + } func (cmd *XStreamSliceCmd) Result() ([]XStream, error) { + return cmd.val, cmd.err + } func (cmd *XStreamSliceCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *XStreamSliceCmd) readReply(rd *proto.Reader) error { + typ, err := rd.PeekReplyType() + if err != nil { + return err + } var n int + if typ == proto.RespMap { + n, err = rd.ReadMapLen() + } else { + n, err = rd.ReadArrayLen() + } + if err != nil { + return err + } + cmd.val = make([]XStream, n) + for i := 0; i < len(cmd.val); i++ { + if typ != proto.RespMap { + if err = rd.ReadFixedArrayLen(2); err != nil { + return err + } + } + if cmd.val[i].Stream, err = rd.ReadString(); err != nil { + return err + } + if cmd.val[i].Messages, err = readXMessageSlice(rd); err != nil { + return err + } + } + return nil + } //------------------------------------------------------------------------------ type XPending struct { - Count int64 - Lower string - Higher string + Count int64 + + Lower string + + Higher string + Consumers map[string]int64 } type XPendingCmd struct { baseCmd + val *XPending } var _ Cmder = (*XPendingCmd)(nil) func NewXPendingCmd(ctx context.Context, args ...interface{}) *XPendingCmd { + return &XPendingCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *XPendingCmd) SetVal(val *XPending) { + cmd.val = val + } func (cmd *XPendingCmd) Val() *XPending { + return cmd.val + } func (cmd *XPendingCmd) Result() (*XPending, error) { + return cmd.val, cmd.err + } func (cmd *XPendingCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *XPendingCmd) readReply(rd *proto.Reader) error { + var err error + if err = rd.ReadFixedArrayLen(4); err != nil { + return err + } + cmd.val = &XPending{} if cmd.val.Count, err = rd.ReadInt(); err != nil { + return err + } if cmd.val.Lower, err = rd.ReadString(); err != nil && err != Nil { + return err + } if cmd.val.Higher, err = rd.ReadString(); err != nil && err != Nil { + return err + } n, err := rd.ReadArrayLen() + if err != nil && err != Nil { + return err + } + cmd.val.Consumers = make(map[string]int64, n) + for i := 0; i < n; i++ { + if err = rd.ReadFixedArrayLen(2); err != nil { + return err + } consumerName, err := rd.ReadString() + if err != nil { + return err + } + consumerPending, err := rd.ReadInt() + if err != nil { + return err + } + cmd.val.Consumers[consumerName] = consumerPending + } + return nil + } //------------------------------------------------------------------------------ type XPendingExt struct { - ID string - Consumer string - Idle time.Duration + ID string + + Consumer string + + Idle time.Duration + RetryCount int64 } type XPendingExtCmd struct { baseCmd + val []XPendingExt } var _ Cmder = (*XPendingExtCmd)(nil) func NewXPendingExtCmd(ctx context.Context, args ...interface{}) *XPendingExtCmd { + return &XPendingExtCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *XPendingExtCmd) SetVal(val []XPendingExt) { + cmd.val = val + } func (cmd *XPendingExtCmd) Val() []XPendingExt { + return cmd.val + } func (cmd *XPendingExtCmd) Result() ([]XPendingExt, error) { + return cmd.val, cmd.err + } func (cmd *XPendingExtCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *XPendingExtCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } + cmd.val = make([]XPendingExt, n) for i := 0; i < len(cmd.val); i++ { + if err = rd.ReadFixedArrayLen(4); err != nil { + return err + } if cmd.val[i].ID, err = rd.ReadString(); err != nil { + return err + } if cmd.val[i].Consumer, err = rd.ReadString(); err != nil && err != Nil { + return err + } idle, err := rd.ReadInt() + if err != nil && err != Nil { + return err + } + cmd.val[i].Idle = time.Duration(idle) * time.Millisecond if cmd.val[i].RetryCount, err = rd.ReadInt(); err != nil && err != Nil { + return err + } + } return nil + } //------------------------------------------------------------------------------ @@ -1815,68 +2839,104 @@ type XAutoClaimCmd struct { baseCmd start string - val []XMessage + + val []XMessage } var _ Cmder = (*XAutoClaimCmd)(nil) func NewXAutoClaimCmd(ctx context.Context, args ...interface{}) *XAutoClaimCmd { + return &XAutoClaimCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *XAutoClaimCmd) SetVal(val []XMessage, start string) { + cmd.val = val + cmd.start = start + } func (cmd *XAutoClaimCmd) Val() (messages []XMessage, start string) { + return cmd.val, cmd.start + } func (cmd *XAutoClaimCmd) Result() (messages []XMessage, start string, err error) { + return cmd.val, cmd.start, cmd.err + } func (cmd *XAutoClaimCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *XAutoClaimCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } switch n { + case 2, // Redis 6 + 3: // Redis 7: + // ok + default: + return fmt.Errorf("redis: got %d elements in XAutoClaim reply, wanted 2/3", n) + } cmd.start, err = rd.ReadString() + if err != nil { + return err + } cmd.val, err = readXMessageSlice(rd) + if err != nil { + return err + } if n >= 3 { + if err := rd.DiscardNext(); err != nil { + return err + } + } return nil + } //------------------------------------------------------------------------------ @@ -1885,728 +2945,1214 @@ type XAutoClaimJustIDCmd struct { baseCmd start string - val []string + + val []string } var _ Cmder = (*XAutoClaimJustIDCmd)(nil) func NewXAutoClaimJustIDCmd(ctx context.Context, args ...interface{}) *XAutoClaimJustIDCmd { + return &XAutoClaimJustIDCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *XAutoClaimJustIDCmd) SetVal(val []string, start string) { + cmd.val = val + cmd.start = start + } func (cmd *XAutoClaimJustIDCmd) Val() (ids []string, start string) { + return cmd.val, cmd.start + } func (cmd *XAutoClaimJustIDCmd) Result() (ids []string, start string, err error) { + return cmd.val, cmd.start, cmd.err + } func (cmd *XAutoClaimJustIDCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *XAutoClaimJustIDCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } switch n { + case 2, // Redis 6 + 3: // Redis 7: + // ok + default: + return fmt.Errorf("redis: got %d elements in XAutoClaimJustID reply, wanted 2/3", n) + } cmd.start, err = rd.ReadString() + if err != nil { + return err + } nn, err := rd.ReadArrayLen() + if err != nil { + return err + } cmd.val = make([]string, nn) + for i := 0; i < nn; i++ { + cmd.val[i], err = rd.ReadString() + if err != nil { + return err + } + } if n >= 3 { + if err := rd.DiscardNext(); err != nil { + return err + } + } return nil + } //------------------------------------------------------------------------------ type XInfoConsumersCmd struct { baseCmd + val []XInfoConsumer } type XInfoConsumer struct { - Name string - Pending int64 - Idle time.Duration + Name string + + Pending int64 + + Idle time.Duration + Inactive time.Duration } var _ Cmder = (*XInfoConsumersCmd)(nil) func NewXInfoConsumersCmd(ctx context.Context, stream string, group string) *XInfoConsumersCmd { + return &XInfoConsumersCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: []interface{}{"xinfo", "consumers", stream, group}, }, } + } func (cmd *XInfoConsumersCmd) SetVal(val []XInfoConsumer) { + cmd.val = val + } func (cmd *XInfoConsumersCmd) Val() []XInfoConsumer { + return cmd.val + } func (cmd *XInfoConsumersCmd) Result() ([]XInfoConsumer, error) { + return cmd.val, cmd.err + } func (cmd *XInfoConsumersCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *XInfoConsumersCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } + cmd.val = make([]XInfoConsumer, n) for i := 0; i < len(cmd.val); i++ { + nn, err := rd.ReadMapLen() + if err != nil { + return err + } var key string + for f := 0; f < nn; f++ { + key, err = rd.ReadString() + if err != nil { + return err + } switch key { + case "name": + cmd.val[i].Name, err = rd.ReadString() + case "pending": + cmd.val[i].Pending, err = rd.ReadInt() + case "idle": + var idle int64 + idle, err = rd.ReadInt() + cmd.val[i].Idle = time.Duration(idle) * time.Millisecond + case "inactive": + var inactive int64 + inactive, err = rd.ReadInt() + cmd.val[i].Inactive = time.Duration(inactive) * time.Millisecond + default: + return fmt.Errorf("redis: unexpected content %s in XINFO CONSUMERS reply", key) + } + if err != nil { + return err + } + } + } return nil + } //------------------------------------------------------------------------------ type XInfoGroupsCmd struct { baseCmd + val []XInfoGroup } type XInfoGroup struct { - Name string - Consumers int64 - Pending int64 + Name string + + Consumers int64 + + Pending int64 + LastDeliveredID string - EntriesRead int64 - Lag int64 + + EntriesRead int64 + + Lag int64 } var _ Cmder = (*XInfoGroupsCmd)(nil) func NewXInfoGroupsCmd(ctx context.Context, stream string) *XInfoGroupsCmd { + return &XInfoGroupsCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: []interface{}{"xinfo", "groups", stream}, }, } + } func (cmd *XInfoGroupsCmd) SetVal(val []XInfoGroup) { + cmd.val = val + } func (cmd *XInfoGroupsCmd) Val() []XInfoGroup { + return cmd.val + } func (cmd *XInfoGroupsCmd) Result() ([]XInfoGroup, error) { + return cmd.val, cmd.err + } func (cmd *XInfoGroupsCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *XInfoGroupsCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } + cmd.val = make([]XInfoGroup, n) for i := 0; i < len(cmd.val); i++ { + group := &cmd.val[i] nn, err := rd.ReadMapLen() + if err != nil { + return err + } var key string + for j := 0; j < nn; j++ { + key, err = rd.ReadString() + if err != nil { + return err + } switch key { + case "name": + group.Name, err = rd.ReadString() + if err != nil { + return err + } + case "consumers": + group.Consumers, err = rd.ReadInt() + if err != nil { + return err + } + case "pending": + group.Pending, err = rd.ReadInt() + if err != nil { + return err + } + case "last-delivered-id": + group.LastDeliveredID, err = rd.ReadString() + if err != nil { + return err + } + case "entries-read": + group.EntriesRead, err = rd.ReadInt() + if err != nil && err != Nil { + return err + } + case "lag": + group.Lag, err = rd.ReadInt() // lag: the number of entries in the stream that are still waiting to be delivered + // to the group's consumers, or a NULL(Nil) when that number can't be determined. + if err != nil && err != Nil { + return err + } + default: + return fmt.Errorf("redis: unexpected key %q in XINFO GROUPS reply", key) + } + } + } return nil + } //------------------------------------------------------------------------------ type XInfoStreamCmd struct { baseCmd + val *XInfoStream } type XInfoStream struct { - Length int64 - RadixTreeKeys int64 - RadixTreeNodes int64 - Groups int64 - LastGeneratedID string - MaxDeletedEntryID string - EntriesAdded int64 - FirstEntry XMessage - LastEntry XMessage + Length int64 + + RadixTreeKeys int64 + + RadixTreeNodes int64 + + Groups int64 + + LastGeneratedID string + + MaxDeletedEntryID string + + EntriesAdded int64 + + FirstEntry XMessage + + LastEntry XMessage + RecordedFirstEntryID string } var _ Cmder = (*XInfoStreamCmd)(nil) func NewXInfoStreamCmd(ctx context.Context, stream string) *XInfoStreamCmd { + return &XInfoStreamCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: []interface{}{"xinfo", "stream", stream}, }, } + } func (cmd *XInfoStreamCmd) SetVal(val *XInfoStream) { + cmd.val = val + } func (cmd *XInfoStreamCmd) Val() *XInfoStream { + return cmd.val + } func (cmd *XInfoStreamCmd) Result() (*XInfoStream, error) { + return cmd.val, cmd.err + } func (cmd *XInfoStreamCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *XInfoStreamCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadMapLen() + if err != nil { + return err + } + cmd.val = &XInfoStream{} for i := 0; i < n; i++ { + key, err := rd.ReadString() + if err != nil { + return err + } + switch key { + case "length": + cmd.val.Length, err = rd.ReadInt() + if err != nil { + return err + } + case "radix-tree-keys": + cmd.val.RadixTreeKeys, err = rd.ReadInt() + if err != nil { + return err + } + case "radix-tree-nodes": + cmd.val.RadixTreeNodes, err = rd.ReadInt() + if err != nil { + return err + } + case "groups": + cmd.val.Groups, err = rd.ReadInt() + if err != nil { + return err + } + case "last-generated-id": + cmd.val.LastGeneratedID, err = rd.ReadString() + if err != nil { + return err + } + case "max-deleted-entry-id": + cmd.val.MaxDeletedEntryID, err = rd.ReadString() + if err != nil { + return err + } + case "entries-added": + cmd.val.EntriesAdded, err = rd.ReadInt() + if err != nil { + return err + } + case "first-entry": + cmd.val.FirstEntry, err = readXMessage(rd) + if err != nil && err != Nil { + return err + } + case "last-entry": + cmd.val.LastEntry, err = readXMessage(rd) + if err != nil && err != Nil { + return err + } + case "recorded-first-entry-id": + cmd.val.RecordedFirstEntryID, err = rd.ReadString() + if err != nil { + return err + } + default: + return fmt.Errorf("redis: unexpected key %q in XINFO STREAM reply", key) + } + } + return nil + } //------------------------------------------------------------------------------ type XInfoStreamFullCmd struct { baseCmd + val *XInfoStreamFull } type XInfoStreamFull struct { - Length int64 - RadixTreeKeys int64 - RadixTreeNodes int64 - LastGeneratedID string - MaxDeletedEntryID string - EntriesAdded int64 - Entries []XMessage - Groups []XInfoStreamGroup + Length int64 + + RadixTreeKeys int64 + + RadixTreeNodes int64 + + LastGeneratedID string + + MaxDeletedEntryID string + + EntriesAdded int64 + + Entries []XMessage + + Groups []XInfoStreamGroup + RecordedFirstEntryID string } type XInfoStreamGroup struct { - Name string + Name string + LastDeliveredID string - EntriesRead int64 - Lag int64 - PelCount int64 - Pending []XInfoStreamGroupPending - Consumers []XInfoStreamConsumer + + EntriesRead int64 + + Lag int64 + + PelCount int64 + + Pending []XInfoStreamGroupPending + + Consumers []XInfoStreamConsumer } type XInfoStreamGroupPending struct { - ID string - Consumer string - DeliveryTime time.Time + ID string + + Consumer string + + DeliveryTime time.Time + DeliveryCount int64 } type XInfoStreamConsumer struct { - Name string - SeenTime time.Time + Name string + + SeenTime time.Time + ActiveTime time.Time - PelCount int64 - Pending []XInfoStreamConsumerPending + + PelCount int64 + + Pending []XInfoStreamConsumerPending } type XInfoStreamConsumerPending struct { - ID string - DeliveryTime time.Time + ID string + + DeliveryTime time.Time + DeliveryCount int64 } var _ Cmder = (*XInfoStreamFullCmd)(nil) func NewXInfoStreamFullCmd(ctx context.Context, args ...interface{}) *XInfoStreamFullCmd { + return &XInfoStreamFullCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *XInfoStreamFullCmd) SetVal(val *XInfoStreamFull) { + cmd.val = val + } func (cmd *XInfoStreamFullCmd) Val() *XInfoStreamFull { + return cmd.val + } func (cmd *XInfoStreamFullCmd) Result() (*XInfoStreamFull, error) { + return cmd.val, cmd.err + } func (cmd *XInfoStreamFullCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *XInfoStreamFullCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadMapLen() + if err != nil { + return err + } cmd.val = &XInfoStreamFull{} for i := 0; i < n; i++ { + key, err := rd.ReadString() + if err != nil { + return err + } switch key { + case "length": + cmd.val.Length, err = rd.ReadInt() + if err != nil { + return err + } + case "radix-tree-keys": + cmd.val.RadixTreeKeys, err = rd.ReadInt() + if err != nil { + return err + } + case "radix-tree-nodes": + cmd.val.RadixTreeNodes, err = rd.ReadInt() + if err != nil { + return err + } + case "last-generated-id": + cmd.val.LastGeneratedID, err = rd.ReadString() + if err != nil { + return err + } + case "entries-added": + cmd.val.EntriesAdded, err = rd.ReadInt() + if err != nil { + return err + } + case "entries": + cmd.val.Entries, err = readXMessageSlice(rd) + if err != nil { + return err + } + case "groups": + cmd.val.Groups, err = readStreamGroups(rd) + if err != nil { + return err + } + case "max-deleted-entry-id": + cmd.val.MaxDeletedEntryID, err = rd.ReadString() + if err != nil { + return err + } + case "recorded-first-entry-id": + cmd.val.RecordedFirstEntryID, err = rd.ReadString() + if err != nil { + return err + } + default: + return fmt.Errorf("redis: unexpected key %q in XINFO STREAM FULL reply", key) + } + } + return nil + } func readStreamGroups(rd *proto.Reader) ([]XInfoStreamGroup, error) { + n, err := rd.ReadArrayLen() + if err != nil { + return nil, err + } + groups := make([]XInfoStreamGroup, 0, n) + for i := 0; i < n; i++ { + nn, err := rd.ReadMapLen() + if err != nil { + return nil, err + } group := XInfoStreamGroup{} for j := 0; j < nn; j++ { + key, err := rd.ReadString() + if err != nil { + return nil, err + } switch key { + case "name": + group.Name, err = rd.ReadString() + if err != nil { + return nil, err + } + case "last-delivered-id": + group.LastDeliveredID, err = rd.ReadString() + if err != nil { + return nil, err + } + case "entries-read": + group.EntriesRead, err = rd.ReadInt() + if err != nil && err != Nil { + return nil, err + } + case "lag": + // lag: the number of entries in the stream that are still waiting to be delivered + // to the group's consumers, or a NULL(Nil) when that number can't be determined. + group.Lag, err = rd.ReadInt() + if err != nil && err != Nil { + return nil, err + } + case "pel-count": + group.PelCount, err = rd.ReadInt() + if err != nil { + return nil, err + } + case "pending": + group.Pending, err = readXInfoStreamGroupPending(rd) + if err != nil { + return nil, err + } + case "consumers": + group.Consumers, err = readXInfoStreamConsumers(rd) + if err != nil { + return nil, err + } + default: + return nil, fmt.Errorf("redis: unexpected key %q in XINFO STREAM FULL reply", key) + } + } groups = append(groups, group) + } return groups, nil + } func readXInfoStreamGroupPending(rd *proto.Reader) ([]XInfoStreamGroupPending, error) { + n, err := rd.ReadArrayLen() + if err != nil { + return nil, err + } pending := make([]XInfoStreamGroupPending, 0, n) for i := 0; i < n; i++ { + if err = rd.ReadFixedArrayLen(4); err != nil { + return nil, err + } p := XInfoStreamGroupPending{} p.ID, err = rd.ReadString() + if err != nil { + return nil, err + } p.Consumer, err = rd.ReadString() + if err != nil { + return nil, err + } delivery, err := rd.ReadInt() + if err != nil { + return nil, err + } + p.DeliveryTime = time.Unix(delivery/1000, delivery%1000*int64(time.Millisecond)) p.DeliveryCount, err = rd.ReadInt() + if err != nil { + return nil, err + } pending = append(pending, p) + } return pending, nil + } func readXInfoStreamConsumers(rd *proto.Reader) ([]XInfoStreamConsumer, error) { + n, err := rd.ReadArrayLen() + if err != nil { + return nil, err + } consumers := make([]XInfoStreamConsumer, 0, n) for i := 0; i < n; i++ { + nn, err := rd.ReadMapLen() + if err != nil { + return nil, err + } c := XInfoStreamConsumer{} for f := 0; f < nn; f++ { + cKey, err := rd.ReadString() + if err != nil { + return nil, err + } switch cKey { + case "name": + c.Name, err = rd.ReadString() + case "seen-time": + seen, err := rd.ReadInt() + if err != nil { + return nil, err + } + c.SeenTime = time.UnixMilli(seen) + case "active-time": + active, err := rd.ReadInt() + if err != nil { + return nil, err + } + c.ActiveTime = time.UnixMilli(active) + case "pel-count": + c.PelCount, err = rd.ReadInt() + case "pending": + pendingNumber, err := rd.ReadArrayLen() + if err != nil { + return nil, err + } c.Pending = make([]XInfoStreamConsumerPending, 0, pendingNumber) for pn := 0; pn < pendingNumber; pn++ { + if err = rd.ReadFixedArrayLen(3); err != nil { + return nil, err + } p := XInfoStreamConsumerPending{} p.ID, err = rd.ReadString() + if err != nil { + return nil, err + } delivery, err := rd.ReadInt() + if err != nil { + return nil, err + } + p.DeliveryTime = time.Unix(delivery/1000, delivery%1000*int64(time.Millisecond)) p.DeliveryCount, err = rd.ReadInt() + if err != nil { + return nil, err + } c.Pending = append(c.Pending, p) + } + default: + return nil, fmt.Errorf("redis: unexpected content %s "+ + "in XINFO STREAM FULL reply", cKey) + } + if err != nil { + return nil, err + } + } + consumers = append(consumers, c) + } return consumers, nil + } //------------------------------------------------------------------------------ @@ -2620,71 +4166,111 @@ type ZSliceCmd struct { var _ Cmder = (*ZSliceCmd)(nil) func NewZSliceCmd(ctx context.Context, args ...interface{}) *ZSliceCmd { + return &ZSliceCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *ZSliceCmd) SetVal(val []Z) { + cmd.val = val + } func (cmd *ZSliceCmd) Val() []Z { + return cmd.val + } func (cmd *ZSliceCmd) Result() ([]Z, error) { + return cmd.val, cmd.err + } func (cmd *ZSliceCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *ZSliceCmd) readReply(rd *proto.Reader) error { // nolint:dupl + n, err := rd.ReadArrayLen() + if err != nil { + return err + } // If the n is 0, can't continue reading. + if n == 0 { + cmd.val = make([]Z, 0) + return nil + } typ, err := rd.PeekReplyType() + if err != nil { + return err + } + array := typ == proto.RespArray if array { + cmd.val = make([]Z, n) + } else { + cmd.val = make([]Z, n/2) + } for i := 0; i < len(cmd.val); i++ { + if array { + if err = rd.ReadFixedArrayLen(2); err != nil { + return err + } + } if cmd.val[i].Member, err = rd.ReadString(); err != nil { + return err + } if cmd.val[i].Score, err = rd.ReadFloat(); err != nil { + return err + } + } return nil + } //------------------------------------------------------------------------------ @@ -2698,47 +4284,73 @@ type ZWithKeyCmd struct { var _ Cmder = (*ZWithKeyCmd)(nil) func NewZWithKeyCmd(ctx context.Context, args ...interface{}) *ZWithKeyCmd { + return &ZWithKeyCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *ZWithKeyCmd) SetVal(val *ZWithKey) { + cmd.val = val + } func (cmd *ZWithKeyCmd) Val() *ZWithKey { + return cmd.val + } func (cmd *ZWithKeyCmd) Result() (*ZWithKey, error) { + return cmd.val, cmd.err + } func (cmd *ZWithKeyCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *ZWithKeyCmd) readReply(rd *proto.Reader) (err error) { + if err = rd.ReadFixedArrayLen(3); err != nil { + return err + } + cmd.val = &ZWithKey{} if cmd.val.Key, err = rd.ReadString(); err != nil { + return err + } + if cmd.val.Member, err = rd.ReadString(); err != nil { + return err + } + if cmd.val.Score, err = rd.ReadFloat(); err != nil { + return err + } return nil + } //------------------------------------------------------------------------------ @@ -2746,7 +4358,8 @@ func (cmd *ZWithKeyCmd) readReply(rd *proto.Reader) (err error) { type ScanCmd struct { baseCmd - page []string + page []string + cursor uint64 process cmdable @@ -2755,75 +4368,115 @@ type ScanCmd struct { var _ Cmder = (*ScanCmd)(nil) func NewScanCmd(ctx context.Context, process cmdable, args ...interface{}) *ScanCmd { + return &ScanCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, + process: process, } + } func (cmd *ScanCmd) SetVal(page []string, cursor uint64) { + cmd.page = page + cmd.cursor = cursor + } func (cmd *ScanCmd) Val() (keys []string, cursor uint64) { + return cmd.page, cmd.cursor + } func (cmd *ScanCmd) Result() (keys []string, cursor uint64, err error) { + return cmd.page, cmd.cursor, cmd.err + } func (cmd *ScanCmd) String() string { + return cmdString(cmd, cmd.page) + } func (cmd *ScanCmd) readReply(rd *proto.Reader) error { + if err := rd.ReadFixedArrayLen(2); err != nil { + return err + } cursor, err := rd.ReadUint() + if err != nil { + return err + } + cmd.cursor = cursor n, err := rd.ReadArrayLen() + if err != nil { + return err + } + cmd.page = make([]string, n) for i := 0; i < len(cmd.page); i++ { + if cmd.page[i], err = rd.ReadString(); err != nil { + return err + } + } + return nil + } // Iterator creates a new ScanIterator. + func (cmd *ScanCmd) Iterator() *ScanIterator { + return &ScanIterator{ + cmd: cmd, } + } //------------------------------------------------------------------------------ type ClusterNode struct { - ID string - Addr string + ID string + + Addr string + NetworkingMetadata map[string]string } type ClusterSlot struct { Start int - End int + + End int + Nodes []ClusterNode } @@ -2836,294 +4489,483 @@ type ClusterSlotsCmd struct { var _ Cmder = (*ClusterSlotsCmd)(nil) func NewClusterSlotsCmd(ctx context.Context, args ...interface{}) *ClusterSlotsCmd { + return &ClusterSlotsCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *ClusterSlotsCmd) SetVal(val []ClusterSlot) { + cmd.val = val + } func (cmd *ClusterSlotsCmd) Val() []ClusterSlot { + return cmd.val + } func (cmd *ClusterSlotsCmd) Result() ([]ClusterSlot, error) { + return cmd.val, cmd.err + } func (cmd *ClusterSlotsCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *ClusterSlotsCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } + cmd.val = make([]ClusterSlot, n) for i := 0; i < len(cmd.val); i++ { + n, err = rd.ReadArrayLen() + if err != nil { + return err + } + if n < 2 { + return fmt.Errorf("redis: got %d elements in cluster info, expected at least 2", n) + } start, err := rd.ReadInt() + if err != nil { + return err + } end, err := rd.ReadInt() + if err != nil { + return err + } // subtract start and end. + nodes := make([]ClusterNode, n-2) for j := 0; j < len(nodes); j++ { + nn, err := rd.ReadArrayLen() + if err != nil { + return err + } + if nn < 2 || nn > 4 { + return fmt.Errorf("got %d elements in cluster info address, expected 2, 3, or 4", n) + } ip, err := rd.ReadString() + if err != nil { + return err + } port, err := rd.ReadString() + if err != nil { + return err + } nodes[j].Addr = net.JoinHostPort(ip, port) if nn >= 3 { + id, err := rd.ReadString() + if err != nil { + return err + } + nodes[j].ID = id + } if nn >= 4 { + metadataLength, err := rd.ReadMapLen() + if err != nil { + return err + } networkingMetadata := make(map[string]string, metadataLength) for i := 0; i < metadataLength; i++ { + key, err := rd.ReadString() + if err != nil { + return err + } + value, err := rd.ReadString() + if err != nil { + return err + } + networkingMetadata[key] = value + } nodes[j].NetworkingMetadata = networkingMetadata + } + } cmd.val[i] = ClusterSlot{ + Start: int(start), - End: int(end), + + End: int(end), + Nodes: nodes, } + } return nil + } //------------------------------------------------------------------------------ // GeoLocation is used with GeoAdd to add geospatial location. + type GeoLocation struct { - Name string + Name string + Longitude, Latitude, Dist float64 - GeoHash int64 + + GeoHash int64 } // GeoRadiusQuery is used with GeoRadius to query geospatial index. + type GeoRadiusQuery struct { Radius float64 + // Can be m, km, ft, or mi. Default is km. - Unit string - WithCoord bool - WithDist bool + + Unit string + + WithCoord bool + + WithDist bool + WithGeoHash bool - Count int + + Count int + // Can be ASC or DESC. Default is no sort order. - Sort string - Store string + + Sort string + + Store string + StoreDist string // WithCoord+WithDist+WithGeoHash + withLen int } type GeoLocationCmd struct { baseCmd - q *GeoRadiusQuery + q *GeoRadiusQuery + locations []GeoLocation } var _ Cmder = (*GeoLocationCmd)(nil) func NewGeoLocationCmd(ctx context.Context, q *GeoRadiusQuery, args ...interface{}) *GeoLocationCmd { + return &GeoLocationCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: geoLocationArgs(q, args...), }, + q: q, } + } func geoLocationArgs(q *GeoRadiusQuery, args ...interface{}) []interface{} { + args = append(args, q.Radius) + if q.Unit != "" { + args = append(args, q.Unit) + } else { + args = append(args, "km") + } + if q.WithCoord { + args = append(args, "withcoord") + q.withLen++ + } + if q.WithDist { + args = append(args, "withdist") + q.withLen++ + } + if q.WithGeoHash { + args = append(args, "withhash") + q.withLen++ + } + if q.Count > 0 { + args = append(args, "count", q.Count) + } + if q.Sort != "" { + args = append(args, q.Sort) + } + if q.Store != "" { + args = append(args, "store") + args = append(args, q.Store) + } + if q.StoreDist != "" { + args = append(args, "storedist") + args = append(args, q.StoreDist) + } + return args + } func (cmd *GeoLocationCmd) SetVal(locations []GeoLocation) { + cmd.locations = locations + } func (cmd *GeoLocationCmd) Val() []GeoLocation { + return cmd.locations + } func (cmd *GeoLocationCmd) Result() ([]GeoLocation, error) { + return cmd.locations, cmd.err + } func (cmd *GeoLocationCmd) String() string { + return cmdString(cmd, cmd.locations) + } func (cmd *GeoLocationCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } + cmd.locations = make([]GeoLocation, n) for i := 0; i < len(cmd.locations); i++ { + // only name + if cmd.q.withLen == 0 { + if cmd.locations[i].Name, err = rd.ReadString(); err != nil { + return err + } + continue + } // +name + if err = rd.ReadFixedArrayLen(cmd.q.withLen + 1); err != nil { + return err + } if cmd.locations[i].Name, err = rd.ReadString(); err != nil { + return err + } + if cmd.q.WithDist { + if cmd.locations[i].Dist, err = rd.ReadFloat(); err != nil { + return err + } + } + if cmd.q.WithGeoHash { + if cmd.locations[i].GeoHash, err = rd.ReadInt(); err != nil { + return err + } + } + if cmd.q.WithCoord { + if err = rd.ReadFixedArrayLen(2); err != nil { + return err + } + if cmd.locations[i].Longitude, err = rd.ReadFloat(); err != nil { + return err + } + if cmd.locations[i].Latitude, err = rd.ReadFloat(); err != nil { + return err + } + } + } return nil + } //------------------------------------------------------------------------------ // GeoSearchQuery is used for GEOSearch/GEOSearchStore command query. + type GeoSearchQuery struct { Member string // Latitude and Longitude when using FromLonLat option. + Longitude float64 - Latitude float64 + + Latitude float64 // Distance and unit when using ByRadius option. + // Can use m, km, ft, or mi. Default is km. - Radius float64 + + Radius float64 + RadiusUnit string // Height, width and unit when using ByBox option. + // Can be m, km, ft, or mi. Default is km. - BoxWidth float64 + + BoxWidth float64 + BoxHeight float64 - BoxUnit string + + BoxUnit string // Can be ASC or DESC. Default is no sort order. - Sort string - Count int + + Sort string + + Count int + CountAny bool } @@ -3131,154 +4973,248 @@ type GeoSearchLocationQuery struct { GeoSearchQuery WithCoord bool - WithDist bool - WithHash bool + + WithDist bool + + WithHash bool } type GeoSearchStoreQuery struct { GeoSearchQuery // When using the StoreDist option, the command stores the items in a + // sorted set populated with their distance from the center of the circle or box, + // as a floating-point number, in the same unit specified for that shape. + StoreDist bool } func geoSearchLocationArgs(q *GeoSearchLocationQuery, args []interface{}) []interface{} { + args = geoSearchArgs(&q.GeoSearchQuery, args) if q.WithCoord { + args = append(args, "withcoord") + } + if q.WithDist { + args = append(args, "withdist") + } + if q.WithHash { + args = append(args, "withhash") + } return args + } func geoSearchArgs(q *GeoSearchQuery, args []interface{}) []interface{} { + if q.Member != "" { + args = append(args, "frommember", q.Member) + } else { + args = append(args, "fromlonlat", q.Longitude, q.Latitude) + } if q.Radius > 0 { + if q.RadiusUnit == "" { + q.RadiusUnit = "km" + } + args = append(args, "byradius", q.Radius, q.RadiusUnit) + } else { + if q.BoxUnit == "" { + q.BoxUnit = "km" + } + args = append(args, "bybox", q.BoxWidth, q.BoxHeight, q.BoxUnit) + } if q.Sort != "" { + args = append(args, q.Sort) + } if q.Count > 0 { + args = append(args, "count", q.Count) + if q.CountAny { + args = append(args, "any") + } + } return args + } type GeoSearchLocationCmd struct { baseCmd opt *GeoSearchLocationQuery + val []GeoLocation } var _ Cmder = (*GeoSearchLocationCmd)(nil) func NewGeoSearchLocationCmd( + ctx context.Context, opt *GeoSearchLocationQuery, args ...interface{}, + ) *GeoSearchLocationCmd { + return &GeoSearchLocationCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, + opt: opt, } + } func (cmd *GeoSearchLocationCmd) SetVal(val []GeoLocation) { + cmd.val = val + } func (cmd *GeoSearchLocationCmd) Val() []GeoLocation { + return cmd.val + } func (cmd *GeoSearchLocationCmd) Result() ([]GeoLocation, error) { + return cmd.val, cmd.err + } func (cmd *GeoSearchLocationCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *GeoSearchLocationCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } cmd.val = make([]GeoLocation, n) + for i := 0; i < n; i++ { + _, err = rd.ReadArrayLen() + if err != nil { + return err + } var loc GeoLocation loc.Name, err = rd.ReadString() + if err != nil { + return err + } + if cmd.opt.WithDist { + loc.Dist, err = rd.ReadFloat() + if err != nil { + return err + } + } + if cmd.opt.WithHash { + loc.GeoHash, err = rd.ReadInt() + if err != nil { + return err + } + } + if cmd.opt.WithCoord { + if err = rd.ReadFixedArrayLen(2); err != nil { + return err + } + loc.Longitude, err = rd.ReadFloat() + if err != nil { + return err + } + loc.Latitude, err = rd.ReadFloat() + if err != nil { + return err + } + } cmd.val[i] = loc + } return nil + } //------------------------------------------------------------------------------ @@ -3296,76 +5232,120 @@ type GeoPosCmd struct { var _ Cmder = (*GeoPosCmd)(nil) func NewGeoPosCmd(ctx context.Context, args ...interface{}) *GeoPosCmd { + return &GeoPosCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *GeoPosCmd) SetVal(val []*GeoPos) { + cmd.val = val + } func (cmd *GeoPosCmd) Val() []*GeoPos { + return cmd.val + } func (cmd *GeoPosCmd) Result() ([]*GeoPos, error) { + return cmd.val, cmd.err + } func (cmd *GeoPosCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *GeoPosCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } + cmd.val = make([]*GeoPos, n) for i := 0; i < len(cmd.val); i++ { + err = rd.ReadFixedArrayLen(2) + if err != nil { + if err == Nil { + cmd.val[i] = nil + continue + } + return err + } longitude, err := rd.ReadFloat() + if err != nil { + return err + } + latitude, err := rd.ReadFloat() + if err != nil { + return err + } cmd.val[i] = &GeoPos{ + Longitude: longitude, - Latitude: latitude, + + Latitude: latitude, } + } return nil + } //------------------------------------------------------------------------------ type CommandInfo struct { - Name string - Arity int8 - Flags []string - ACLFlags []string + Name string + + Arity int8 + + Flags []string + + ACLFlags []string + FirstKeyPos int8 - LastKeyPos int8 - StepCount int8 - ReadOnly bool + + LastKeyPos int8 + + StepCount int8 + + ReadOnly bool } type CommandsInfoCmd struct { @@ -3377,136 +5357,229 @@ type CommandsInfoCmd struct { var _ Cmder = (*CommandsInfoCmd)(nil) func NewCommandsInfoCmd(ctx context.Context, args ...interface{}) *CommandsInfoCmd { + return &CommandsInfoCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *CommandsInfoCmd) SetVal(val map[string]*CommandInfo) { + cmd.val = val + } func (cmd *CommandsInfoCmd) Val() map[string]*CommandInfo { + return cmd.val + } func (cmd *CommandsInfoCmd) Result() (map[string]*CommandInfo, error) { + return cmd.val, cmd.err + } func (cmd *CommandsInfoCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *CommandsInfoCmd) readReply(rd *proto.Reader) error { + const numArgRedis5 = 6 + const numArgRedis6 = 7 + const numArgRedis7 = 10 n, err := rd.ReadArrayLen() + if err != nil { + return err + } + cmd.val = make(map[string]*CommandInfo, n) for i := 0; i < n; i++ { + nn, err := rd.ReadArrayLen() + if err != nil { + return err + } switch nn { + case numArgRedis5, numArgRedis6, numArgRedis7: + // ok + default: + return fmt.Errorf("redis: got %d elements in COMMAND reply, wanted 6/7/10", nn) + } cmdInfo := &CommandInfo{} + if cmdInfo.Name, err = rd.ReadString(); err != nil { + return err + } arity, err := rd.ReadInt() + if err != nil { + return err + } + cmdInfo.Arity = int8(arity) flagLen, err := rd.ReadArrayLen() + if err != nil { + return err + } + cmdInfo.Flags = make([]string, flagLen) + for f := 0; f < len(cmdInfo.Flags); f++ { + switch s, err := rd.ReadString(); { + case err == Nil: + cmdInfo.Flags[f] = "" + case err != nil: + return err + default: + if !cmdInfo.ReadOnly && s == "readonly" { + cmdInfo.ReadOnly = true + } + cmdInfo.Flags[f] = s + } + } firstKeyPos, err := rd.ReadInt() + if err != nil { + return err + } + cmdInfo.FirstKeyPos = int8(firstKeyPos) lastKeyPos, err := rd.ReadInt() + if err != nil { + return err + } + cmdInfo.LastKeyPos = int8(lastKeyPos) stepCount, err := rd.ReadInt() + if err != nil { + return err + } + cmdInfo.StepCount = int8(stepCount) if nn >= numArgRedis6 { + aclFlagLen, err := rd.ReadArrayLen() + if err != nil { + return err + } + cmdInfo.ACLFlags = make([]string, aclFlagLen) + for f := 0; f < len(cmdInfo.ACLFlags); f++ { + switch s, err := rd.ReadString(); { + case err == Nil: + cmdInfo.ACLFlags[f] = "" + case err != nil: + return err + default: + cmdInfo.ACLFlags[f] = s + } + } + } if nn >= numArgRedis7 { + if err := rd.DiscardNext(); err != nil { + return err + } + if err := rd.DiscardNext(); err != nil { + return err + } + if err := rd.DiscardNext(); err != nil { + return err + } + } cmd.val[cmdInfo.Name] = cmdInfo + } return nil + } //------------------------------------------------------------------------------ @@ -3515,46 +5588,72 @@ type cmdsInfoCache struct { fn func(ctx context.Context) (map[string]*CommandInfo, error) once internal.Once + cmds map[string]*CommandInfo } func newCmdsInfoCache(fn func(ctx context.Context) (map[string]*CommandInfo, error)) *cmdsInfoCache { + return &cmdsInfoCache{ + fn: fn, } + } func (c *cmdsInfoCache) Get(ctx context.Context) (map[string]*CommandInfo, error) { + err := c.once.Do(func() error { + cmds, err := c.fn(ctx) + if err != nil { + return err + } // Extensions have cmd names in upper case. Convert them to lower case. + for k, v := range cmds { + lower := internal.ToLower(k) + if lower != k { + cmds[lower] = v + } + } c.cmds = cmds + return nil + }) + return c.cmds, err + } //------------------------------------------------------------------------------ type SlowLog struct { - ID int64 - Time time.Time + ID int64 + + Time time.Time + Duration time.Duration - Args []string + + Args []string + // These are also optional fields emitted only by Redis 4.0 or greater: + // https://redis.io/commands/slowlog#output-format + ClientAddr string + ClientName string } @@ -3567,92 +5666,149 @@ type SlowLogCmd struct { var _ Cmder = (*SlowLogCmd)(nil) func NewSlowLogCmd(ctx context.Context, args ...interface{}) *SlowLogCmd { + return &SlowLogCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *SlowLogCmd) SetVal(val []SlowLog) { + cmd.val = val + } func (cmd *SlowLogCmd) Val() []SlowLog { + return cmd.val + } func (cmd *SlowLogCmd) Result() ([]SlowLog, error) { + return cmd.val, cmd.err + } func (cmd *SlowLogCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *SlowLogCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } + cmd.val = make([]SlowLog, n) for i := 0; i < len(cmd.val); i++ { + nn, err := rd.ReadArrayLen() + if err != nil { + return err + } + if nn < 4 { + return fmt.Errorf("redis: got %d elements in slowlog get, expected at least 4", nn) + } if cmd.val[i].ID, err = rd.ReadInt(); err != nil { + return err + } createdAt, err := rd.ReadInt() + if err != nil { + return err + } + cmd.val[i].Time = time.Unix(createdAt, 0) costs, err := rd.ReadInt() + if err != nil { + return err + } + cmd.val[i].Duration = time.Duration(costs) * time.Microsecond cmdLen, err := rd.ReadArrayLen() + if err != nil { + return err + } + if cmdLen < 1 { + return fmt.Errorf("redis: got %d elements commands reply in slowlog get, expected at least 1", cmdLen) + } cmd.val[i].Args = make([]string, cmdLen) + for f := 0; f < len(cmd.val[i].Args); f++ { + cmd.val[i].Args[f], err = rd.ReadString() + if err != nil { + return err + } + } if nn >= 5 { + if cmd.val[i].ClientAddr, err = rd.ReadString(); err != nil { + return err + } + } if nn >= 6 { + if cmd.val[i].ClientName, err = rd.ReadString(); err != nil { + return err + } + } + } return nil + } //----------------------------------------------------------------------- @@ -3666,57 +5822,95 @@ type MapStringInterfaceCmd struct { var _ Cmder = (*MapStringInterfaceCmd)(nil) func NewMapStringInterfaceCmd(ctx context.Context, args ...interface{}) *MapStringInterfaceCmd { + return &MapStringInterfaceCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *MapStringInterfaceCmd) SetVal(val map[string]interface{}) { + cmd.val = val + } func (cmd *MapStringInterfaceCmd) Val() map[string]interface{} { + return cmd.val + } func (cmd *MapStringInterfaceCmd) Result() (map[string]interface{}, error) { + return cmd.val, cmd.err + } func (cmd *MapStringInterfaceCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *MapStringInterfaceCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadMapLen() + if err != nil { + return err + } cmd.val = make(map[string]interface{}, n) + for i := 0; i < n; i++ { + k, err := rd.ReadString() + if err != nil { + return err + } + v, err := rd.ReadReply() + if err != nil { + if err == Nil { + cmd.val[k] = Nil + continue + } + if err, ok := err.(proto.RedisError); ok { + cmd.val[k] = err + continue + } + return err + } + cmd.val[k] = v + } + return nil + } //----------------------------------------------------------------------- @@ -3730,57 +5924,93 @@ type MapStringStringSliceCmd struct { var _ Cmder = (*MapStringStringSliceCmd)(nil) func NewMapStringStringSliceCmd(ctx context.Context, args ...interface{}) *MapStringStringSliceCmd { + return &MapStringStringSliceCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *MapStringStringSliceCmd) SetVal(val []map[string]string) { + cmd.val = val + } func (cmd *MapStringStringSliceCmd) Val() []map[string]string { + return cmd.val + } func (cmd *MapStringStringSliceCmd) Result() ([]map[string]string, error) { + return cmd.val, cmd.err + } func (cmd *MapStringStringSliceCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *MapStringStringSliceCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } cmd.val = make([]map[string]string, n) + for i := 0; i < n; i++ { + nn, err := rd.ReadMapLen() + if err != nil { + return err + } + cmd.val[i] = make(map[string]string, nn) + for f := 0; f < nn; f++ { + k, err := rd.ReadString() + if err != nil { + return err + } v, err := rd.ReadString() + if err != nil { + return err + } + cmd.val[i][k] = v + } + } + return nil + } //----------------------------------------------------------------------- @@ -3794,58 +6024,97 @@ type MapStringInterfaceSliceCmd struct { var _ Cmder = (*MapStringInterfaceSliceCmd)(nil) func NewMapStringInterfaceSliceCmd(ctx context.Context, args ...interface{}) *MapStringInterfaceSliceCmd { + return &MapStringInterfaceSliceCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *MapStringInterfaceSliceCmd) SetVal(val []map[string]interface{}) { + cmd.val = val + } func (cmd *MapStringInterfaceSliceCmd) Val() []map[string]interface{} { + return cmd.val + } func (cmd *MapStringInterfaceSliceCmd) Result() ([]map[string]interface{}, error) { + return cmd.val, cmd.err + } func (cmd *MapStringInterfaceSliceCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *MapStringInterfaceSliceCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } cmd.val = make([]map[string]interface{}, n) + for i := 0; i < n; i++ { + nn, err := rd.ReadMapLen() + if err != nil { + return err + } + cmd.val[i] = make(map[string]interface{}, nn) + for f := 0; f < nn; f++ { + k, err := rd.ReadString() + if err != nil { + return err + } + v, err := rd.ReadReply() + if err != nil { + if err != Nil { + return err + } + } + cmd.val[i][k] = v + } + } + return nil + } //------------------------------------------------------------------------------ @@ -3854,60 +6123,92 @@ type KeyValuesCmd struct { baseCmd key string + val []string } var _ Cmder = (*KeyValuesCmd)(nil) func NewKeyValuesCmd(ctx context.Context, args ...interface{}) *KeyValuesCmd { + return &KeyValuesCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *KeyValuesCmd) SetVal(key string, val []string) { + cmd.key = key + cmd.val = val + } func (cmd *KeyValuesCmd) Val() (string, []string) { + return cmd.key, cmd.val + } func (cmd *KeyValuesCmd) Result() (string, []string, error) { + return cmd.key, cmd.val, cmd.err + } func (cmd *KeyValuesCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *KeyValuesCmd) readReply(rd *proto.Reader) (err error) { + if err = rd.ReadFixedArrayLen(2); err != nil { + return err + } cmd.key, err = rd.ReadString() + if err != nil { + return err + } n, err := rd.ReadArrayLen() + if err != nil { + return err + } + cmd.val = make([]string, n) + for i := 0; i < n; i++ { + cmd.val[i], err = rd.ReadString() + if err != nil { + return err + } + } return nil + } //------------------------------------------------------------------------------ @@ -3916,94 +6217,142 @@ type ZSliceWithKeyCmd struct { baseCmd key string + val []Z } var _ Cmder = (*ZSliceWithKeyCmd)(nil) func NewZSliceWithKeyCmd(ctx context.Context, args ...interface{}) *ZSliceWithKeyCmd { + return &ZSliceWithKeyCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *ZSliceWithKeyCmd) SetVal(key string, val []Z) { + cmd.key = key + cmd.val = val + } func (cmd *ZSliceWithKeyCmd) Val() (string, []Z) { + return cmd.key, cmd.val + } func (cmd *ZSliceWithKeyCmd) Result() (string, []Z, error) { + return cmd.key, cmd.val, cmd.err + } func (cmd *ZSliceWithKeyCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *ZSliceWithKeyCmd) readReply(rd *proto.Reader) (err error) { + if err = rd.ReadFixedArrayLen(2); err != nil { + return err + } cmd.key, err = rd.ReadString() + if err != nil { + return err + } n, err := rd.ReadArrayLen() + if err != nil { + return err + } typ, err := rd.PeekReplyType() + if err != nil { + return err + } + array := typ == proto.RespArray if array { + cmd.val = make([]Z, n) + } else { + cmd.val = make([]Z, n/2) + } for i := 0; i < len(cmd.val); i++ { + if array { + if err = rd.ReadFixedArrayLen(2); err != nil { + return err + } + } if cmd.val[i].Member, err = rd.ReadString(); err != nil { + return err + } if cmd.val[i].Score, err = rd.ReadFloat(); err != nil { + return err + } + } return nil + } type Function struct { - Name string + Name string + Description string - Flags []string + + Flags []string } type Library struct { - Name string - Engine string + Name string + + Engine string + Functions []Function - Code string + + Code string } type FunctionListCmd struct { @@ -4015,541 +6364,893 @@ type FunctionListCmd struct { var _ Cmder = (*FunctionListCmd)(nil) func NewFunctionListCmd(ctx context.Context, args ...interface{}) *FunctionListCmd { + return &FunctionListCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *FunctionListCmd) SetVal(val []Library) { + cmd.val = val + } func (cmd *FunctionListCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *FunctionListCmd) Val() []Library { + return cmd.val + } func (cmd *FunctionListCmd) Result() ([]Library, error) { + return cmd.val, cmd.err + } func (cmd *FunctionListCmd) First() (*Library, error) { + if cmd.err != nil { + return nil, cmd.err + } + if len(cmd.val) > 0 { + return &cmd.val[0], nil + } + return nil, Nil + } func (cmd *FunctionListCmd) readReply(rd *proto.Reader) (err error) { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } libraries := make([]Library, n) + for i := 0; i < n; i++ { + nn, err := rd.ReadMapLen() + if err != nil { + return err + } library := Library{} + for f := 0; f < nn; f++ { + key, err := rd.ReadString() + if err != nil { + return err + } switch key { + case "library_name": + library.Name, err = rd.ReadString() + case "engine": + library.Engine, err = rd.ReadString() + case "functions": + library.Functions, err = cmd.readFunctions(rd) + case "library_code": + library.Code, err = rd.ReadString() + default: + return fmt.Errorf("redis: function list unexpected key %s", key) + } if err != nil { + return err + } + } libraries[i] = library + } + cmd.val = libraries + return nil + } func (cmd *FunctionListCmd) readFunctions(rd *proto.Reader) ([]Function, error) { + n, err := rd.ReadArrayLen() + if err != nil { + return nil, err + } functions := make([]Function, n) + for i := 0; i < n; i++ { + nn, err := rd.ReadMapLen() + if err != nil { + return nil, err + } function := Function{} + for f := 0; f < nn; f++ { + key, err := rd.ReadString() + if err != nil { + return nil, err + } switch key { + case "name": + if function.Name, err = rd.ReadString(); err != nil { + return nil, err + } + case "description": + if function.Description, err = rd.ReadString(); err != nil && err != Nil { + return nil, err + } + case "flags": + // resp set + nx, err := rd.ReadArrayLen() + if err != nil { + return nil, err + } function.Flags = make([]string, nx) + for j := 0; j < nx; j++ { + if function.Flags[j], err = rd.ReadString(); err != nil { + return nil, err + } + } + default: + return nil, fmt.Errorf("redis: function list unexpected key %s", key) + } + } functions[i] = function + } + return functions, nil + } // FunctionStats contains information about the scripts currently executing on the server, and the available engines + // - Engines: + // Statistics about the engine like number of functions and number of libraries + // - RunningScript: + // The script currently running on the shard we're connecting to. + // For Redis Enterprise and Redis Cloud, this represents the + // function with the longest running time, across all the running functions, on all shards + // - RunningScripts + // All scripts currently running in a Redis Enterprise clustered database. + // Only available on Redis Enterprise + type FunctionStats struct { - Engines []Engine + Engines []Engine + isRunning bool - rs RunningScript - allrs []RunningScript + + rs RunningScript + + allrs []RunningScript } func (fs *FunctionStats) Running() bool { + return fs.isRunning + } func (fs *FunctionStats) RunningScript() (RunningScript, bool) { + return fs.rs, fs.isRunning + } // AllRunningScripts returns all scripts currently running in a Redis Enterprise clustered database. + // Only available on Redis Enterprise + func (fs *FunctionStats) AllRunningScripts() []RunningScript { + return fs.allrs + } type RunningScript struct { - Name string - Command []string + Name string + + Command []string + Duration time.Duration } type Engine struct { - Language string + Language string + LibrariesCount int64 + FunctionsCount int64 } type FunctionStatsCmd struct { baseCmd + val FunctionStats } var _ Cmder = (*FunctionStatsCmd)(nil) func NewFunctionStatsCmd(ctx context.Context, args ...interface{}) *FunctionStatsCmd { + return &FunctionStatsCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *FunctionStatsCmd) SetVal(val FunctionStats) { + cmd.val = val + } func (cmd *FunctionStatsCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *FunctionStatsCmd) Val() FunctionStats { + return cmd.val + } func (cmd *FunctionStatsCmd) Result() (FunctionStats, error) { + return cmd.val, cmd.err + } func (cmd *FunctionStatsCmd) readReply(rd *proto.Reader) (err error) { + n, err := rd.ReadMapLen() + if err != nil { + return err + } var key string + var result FunctionStats + for f := 0; f < n; f++ { + key, err = rd.ReadString() + if err != nil { + return err + } switch key { + case "running_script": + result.rs, result.isRunning, err = cmd.readRunningScript(rd) + case "engines": + result.Engines, err = cmd.readEngines(rd) + case "all_running_scripts": // Redis Enterprise only + result.allrs, result.isRunning, err = cmd.readRunningScripts(rd) + default: + return fmt.Errorf("redis: function stats unexpected key %s", key) + } if err != nil { + return err + } + } cmd.val = result + return nil + } func (cmd *FunctionStatsCmd) readRunningScript(rd *proto.Reader) (RunningScript, bool, error) { + err := rd.ReadFixedMapLen(3) + if err != nil { + if err == Nil { + return RunningScript{}, false, nil + } + return RunningScript{}, false, err + } var runningScript RunningScript + for i := 0; i < 3; i++ { + key, err := rd.ReadString() + if err != nil { + return RunningScript{}, false, err + } switch key { + case "name": + runningScript.Name, err = rd.ReadString() + case "duration_ms": + runningScript.Duration, err = cmd.readDuration(rd) + case "command": + runningScript.Command, err = cmd.readCommand(rd) + default: + return RunningScript{}, false, fmt.Errorf("redis: function stats unexpected running_script key %s", key) + } if err != nil { + return RunningScript{}, false, err + } + } return runningScript, true, nil + } func (cmd *FunctionStatsCmd) readEngines(rd *proto.Reader) ([]Engine, error) { + n, err := rd.ReadMapLen() + if err != nil { + return nil, err + } engines := make([]Engine, 0, n) + for i := 0; i < n; i++ { + engine := Engine{} + engine.Language, err = rd.ReadString() + if err != nil { + return nil, err + } err = rd.ReadFixedMapLen(2) + if err != nil { + return nil, fmt.Errorf("redis: function stats unexpected %s engine map length", engine.Language) + } for i := 0; i < 2; i++ { + key, err := rd.ReadString() + switch key { + case "libraries_count": + engine.LibrariesCount, err = rd.ReadInt() + case "functions_count": + engine.FunctionsCount, err = rd.ReadInt() + } + if err != nil { + return nil, err + } + } engines = append(engines, engine) + } + return engines, nil + } func (cmd *FunctionStatsCmd) readDuration(rd *proto.Reader) (time.Duration, error) { + t, err := rd.ReadInt() + if err != nil { + return time.Duration(0), err + } + return time.Duration(t) * time.Millisecond, nil + } func (cmd *FunctionStatsCmd) readCommand(rd *proto.Reader) ([]string, error) { + n, err := rd.ReadArrayLen() + if err != nil { + return nil, err + } command := make([]string, 0, n) + for i := 0; i < n; i++ { + x, err := rd.ReadString() + if err != nil { + return nil, err + } + command = append(command, x) + } return command, nil + } func (cmd *FunctionStatsCmd) readRunningScripts(rd *proto.Reader) ([]RunningScript, bool, error) { + n, err := rd.ReadArrayLen() + if err != nil { + return nil, false, err + } runningScripts := make([]RunningScript, 0, n) + for i := 0; i < n; i++ { + rs, _, err := cmd.readRunningScript(rd) + if err != nil { + return nil, false, err + } + runningScripts = append(runningScripts, rs) + } return runningScripts, len(runningScripts) > 0, nil + } //------------------------------------------------------------------------------ // LCSQuery is a parameter used for the LCS command + type LCSQuery struct { - Key1 string - Key2 string - Len bool - Idx bool - MinMatchLen int + Key1 string + + Key2 string + + Len bool + + Idx bool + + MinMatchLen int + WithMatchLen bool } // LCSMatch is the result set of the LCS command. + type LCSMatch struct { MatchString string - Matches []LCSMatchedPosition - Len int64 + + Matches []LCSMatchedPosition + + Len int64 } type LCSMatchedPosition struct { Key1 LCSPosition + Key2 LCSPosition // only for withMatchLen is true + MatchLen int64 } type LCSPosition struct { Start int64 - End int64 + + End int64 } type LCSCmd struct { baseCmd // 1: match string + // 2: match len + // 3: match idx LCSMatch + readType uint8 - val *LCSMatch + + val *LCSMatch } func NewLCSCmd(ctx context.Context, q *LCSQuery) *LCSCmd { + args := make([]interface{}, 3, 7) + args[0] = "lcs" + args[1] = q.Key1 + args[2] = q.Key2 cmd := &LCSCmd{readType: 1} + if q.Len { + cmd.readType = 2 + args = append(args, "len") + } else if q.Idx { + cmd.readType = 3 + args = append(args, "idx") + if q.MinMatchLen != 0 { + args = append(args, "minmatchlen", q.MinMatchLen) + } + if q.WithMatchLen { + args = append(args, "withmatchlen") + } + } + cmd.baseCmd = baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, } return cmd + } func (cmd *LCSCmd) SetVal(val *LCSMatch) { + cmd.val = val + } func (cmd *LCSCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *LCSCmd) Val() *LCSMatch { + return cmd.val + } func (cmd *LCSCmd) Result() (*LCSMatch, error) { + return cmd.val, cmd.err + } func (cmd *LCSCmd) readReply(rd *proto.Reader) (err error) { + lcs := &LCSMatch{} + switch cmd.readType { + case 1: + // match string + if lcs.MatchString, err = rd.ReadString(); err != nil { + return err + } + case 2: + // match len + if lcs.Len, err = rd.ReadInt(); err != nil { + return err + } + case 3: + // read LCSMatch + if err = rd.ReadFixedMapLen(2); err != nil { + return err + } // read matches or len field + for i := 0; i < 2; i++ { + key, err := rd.ReadString() + if err != nil { + return err + } switch key { + case "matches": + // read array of matched positions + if lcs.Matches, err = cmd.readMatchedPositions(rd); err != nil { + return err + } + case "len": + // read match length + if lcs.Len, err = rd.ReadInt(); err != nil { + return err + } + } + } + } cmd.val = lcs + return nil + } func (cmd *LCSCmd) readMatchedPositions(rd *proto.Reader) ([]LCSMatchedPosition, error) { + n, err := rd.ReadArrayLen() + if err != nil { + return nil, err + } positions := make([]LCSMatchedPosition, n) + for i := 0; i < n; i++ { + pn, err := rd.ReadArrayLen() + if err != nil { + return nil, err + } if positions[i].Key1, err = cmd.readPosition(rd); err != nil { + return nil, err + } + if positions[i].Key2, err = cmd.readPosition(rd); err != nil { + return nil, err + } // read match length if WithMatchLen is true + if pn > 2 { + if positions[i].MatchLen, err = rd.ReadInt(); err != nil { + return nil, err + } + } + } return positions, nil + } func (cmd *LCSCmd) readPosition(rd *proto.Reader) (pos LCSPosition, err error) { + if err = rd.ReadFixedArrayLen(2); err != nil { + return pos, err + } + if pos.Start, err = rd.ReadInt(); err != nil { + return pos, err + } + if pos.End, err = rd.ReadInt(); err != nil { + return pos, err + } return pos, nil + } // ------------------------------------------------------------------------ type KeyFlags struct { - Key string + Key string + Flags []string } @@ -4562,39 +7263,59 @@ type KeyFlagsCmd struct { var _ Cmder = (*KeyFlagsCmd)(nil) func NewKeyFlagsCmd(ctx context.Context, args ...interface{}) *KeyFlagsCmd { + return &KeyFlagsCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *KeyFlagsCmd) SetVal(val []KeyFlags) { + cmd.val = val + } func (cmd *KeyFlagsCmd) Val() []KeyFlags { + return cmd.val + } func (cmd *KeyFlagsCmd) Result() ([]KeyFlags, error) { + return cmd.val, cmd.err + } func (cmd *KeyFlagsCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *KeyFlagsCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } if n == 0 { + cmd.val = make([]KeyFlags, 0) + return nil + } cmd.val = make([]KeyFlags, n) @@ -4602,37 +7323,57 @@ func (cmd *KeyFlagsCmd) readReply(rd *proto.Reader) error { for i := 0; i < len(cmd.val); i++ { if err = rd.ReadFixedArrayLen(2); err != nil { + return err + } if cmd.val[i].Key, err = rd.ReadString(); err != nil { + return err + } + flagsLen, err := rd.ReadArrayLen() + if err != nil { + return err + } + cmd.val[i].Flags = make([]string, flagsLen) for j := 0; j < flagsLen; j++ { + if cmd.val[i].Flags[j], err = rd.ReadString(); err != nil { + return err + } + } + } return nil + } // --------------------------------------------------------------------------------------------------- type ClusterLink struct { - Direction string - Node string - CreateTime int64 - Events string + Direction string + + Node string + + CreateTime int64 + + Events string + SendBufferAllocated int64 - SendBufferUsed int64 + + SendBufferUsed int64 } type ClusterLinksCmd struct { @@ -4644,96 +7385,152 @@ type ClusterLinksCmd struct { var _ Cmder = (*ClusterLinksCmd)(nil) func NewClusterLinksCmd(ctx context.Context, args ...interface{}) *ClusterLinksCmd { + return &ClusterLinksCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *ClusterLinksCmd) SetVal(val []ClusterLink) { + cmd.val = val + } func (cmd *ClusterLinksCmd) Val() []ClusterLink { + return cmd.val + } func (cmd *ClusterLinksCmd) Result() ([]ClusterLink, error) { + return cmd.val, cmd.err + } func (cmd *ClusterLinksCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *ClusterLinksCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } + cmd.val = make([]ClusterLink, n) for i := 0; i < len(cmd.val); i++ { + m, err := rd.ReadMapLen() + if err != nil { + return err + } for j := 0; j < m; j++ { + key, err := rd.ReadString() + if err != nil { + return err + } switch key { + case "direction": + cmd.val[i].Direction, err = rd.ReadString() + case "node": + cmd.val[i].Node, err = rd.ReadString() + case "create-time": + cmd.val[i].CreateTime, err = rd.ReadInt() + case "events": + cmd.val[i].Events, err = rd.ReadString() + case "send-buffer-allocated": + cmd.val[i].SendBufferAllocated, err = rd.ReadInt() + case "send-buffer-used": + cmd.val[i].SendBufferUsed, err = rd.ReadInt() + default: + return fmt.Errorf("redis: unexpected key %q in CLUSTER LINKS reply", key) + } if err != nil { + return err + } + } + } return nil + } // ------------------------------------------------------------------------------------------------------------------ type SlotRange struct { Start int64 - End int64 + + End int64 } type Node struct { - ID string - Endpoint string - IP string - Hostname string - Port int64 - TLSPort int64 - Role string + ID string + + Endpoint string + + IP string + + Hostname string + + Port int64 + + TLSPort int64 + + Role string + ReplicationOffset int64 - Health string + + Health string } type ClusterShard struct { Slots []SlotRange + Nodes []Node } @@ -4746,127 +7543,214 @@ type ClusterShardsCmd struct { var _ Cmder = (*ClusterShardsCmd)(nil) func NewClusterShardsCmd(ctx context.Context, args ...interface{}) *ClusterShardsCmd { + return &ClusterShardsCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *ClusterShardsCmd) SetVal(val []ClusterShard) { + cmd.val = val + } func (cmd *ClusterShardsCmd) Val() []ClusterShard { + return cmd.val + } func (cmd *ClusterShardsCmd) Result() ([]ClusterShard, error) { + return cmd.val, cmd.err + } func (cmd *ClusterShardsCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *ClusterShardsCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } + cmd.val = make([]ClusterShard, n) for i := 0; i < n; i++ { + m, err := rd.ReadMapLen() + if err != nil { + return err + } for j := 0; j < m; j++ { + key, err := rd.ReadString() + if err != nil { + return err + } switch key { + case "slots": + l, err := rd.ReadArrayLen() + if err != nil { + return err + } + for k := 0; k < l; k += 2 { + start, err := rd.ReadInt() + if err != nil { + return err + } end, err := rd.ReadInt() + if err != nil { + return err + } cmd.val[i].Slots = append(cmd.val[i].Slots, SlotRange{Start: start, End: end}) + } + case "nodes": + nodesLen, err := rd.ReadArrayLen() + if err != nil { + return err + } + cmd.val[i].Nodes = make([]Node, nodesLen) + for k := 0; k < nodesLen; k++ { + nodeMapLen, err := rd.ReadMapLen() + if err != nil { + return err + } for l := 0; l < nodeMapLen; l++ { + nodeKey, err := rd.ReadString() + if err != nil { + return err + } switch nodeKey { + case "id": + cmd.val[i].Nodes[k].ID, err = rd.ReadString() + case "endpoint": + cmd.val[i].Nodes[k].Endpoint, err = rd.ReadString() + case "ip": + cmd.val[i].Nodes[k].IP, err = rd.ReadString() + case "hostname": + cmd.val[i].Nodes[k].Hostname, err = rd.ReadString() + case "port": + cmd.val[i].Nodes[k].Port, err = rd.ReadInt() + case "tls-port": + cmd.val[i].Nodes[k].TLSPort, err = rd.ReadInt() + case "role": + cmd.val[i].Nodes[k].Role, err = rd.ReadString() + case "replication-offset": + cmd.val[i].Nodes[k].ReplicationOffset, err = rd.ReadInt() + case "health": + cmd.val[i].Nodes[k].Health, err = rd.ReadString() + default: + return fmt.Errorf("redis: unexpected key %q in CLUSTER SHARDS node reply", nodeKey) + } if err != nil { + return err + } + } + } + default: + return fmt.Errorf("redis: unexpected key %q in CLUSTER SHARDS reply", key) + } + } + } return nil + } // ----------------------------------------- type RankScore struct { - Rank int64 + Rank int64 + Score float64 } @@ -4879,141 +7763,247 @@ type RankWithScoreCmd struct { var _ Cmder = (*RankWithScoreCmd)(nil) func NewRankWithScoreCmd(ctx context.Context, args ...interface{}) *RankWithScoreCmd { + return &RankWithScoreCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *RankWithScoreCmd) SetVal(val RankScore) { + cmd.val = val + } func (cmd *RankWithScoreCmd) Val() RankScore { + return cmd.val + } func (cmd *RankWithScoreCmd) Result() (RankScore, error) { + return cmd.val, cmd.err + } func (cmd *RankWithScoreCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *RankWithScoreCmd) readReply(rd *proto.Reader) error { + if err := rd.ReadFixedArrayLen(2); err != nil { + return err + } rank, err := rd.ReadInt() + if err != nil { + return err + } score, err := rd.ReadFloat() + if err != nil { + return err + } cmd.val = RankScore{Rank: rank, Score: score} return nil + } // -------------------------------------------------------------------------------------------------- // ClientFlags is redis-server client flags, copy from redis/src/server.h (redis 7.0) + type ClientFlags uint64 const ( - ClientSlave ClientFlags = 1 << 0 /* This client is a replica */ - ClientMaster ClientFlags = 1 << 1 /* This client is a master */ - ClientMonitor ClientFlags = 1 << 2 /* This client is a slave monitor, see MONITOR */ - ClientMulti ClientFlags = 1 << 3 /* This client is in a MULTI context */ - ClientBlocked ClientFlags = 1 << 4 /* The client is waiting in a blocking operation */ - ClientDirtyCAS ClientFlags = 1 << 5 /* Watched keys modified. EXEC will fail. */ - ClientCloseAfterReply ClientFlags = 1 << 6 /* Close after writing entire reply. */ - ClientUnBlocked ClientFlags = 1 << 7 /* This client was unblocked and is stored in server.unblocked_clients */ - ClientScript ClientFlags = 1 << 8 /* This is a non-connected client used by Lua */ - ClientAsking ClientFlags = 1 << 9 /* Client issued the ASKING command */ - ClientCloseASAP ClientFlags = 1 << 10 /* Close this client ASAP */ - ClientUnixSocket ClientFlags = 1 << 11 /* Client connected via Unix domain socket */ - ClientDirtyExec ClientFlags = 1 << 12 /* EXEC will fail for errors while queueing */ + ClientSlave ClientFlags = 1 << 0 /* This client is a replica */ + + ClientMaster ClientFlags = 1 << 1 /* This client is a master */ + + ClientMonitor ClientFlags = 1 << 2 /* This client is a slave monitor, see MONITOR */ + + ClientMulti ClientFlags = 1 << 3 /* This client is in a MULTI context */ + + ClientBlocked ClientFlags = 1 << 4 /* The client is waiting in a blocking operation */ + + ClientDirtyCAS ClientFlags = 1 << 5 /* Watched keys modified. EXEC will fail. */ + + ClientCloseAfterReply ClientFlags = 1 << 6 /* Close after writing entire reply. */ + + ClientUnBlocked ClientFlags = 1 << 7 /* This client was unblocked and is stored in server.unblocked_clients */ + + ClientScript ClientFlags = 1 << 8 /* This is a non-connected client used by Lua */ + + ClientAsking ClientFlags = 1 << 9 /* Client issued the ASKING command */ + + ClientCloseASAP ClientFlags = 1 << 10 /* Close this client ASAP */ + + ClientUnixSocket ClientFlags = 1 << 11 /* Client connected via Unix domain socket */ + + ClientDirtyExec ClientFlags = 1 << 12 /* EXEC will fail for errors while queueing */ + ClientMasterForceReply ClientFlags = 1 << 13 /* Queue replies even if is master */ - ClientForceAOF ClientFlags = 1 << 14 /* Force AOF propagation of current cmd. */ - ClientForceRepl ClientFlags = 1 << 15 /* Force replication of current cmd. */ - ClientPrePSync ClientFlags = 1 << 16 /* Instance don't understand PSYNC. */ - ClientReadOnly ClientFlags = 1 << 17 /* Cluster client is in read-only state. */ - ClientPubSub ClientFlags = 1 << 18 /* Client is in Pub/Sub mode. */ - ClientPreventAOFProp ClientFlags = 1 << 19 /* Don't propagate to AOF. */ - ClientPreventReplProp ClientFlags = 1 << 20 /* Don't propagate to slaves. */ - ClientPreventProp ClientFlags = ClientPreventAOFProp | ClientPreventReplProp - ClientPendingWrite ClientFlags = 1 << 21 /* Client has output to send but a-write handler is yet not installed. */ - ClientReplyOff ClientFlags = 1 << 22 /* Don't send replies to client. */ - ClientReplySkipNext ClientFlags = 1 << 23 /* Set ClientREPLY_SKIP for next cmd */ - ClientReplySkip ClientFlags = 1 << 24 /* Don't send just this reply. */ - ClientLuaDebug ClientFlags = 1 << 25 /* Run EVAL in debug mode. */ - ClientLuaDebugSync ClientFlags = 1 << 26 /* EVAL debugging without fork() */ - ClientModule ClientFlags = 1 << 27 /* Non connected client used by some module. */ - ClientProtected ClientFlags = 1 << 28 /* Client should not be freed for now. */ + + ClientForceAOF ClientFlags = 1 << 14 /* Force AOF propagation of current cmd. */ + + ClientForceRepl ClientFlags = 1 << 15 /* Force replication of current cmd. */ + + ClientPrePSync ClientFlags = 1 << 16 /* Instance don't understand PSYNC. */ + + ClientReadOnly ClientFlags = 1 << 17 /* Cluster client is in read-only state. */ + + ClientPubSub ClientFlags = 1 << 18 /* Client is in Pub/Sub mode. */ + + ClientPreventAOFProp ClientFlags = 1 << 19 /* Don't propagate to AOF. */ + + ClientPreventReplProp ClientFlags = 1 << 20 /* Don't propagate to slaves. */ + + ClientPreventProp ClientFlags = ClientPreventAOFProp | ClientPreventReplProp + + ClientPendingWrite ClientFlags = 1 << 21 /* Client has output to send but a-write handler is yet not installed. */ + + ClientReplyOff ClientFlags = 1 << 22 /* Don't send replies to client. */ + + ClientReplySkipNext ClientFlags = 1 << 23 /* Set ClientREPLY_SKIP for next cmd */ + + ClientReplySkip ClientFlags = 1 << 24 /* Don't send just this reply. */ + + ClientLuaDebug ClientFlags = 1 << 25 /* Run EVAL in debug mode. */ + + ClientLuaDebugSync ClientFlags = 1 << 26 /* EVAL debugging without fork() */ + + ClientModule ClientFlags = 1 << 27 /* Non connected client used by some module. */ + + ClientProtected ClientFlags = 1 << 28 /* Client should not be freed for now. */ + ClientExecutingCommand ClientFlags = 1 << 29 /* Indicates that the client is currently in the process of handling + a command. usually this will be marked only during call() + however, blocked clients might have this flag kept until they + will try to reprocess the command. */ - ClientPendingCommand ClientFlags = 1 << 30 /* Indicates the client has a fully * parsed command ready for execution. */ - ClientTracking ClientFlags = 1 << 31 /* Client enabled keys tracking in order to perform client side caching. */ + + ClientPendingCommand ClientFlags = 1 << 30 /* Indicates the client has a fully * parsed command ready for execution. */ + + ClientTracking ClientFlags = 1 << 31 /* Client enabled keys tracking in order to perform client side caching. */ + ClientTrackingBrokenRedir ClientFlags = 1 << 32 /* Target client is invalid. */ - ClientTrackingBCAST ClientFlags = 1 << 33 /* Tracking in BCAST mode. */ - ClientTrackingOptIn ClientFlags = 1 << 34 /* Tracking in opt-in mode. */ - ClientTrackingOptOut ClientFlags = 1 << 35 /* Tracking in opt-out mode. */ - ClientTrackingCaching ClientFlags = 1 << 36 /* CACHING yes/no was given, depending on optin/optout mode. */ - ClientTrackingNoLoop ClientFlags = 1 << 37 /* Don't send invalidation messages about writes performed by myself.*/ - ClientInTimeoutTable ClientFlags = 1 << 38 /* This client is in the timeout table. */ - ClientProtocolError ClientFlags = 1 << 39 /* Protocol error chatting with it. */ - ClientCloseAfterCommand ClientFlags = 1 << 40 /* Close after executing commands * and writing entire reply. */ - ClientDenyBlocking ClientFlags = 1 << 41 /* Indicate that the client should not be blocked. currently, turned on inside MULTI, Lua, RM_Call, and AOF client */ - ClientReplRDBOnly ClientFlags = 1 << 42 /* This client is a replica that only wants RDB without replication buffer. */ - ClientNoEvict ClientFlags = 1 << 43 /* This client is protected against client memory eviction. */ - ClientAllowOOM ClientFlags = 1 << 44 /* Client used by RM_Call is allowed to fully execute scripts even when in OOM */ - ClientNoTouch ClientFlags = 1 << 45 /* This client will not touch LFU/LRU stats. */ - ClientPushing ClientFlags = 1 << 46 /* This client is pushing notifications. */ + + ClientTrackingBCAST ClientFlags = 1 << 33 /* Tracking in BCAST mode. */ + + ClientTrackingOptIn ClientFlags = 1 << 34 /* Tracking in opt-in mode. */ + + ClientTrackingOptOut ClientFlags = 1 << 35 /* Tracking in opt-out mode. */ + + ClientTrackingCaching ClientFlags = 1 << 36 /* CACHING yes/no was given, depending on optin/optout mode. */ + + ClientTrackingNoLoop ClientFlags = 1 << 37 /* Don't send invalidation messages about writes performed by myself.*/ + + ClientInTimeoutTable ClientFlags = 1 << 38 /* This client is in the timeout table. */ + + ClientProtocolError ClientFlags = 1 << 39 /* Protocol error chatting with it. */ + + ClientCloseAfterCommand ClientFlags = 1 << 40 /* Close after executing commands * and writing entire reply. */ + + ClientDenyBlocking ClientFlags = 1 << 41 /* Indicate that the client should not be blocked. currently, turned on inside MULTI, Lua, RM_Call, and AOF client */ + + ClientReplRDBOnly ClientFlags = 1 << 42 /* This client is a replica that only wants RDB without replication buffer. */ + + ClientNoEvict ClientFlags = 1 << 43 /* This client is protected against client memory eviction. */ + + ClientAllowOOM ClientFlags = 1 << 44 /* Client used by RM_Call is allowed to fully execute scripts even when in OOM */ + + ClientNoTouch ClientFlags = 1 << 45 /* This client will not touch LFU/LRU stats. */ + + ClientPushing ClientFlags = 1 << 46 /* This client is pushing notifications. */ + ) // ClientInfo is redis-server ClientInfo, not go-redis *Client + type ClientInfo struct { - ID int64 // redis version 2.8.12, a unique 64-bit client ID - Addr string // address/port of the client - LAddr string // address/port of local address client connected to (bind address) - FD int64 // file descriptor corresponding to the socket - Name string // the name set by the client with CLIENT SETNAME - Age time.Duration // total duration of the connection in seconds - Idle time.Duration // idle time of the connection in seconds - Flags ClientFlags // client flags (see below) - DB int // current database ID - Sub int // number of channel subscriptions - PSub int // number of pattern matching subscriptions - SSub int // redis version 7.0.3, number of shard channel subscriptions - Multi int // number of commands in a MULTI/EXEC context - QueryBuf int // qbuf, query buffer length (0 means no query pending) - QueryBufFree int // qbuf-free, free space of the query buffer (0 means the buffer is full) - ArgvMem int // incomplete arguments for the next command (already extracted from query buffer) - MultiMem int // redis version 7.0, memory is used up by buffered multi commands - BufferSize int // rbs, usable size of buffer - BufferPeak int // rbp, peak used size of buffer in last 5 sec interval - OutputBufferLength int // obl, output buffer length - OutputListLength int // oll, output list length (replies are queued in this list when the buffer is full) - OutputMemory int // omem, output buffer memory usage - TotalMemory int // tot-mem, total memory consumed by this client in its various buffers - Events string // file descriptor events (see below) - LastCmd string // cmd, last command played - User string // the authenticated username of the client - Redir int64 // client id of current client tracking redirection - Resp int // redis version 7.0, client RESP protocol version - LibName string // redis version 7.2, client library name - LibVer string // redis version 7.2, client library version + ID int64 // redis version 2.8.12, a unique 64-bit client ID + + Addr string // address/port of the client + + LAddr string // address/port of local address client connected to (bind address) + + FD int64 // file descriptor corresponding to the socket + + Name string // the name set by the client with CLIENT SETNAME + + Age time.Duration // total duration of the connection in seconds + + Idle time.Duration // idle time of the connection in seconds + + Flags ClientFlags // client flags (see below) + + DB int // current database ID + + Sub int // number of channel subscriptions + + PSub int // number of pattern matching subscriptions + + SSub int // redis version 7.0.3, number of shard channel subscriptions + + Multi int // number of commands in a MULTI/EXEC context + + QueryBuf int // qbuf, query buffer length (0 means no query pending) + + QueryBufFree int // qbuf-free, free space of the query buffer (0 means the buffer is full) + + ArgvMem int // incomplete arguments for the next command (already extracted from query buffer) + + MultiMem int // redis version 7.0, memory is used up by buffered multi commands + + BufferSize int // rbs, usable size of buffer + + BufferPeak int // rbp, peak used size of buffer in last 5 sec interval + + OutputBufferLength int // obl, output buffer length + + OutputListLength int // oll, output list length (replies are queued in this list when the buffer is full) + + OutputMemory int // omem, output buffer memory usage + + TotalMemory int // tot-mem, total memory consumed by this client in its various buffers + + Events string // file descriptor events (see below) + + LastCmd string // cmd, last command played + + User string // the authenticated username of the client + + Redir int64 // client id of current client tracking redirection + + Resp int // redis version 7.0, client RESP protocol version + + LibName string // redis version 7.2, client library name + + LibVer string // redis version 7.2, client library version + } type ClientInfoCmd struct { @@ -5025,188 +8015,342 @@ type ClientInfoCmd struct { var _ Cmder = (*ClientInfoCmd)(nil) func NewClientInfoCmd(ctx context.Context, args ...interface{}) *ClientInfoCmd { + return &ClientInfoCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *ClientInfoCmd) SetVal(val *ClientInfo) { + cmd.val = val + } func (cmd *ClientInfoCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *ClientInfoCmd) Val() *ClientInfo { + return cmd.val + } func (cmd *ClientInfoCmd) Result() (*ClientInfo, error) { + return cmd.val, cmd.err + } func (cmd *ClientInfoCmd) readReply(rd *proto.Reader) (err error) { + txt, err := rd.ReadString() + if err != nil { + return err + } // sds o = catClientInfoString(sdsempty(), c); + // o = sdscatlen(o,"\n",1); + // addReplyVerbatim(c,o,sdslen(o),"txt"); + // sdsfree(o); + cmd.val, err = parseClientInfo(strings.TrimSpace(txt)) + return err + } // fmt.Sscanf() cannot handle null values + func parseClientInfo(txt string) (info *ClientInfo, err error) { + info = &ClientInfo{} + for _, s := range strings.Split(txt, " ") { + kv := strings.Split(s, "=") + if len(kv) != 2 { + return nil, fmt.Errorf("redis: unexpected client info data (%s)", s) + } + key, val := kv[0], kv[1] switch key { + case "id": + info.ID, err = strconv.ParseInt(val, 10, 64) + case "addr": + info.Addr = val + case "laddr": + info.LAddr = val + case "fd": + info.FD, err = strconv.ParseInt(val, 10, 64) + case "name": + info.Name = val + case "age": + var age int + if age, err = strconv.Atoi(val); err == nil { + info.Age = time.Duration(age) * time.Second + } + case "idle": + var idle int + if idle, err = strconv.Atoi(val); err == nil { + info.Idle = time.Duration(idle) * time.Second + } + case "flags": + if val == "N" { + break + } for i := 0; i < len(val); i++ { + switch val[i] { + case 'S': + info.Flags |= ClientSlave + case 'O': + info.Flags |= ClientSlave | ClientMonitor + case 'M': + info.Flags |= ClientMaster + case 'P': + info.Flags |= ClientPubSub + case 'x': + info.Flags |= ClientMulti + case 'b': + info.Flags |= ClientBlocked + case 't': + info.Flags |= ClientTracking + case 'R': + info.Flags |= ClientTrackingBrokenRedir + case 'B': + info.Flags |= ClientTrackingBCAST + case 'd': + info.Flags |= ClientDirtyCAS + case 'c': + info.Flags |= ClientCloseAfterCommand + case 'u': + info.Flags |= ClientUnBlocked + case 'A': + info.Flags |= ClientCloseASAP + case 'U': + info.Flags |= ClientUnixSocket + case 'r': + info.Flags |= ClientReadOnly + case 'e': + info.Flags |= ClientNoEvict + case 'T': + info.Flags |= ClientNoTouch + default: + return nil, fmt.Errorf("redis: unexpected client info flags(%s)", string(val[i])) + } + } + case "db": + info.DB, err = strconv.Atoi(val) + case "sub": + info.Sub, err = strconv.Atoi(val) + case "psub": + info.PSub, err = strconv.Atoi(val) + case "ssub": + info.SSub, err = strconv.Atoi(val) + case "multi": + info.Multi, err = strconv.Atoi(val) + case "qbuf": + info.QueryBuf, err = strconv.Atoi(val) + case "qbuf-free": + info.QueryBufFree, err = strconv.Atoi(val) + case "argv-mem": + info.ArgvMem, err = strconv.Atoi(val) + case "multi-mem": + info.MultiMem, err = strconv.Atoi(val) + case "rbs": + info.BufferSize, err = strconv.Atoi(val) + case "rbp": + info.BufferPeak, err = strconv.Atoi(val) + case "obl": + info.OutputBufferLength, err = strconv.Atoi(val) + case "oll": + info.OutputListLength, err = strconv.Atoi(val) + case "omem": + info.OutputMemory, err = strconv.Atoi(val) + case "tot-mem": + info.TotalMemory, err = strconv.Atoi(val) + case "events": + info.Events = val + case "cmd": + info.LastCmd = val + case "user": + info.User = val + case "redir": + info.Redir, err = strconv.ParseInt(val, 10, 64) + case "resp": + info.Resp, err = strconv.Atoi(val) + case "lib-name": + info.LibName = val + case "lib-ver": + info.LibVer = val + default: + return nil, fmt.Errorf("redis: unexpected client info key(%s)", key) + } if err != nil { + return nil, err + } + } return info, nil + } // ------------------------------------------- type ACLLogEntry struct { - Count int64 - Reason string - Context string - Object string - Username string - AgeSeconds float64 - ClientInfo *ClientInfo - EntryID int64 - TimestampCreated int64 + Count int64 + + Reason string + + Context string + + Object string + + Username string + + AgeSeconds float64 + + ClientInfo *ClientInfo + + EntryID int64 + + TimestampCreated int64 + TimestampLastUpdated int64 } @@ -5219,255 +8363,429 @@ type ACLLogCmd struct { var _ Cmder = (*ACLLogCmd)(nil) func NewACLLogCmd(ctx context.Context, args ...interface{}) *ACLLogCmd { + return &ACLLogCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *ACLLogCmd) SetVal(val []*ACLLogEntry) { + cmd.val = val + } func (cmd *ACLLogCmd) Val() []*ACLLogEntry { + return cmd.val + } func (cmd *ACLLogCmd) Result() ([]*ACLLogEntry, error) { + return cmd.val, cmd.err + } func (cmd *ACLLogCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *ACLLogCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } cmd.val = make([]*ACLLogEntry, n) + for i := 0; i < n; i++ { + cmd.val[i] = &ACLLogEntry{} + entry := cmd.val[i] + respLen, err := rd.ReadMapLen() + if err != nil { + return err + } + for j := 0; j < respLen; j++ { + key, err := rd.ReadString() + if err != nil { + return err + } switch key { + case "count": + entry.Count, err = rd.ReadInt() + case "reason": + entry.Reason, err = rd.ReadString() + case "context": + entry.Context, err = rd.ReadString() + case "object": + entry.Object, err = rd.ReadString() + case "username": + entry.Username, err = rd.ReadString() + case "age-seconds": + entry.AgeSeconds, err = rd.ReadFloat() + case "client-info": + txt, err := rd.ReadString() + if err != nil { + return err + } + entry.ClientInfo, err = parseClientInfo(strings.TrimSpace(txt)) + if err != nil { + return err + } + case "entry-id": + entry.EntryID, err = rd.ReadInt() + case "timestamp-created": + entry.TimestampCreated, err = rd.ReadInt() + case "timestamp-last-updated": + entry.TimestampLastUpdated, err = rd.ReadInt() + default: + return fmt.Errorf("redis: unexpected key %q in ACL LOG reply", key) + } if err != nil { + return err + } + } + } return nil + } // LibraryInfo holds the library info. + type LibraryInfo struct { LibName *string - LibVer *string + + LibVer *string } // ------------------------------------------- type InfoCmd struct { baseCmd + val map[string]map[string]string } var _ Cmder = (*InfoCmd)(nil) func NewInfoCmd(ctx context.Context, args ...interface{}) *InfoCmd { + return &InfoCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: args, }, } + } func (cmd *InfoCmd) SetVal(val map[string]map[string]string) { + cmd.val = val + } func (cmd *InfoCmd) Val() map[string]map[string]string { + return cmd.val + } func (cmd *InfoCmd) Result() (map[string]map[string]string, error) { + return cmd.val, cmd.err + } func (cmd *InfoCmd) String() string { + return cmdString(cmd, cmd.val) + } func (cmd *InfoCmd) readReply(rd *proto.Reader) error { + val, err := rd.ReadString() + if err != nil { + return err + } section := "" + scanner := bufio.NewScanner(strings.NewReader(val)) + moduleRe := regexp.MustCompile(`module:name=(.+?),(.+)$`) for scanner.Scan() { + line := scanner.Text() + if strings.HasPrefix(line, "#") { + if cmd.val == nil { + cmd.val = make(map[string]map[string]string) + } + section = strings.TrimPrefix(line, "# ") + cmd.val[section] = make(map[string]string) + } else if line != "" { + if section == "Modules" { + kv := moduleRe.FindStringSubmatch(line) + if len(kv) == 3 { + cmd.val[section][kv[1]] = kv[2] + } + } else { + kv := strings.SplitN(line, ":", 2) + if len(kv) == 2 { + cmd.val[section][kv[0]] = kv[1] + } + } + } + } return nil + } func (cmd *InfoCmd) Item(section, key string) string { + if cmd.val == nil { + return "" + } else if cmd.val[section] == nil { + return "" + } else { + return cmd.val[section][key] + } + } type MonitorStatus int const ( monitorStatusIdle MonitorStatus = iota + monitorStatusStart + monitorStatusStop ) type MonitorCmd struct { baseCmd - ch chan string + + ch chan string + status MonitorStatus - mu sync.Mutex + + mu sync.Mutex } func newMonitorCmd(ctx context.Context, ch chan string) *MonitorCmd { + return &MonitorCmd{ + baseCmd: baseCmd{ - ctx: ctx, + + ctx: ctx, + args: []interface{}{"monitor"}, }, - ch: ch, + + ch: ch, + status: monitorStatusIdle, - mu: sync.Mutex{}, + + mu: sync.Mutex{}, } + } func (cmd *MonitorCmd) String() string { + return cmdString(cmd, nil) + } func (cmd *MonitorCmd) readReply(rd *proto.Reader) error { + ctx, cancel := context.WithCancel(cmd.ctx) + go func(ctx context.Context) { + for { + select { + case <-ctx.Done(): + return + default: + err := cmd.readMonitor(rd, cancel) + if err != nil { + cmd.err = err + return + } + } + } + }(ctx) + return nil + } func (cmd *MonitorCmd) readMonitor(rd *proto.Reader, cancel context.CancelFunc) error { + for { + cmd.mu.Lock() + st := cmd.status + cmd.mu.Unlock() + if pk, _ := rd.Peek(1); len(pk) != 0 && st == monitorStatusStart { + line, err := rd.ReadString() + if err != nil { + return err + } + cmd.ch <- line + } + if st == monitorStatusStop { + cancel() + break + } + } + return nil + } func (cmd *MonitorCmd) Start() { + cmd.mu.Lock() + defer cmd.mu.Unlock() + cmd.status = monitorStatusStart + } func (cmd *MonitorCmd) Stop() { + cmd.mu.Lock() + defer cmd.mu.Unlock() + cmd.status = monitorStatusStop + } diff --git a/vendor/github.com/redis/go-redis/v9/commands.go b/vendor/github.com/redis/go-redis/v9/commands.go index 546ebaf..03b7628 100644 --- a/vendor/github.com/redis/go-redis/v9/commands.go +++ b/vendor/github.com/redis/go-redis/v9/commands.go @@ -16,233 +16,408 @@ import ( ) // KeepTTL is a Redis KEEPTTL option to keep existing TTL, it requires your redis-server version >= 6.0, + // otherwise you will receive an error: (error) ERR syntax error. + // For example: + // + // rdb.Set(ctx, key, value, redis.KeepTTL) + const KeepTTL = -1 func usePrecise(dur time.Duration) bool { + return dur < time.Second || dur%time.Second != 0 + } func formatMs(ctx context.Context, dur time.Duration) int64 { + if dur > 0 && dur < time.Millisecond { + internal.Logger.Printf( + ctx, + "specified duration is %s, but minimal supported value is %s - truncating to 1ms", + dur, time.Millisecond, ) + return 1 + } + return int64(dur / time.Millisecond) + } func formatSec(ctx context.Context, dur time.Duration) int64 { + if dur > 0 && dur < time.Second { + internal.Logger.Printf( + ctx, + "specified duration is %s, but minimal supported value is %s - truncating to 1s", + dur, time.Second, ) + return 1 + } + return int64(dur / time.Second) + } func appendArgs(dst, src []interface{}) []interface{} { + if len(src) == 1 { + return appendArg(dst, src[0]) + } dst = append(dst, src...) + return dst + } func appendArg(dst []interface{}, arg interface{}) []interface{} { + switch arg := arg.(type) { + case []string: + for _, s := range arg { + dst = append(dst, s) + } + return dst + case []interface{}: + dst = append(dst, arg...) + return dst + case map[string]interface{}: + for k, v := range arg { + dst = append(dst, k, v) + } + return dst + case map[string]string: + for k, v := range arg { + dst = append(dst, k, v) + } + return dst + case time.Time, time.Duration, encoding.BinaryMarshaler, net.IP: + return append(dst, arg) + default: + // scan struct field + v := reflect.ValueOf(arg) + if v.Type().Kind() == reflect.Ptr { + if v.IsNil() { + // error: arg is not a valid object + return dst + } + v = v.Elem() + } if v.Type().Kind() == reflect.Struct { + return appendStructField(dst, v) + } return append(dst, arg) + } + } // appendStructField appends the field and value held by the structure v to dst, and returns the appended dst. + func appendStructField(dst []interface{}, v reflect.Value) []interface{} { + typ := v.Type() + for i := 0; i < typ.NumField(); i++ { + tag := typ.Field(i).Tag.Get("redis") + if tag == "" || tag == "-" { + continue + } + name, opt, _ := strings.Cut(tag, ",") + if name == "" { + continue + } field := v.Field(i) // miss field + if omitEmpty(opt) && isEmptyValue(field) { + continue + } if field.CanInterface() { + dst = append(dst, name, field.Interface()) + } + } return dst + } func omitEmpty(opt string) bool { + for opt != "" { + var name string + name, opt, _ = strings.Cut(opt, ",") + if name == "omitempty" { + return true + } + } + return false + } func isEmptyValue(v reflect.Value) bool { + switch v.Kind() { + case reflect.Array, reflect.Map, reflect.Slice, reflect.String: + return v.Len() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Interface, reflect.Pointer: + return v.IsNil() + } + return false + } type Cmdable interface { Pipeline() Pipeliner + Pipelined(ctx context.Context, fn func(Pipeliner) error) ([]Cmder, error) TxPipelined(ctx context.Context, fn func(Pipeliner) error) ([]Cmder, error) + TxPipeline() Pipeliner Command(ctx context.Context) *CommandsInfoCmd + CommandList(ctx context.Context, filter *FilterBy) *StringSliceCmd + CommandGetKeys(ctx context.Context, commands ...interface{}) *StringSliceCmd + CommandGetKeysAndFlags(ctx context.Context, commands ...interface{}) *KeyFlagsCmd + ClientGetName(ctx context.Context) *StringCmd + Echo(ctx context.Context, message interface{}) *StringCmd + Ping(ctx context.Context) *StatusCmd + Quit(ctx context.Context) *StatusCmd + Unlink(ctx context.Context, keys ...string) *IntCmd BgRewriteAOF(ctx context.Context) *StatusCmd + BgSave(ctx context.Context) *StatusCmd + ClientKill(ctx context.Context, ipPort string) *StatusCmd + ClientKillByFilter(ctx context.Context, keys ...string) *IntCmd + ClientList(ctx context.Context) *StringCmd + ClientInfo(ctx context.Context) *ClientInfoCmd + ClientPause(ctx context.Context, dur time.Duration) *BoolCmd + ClientUnpause(ctx context.Context) *BoolCmd + ClientID(ctx context.Context) *IntCmd + ClientUnblock(ctx context.Context, id int64) *IntCmd + ClientUnblockWithError(ctx context.Context, id int64) *IntCmd + ConfigGet(ctx context.Context, parameter string) *MapStringStringCmd + ConfigResetStat(ctx context.Context) *StatusCmd + ConfigSet(ctx context.Context, parameter, value string) *StatusCmd + ConfigRewrite(ctx context.Context) *StatusCmd + DBSize(ctx context.Context) *IntCmd + FlushAll(ctx context.Context) *StatusCmd + FlushAllAsync(ctx context.Context) *StatusCmd + FlushDB(ctx context.Context) *StatusCmd + FlushDBAsync(ctx context.Context) *StatusCmd + Info(ctx context.Context, section ...string) *StringCmd + LastSave(ctx context.Context) *IntCmd + Save(ctx context.Context) *StatusCmd + Shutdown(ctx context.Context) *StatusCmd + ShutdownSave(ctx context.Context) *StatusCmd + ShutdownNoSave(ctx context.Context) *StatusCmd + SlaveOf(ctx context.Context, host, port string) *StatusCmd + SlowLogGet(ctx context.Context, num int64) *SlowLogCmd + Time(ctx context.Context) *TimeCmd + DebugObject(ctx context.Context, key string) *StringCmd + MemoryUsage(ctx context.Context, key string, samples ...int) *IntCmd ModuleLoadex(ctx context.Context, conf *ModuleLoadexConfig) *StringCmd ACLCmdable + BitMapCmdable + ClusterCmdable + GearsCmdable + GenericCmdable + GeoCmdable + HashCmdable + HyperLogLogCmdable + ListCmdable + ProbabilisticCmdable + PubSubCmdable + ScriptingFunctionsCmdable + SetCmdable + SortedSetCmdable + StringCmdable + StreamCmdable + TimeseriesCmdable + JSONCmdable } type StatefulCmdable interface { Cmdable + Auth(ctx context.Context, password string) *StatusCmd + AuthACL(ctx context.Context, username, password string) *StatusCmd + Select(ctx context.Context, index int) *StatusCmd + SwapDB(ctx context.Context, index1, index2 int) *StatusCmd + ClientSetName(ctx context.Context, name string) *BoolCmd + ClientSetInfo(ctx context.Context, info LibraryInfo) *StatusCmd + Hello(ctx context.Context, ver int, username, password, clientName string) *MapStringInterfaceCmd } var ( _ Cmdable = (*Client)(nil) + _ Cmdable = (*Tx)(nil) + _ Cmdable = (*Ring)(nil) + _ Cmdable = (*ClusterClient)(nil) ) @@ -253,466 +428,801 @@ type statefulCmdable func(ctx context.Context, cmd Cmder) error //------------------------------------------------------------------------------ func (c statefulCmdable) Auth(ctx context.Context, password string) *StatusCmd { + cmd := NewStatusCmd(ctx, "auth", password) + _ = c(ctx, cmd) + return cmd + } // AuthACL Perform an AUTH command, using the given user and pass. + // Should be used to authenticate the current connection with one of the connections defined in the ACL list + // when connecting to a Redis 6.0 instance, or greater, that is using the Redis ACL system. + func (c statefulCmdable) AuthACL(ctx context.Context, username, password string) *StatusCmd { + cmd := NewStatusCmd(ctx, "auth", username, password) + _ = c(ctx, cmd) + return cmd + } func (c cmdable) Wait(ctx context.Context, numSlaves int, timeout time.Duration) *IntCmd { + cmd := NewIntCmd(ctx, "wait", numSlaves, int(timeout/time.Millisecond)) + cmd.setReadTimeout(timeout) + _ = c(ctx, cmd) + return cmd + } func (c cmdable) WaitAOF(ctx context.Context, numLocal, numSlaves int, timeout time.Duration) *IntCmd { + cmd := NewIntCmd(ctx, "waitAOF", numLocal, numSlaves, int(timeout/time.Millisecond)) + cmd.setReadTimeout(timeout) + _ = c(ctx, cmd) + return cmd + } func (c statefulCmdable) Select(ctx context.Context, index int) *StatusCmd { + cmd := NewStatusCmd(ctx, "select", index) + _ = c(ctx, cmd) + return cmd + } func (c statefulCmdable) SwapDB(ctx context.Context, index1, index2 int) *StatusCmd { + cmd := NewStatusCmd(ctx, "swapdb", index1, index2) + _ = c(ctx, cmd) + return cmd + } // ClientSetName assigns a name to the connection. + func (c statefulCmdable) ClientSetName(ctx context.Context, name string) *BoolCmd { + cmd := NewBoolCmd(ctx, "client", "setname", name) + _ = c(ctx, cmd) + return cmd + } // ClientSetInfo sends a CLIENT SETINFO command with the provided info. + func (c statefulCmdable) ClientSetInfo(ctx context.Context, info LibraryInfo) *StatusCmd { + err := info.Validate() + if err != nil { + panic(err.Error()) + } var cmd *StatusCmd + if info.LibName != nil { + libName := fmt.Sprintf("go-redis(%s,%s)", *info.LibName, runtime.Version()) + cmd = NewStatusCmd(ctx, "client", "setinfo", "LIB-NAME", libName) + } else { + cmd = NewStatusCmd(ctx, "client", "setinfo", "LIB-VER", *info.LibVer) + } _ = c(ctx, cmd) + return cmd + } // Validate checks if only one field in the struct is non-nil. + func (info LibraryInfo) Validate() error { + if info.LibName != nil && info.LibVer != nil { + return errors.New("both LibName and LibVer cannot be set at the same time") + } + if info.LibName == nil && info.LibVer == nil { + return errors.New("at least one of LibName and LibVer should be set") + } + return nil + } // Hello Set the resp protocol used. + func (c statefulCmdable) Hello(ctx context.Context, + ver int, username, password, clientName string, + ) *MapStringInterfaceCmd { + args := make([]interface{}, 0, 7) + args = append(args, "hello", ver) + if password != "" { + if username != "" { + args = append(args, "auth", username, password) + } else { + args = append(args, "auth", "default", password) + } + } + if clientName != "" { + args = append(args, "setname", clientName) + } + cmd := NewMapStringInterfaceCmd(ctx, args...) + _ = c(ctx, cmd) + return cmd + } //------------------------------------------------------------------------------ func (c cmdable) Command(ctx context.Context) *CommandsInfoCmd { + cmd := NewCommandsInfoCmd(ctx, "command") + _ = c(ctx, cmd) + return cmd + } // FilterBy is used for the `CommandList` command parameter. + type FilterBy struct { - Module string - ACLCat string + Module string + + ACLCat string + Pattern string } func (c cmdable) CommandList(ctx context.Context, filter *FilterBy) *StringSliceCmd { + args := make([]interface{}, 0, 5) + args = append(args, "command", "list") + if filter != nil { + if filter.Module != "" { + args = append(args, "filterby", "module", filter.Module) + } else if filter.ACLCat != "" { + args = append(args, "filterby", "aclcat", filter.ACLCat) + } else if filter.Pattern != "" { + args = append(args, "filterby", "pattern", filter.Pattern) + } + } + cmd := NewStringSliceCmd(ctx, args...) + _ = c(ctx, cmd) + return cmd + } func (c cmdable) CommandGetKeys(ctx context.Context, commands ...interface{}) *StringSliceCmd { + args := make([]interface{}, 2+len(commands)) + args[0] = "command" + args[1] = "getkeys" + copy(args[2:], commands) + cmd := NewStringSliceCmd(ctx, args...) + _ = c(ctx, cmd) + return cmd + } func (c cmdable) CommandGetKeysAndFlags(ctx context.Context, commands ...interface{}) *KeyFlagsCmd { + args := make([]interface{}, 2+len(commands)) + args[0] = "command" + args[1] = "getkeysandflags" + copy(args[2:], commands) + cmd := NewKeyFlagsCmd(ctx, args...) + _ = c(ctx, cmd) + return cmd + } // ClientGetName returns the name of the connection. + func (c cmdable) ClientGetName(ctx context.Context) *StringCmd { + cmd := NewStringCmd(ctx, "client", "getname") + _ = c(ctx, cmd) + return cmd + } func (c cmdable) Echo(ctx context.Context, message interface{}) *StringCmd { + cmd := NewStringCmd(ctx, "echo", message) + _ = c(ctx, cmd) + return cmd + } func (c cmdable) Ping(ctx context.Context) *StatusCmd { + cmd := NewStatusCmd(ctx, "ping") + _ = c(ctx, cmd) + return cmd + } func (c cmdable) Quit(_ context.Context) *StatusCmd { + panic("not implemented") + } //------------------------------------------------------------------------------ func (c cmdable) BgRewriteAOF(ctx context.Context) *StatusCmd { + cmd := NewStatusCmd(ctx, "bgrewriteaof") + _ = c(ctx, cmd) + return cmd + } func (c cmdable) BgSave(ctx context.Context) *StatusCmd { + cmd := NewStatusCmd(ctx, "bgsave") + _ = c(ctx, cmd) + return cmd + } func (c cmdable) ClientKill(ctx context.Context, ipPort string) *StatusCmd { + cmd := NewStatusCmd(ctx, "client", "kill", ipPort) + _ = c(ctx, cmd) + return cmd + } // ClientKillByFilter is new style syntax, while the ClientKill is old + // + // CLIENT KILL

+ + + + + + + + ` diff --git a/vendor/github.com/swaggo/files/v2/files.go b/vendor/github.com/swaggo/files/v2/files.go index d7b452e..8929749 100644 --- a/vendor/github.com/swaggo/files/v2/files.go +++ b/vendor/github.com/swaggo/files/v2/files.go @@ -6,7 +6,9 @@ import ( ) //go:embed dist/* + var dist embed.FS // FS holds embedded swagger ui files + var FS, _ = fs.Sub(dist, "dist") diff --git a/vendor/github.com/swaggo/swag/const.go b/vendor/github.com/swaggo/swag/const.go index 8375510..917c9b1 100644 --- a/vendor/github.com/swaggo/swag/const.go +++ b/vendor/github.com/swaggo/swag/const.go @@ -10,558 +10,1082 @@ import ( ) // ConstVariable a model to record a const variable + type ConstVariable struct { - Name *ast.Ident - Type ast.Expr - Value interface{} + Name *ast.Ident + + Type ast.Expr + + Value interface{} + Comment *ast.CommentGroup - File *ast.File - Pkg *PackageDefinitions + + File *ast.File + + Pkg *PackageDefinitions } var escapedChars = map[uint8]uint8{ - 'n': '\n', - 'r': '\r', - 't': '\t', - 'v': '\v', + + 'n': '\n', + + 'r': '\r', + + 't': '\t', + + 'v': '\v', + '\\': '\\', - '"': '"', + + '"': '"', } // EvaluateEscapedChar parse escaped character + func EvaluateEscapedChar(text string) rune { + if len(text) == 1 { + return rune(text[0]) + } if len(text) == 2 && text[0] == '\\' { + return rune(escapedChars[text[1]]) + } if len(text) == 6 && text[0:2] == "\\u" { + n, err := strconv.ParseInt(text[2:], 16, 32) + if err == nil { + return rune(n) + } + } return 0 + } // EvaluateEscapedString parse escaped characters in string + func EvaluateEscapedString(text string) string { + if !strings.ContainsRune(text, '\\') { + return text + } + result := make([]byte, 0, len(text)) + for i := 0; i < len(text); i++ { + if text[i] == '\\' { + i++ + if text[i] == 'u' { + i++ + char, err := strconv.ParseInt(text[i:i+4], 16, 32) + if err == nil { + result = utf8.AppendRune(result, rune(char)) + } + i += 3 + } else if c, ok := escapedChars[text[i]]; ok { + result = append(result, c) + } + } else { + result = append(result, text[i]) + } + } + return string(result) + } // EvaluateDataConversion evaluate the type a explicit type conversion + func EvaluateDataConversion(x interface{}, typeName string) interface{} { + switch value := x.(type) { + case int: + switch typeName { + case "int": + return int(value) + case "byte": + return byte(value) + case "int8": + return int8(value) + case "int16": + return int16(value) + case "int32": + return int32(value) + case "int64": + return int64(value) + case "uint": + return uint(value) + case "uint8": + return uint8(value) + case "uint16": + return uint16(value) + case "uint32": + return uint32(value) + case "uint64": + return uint64(value) + case "rune": + return rune(value) + } + case uint: + switch typeName { + case "int": + return int(value) + case "byte": + return byte(value) + case "int8": + return int8(value) + case "int16": + return int16(value) + case "int32": + return int32(value) + case "int64": + return int64(value) + case "uint": + return uint(value) + case "uint8": + return uint8(value) + case "uint16": + return uint16(value) + case "uint32": + return uint32(value) + case "uint64": + return uint64(value) + case "rune": + return rune(value) + } + case int8: + switch typeName { + case "int": + return int(value) + case "byte": + return byte(value) + case "int8": + return int8(value) + case "int16": + return int16(value) + case "int32": + return int32(value) + case "int64": + return int64(value) + case "uint": + return uint(value) + case "uint8": + return uint8(value) + case "uint16": + return uint16(value) + case "uint32": + return uint32(value) + case "uint64": + return uint64(value) + case "rune": + return rune(value) + } + case uint8: + switch typeName { + case "int": + return int(value) + case "byte": + return byte(value) + case "int8": + return int8(value) + case "int16": + return int16(value) + case "int32": + return int32(value) + case "int64": + return int64(value) + case "uint": + return uint(value) + case "uint8": + return uint8(value) + case "uint16": + return uint16(value) + case "uint32": + return uint32(value) + case "uint64": + return uint64(value) + case "rune": + return rune(value) + } + case int16: + switch typeName { + case "int": + return int(value) + case "byte": + return byte(value) + case "int8": + return int8(value) + case "int16": + return int16(value) + case "int32": + return int32(value) + case "int64": + return int64(value) + case "uint": + return uint(value) + case "uint8": + return uint8(value) + case "uint16": + return uint16(value) + case "uint32": + return uint32(value) + case "uint64": + return uint64(value) + case "rune": + return rune(value) + } + case uint16: + switch typeName { + case "int": + return int(value) + case "byte": + return byte(value) + case "int8": + return int8(value) + case "int16": + return int16(value) + case "int32": + return int32(value) + case "int64": + return int64(value) + case "uint": + return uint(value) + case "uint8": + return uint8(value) + case "uint16": + return uint16(value) + case "uint32": + return uint32(value) + case "uint64": + return uint64(value) + case "rune": + return rune(value) + } + case int32: + switch typeName { + case "int": + return int(value) + case "byte": + return byte(value) + case "int8": + return int8(value) + case "int16": + return int16(value) + case "int32": + return int32(value) + case "int64": + return int64(value) + case "uint": + return uint(value) + case "uint8": + return uint8(value) + case "uint16": + return uint16(value) + case "uint32": + return uint32(value) + case "uint64": + return uint64(value) + case "rune": + return rune(value) + case "string": + return string(value) + } + case uint32: + switch typeName { + case "int": + return int(value) + case "byte": + return byte(value) + case "int8": + return int8(value) + case "int16": + return int16(value) + case "int32": + return int32(value) + case "int64": + return int64(value) + case "uint": + return uint(value) + case "uint8": + return uint8(value) + case "uint16": + return uint16(value) + case "uint32": + return uint32(value) + case "uint64": + return uint64(value) + case "rune": + return rune(value) + } + case int64: + switch typeName { + case "int": + return int(value) + case "byte": + return byte(value) + case "int8": + return int8(value) + case "int16": + return int16(value) + case "int32": + return int32(value) + case "int64": + return int64(value) + case "uint": + return uint(value) + case "uint8": + return uint8(value) + case "uint16": + return uint16(value) + case "uint32": + return uint32(value) + case "uint64": + return uint64(value) + case "rune": + return rune(value) + } + case uint64: + switch typeName { + case "int": + return int(value) + case "byte": + return byte(value) + case "int8": + return int8(value) + case "int16": + return int16(value) + case "int32": + return int32(value) + case "int64": + return int64(value) + case "uint": + return uint(value) + case "uint8": + return uint8(value) + case "uint16": + return uint16(value) + case "uint32": + return uint32(value) + case "uint64": + return uint64(value) + case "rune": + return rune(value) + } + case string: + switch typeName { + case "string": + return value + } + } + return nil + } // EvaluateUnary evaluate the type and value of a unary expression + func EvaluateUnary(x interface{}, operator token.Token, xtype ast.Expr) (interface{}, ast.Expr) { + switch operator { + case token.SUB: + switch value := x.(type) { + case int: + return -value, xtype + case int8: + return -value, xtype + case int16: + return -value, xtype + case int32: + return -value, xtype + case int64: + return -value, xtype + } + case token.XOR: + switch value := x.(type) { + case int: + return ^value, xtype + case int8: + return ^value, xtype + case int16: + return ^value, xtype + case int32: + return ^value, xtype + case int64: + return ^value, xtype + case uint: + return ^value, xtype + case uint8: + return ^value, xtype + case uint16: + return ^value, xtype + case uint32: + return ^value, xtype + case uint64: + return ^value, xtype + } + } + return nil, nil + } // EvaluateBinary evaluate the type and value of a binary expression + func EvaluateBinary(x, y interface{}, operator token.Token, xtype, ytype ast.Expr) (interface{}, ast.Expr) { + if operator == token.SHR || operator == token.SHL { + var rightOperand uint64 + yValue := reflect.ValueOf(y) + if yValue.CanUint() { + rightOperand = yValue.Uint() + } else if yValue.CanInt() { + rightOperand = uint64(yValue.Int()) + } switch operator { + case token.SHL: + switch xValue := x.(type) { + case int: + return xValue << rightOperand, xtype + case int8: + return xValue << rightOperand, xtype + case int16: + return xValue << rightOperand, xtype + case int32: + return xValue << rightOperand, xtype + case int64: + return xValue << rightOperand, xtype + case uint: + return xValue << rightOperand, xtype + case uint8: + return xValue << rightOperand, xtype + case uint16: + return xValue << rightOperand, xtype + case uint32: + return xValue << rightOperand, xtype + case uint64: + return xValue << rightOperand, xtype + } + case token.SHR: + switch xValue := x.(type) { + case int: + return xValue >> rightOperand, xtype + case int8: + return xValue >> rightOperand, xtype + case int16: + return xValue >> rightOperand, xtype + case int32: + return xValue >> rightOperand, xtype + case int64: + return xValue >> rightOperand, xtype + case uint: + return xValue >> rightOperand, xtype + case uint8: + return xValue >> rightOperand, xtype + case uint16: + return xValue >> rightOperand, xtype + case uint32: + return xValue >> rightOperand, xtype + case uint64: + return xValue >> rightOperand, xtype + } + } + return nil, nil + } evalType := xtype + if evalType == nil { + evalType = ytype + } xValue := reflect.ValueOf(x) + yValue := reflect.ValueOf(y) + if xValue.Kind() == reflect.String && yValue.Kind() == reflect.String { + return xValue.String() + yValue.String(), evalType + } var targetValue reflect.Value + if xValue.Kind() != reflect.Int { + targetValue = reflect.New(xValue.Type()).Elem() + } else { + targetValue = reflect.New(yValue.Type()).Elem() + } switch operator { + case token.ADD: + if xValue.CanInt() && yValue.CanInt() { + targetValue.SetInt(xValue.Int() + yValue.Int()) + } else if xValue.CanUint() && yValue.CanUint() { + targetValue.SetUint(xValue.Uint() + yValue.Uint()) + } else if xValue.CanInt() && yValue.CanUint() { + targetValue.SetUint(uint64(xValue.Int()) + yValue.Uint()) + } else if xValue.CanUint() && yValue.CanInt() { + targetValue.SetUint(xValue.Uint() + uint64(yValue.Int())) + } + case token.SUB: + if xValue.CanInt() && yValue.CanInt() { + targetValue.SetInt(xValue.Int() - yValue.Int()) + } else if xValue.CanUint() && yValue.CanUint() { + targetValue.SetUint(xValue.Uint() - yValue.Uint()) + } else if xValue.CanInt() && yValue.CanUint() { + targetValue.SetUint(uint64(xValue.Int()) - yValue.Uint()) + } else if xValue.CanUint() && yValue.CanInt() { + targetValue.SetUint(xValue.Uint() - uint64(yValue.Int())) + } + case token.MUL: + if xValue.CanInt() && yValue.CanInt() { + targetValue.SetInt(xValue.Int() * yValue.Int()) + } else if xValue.CanUint() && yValue.CanUint() { + targetValue.SetUint(xValue.Uint() * yValue.Uint()) + } else if xValue.CanInt() && yValue.CanUint() { + targetValue.SetUint(uint64(xValue.Int()) * yValue.Uint()) + } else if xValue.CanUint() && yValue.CanInt() { + targetValue.SetUint(xValue.Uint() * uint64(yValue.Int())) + } + case token.QUO: + if xValue.CanInt() && yValue.CanInt() { + targetValue.SetInt(xValue.Int() / yValue.Int()) + } else if xValue.CanUint() && yValue.CanUint() { + targetValue.SetUint(xValue.Uint() / yValue.Uint()) + } else if xValue.CanInt() && yValue.CanUint() { + targetValue.SetUint(uint64(xValue.Int()) / yValue.Uint()) + } else if xValue.CanUint() && yValue.CanInt() { + targetValue.SetUint(xValue.Uint() / uint64(yValue.Int())) + } + case token.REM: + if xValue.CanInt() && yValue.CanInt() { + targetValue.SetInt(xValue.Int() % yValue.Int()) + } else if xValue.CanUint() && yValue.CanUint() { + targetValue.SetUint(xValue.Uint() % yValue.Uint()) + } else if xValue.CanInt() && yValue.CanUint() { + targetValue.SetUint(uint64(xValue.Int()) % yValue.Uint()) + } else if xValue.CanUint() && yValue.CanInt() { + targetValue.SetUint(xValue.Uint() % uint64(yValue.Int())) + } + case token.AND: + if xValue.CanInt() && yValue.CanInt() { + targetValue.SetInt(xValue.Int() & yValue.Int()) + } else if xValue.CanUint() && yValue.CanUint() { + targetValue.SetUint(xValue.Uint() & yValue.Uint()) + } else if xValue.CanInt() && yValue.CanUint() { + targetValue.SetUint(uint64(xValue.Int()) & yValue.Uint()) + } else if xValue.CanUint() && yValue.CanInt() { + targetValue.SetUint(xValue.Uint() & uint64(yValue.Int())) + } + case token.OR: + if xValue.CanInt() && yValue.CanInt() { + targetValue.SetInt(xValue.Int() | yValue.Int()) + } else if xValue.CanUint() && yValue.CanUint() { + targetValue.SetUint(xValue.Uint() | yValue.Uint()) + } else if xValue.CanInt() && yValue.CanUint() { + targetValue.SetUint(uint64(xValue.Int()) | yValue.Uint()) + } else if xValue.CanUint() && yValue.CanInt() { + targetValue.SetUint(xValue.Uint() | uint64(yValue.Int())) + } + case token.XOR: + if xValue.CanInt() && yValue.CanInt() { + targetValue.SetInt(xValue.Int() ^ yValue.Int()) + } else if xValue.CanUint() && yValue.CanUint() { + targetValue.SetUint(xValue.Uint() ^ yValue.Uint()) + } else if xValue.CanInt() && yValue.CanUint() { + targetValue.SetUint(uint64(xValue.Int()) ^ yValue.Uint()) + } else if xValue.CanUint() && yValue.CanInt() { + targetValue.SetUint(xValue.Uint() ^ uint64(yValue.Int())) + } + } + return targetValue.Interface(), evalType + } diff --git a/vendor/github.com/swaggo/swag/field_parser.go b/vendor/github.com/swaggo/swag/field_parser.go index 9b24e78..bb14aed 100644 --- a/vendor/github.com/swaggo/swag/field_parser.go +++ b/vendor/github.com/swaggo/swag/field_parser.go @@ -16,665 +16,1065 @@ import ( var _ FieldParser = &tagBaseFieldParser{p: nil, field: nil, tag: ""} const ( - requiredLabel = "required" - optionalLabel = "optional" - swaggerTypeTag = "swaggertype" + requiredLabel = "required" + + optionalLabel = "optional" + + swaggerTypeTag = "swaggertype" + swaggerIgnoreTag = "swaggerignore" ) type tagBaseFieldParser struct { - p *Parser + p *Parser + field *ast.Field - tag reflect.StructTag + + tag reflect.StructTag } func newTagBaseFieldParser(p *Parser, field *ast.Field) FieldParser { + fieldParser := tagBaseFieldParser{ - p: p, + + p: p, + field: field, - tag: "", + + tag: "", } + if fieldParser.field.Tag != nil { + fieldParser.tag = reflect.StructTag(strings.ReplaceAll(field.Tag.Value, "`", "")) + } return &fieldParser + } func (ps *tagBaseFieldParser) ShouldSkip() bool { + // Skip non-exported fields. + if ps.field.Names != nil && !ast.IsExported(ps.field.Names[0].Name) { + return true + } if ps.field.Tag == nil { + return false + } ignoreTag := ps.tag.Get(swaggerIgnoreTag) + if strings.EqualFold(ignoreTag, "true") { + return true + } // json:"tag,hoge" + name := strings.TrimSpace(strings.Split(ps.tag.Get(jsonTag), ",")[0]) + if name == "-" { + return true + } return false + } func (ps *tagBaseFieldParser) FieldName() (string, error) { + var name string if ps.field.Tag != nil { + // json:"tag,hoge" + name = strings.TrimSpace(strings.Split(ps.tag.Get(jsonTag), ",")[0]) + if name != "" { + return name, nil + } // use "form" tag over json tag + name = ps.FormName() + if name != "" { + return name, nil + } + } if ps.field.Names == nil { + return "", nil + } switch ps.p.PropNamingStrategy { + case SnakeCase: + return toSnakeCase(ps.field.Names[0].Name), nil + case PascalCase: + return ps.field.Names[0].Name, nil + default: + return toLowerCamelCase(ps.field.Names[0].Name), nil + } + } func (ps *tagBaseFieldParser) firstTagValue(tag string) string { + if ps.field.Tag != nil { + return strings.TrimRight(strings.TrimSpace(strings.Split(ps.tag.Get(tag), ",")[0]), "[]") + } + return "" + } func (ps *tagBaseFieldParser) FormName() string { + return ps.firstTagValue(formTag) + } func (ps *tagBaseFieldParser) HeaderName() string { + return ps.firstTagValue(headerTag) + } func (ps *tagBaseFieldParser) PathName() string { + return ps.firstTagValue(uriTag) + } func toSnakeCase(in string) string { + var ( - runes = []rune(in) + runes = []rune(in) + length = len(runes) - out []rune + + out []rune ) for idx := 0; idx < length; idx++ { + if idx > 0 && unicode.IsUpper(runes[idx]) && + ((idx+1 < length && unicode.IsLower(runes[idx+1])) || unicode.IsLower(runes[idx-1])) { + out = append(out, '_') + } out = append(out, unicode.ToLower(runes[idx])) + } return string(out) + } func toLowerCamelCase(in string) string { + var flag bool out := make([]rune, len(in)) runes := []rune(in) + for i, curr := range runes { + if (i == 0 && unicode.IsUpper(curr)) || (flag && unicode.IsUpper(curr)) { + out[i] = unicode.ToLower(curr) + flag = true continue + } out[i] = curr + flag = false + } return string(out) + } func (ps *tagBaseFieldParser) CustomSchema() (*spec.Schema, error) { + if ps.field.Tag == nil { + return nil, nil + } typeTag := ps.tag.Get(swaggerTypeTag) + if typeTag != "" { + return BuildCustomSchema(strings.Split(typeTag, ",")) + } return nil, nil + } type structField struct { - schemaType string - arrayType string - formatType string - maximum *float64 - minimum *float64 - multipleOf *float64 - maxLength *int64 - minLength *int64 - maxItems *int64 - minItems *int64 + schemaType string + + arrayType string + + formatType string + + maximum *float64 + + minimum *float64 + + multipleOf *float64 + + maxLength *int64 + + minLength *int64 + + maxItems *int64 + + minItems *int64 + exampleValue interface{} - enums []interface{} + + enums []interface{} + enumVarNames []interface{} - unique bool + + unique bool } // splitNotWrapped slices s into all substrings separated by sep if sep is not + // wrapped by brackets and returns a slice of the substrings between those separators. + func splitNotWrapped(s string, sep rune) []string { + openCloseMap := map[rune]rune{ + '(': ')', + '[': ']', + '{': '}', } var ( - result = make([]string, 0) - current = strings.Builder{} + result = make([]string, 0) + + current = strings.Builder{} + openCount = 0 - openChar rune + + openChar rune ) for _, char := range s { + switch { + case openChar == 0 && openCloseMap[char] != 0: + openChar = char openCount++ current.WriteRune(char) + case char == openChar: + openCount++ current.WriteRune(char) + case openCount > 0 && char == openCloseMap[openChar]: + openCount-- current.WriteRune(char) + case openCount == 0 && char == sep: + result = append(result, current.String()) openChar = 0 current = strings.Builder{} + default: + current.WriteRune(char) + } + } if current.String() != "" { + result = append(result, current.String()) + } return result + } // ComplementSchema complement schema with field properties + func (ps *tagBaseFieldParser) ComplementSchema(schema *spec.Schema) error { + types := ps.p.GetSchemaTypePath(schema, 2) + if len(types) == 0 { + return fmt.Errorf("invalid type for field: %s", ps.field.Names[0]) + } if IsRefSchema(schema) { + var newSchema = spec.Schema{} + err := ps.complementSchema(&newSchema, types) + if err != nil { + return err + } + if !reflect.ValueOf(newSchema).IsZero() { + *schema = *(newSchema.WithAllOf(*schema)) + } + return nil + } return ps.complementSchema(schema, types) + } // complementSchema complement schema with field properties + func (ps *tagBaseFieldParser) complementSchema(schema *spec.Schema, types []string) error { + if ps.field.Tag == nil { + if ps.field.Doc != nil { + schema.Description = strings.TrimSpace(ps.field.Doc.Text()) + } if schema.Description == "" && ps.field.Comment != nil { + schema.Description = strings.TrimSpace(ps.field.Comment.Text()) + } return nil + } field := &structField{ + schemaType: types[0], + formatType: ps.tag.Get(formatTag), } if len(types) > 1 && (types[0] == ARRAY || types[0] == OBJECT) { + field.arrayType = types[1] + } jsonTagValue := ps.tag.Get(jsonTag) bindingTagValue := ps.tag.Get(bindingTag) + if bindingTagValue != "" { + parseValidTags(bindingTagValue, field) + } validateTagValue := ps.tag.Get(validateTag) + if validateTagValue != "" { + parseValidTags(validateTagValue, field) + } enumsTagValue := ps.tag.Get(enumsTag) + if enumsTagValue != "" { + err := parseEnumTags(enumsTagValue, field) + if err != nil { + return err + } + } if IsNumericType(field.schemaType) || IsNumericType(field.arrayType) { + maximum, err := getFloatTag(ps.tag, maximumTag) + if err != nil { + return err + } if maximum != nil { + field.maximum = maximum + } minimum, err := getFloatTag(ps.tag, minimumTag) + if err != nil { + return err + } if minimum != nil { + field.minimum = minimum + } multipleOf, err := getFloatTag(ps.tag, multipleOfTag) + if err != nil { + return err + } if multipleOf != nil { + field.multipleOf = multipleOf + } + } if field.schemaType == STRING || field.arrayType == STRING { + maxLength, err := getIntTag(ps.tag, maxLengthTag) + if err != nil { + return err + } if maxLength != nil { + field.maxLength = maxLength + } minLength, err := getIntTag(ps.tag, minLengthTag) + if err != nil { + return err + } if minLength != nil { + field.minLength = minLength + } + } // json:"name,string" or json:",string" + exampleTagValue, ok := ps.tag.Lookup(exampleTag) + if ok { + field.exampleValue = exampleTagValue if !strings.Contains(jsonTagValue, ",string") { + example, err := defineTypeOfExample(field.schemaType, field.arrayType, exampleTagValue) + if err != nil { + return err + } field.exampleValue = example + } + } // perform this after setting everything else (min, max, etc...) + if strings.Contains(jsonTagValue, ",string") { + // @encoding/json: "It applies only to fields of string, floating point, integer, or boolean types." + defaultValues := map[string]string{ + // Zero Values as string - STRING: "", + + STRING: "", + INTEGER: "0", + BOOLEAN: "false", - NUMBER: "0", + + NUMBER: "0", } defaultValue, ok := defaultValues[field.schemaType] + if ok { + field.schemaType = STRING + *schema = *PrimitiveSchema(field.schemaType) if field.exampleValue == nil { + // if exampleValue is not defined by the user, + // we will force an example with a correct value + // (eg: int->"0", bool:"false") + field.exampleValue = defaultValue + } + } + } if ps.field.Doc != nil { + schema.Description = strings.TrimSpace(ps.field.Doc.Text()) + } if schema.Description == "" && ps.field.Comment != nil { + schema.Description = strings.TrimSpace(ps.field.Comment.Text()) + } schema.ReadOnly = ps.tag.Get(readOnlyTag) == "true" defaultTagValue := ps.tag.Get(defaultTag) + if defaultTagValue != "" { + value, err := defineType(field.schemaType, defaultTagValue) + if err != nil { + return err + } schema.Default = value + } schema.Example = field.exampleValue if field.schemaType != ARRAY { + schema.Format = field.formatType + } extensionsTagValue := ps.tag.Get(extensionsTag) + if extensionsTagValue != "" { + schema.Extensions = setExtensionParam(extensionsTagValue) + } varNamesTag := ps.tag.Get("x-enum-varnames") + if varNamesTag != "" { + varNames := strings.Split(varNamesTag, ",") + if len(varNames) != len(field.enums) { + return fmt.Errorf("invalid count of x-enum-varnames. expected %d, got %d", len(field.enums), len(varNames)) + } field.enumVarNames = nil for _, v := range varNames { + field.enumVarNames = append(field.enumVarNames, v) + } if field.schemaType == ARRAY { + // Add the var names in the items schema + if schema.Items.Schema.Extensions == nil { + schema.Items.Schema.Extensions = map[string]interface{}{} + } + schema.Items.Schema.Extensions[enumVarNamesExtension] = field.enumVarNames + } else { + // Add to top level schema + if schema.Extensions == nil { + schema.Extensions = map[string]interface{}{} + } + schema.Extensions[enumVarNamesExtension] = field.enumVarNames + } + } eleSchema := schema if field.schemaType == ARRAY { + // For Array only + schema.MaxItems = field.maxItems + schema.MinItems = field.minItems + schema.UniqueItems = field.unique eleSchema = schema.Items.Schema + eleSchema.Format = field.formatType + } eleSchema.Maximum = field.maximum + eleSchema.Minimum = field.minimum + eleSchema.MultipleOf = field.multipleOf + eleSchema.MaxLength = field.maxLength + eleSchema.MinLength = field.minLength + eleSchema.Enum = field.enums return nil + } func getFloatTag(structTag reflect.StructTag, tagName string) (*float64, error) { + strValue := structTag.Get(tagName) + if strValue == "" { + return nil, nil + } value, err := strconv.ParseFloat(strValue, 64) + if err != nil { + return nil, fmt.Errorf("can't parse numeric value of %q tag: %v", tagName, err) + } return &value, nil + } func getIntTag(structTag reflect.StructTag, tagName string) (*int64, error) { + strValue := structTag.Get(tagName) + if strValue == "" { + return nil, nil + } value, err := strconv.ParseInt(strValue, 10, 64) + if err != nil { + return nil, fmt.Errorf("can't parse numeric value of %q tag: %v", tagName, err) + } return &value, nil + } func (ps *tagBaseFieldParser) IsRequired() (bool, error) { + if ps.field.Tag == nil { + return false, nil + } bindingTag := ps.tag.Get(bindingTag) + if bindingTag != "" { + for _, val := range strings.Split(bindingTag, ",") { + switch val { + case requiredLabel: + return true, nil + case optionalLabel: + return false, nil + } + } + } validateTag := ps.tag.Get(validateTag) + if validateTag != "" { + for _, val := range strings.Split(validateTag, ",") { + switch val { + case requiredLabel: + return true, nil + case optionalLabel: + return false, nil + } + } + } return ps.p.RequiredByDefault, nil + } func parseValidTags(validTag string, sf *structField) { + // `validate:"required,max=10,min=1"` + // ps. required checked by IsRequired(). + for _, val := range strings.Split(validTag, ",") { + var ( valValue string - keyVal = strings.Split(val, "=") + + keyVal = strings.Split(val, "=") ) switch len(keyVal) { + case 1: + case 2: + valValue = strings.ReplaceAll(strings.ReplaceAll(keyVal[1], utf8HexComma, ","), utf8Pipe, "|") + default: + continue + } switch keyVal[0] { + case "max", "lte": + sf.setMax(valValue) + case "min", "gte": + sf.setMin(valValue) + case "oneof": + sf.setOneOf(valValue) + case "unique": + if sf.schemaType == ARRAY { + sf.unique = true + } + case "dive": + // ignore dive + return + default: + continue + } + } + } func parseEnumTags(enumTag string, field *structField) error { + enumType := field.schemaType + if field.schemaType == ARRAY { + enumType = field.arrayType + } field.enums = nil for _, e := range strings.Split(enumTag, ",") { + value, err := defineType(enumType, e) + if err != nil { + return err + } field.enums = append(field.enums, value) + } return nil + } func (sf *structField) setOneOf(valValue string) { + if len(sf.enums) != 0 { + return + } enumType := sf.schemaType + if sf.schemaType == ARRAY { + enumType = sf.arrayType + } valValues := parseOneOfParam2(valValue) + for i := range valValues { + value, err := defineType(enumType, valValues[i]) + if err != nil { + continue + } sf.enums = append(sf.enums, value) + } + } func (sf *structField) setMin(valValue string) { + value, err := strconv.ParseFloat(valValue, 64) + if err != nil { + return + } switch sf.schemaType { + case INTEGER, NUMBER: + sf.minimum = &value + case STRING: + intValue := int64(value) + sf.minLength = &intValue + case ARRAY: + intValue := int64(value) + sf.minItems = &intValue + } + } func (sf *structField) setMax(valValue string) { + value, err := strconv.ParseFloat(valValue, 64) + if err != nil { + return + } switch sf.schemaType { + case INTEGER, NUMBER: + sf.maximum = &value + case STRING: + intValue := int64(value) + sf.maxLength = &intValue + case ARRAY: + intValue := int64(value) + sf.maxItems = &intValue + } + } const ( utf8HexComma = "0x2C" - utf8Pipe = "0x7C" + + utf8Pipe = "0x7C" ) // These code copy from + // https://github.com/go-playground/validator/blob/d4271985b44b735c6f76abc7a06532ee997f9476/baked_in.go#L207 + // ---. + var oneofValsCache = map[string][]string{} + var oneofValsCacheRWLock = sync.RWMutex{} + var splitParamsRegex = regexp.MustCompile(`'[^']*'|\S+`) func parseOneOfParam2(param string) []string { + oneofValsCacheRWLock.RLock() + values, ok := oneofValsCache[param] + oneofValsCacheRWLock.RUnlock() if !ok { + oneofValsCacheRWLock.Lock() + values = splitParamsRegex.FindAllString(param, -1) for i := 0; i < len(values); i++ { + values[i] = strings.ReplaceAll(values[i], "'", "") + } oneofValsCache[param] = values oneofValsCacheRWLock.Unlock() + } return values + } // ---. diff --git a/vendor/github.com/swaggo/swag/formatter.go b/vendor/github.com/swaggo/swag/formatter.go index 511e3a8..0370f8f 100644 --- a/vendor/github.com/swaggo/swag/formatter.go +++ b/vendor/github.com/swaggo/swag/formatter.go @@ -15,168 +15,282 @@ import ( ) // Check of @Param @Success @Failure @Response @Header + var specialTagForSplit = map[string]bool{ - paramAttr: true, - successAttr: true, - failureAttr: true, + + paramAttr: true, + + successAttr: true, + + failureAttr: true, + responseAttr: true, - headerAttr: true, + + headerAttr: true, } var skipChar = map[byte]byte{ + '"': '"', + '(': ')', + '{': '}', + '[': ']', } // Formatter implements a formatter for Go source files. + type Formatter struct { + // debugging output goes here + debug Debugger } // NewFormatter create a new formatter instance. + func NewFormatter() *Formatter { + formatter := &Formatter{ + debug: log.New(os.Stdout, "", log.LstdFlags), } + return formatter + } // Format formats swag comments in contents. It uses fileName to report errors + // that happen during parsing of contents. + func (f *Formatter) Format(fileName string, contents []byte) ([]byte, error) { + fileSet := token.NewFileSet() + ast, err := goparser.ParseFile(fileSet, fileName, contents, goparser.ParseComments) + if err != nil { + return nil, err + } // Formatting changes are described as an edit list of byte range + // replacements. We make these content-level edits directly rather than + // changing the AST nodes and writing those out (via [go/printer] or + // [go/format]) so that we only change the formatting of Swag attribute + // comments. This won't touch the formatting of any other comments, or of + // functions, etc. + maxEdits := 0 + for _, comment := range ast.Comments { + maxEdits += len(comment.List) + } + edits := make(edits, 0, maxEdits) for _, comment := range ast.Comments { + formatFuncDoc(fileSet, comment.List, &edits) + } return edits.apply(contents), nil + } type edit struct { - begin int - end int + begin int + + end int + replacement []byte } type edits []edit func (edits edits) apply(contents []byte) []byte { + // Apply the edits with the highest offset first, so that earlier edits + // don't affect the offsets of later edits. + sort.Slice(edits, func(i, j int) bool { + return edits[i].begin > edits[j].begin + }) for _, edit := range edits { + prefix := contents[:edit.begin] + suffix := contents[edit.end:] + contents = append(prefix, append(edit.replacement, suffix...)...) + } return contents + } // formatFuncDoc reformats the comment lines in commentList, and appends any + // changes to the edit list. + func formatFuncDoc(fileSet *token.FileSet, commentList []*ast.Comment, edits *edits) { + // Building the edit list to format a comment block is a two-step process. + // First, we iterate over each comment line looking for Swag attributes. In + // each one we find, we replace alignment whitespace with a tab character, + // then write the result into a tab writer. linesToComments := make(map[int]int, len(commentList)) buffer := &bytes.Buffer{} + w := tabwriter.NewWriter(buffer, 1, 4, 1, '\t', 0) for commentIndex, comment := range commentList { + text := comment.Text + if attr, body, found := swagComment(text); found { + formatted := "//\t" + attr + if body != "" { + formatted += "\t" + splitComment2(attr, body) + } + _, _ = fmt.Fprintln(w, formatted) + linesToComments[len(linesToComments)] = commentIndex + } + } // Once we've loaded all of the comment lines to be aligned into the tab + // writer, flushing it causes the aligned text to be written out to the + // backing buffer. + _ = w.Flush() // Now the second step: we iterate over the aligned comment lines that were + // written into the backing buffer, pair each one up to its original + // comment line, and use the combination to describe the edit that needs to + // be made to the original input. + formattedComments := bytes.Split(buffer.Bytes(), []byte("\n")) + for lineIndex, commentIndex := range linesToComments { + comment := commentList[commentIndex] + *edits = append(*edits, edit{ - begin: fileSet.Position(comment.Pos()).Offset, - end: fileSet.Position(comment.End()).Offset, + + begin: fileSet.Position(comment.Pos()).Offset, + + end: fileSet.Position(comment.End()).Offset, + replacement: formattedComments[lineIndex], }) + } + } func splitComment2(attr, body string) string { + if specialTagForSplit[strings.ToLower(attr)] { + for i := 0; i < len(body); i++ { + if skipEnd, ok := skipChar[body[i]]; ok { + skipStart, n := body[i], 1 + for i++; i < len(body); i++ { + if skipStart != skipEnd && body[i] == skipStart { + n++ + } else if body[i] == skipEnd { + n-- + if n == 0 { + break + } + } + } + } else if body[i] == ' ' || body[i] == '\t' { + j := i + for ; j < len(body) && (body[j] == ' ' || body[j] == '\t'); j++ { + } + body = replaceRange(body, i, j, "\t") + } + } + } + return body + } func replaceRange(s string, start, end int, new string) string { + return s[:start] + new + s[end:] + } var swagCommentLineExpression = regexp.MustCompile(`^\/\/\s+(@[\S.]+)\s*(.*)`) func swagComment(comment string) (string, string, bool) { + matches := swagCommentLineExpression.FindStringSubmatch(comment) + if matches == nil { + return "", "", false + } + return matches[1], matches[2], true + } diff --git a/vendor/github.com/swaggo/swag/generics.go b/vendor/github.com/swaggo/swag/generics.go index 07344bb..342de81 100644 --- a/vendor/github.com/swaggo/swag/generics.go +++ b/vendor/github.com/swaggo/swag/generics.go @@ -15,418 +15,720 @@ import ( type genericTypeSpec struct { TypeSpec *TypeSpecDef - Name string + + Name string } type formalParamType struct { Name string + Type string } func (t *genericTypeSpec) TypeName() string { + if t.TypeSpec != nil { + return t.TypeSpec.TypeName() + } + return t.Name + } func normalizeGenericTypeName(name string) string { + return strings.Replace(name, ".", "_", -1) + } func (pkgDefs *PackagesDefinitions) getTypeFromGenericParam(genericParam string, file *ast.File) (typeSpecDef *TypeSpecDef) { + if strings.HasPrefix(genericParam, "[]") { + typeSpecDef = pkgDefs.getTypeFromGenericParam(genericParam[2:], file) + if typeSpecDef == nil { + return nil + } + var expr ast.Expr + switch typeSpecDef.TypeSpec.Type.(type) { + case *ast.ArrayType, *ast.MapType: + expr = typeSpecDef.TypeSpec.Type + default: + name := typeSpecDef.TypeName() + expr = ast.NewIdent(name) + if _, ok := pkgDefs.uniqueDefinitions[name]; !ok { + pkgDefs.uniqueDefinitions[name] = typeSpecDef + } + } + return &TypeSpecDef{ + TypeSpec: &ast.TypeSpec{ + Name: ast.NewIdent(string(IgnoreNameOverridePrefix) + "array_" + typeSpecDef.TypeName()), + Type: &ast.ArrayType{ + Elt: expr, }, }, - Enums: typeSpecDef.Enums, - PkgPath: typeSpecDef.PkgPath, + + Enums: typeSpecDef.Enums, + + PkgPath: typeSpecDef.PkgPath, + ParentSpec: typeSpecDef.ParentSpec, - NotUnique: false, + + NotUnique: false, } + } if strings.HasPrefix(genericParam, "map[") { + parts := strings.SplitN(genericParam[4:], "]", 2) + if len(parts) != 2 { + return nil + } + typeSpecDef = pkgDefs.getTypeFromGenericParam(parts[1], file) + if typeSpecDef == nil { + return nil + } + var expr ast.Expr + switch typeSpecDef.TypeSpec.Type.(type) { + case *ast.ArrayType, *ast.MapType: + expr = typeSpecDef.TypeSpec.Type + default: + name := typeSpecDef.TypeName() + expr = ast.NewIdent(name) + if _, ok := pkgDefs.uniqueDefinitions[name]; !ok { + pkgDefs.uniqueDefinitions[name] = typeSpecDef + } + } + return &TypeSpecDef{ + TypeSpec: &ast.TypeSpec{ + Name: ast.NewIdent(string(IgnoreNameOverridePrefix) + "map_" + parts[0] + "_" + typeSpecDef.TypeName()), + Type: &ast.MapType{ - Key: ast.NewIdent(parts[0]), //assume key is string or integer + + Key: ast.NewIdent(parts[0]), //assume key is string or integer + Value: expr, }, }, - Enums: typeSpecDef.Enums, - PkgPath: typeSpecDef.PkgPath, + + Enums: typeSpecDef.Enums, + + PkgPath: typeSpecDef.PkgPath, + ParentSpec: typeSpecDef.ParentSpec, - NotUnique: false, + + NotUnique: false, } } + if IsGolangPrimitiveType(genericParam) { + return &TypeSpecDef{ + TypeSpec: &ast.TypeSpec{ + Name: ast.NewIdent(genericParam), + Type: ast.NewIdent(genericParam), }, } + } + return pkgDefs.FindTypeSpec(genericParam, file) + } func (pkgDefs *PackagesDefinitions) parametrizeGenericType(file *ast.File, original *TypeSpecDef, fullGenericForm string) *TypeSpecDef { + if original == nil || original.TypeSpec.TypeParams == nil || len(original.TypeSpec.TypeParams.List) == 0 { + return original + } name, genericParams := splitGenericsTypeName(fullGenericForm) + if genericParams == nil { + return nil + } //generic[x,y any,z any] considered, TODO what if the type is not `any`, but a concrete one, such as `int32|int64` or an certain interface{} + var formals []formalParamType + for _, field := range original.TypeSpec.TypeParams.List { + for _, ident := range field.Names { + formal := formalParamType{Name: ident.Name} + if ident, ok := field.Type.(*ast.Ident); ok { + formal.Type = ident.Name + } + formals = append(formals, formal) + } + } + if len(genericParams) != len(formals) { + return nil + } + genericParamTypeDefs := map[string]*genericTypeSpec{} for i, genericParam := range genericParams { + var typeDef *TypeSpecDef + if !IsGolangPrimitiveType(genericParam) { + typeDef = pkgDefs.getTypeFromGenericParam(genericParam, file) + if typeDef != nil { + genericParam = typeDef.TypeName() + if _, ok := pkgDefs.uniqueDefinitions[genericParam]; !ok { + pkgDefs.uniqueDefinitions[genericParam] = typeDef + } + } + } + genericParamTypeDefs[formals[i].Name] = &genericTypeSpec{ + TypeSpec: typeDef, - Name: genericParam, + + Name: genericParam, } + } name = fmt.Sprintf("%s%s-", string(IgnoreNameOverridePrefix), original.TypeName()) + var nameParts []string + for _, def := range formals { + if specDef, ok := genericParamTypeDefs[def.Name]; ok { + nameParts = append(nameParts, specDef.TypeName()) + } + } name += normalizeGenericTypeName(strings.Join(nameParts, "-")) if typeSpec, ok := pkgDefs.uniqueDefinitions[name]; ok { + return typeSpec + } parametrizedTypeSpec := &TypeSpecDef{ - File: original.File, + + File: original.File, + PkgPath: original.PkgPath, + TypeSpec: &ast.TypeSpec{ + Name: &ast.Ident{ - Name: name, + + Name: name, + NamePos: original.TypeSpec.Name.NamePos, - Obj: original.TypeSpec.Name.Obj, + + Obj: original.TypeSpec.Name.Obj, }, - Doc: original.TypeSpec.Doc, + + Doc: original.TypeSpec.Doc, + Assign: original.TypeSpec.Assign, }, } + pkgDefs.uniqueDefinitions[name] = parametrizedTypeSpec parametrizedTypeSpec.TypeSpec.Type = pkgDefs.resolveGenericType(original.File, original.TypeSpec.Type, genericParamTypeDefs) return parametrizedTypeSpec + } // splitGenericsTypeName splits a generic struct name in his parts + func splitGenericsTypeName(fullGenericForm string) (string, []string) { + //remove all spaces character + fullGenericForm = strings.Map(func(r rune) rune { + if unicode.IsSpace(r) { + return -1 + } + return r + }, fullGenericForm) // split only at the first '[' and remove the last ']' + if fullGenericForm[len(fullGenericForm)-1] != ']' { + return "", nil + } genericParams := strings.SplitN(fullGenericForm[:len(fullGenericForm)-1], "[", 2) + if len(genericParams) == 1 { + return "", nil + } // generic type name + genericTypeName := genericParams[0] depth := 0 + genericParams = strings.FieldsFunc(genericParams[1], func(r rune) bool { + if r == '[' { + depth++ + } else if r == ']' { + depth-- + } else if r == ',' && depth == 0 { + return true + } + return false + }) + if depth != 0 { + return "", nil + } return genericTypeName, genericParams + } func (pkgDefs *PackagesDefinitions) getParametrizedType(genTypeSpec *genericTypeSpec) ast.Expr { + if genTypeSpec.TypeSpec != nil && strings.Contains(genTypeSpec.Name, ".") { + parts := strings.SplitN(genTypeSpec.Name, ".", 2) + return &ast.SelectorExpr{ - X: &ast.Ident{Name: parts[0]}, + + X: &ast.Ident{Name: parts[0]}, + Sel: &ast.Ident{Name: parts[1]}, } + } //a primitive type name or a type name in current package + return &ast.Ident{Name: genTypeSpec.Name} + } func (pkgDefs *PackagesDefinitions) resolveGenericType(file *ast.File, expr ast.Expr, genericParamTypeDefs map[string]*genericTypeSpec) ast.Expr { + switch astExpr := expr.(type) { + case *ast.Ident: + if genTypeSpec, ok := genericParamTypeDefs[astExpr.Name]; ok { + return pkgDefs.getParametrizedType(genTypeSpec) + } + case *ast.ArrayType: + return &ast.ArrayType{ - Elt: pkgDefs.resolveGenericType(file, astExpr.Elt, genericParamTypeDefs), - Len: astExpr.Len, + + Elt: pkgDefs.resolveGenericType(file, astExpr.Elt, genericParamTypeDefs), + + Len: astExpr.Len, + Lbrack: astExpr.Lbrack, } + case *ast.MapType: + return &ast.MapType{ - Map: astExpr.Map, - Key: pkgDefs.resolveGenericType(file, astExpr.Key, genericParamTypeDefs), + + Map: astExpr.Map, + + Key: pkgDefs.resolveGenericType(file, astExpr.Key, genericParamTypeDefs), + Value: pkgDefs.resolveGenericType(file, astExpr.Value, genericParamTypeDefs), } + case *ast.StarExpr: + return &ast.StarExpr{ + Star: astExpr.Star, - X: pkgDefs.resolveGenericType(file, astExpr.X, genericParamTypeDefs), + + X: pkgDefs.resolveGenericType(file, astExpr.X, genericParamTypeDefs), } + case *ast.IndexExpr, *ast.IndexListExpr: + fullGenericName, _ := getGenericFieldType(file, expr, genericParamTypeDefs) + typeDef := pkgDefs.FindTypeSpec(fullGenericName, file) + if typeDef != nil { + return typeDef.TypeSpec.Name + } + case *ast.StructType: + newStructTypeDef := &ast.StructType{ - Struct: astExpr.Struct, + + Struct: astExpr.Struct, + Incomplete: astExpr.Incomplete, + Fields: &ast.FieldList{ + Opening: astExpr.Fields.Opening, + Closing: astExpr.Fields.Closing, }, } for _, field := range astExpr.Fields.List { + newField := &ast.Field{ - Type: field.Type, - Doc: field.Doc, - Names: field.Names, - Tag: field.Tag, + + Type: field.Type, + + Doc: field.Doc, + + Names: field.Names, + + Tag: field.Tag, + Comment: field.Comment, } newField.Type = pkgDefs.resolveGenericType(file, field.Type, genericParamTypeDefs) newStructTypeDef.Fields.List = append(newStructTypeDef.Fields.List, newField) + } + return newStructTypeDef + } + return expr + } func getExtendedGenericFieldType(file *ast.File, field ast.Expr, genericParamTypeDefs map[string]*genericTypeSpec) (string, error) { + switch fieldType := field.(type) { + case *ast.ArrayType: + fieldName, err := getExtendedGenericFieldType(file, fieldType.Elt, genericParamTypeDefs) + return "[]" + fieldName, err + case *ast.StarExpr: + return getExtendedGenericFieldType(file, fieldType.X, genericParamTypeDefs) + case *ast.Ident: + if genericParamTypeDefs != nil { + if typeSpec, ok := genericParamTypeDefs[fieldType.Name]; ok { + return typeSpec.Name, nil + } + } + if fieldType.Obj == nil { + return fieldType.Name, nil + } tSpec := &TypeSpecDef{ - File: file, + + File: file, + TypeSpec: fieldType.Obj.Decl.(*ast.TypeSpec), - PkgPath: file.Name.Name, + + PkgPath: file.Name.Name, } + return tSpec.TypeName(), nil + default: + return getFieldType(file, field, genericParamTypeDefs) + } + } func getGenericFieldType(file *ast.File, field ast.Expr, genericParamTypeDefs map[string]*genericTypeSpec) (string, error) { + var fullName string + var baseName string + var err error + switch fieldType := field.(type) { + case *ast.IndexListExpr: + baseName, err = getGenericTypeName(file, fieldType.X) + if err != nil { + return "", err + } + fullName = baseName + "[" for _, index := range fieldType.Indices { + fieldName, err := getExtendedGenericFieldType(file, index, genericParamTypeDefs) + if err != nil { + return "", err + } fullName += fieldName + "," + } fullName = strings.TrimRight(fullName, ",") + "]" + case *ast.IndexExpr: + baseName, err = getGenericTypeName(file, fieldType.X) + if err != nil { + return "", err + } indexName, err := getExtendedGenericFieldType(file, fieldType.Index, genericParamTypeDefs) + if err != nil { + return "", err + } fullName = fmt.Sprintf("%s[%s]", baseName, indexName) + } if fullName == "" { + return "", fmt.Errorf("unknown field type %#v", field) + } var packageName string + if !strings.Contains(baseName, ".") { + if file.Name == nil { + return "", errors.New("file name is nil") + } + packageName, _ = getFieldType(file, file.Name, genericParamTypeDefs) + } return strings.TrimLeft(fmt.Sprintf("%s.%s", packageName, fullName), "."), nil + } func getGenericTypeName(file *ast.File, field ast.Expr) (string, error) { + switch fieldType := field.(type) { + case *ast.Ident: + if fieldType.Obj == nil { + return fieldType.Name, nil + } tSpec := &TypeSpecDef{ - File: file, + + File: file, + TypeSpec: fieldType.Obj.Decl.(*ast.TypeSpec), - PkgPath: file.Name.Name, + + PkgPath: file.Name.Name, } + return tSpec.TypeName(), nil + case *ast.ArrayType: + tSpec := &TypeSpecDef{ - File: file, + + File: file, + TypeSpec: fieldType.Elt.(*ast.Ident).Obj.Decl.(*ast.TypeSpec), - PkgPath: file.Name.Name, + + PkgPath: file.Name.Name, } + return tSpec.TypeName(), nil + case *ast.SelectorExpr: + return fmt.Sprintf("%s.%s", fieldType.X.(*ast.Ident).Name, fieldType.Sel.Name), nil + } + return "", fmt.Errorf("unknown type %#v", field) + } func (parser *Parser) parseGenericTypeExpr(file *ast.File, typeExpr ast.Expr) (*spec.Schema, error) { + switch expr := typeExpr.(type) { + // suppress debug messages for these types + case *ast.InterfaceType: + case *ast.StructType: + case *ast.Ident: + case *ast.StarExpr: + case *ast.SelectorExpr: + case *ast.ArrayType: + case *ast.MapType: + case *ast.FuncType: + case *ast.IndexExpr, *ast.IndexListExpr: + name, err := getExtendedGenericFieldType(file, expr, nil) + if err == nil { + if schema, err := parser.getTypeSchema(name, file, false); err == nil { + return schema, nil + } + } parser.debug.Printf("Type definition of type '%T' is not supported yet. Using 'object' instead. (%s)\n", typeExpr, err) + default: + parser.debug.Printf("Type definition of type '%T' is not supported yet. Using 'object' instead.\n", typeExpr) + } return PrimitiveSchema(OBJECT), nil + } diff --git a/vendor/github.com/swaggo/swag/golist.go b/vendor/github.com/swaggo/swag/golist.go index fa0b2cd..0837fc7 100644 --- a/vendor/github.com/swaggo/swag/golist.go +++ b/vendor/github.com/swaggo/swag/golist.go @@ -11,68 +11,119 @@ import ( ) func listPackages(ctx context.Context, dir string, env []string, args ...string) (pkgs []*build.Package, finalErr error) { + cmd := exec.CommandContext(ctx, "go", append([]string{"list", "-json", "-e"}, args...)...) + cmd.Env = env + cmd.Dir = dir stdout, err := cmd.StdoutPipe() + if err != nil { + return nil, err + } + var stderrBuf bytes.Buffer + cmd.Stderr = &stderrBuf + defer func() { + if stderrBuf.Len() > 0 { + finalErr = fmt.Errorf("%v\n%s", finalErr, stderrBuf.Bytes()) + } + }() err = cmd.Start() + if err != nil { + return nil, err + } + dec := json.NewDecoder(stdout) + for dec.More() { + var pkg build.Package + err = dec.Decode(&pkg) + if err != nil { + return nil, err + } + pkgs = append(pkgs, &pkg) + } + err = cmd.Wait() + if err != nil { + return nil, err + } + return pkgs, nil + } func (parser *Parser) getAllGoFileInfoFromDepsByList(pkg *build.Package, parseFlag ParseFlag) error { + ignoreInternal := pkg.Goroot && !parser.ParseInternal + if ignoreInternal { // ignored internal + return nil + } if parser.skipPackageByPrefix(pkg.ImportPath) { + return nil // ignored by user-defined package path prefixes + } srcDir := pkg.Dir + var err error + for i := range pkg.GoFiles { + err = parser.parseFile(pkg.ImportPath, filepath.Join(srcDir, pkg.GoFiles[i]), nil, parseFlag) + if err != nil { + return err + } + } // parse .go source files that import "C" + for i := range pkg.CgoFiles { + err = parser.parseFile(pkg.ImportPath, filepath.Join(srcDir, pkg.CgoFiles[i]), nil, parseFlag) + if err != nil { + return err + } + } return nil + } diff --git a/vendor/github.com/swaggo/swag/operation.go b/vendor/github.com/swaggo/swag/operation.go index 169510f..42a2a59 100644 --- a/vendor/github.com/swaggo/swag/operation.go +++ b/vendor/github.com/swaggo/swag/operation.go @@ -18,1045 +18,1719 @@ import ( ) // RouteProperties describes HTTP properties of a single router comment. + type RouteProperties struct { HTTPMethod string - Path string + + Path string + Deprecated bool } // Operation describes a single API operation on a path. + // For more information: https://github.com/swaggo/swag#api-operation + type Operation struct { - parser *Parser + parser *Parser + codeExampleFilesDir string + spec.Operation + RouterProperties []RouteProperties - State string + + State string } var mimeTypeAliases = map[string]string{ - "json": "application/json", - "xml": "text/xml", - "plain": "text/plain", - "html": "text/html", - "mpfd": "multipart/form-data", + + "json": "application/json", + + "xml": "text/xml", + + "plain": "text/plain", + + "html": "text/html", + + "mpfd": "multipart/form-data", + "x-www-form-urlencoded": "application/x-www-form-urlencoded", - "json-api": "application/vnd.api+json", - "json-stream": "application/x-json-stream", - "octet-stream": "application/octet-stream", - "png": "image/png", - "jpeg": "image/jpeg", - "gif": "image/gif", + + "json-api": "application/vnd.api+json", + + "json-stream": "application/x-json-stream", + + "octet-stream": "application/octet-stream", + + "png": "image/png", + + "jpeg": "image/jpeg", + + "gif": "image/gif", } var mimeTypePattern = regexp.MustCompile("^[^/]+/[^/]+$") // NewOperation creates a new Operation with default properties. + // map[int]Response. + func NewOperation(parser *Parser, options ...func(*Operation)) *Operation { + if parser == nil { + parser = New() + } result := &Operation{ - parser: parser, + + parser: parser, + RouterProperties: []RouteProperties{}, + Operation: spec.Operation{ + OperationProps: spec.OperationProps{ - ID: "", - Description: "", - Summary: "", - Security: nil, + + ID: "", + + Description: "", + + Summary: "", + + Security: nil, + ExternalDocs: nil, - Deprecated: false, - Tags: []string{}, - Consumes: []string{}, - Produces: []string{}, - Schemes: []string{}, - Parameters: []spec.Parameter{}, + + Deprecated: false, + + Tags: []string{}, + + Consumes: []string{}, + + Produces: []string{}, + + Schemes: []string{}, + + Parameters: []spec.Parameter{}, + Responses: &spec.Responses{ + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{}, }, + ResponsesProps: spec.ResponsesProps{ - Default: nil, + + Default: nil, + StatusCodeResponses: make(map[int]spec.Response), }, }, }, + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{}, }, }, + codeExampleFilesDir: "", } for _, option := range options { + option(result) + } return result + } // SetCodeExampleFilesDirectory sets the directory to search for codeExamples. + func SetCodeExampleFilesDirectory(directoryPath string) func(*Operation) { + return func(o *Operation) { + o.codeExampleFilesDir = directoryPath + } + } // ParseComment parses comment for given comment string and returns error if error occurs. + func (operation *Operation) ParseComment(comment string, astFile *ast.File) error { + commentLine := strings.TrimSpace(strings.TrimLeft(comment, "/")) + if len(commentLine) == 0 { + return nil + } fields := FieldsByAnySpace(commentLine, 2) + attribute := fields[0] + lowerAttribute := strings.ToLower(attribute) + var lineRemainder string + if len(fields) > 1 { + lineRemainder = fields[1] + } + switch lowerAttribute { + case stateAttr: + operation.ParseStateComment(lineRemainder) + case descriptionAttr: + operation.ParseDescriptionComment(lineRemainder) + case descriptionMarkdownAttr: + commentInfo, err := getMarkdownForTag(lineRemainder, operation.parser.markdownFileDir) + if err != nil { + return err + } operation.ParseDescriptionComment(string(commentInfo)) + case summaryAttr: + operation.Summary = lineRemainder + case idAttr: + operation.ID = lineRemainder + case tagsAttr: + operation.ParseTagsComment(lineRemainder) + case acceptAttr: + return operation.ParseAcceptComment(lineRemainder) + case produceAttr: + return operation.ParseProduceComment(lineRemainder) + case paramAttr: + return operation.ParseParamComment(lineRemainder, astFile) + case successAttr, failureAttr, responseAttr: + return operation.ParseResponseComment(lineRemainder, astFile) + case headerAttr: + return operation.ParseResponseHeaderComment(lineRemainder, astFile) + case routerAttr: + return operation.ParseRouterComment(lineRemainder, false) + case deprecatedRouterAttr: + return operation.ParseRouterComment(lineRemainder, true) + case securityAttr: + return operation.ParseSecurityComment(lineRemainder) + case deprecatedAttr: + operation.Deprecate() + case xCodeSamplesAttr: + return operation.ParseCodeSample(attribute, commentLine, lineRemainder) + default: + return operation.ParseMetadata(attribute, lowerAttribute, lineRemainder) + } return nil + } // ParseCodeSample parse code sample. + func (operation *Operation) ParseCodeSample(attribute, _, lineRemainder string) error { + if lineRemainder == "file" { + data, err := getCodeExampleForSummary(operation.Summary, operation.codeExampleFilesDir) + if err != nil { + return err + } var valueJSON interface{} err = json.Unmarshal(data, &valueJSON) + if err != nil { + return fmt.Errorf("annotation %s need a valid json value", attribute) + } // don't use the method provided by spec lib, because it will call toLower() on attribute names, which is wrongly + operation.Extensions[attribute[1:]] = valueJSON return nil + } // Fallback into existing logic + return operation.ParseMetadata(attribute, strings.ToLower(attribute), lineRemainder) + } // ParseStateComment parse state comment. + func (operation *Operation) ParseStateComment(lineRemainder string) { + operation.State = lineRemainder + } // ParseDescriptionComment parse description comment. + func (operation *Operation) ParseDescriptionComment(lineRemainder string) { + if operation.Description == "" { + operation.Description = lineRemainder return + } operation.Description += "\n" + lineRemainder + } // ParseMetadata parse metadata. + func (operation *Operation) ParseMetadata(attribute, lowerAttribute, lineRemainder string) error { + // parsing specific meta data extensions + if strings.HasPrefix(lowerAttribute, "@x-") { + if len(lineRemainder) == 0 { + return fmt.Errorf("annotation %s need a value", attribute) + } var valueJSON interface{} err := json.Unmarshal([]byte(lineRemainder), &valueJSON) + if err != nil { + return fmt.Errorf("annotation %s need a valid json value", attribute) + } // don't use the method provided by spec lib, because it will call toLower() on attribute names, which is wrongly + operation.Extensions[attribute[1:]] = valueJSON + } return nil + } var paramPattern = regexp.MustCompile(`(\S+)\s+(\w+)\s+([\S. ]+?)\s+(\w+)\s+"([^"]+)"`) func findInSlice(arr []string, target string) bool { + for _, str := range arr { + if str == target { + return true + } + } return false + } // ParseParamComment parses params return []string of param properties + // E.g. @Param queryText formData string true "The email for login" + // + // [param name] [paramType] [data type] [is mandatory?] [Comment] + // + // E.g. @Param some_id path int true "Some ID". + func (operation *Operation) ParseParamComment(commentLine string, astFile *ast.File) error { + matches := paramPattern.FindStringSubmatch(commentLine) + if len(matches) != 6 { + return fmt.Errorf("missing required param comment parameters \"%s\"", commentLine) + } name := matches[1] + paramType := matches[2] + refType := TransToValidSchemeType(matches[3]) // Detect refType + objectType := OBJECT if strings.HasPrefix(refType, "[]") { + objectType = ARRAY + refType = strings.TrimPrefix(refType, "[]") + refType = TransToValidSchemeType(refType) + } else if IsPrimitiveType(refType) || + paramType == "formData" && refType == "file" { + objectType = PRIMITIVE + } var enums []interface{} + if !IsPrimitiveType(refType) { + schema, _ := operation.parser.getTypeSchema(refType, astFile, false) + if schema != nil && len(schema.Type) == 1 && schema.Enum != nil { + if objectType == OBJECT { + objectType = PRIMITIVE + } + refType = TransToValidSchemeType(schema.Type[0]) + enums = schema.Enum + } + } requiredText := strings.ToLower(matches[4]) + required := requiredText == "true" || requiredText == requiredLabel + description := matches[5] param := createParameter(paramType, description, name, objectType, refType, required, enums, operation.parser.collectionFormatInQuery) switch paramType { + case "path", "header", "query", "formData": + switch objectType { + case ARRAY: + if !IsPrimitiveType(refType) && !(refType == "file" && paramType == "formData") { + return fmt.Errorf("%s is not supported array type for %s", refType, paramType) + } + case PRIMITIVE: + break + case OBJECT: + schema, err := operation.parser.getTypeSchema(refType, astFile, false) + if err != nil { + return err + } if len(schema.Properties) == 0 { + return nil + } items := schema.Properties.ToOrderedSchemaItems() for _, item := range items { + name, prop := item.Name, &item.Schema + if len(prop.Type) == 0 { + prop = operation.parser.getUnderlyingSchema(prop) + if len(prop.Type) == 0 { + continue + } + } nameOverrideType := paramType + // query also uses formData tags + if paramType == "query" { + nameOverrideType = "formData" + } + // load overridden type specific name from extensions if exists + if nameVal, ok := item.Schema.Extensions[nameOverrideType]; ok { + name = nameVal.(string) + } switch { + case prop.Type[0] == ARRAY: + if prop.Items.Schema == nil { + continue + } + itemSchema := prop.Items.Schema + if len(itemSchema.Type) == 0 { + itemSchema = operation.parser.getUnderlyingSchema(prop.Items.Schema) + } + if len(itemSchema.Type) == 0 { + continue + } + if !IsSimplePrimitiveType(itemSchema.Type[0]) { + continue + } + param = createParameter(paramType, prop.Description, name, prop.Type[0], itemSchema.Type[0], findInSlice(schema.Required, item.Name), itemSchema.Enum, operation.parser.collectionFormatInQuery) case IsSimplePrimitiveType(prop.Type[0]): + param = createParameter(paramType, prop.Description, name, PRIMITIVE, prop.Type[0], findInSlice(schema.Required, item.Name), nil, operation.parser.collectionFormatInQuery) + default: + operation.parser.debug.Printf("skip field [%s] in %s is not supported type for %s", name, refType, paramType) + continue + } param.Nullable = prop.Nullable + param.Format = prop.Format + param.Default = prop.Default + param.Example = prop.Example + param.Extensions = prop.Extensions + param.CommonValidations.Maximum = prop.Maximum + param.CommonValidations.Minimum = prop.Minimum + param.CommonValidations.ExclusiveMaximum = prop.ExclusiveMaximum + param.CommonValidations.ExclusiveMinimum = prop.ExclusiveMinimum + param.CommonValidations.MaxLength = prop.MaxLength + param.CommonValidations.MinLength = prop.MinLength + param.CommonValidations.Pattern = prop.Pattern + param.CommonValidations.MaxItems = prop.MaxItems + param.CommonValidations.MinItems = prop.MinItems + param.CommonValidations.UniqueItems = prop.UniqueItems + param.CommonValidations.MultipleOf = prop.MultipleOf + param.CommonValidations.Enum = prop.Enum + operation.Operation.Parameters = append(operation.Operation.Parameters, param) + } return nil + } + case "body": + if objectType == PRIMITIVE { + param.Schema = PrimitiveSchema(refType) + } else { + schema, err := operation.parseAPIObjectSchema(commentLine, objectType, refType, astFile) + if err != nil { + return err + } param.Schema = schema + } + default: + return fmt.Errorf("%s is not supported paramType", paramType) + } err := operation.parseParamAttribute(commentLine, objectType, refType, paramType, ¶m) if err != nil { + return err + } operation.Operation.Parameters = append(operation.Operation.Parameters, param) return nil + } const ( - formTag = "form" - jsonTag = "json" - uriTag = "uri" - headerTag = "header" - bindingTag = "binding" - defaultTag = "default" - enumsTag = "enums" - exampleTag = "example" - schemaExampleTag = "schemaExample" - formatTag = "format" - validateTag = "validate" - minimumTag = "minimum" - maximumTag = "maximum" - minLengthTag = "minLength" - maxLengthTag = "maxLength" - multipleOfTag = "multipleOf" - readOnlyTag = "readonly" - extensionsTag = "extensions" + formTag = "form" + + jsonTag = "json" + + uriTag = "uri" + + headerTag = "header" + + bindingTag = "binding" + + defaultTag = "default" + + enumsTag = "enums" + + exampleTag = "example" + + schemaExampleTag = "schemaExample" + + formatTag = "format" + + validateTag = "validate" + + minimumTag = "minimum" + + maximumTag = "maximum" + + minLengthTag = "minLength" + + maxLengthTag = "maxLength" + + multipleOfTag = "multipleOf" + + readOnlyTag = "readonly" + + extensionsTag = "extensions" + collectionFormatTag = "collectionFormat" ) var regexAttributes = map[string]*regexp.Regexp{ + // for Enums(A, B) + enumsTag: regexp.MustCompile(`(?i)\s+enums\(.*\)`), + // for maximum(0) + maximumTag: regexp.MustCompile(`(?i)\s+maxinum|maximum\(.*\)`), + // for minimum(0) + minimumTag: regexp.MustCompile(`(?i)\s+mininum|minimum\(.*\)`), + // for default(0) + defaultTag: regexp.MustCompile(`(?i)\s+default\(.*\)`), + // for minlength(0) + minLengthTag: regexp.MustCompile(`(?i)\s+minlength\(.*\)`), + // for maxlength(0) + maxLengthTag: regexp.MustCompile(`(?i)\s+maxlength\(.*\)`), + // for format(email) + formatTag: regexp.MustCompile(`(?i)\s+format\(.*\)`), + // for extensions(x-example=test) + extensionsTag: regexp.MustCompile(`(?i)\s+extensions\(.*\)`), + // for collectionFormat(csv) + collectionFormatTag: regexp.MustCompile(`(?i)\s+collectionFormat\(.*\)`), + // example(0) + exampleTag: regexp.MustCompile(`(?i)\s+example\(.*\)`), + // schemaExample(0) + schemaExampleTag: regexp.MustCompile(`(?i)\s+schemaExample\(.*\)`), } func (operation *Operation) parseParamAttribute(comment, objectType, schemaType, paramType string, param *spec.Parameter) error { + schemaType = TransToValidSchemeType(schemaType) for attrKey, re := range regexAttributes { + attr, err := findAttr(re, comment) + if err != nil { + continue + } switch attrKey { + case enumsTag: + err = setEnumParam(param, attr, objectType, schemaType, paramType) + case minimumTag, maximumTag: + err = setNumberParam(param, attrKey, schemaType, attr, comment) + case defaultTag: + err = setDefault(param, schemaType, attr) + case minLengthTag, maxLengthTag: + err = setStringParam(param, attrKey, schemaType, attr, comment) + case formatTag: + param.Format = attr + case exampleTag: + err = setExample(param, schemaType, attr) + case schemaExampleTag: + err = setSchemaExample(param, schemaType, attr) + case extensionsTag: + param.Extensions = setExtensionParam(attr) + case collectionFormatTag: + err = setCollectionFormatParam(param, attrKey, objectType, attr, comment) + } if err != nil { + return err + } + } return nil + } func findAttr(re *regexp.Regexp, commentLine string) (string, error) { + attr := re.FindString(commentLine) l, r := strings.Index(attr, "("), strings.Index(attr, ")") + if l == -1 || r == -1 { + return "", fmt.Errorf("can not find regex=%s, comment=%s", re.String(), commentLine) + } return strings.TrimSpace(attr[l+1 : r]), nil + } func setStringParam(param *spec.Parameter, name, schemaType, attr, commentLine string) error { + if schemaType != STRING { + return fmt.Errorf("%s is attribute to set to a number. comment=%s got=%s", name, commentLine, schemaType) + } n, err := strconv.ParseInt(attr, 10, 64) + if err != nil { + return fmt.Errorf("%s is allow only a number got=%s", name, attr) + } switch name { + case minLengthTag: + param.MinLength = &n + case maxLengthTag: + param.MaxLength = &n + } return nil + } func setNumberParam(param *spec.Parameter, name, schemaType, attr, commentLine string) error { + switch schemaType { + case INTEGER, NUMBER: + n, err := strconv.ParseFloat(attr, 64) + if err != nil { + return fmt.Errorf("maximum is allow only a number. comment=%s got=%s", commentLine, attr) + } switch name { + case minimumTag: + param.Minimum = &n + case maximumTag: + param.Maximum = &n + } return nil + default: + return fmt.Errorf("%s is attribute to set to a number. comment=%s got=%s", name, commentLine, schemaType) + } + } func setEnumParam(param *spec.Parameter, attr, objectType, schemaType, paramType string) error { + for _, e := range strings.Split(attr, ",") { + e = strings.TrimSpace(e) value, err := defineType(schemaType, e) + if err != nil { + return err + } switch objectType { + case ARRAY: + param.Items.Enum = append(param.Items.Enum, value) + default: + switch paramType { + case "body": + param.Schema.Enum = append(param.Schema.Enum, value) + default: + param.Enum = append(param.Enum, value) + } + } + } return nil + } func setExtensionParam(attr string) spec.Extensions { + extensions := spec.Extensions{} for _, val := range splitNotWrapped(attr, ',') { + parts := strings.SplitN(val, "=", 2) + if len(parts) == 2 { + extensions.Add(parts[0], parts[1]) continue + } if len(parts[0]) > 0 && string(parts[0][0]) == "!" { + extensions.Add(parts[0][1:], false) continue + } extensions.Add(parts[0], true) + } return extensions + } func setCollectionFormatParam(param *spec.Parameter, name, schemaType, attr, commentLine string) error { + if schemaType == ARRAY { + param.CollectionFormat = TransToValidCollectionFormat(attr) return nil + } return fmt.Errorf("%s is attribute to set to an array. comment=%s got=%s", name, commentLine, schemaType) + } func setDefault(param *spec.Parameter, schemaType string, value string) error { + val, err := defineType(schemaType, value) + if err != nil { + return nil // Don't set a default value if it's not valid + } param.Default = val return nil + } func setSchemaExample(param *spec.Parameter, schemaType string, value string) error { + val, err := defineType(schemaType, value) + if err != nil { + return nil // Don't set a example value if it's not valid + } + // skip schema + if param.Schema == nil { + return nil + } switch v := val.(type) { + case string: + // replaces \r \n \t in example string values. + param.Schema.Example = strings.NewReplacer(`\r`, "\r", `\n`, "\n", `\t`, "\t").Replace(v) + default: + param.Schema.Example = val + } return nil + } func setExample(param *spec.Parameter, schemaType string, value string) error { + val, err := defineType(schemaType, value) + if err != nil { + return nil // Don't set a example value if it's not valid + } param.Example = val return nil + } // defineType enum value define the type (object and array unsupported). + func defineType(schemaType string, value string) (v interface{}, err error) { + schemaType = TransToValidSchemeType(schemaType) switch schemaType { + case STRING: + return value, nil + case NUMBER: + v, err = strconv.ParseFloat(value, 64) + if err != nil { + return nil, fmt.Errorf("enum value %s can't convert to %s err: %s", value, schemaType, err) + } + case INTEGER: + v, err = strconv.Atoi(value) + if err != nil { + return nil, fmt.Errorf("enum value %s can't convert to %s err: %s", value, schemaType, err) + } + case BOOLEAN: + v, err = strconv.ParseBool(value) + if err != nil { + return nil, fmt.Errorf("enum value %s can't convert to %s err: %s", value, schemaType, err) + } + default: + return nil, fmt.Errorf("%s is unsupported type in enum value %s", schemaType, value) + } return v, nil + } // ParseTagsComment parses comment for given `tag` comment string. + func (operation *Operation) ParseTagsComment(commentLine string) { + for _, tag := range strings.Split(commentLine, ",") { + operation.Tags = append(operation.Tags, strings.TrimSpace(tag)) + } + } // ParseAcceptComment parses comment for given `accept` comment string. + func (operation *Operation) ParseAcceptComment(commentLine string) error { + return parseMimeTypeList(commentLine, &operation.Consumes, "%v accept type can't be accepted") + } // ParseProduceComment parses comment for given `produce` comment string. + func (operation *Operation) ParseProduceComment(commentLine string) error { + return parseMimeTypeList(commentLine, &operation.Produces, "%v produce type can't be accepted") + } // parseMimeTypeList parses a list of MIME Types for a comment like + // `produce` (`Content-Type:` response header) or + // `accept` (`Accept:` request header). + func parseMimeTypeList(mimeTypeList string, typeList *[]string, format string) error { + for _, typeName := range strings.Split(mimeTypeList, ",") { + if mimeTypePattern.MatchString(typeName) { + *typeList = append(*typeList, typeName) continue + } aliasMimeType, ok := mimeTypeAliases[typeName] + if !ok { + return fmt.Errorf(format, typeName) + } *typeList = append(*typeList, aliasMimeType) + } return nil + } var routerPattern = regexp.MustCompile(`^(/[\w./\-{}+:$]*)[[:blank:]]+\[(\w+)]`) // ParseRouterComment parses comment for given `router` comment string. + func (operation *Operation) ParseRouterComment(commentLine string, deprecated bool) error { + matches := routerPattern.FindStringSubmatch(commentLine) + if len(matches) != 3 { + return fmt.Errorf("can not parse router comment \"%s\"", commentLine) + } signature := RouteProperties{ - Path: matches[1], + + Path: matches[1], + HTTPMethod: strings.ToUpper(matches[2]), + Deprecated: deprecated, } if _, ok := allMethod[signature.HTTPMethod]; !ok { + return fmt.Errorf("invalid method: %s", signature.HTTPMethod) + } operation.RouterProperties = append(operation.RouterProperties, signature) return nil + } // ParseSecurityComment parses comment for given `security` comment string. + func (operation *Operation) ParseSecurityComment(commentLine string) error { + if len(commentLine) == 0 { + operation.Security = []map[string][]string{} + return nil + } var ( - securityMap = make(map[string][]string) + securityMap = make(map[string][]string) + securitySource = commentLine[strings.Index(commentLine, "@Security")+1:] ) for _, securityOption := range strings.Split(securitySource, "||") { + securityOption = strings.TrimSpace(securityOption) left, right := strings.Index(securityOption, "["), strings.Index(securityOption, "]") if !(left == -1 && right == -1) { + scopes := securityOption[left+1 : right] var options []string for _, scope := range strings.Split(scopes, ",") { + options = append(options, strings.TrimSpace(scope)) + } securityKey := securityOption[0:left] + securityMap[securityKey] = append(securityMap[securityKey], options...) + } else { + securityKey := strings.TrimSpace(securityOption) + securityMap[securityKey] = []string{} + } + } operation.Security = append(operation.Security, securityMap) return nil + } // findTypeDef attempts to find the *ast.TypeSpec for a specific type given the + // type's name and the package's import path. + // TODO: improve finding external pkg. + func findTypeDef(importPath, typeName string) (*ast.TypeSpec, error) { + cwd, err := os.Getwd() + if err != nil { + return nil, err + } conf := loader.Config{ + ParserMode: goparser.SpuriousErrors, - Cwd: cwd, + + Cwd: cwd, } conf.Import(importPath) lprog, err := conf.Load() + if err != nil { + return nil, err + } // If the pkg is vendored, the actual pkg path is going to resemble + // something like "{importPath}/vendor/{importPath}" + for k := range lprog.AllPackages { + realPkgPath := k.Path() if strings.Contains(realPkgPath, "vendor/"+importPath) { + importPath = realPkgPath + } + } pkgInfo := lprog.Package(importPath) if pkgInfo == nil { + return nil, fmt.Errorf("package was nil") + } // TODO: possibly cache pkgInfo since it's an expensive operation + for i := range pkgInfo.Files { + for _, astDeclaration := range pkgInfo.Files[i].Decls { + generalDeclaration, ok := astDeclaration.(*ast.GenDecl) + if ok && generalDeclaration.Tok == token.TYPE { + for _, astSpec := range generalDeclaration.Specs { + typeSpec, ok := astSpec.(*ast.TypeSpec) + if ok { + if typeSpec.Name.String() == typeName { + return typeSpec, nil + } + } + } + } + } + } return nil, fmt.Errorf("type spec not found") + } var responsePattern = regexp.MustCompile(`^([\w,]+)\s+([\w{}]+)\s+([\w\-.\\{}=,\[\s\]]+)\s*(".*)?`) // ResponseType{data1=Type1,data2=Type2}. + var combinedPattern = regexp.MustCompile(`^([\w\-./\[\]]+){(.*)}$`) func (operation *Operation) parseObjectSchema(refType string, astFile *ast.File) (*spec.Schema, error) { + return parseObjectSchema(operation.parser, refType, astFile) + } func parseObjectSchema(parser *Parser, refType string, astFile *ast.File) (*spec.Schema, error) { + switch { + case refType == NIL: + return nil, nil + case refType == INTERFACE: + return PrimitiveSchema(OBJECT), nil + case refType == ANY: + return PrimitiveSchema(OBJECT), nil + case IsGolangPrimitiveType(refType): + refType = TransToValidSchemeType(refType) return PrimitiveSchema(refType), nil + case IsPrimitiveType(refType): + return PrimitiveSchema(refType), nil + case strings.HasPrefix(refType, "[]"): + schema, err := parseObjectSchema(parser, refType[2:], astFile) + if err != nil { + return nil, err + } return spec.ArrayProperty(schema), nil + case strings.HasPrefix(refType, "map["): + // ignore key type + idx := strings.Index(refType, "]") + if idx < 0 { + return nil, fmt.Errorf("invalid type: %s", refType) + } refType = refType[idx+1:] + if refType == INTERFACE || refType == ANY { + return spec.MapProperty(nil), nil + } schema, err := parseObjectSchema(parser, refType, astFile) + if err != nil { + return nil, err + } return spec.MapProperty(schema), nil + case strings.Contains(refType, "{"): + return parseCombinedObjectSchema(parser, refType, astFile) + default: + if parser != nil { // checking refType has existing in 'TypeDefinitions' + schema, err := parser.getTypeSchema(refType, astFile, true) + if err != nil { + return nil, err + } return schema, nil + } return RefSchema(refType), nil + } + } func parseFields(s string) []string { + nestLevel := 0 return strings.FieldsFunc(s, func(char rune) bool { + if char == '{' { + nestLevel++ return false + } else if char == '}' { + nestLevel-- return false + } return char == ',' && nestLevel == 0 + }) + } func parseCombinedObjectSchema(parser *Parser, refType string, astFile *ast.File) (*spec.Schema, error) { + matches := combinedPattern.FindStringSubmatch(refType) + if len(matches) != 3 { + return nil, fmt.Errorf("invalid type: %s", refType) + } schema, err := parseObjectSchema(parser, matches[1], astFile) + if err != nil { + return nil, err + } fields, props := parseFields(matches[2]), map[string]spec.Schema{} for _, field := range fields { + keyVal := strings.SplitN(field, "=", 2) + if len(keyVal) == 2 { + schema, err := parseObjectSchema(parser, keyVal[1], astFile) + if err != nil { + return nil, err + } if schema == nil { + schema = PrimitiveSchema(OBJECT) + } props[keyVal[0]] = *schema + } + } if len(props) == 0 { + return schema, nil + } if schema.Ref.GetURL() == nil && len(schema.Type) > 0 && schema.Type[0] == OBJECT && len(schema.Properties) == 0 && schema.AdditionalProperties == nil { + schema.Properties = props + return schema, nil + } return spec.ComposedSchema(*schema, spec.Schema{ + SchemaProps: spec.SchemaProps{ - Type: []string{OBJECT}, + + Type: []string{OBJECT}, + Properties: props, }, }), nil + } func (operation *Operation) parseAPIObjectSchema(commentLine, schemaType, refType string, astFile *ast.File) (*spec.Schema, error) { + if strings.HasSuffix(refType, ",") && strings.Contains(refType, "[") { + // regexp may have broken generic syntax. find closing bracket and add it back + allMatchesLenOffset := strings.Index(commentLine, refType) + len(refType) + lostPartEndIdx := strings.Index(commentLine[allMatchesLenOffset:], "]") + if lostPartEndIdx >= 0 { + refType += commentLine[allMatchesLenOffset : allMatchesLenOffset+lostPartEndIdx+1] + } + } switch schemaType { + case OBJECT: + if !strings.HasPrefix(refType, "[]") { + return operation.parseObjectSchema(refType, astFile) + } refType = refType[2:] fallthrough + case ARRAY: + schema, err := operation.parseObjectSchema(refType, astFile) + if err != nil { + return nil, err + } return spec.ArrayProperty(schema), nil + default: + return PrimitiveSchema(schemaType), nil + } + } // ParseResponseComment parses comment for given `response` comment string. + func (operation *Operation) ParseResponseComment(commentLine string, astFile *ast.File) error { + matches := responsePattern.FindStringSubmatch(commentLine) + if len(matches) != 5 { + err := operation.ParseEmptyResponseComment(commentLine) + if err != nil { + return operation.ParseEmptyResponseOnly(commentLine) + } return err + } description := strings.Trim(matches[4], "\"") schema, err := operation.parseAPIObjectSchema(commentLine, strings.Trim(matches[2], "{}"), strings.TrimSpace(matches[3]), astFile) + if err != nil { + return err + } for _, codeStr := range strings.Split(matches[1], ",") { + if strings.EqualFold(codeStr, defaultTag) { + operation.DefaultResponse().WithSchema(schema).WithDescription(description) continue + } code, err := strconv.Atoi(codeStr) + if err != nil { + return fmt.Errorf("can not parse response comment \"%s\"", commentLine) + } resp := spec.NewResponse().WithSchema(schema).WithDescription(description) + if description == "" { + resp.WithDescription(http.StatusText(code)) + } operation.AddResponse(code, resp) + } return nil + } func newHeaderSpec(schemaType, description string) spec.Header { + return spec.Header{ + SimpleSchema: spec.SimpleSchema{ + Type: schemaType, }, + HeaderProps: spec.HeaderProps{ + Description: description, }, + VendorExtensible: spec.VendorExtensible{ + Extensions: nil, }, + CommonValidations: spec.CommonValidations{ - Maximum: nil, + + Maximum: nil, + ExclusiveMaximum: false, - Minimum: nil, + + Minimum: nil, + ExclusiveMinimum: false, - MaxLength: nil, - MinLength: nil, - Pattern: "", - MaxItems: nil, - MinItems: nil, - UniqueItems: false, - MultipleOf: nil, - Enum: nil, + + MaxLength: nil, + + MinLength: nil, + + Pattern: "", + + MaxItems: nil, + + MinItems: nil, + + UniqueItems: false, + + MultipleOf: nil, + + Enum: nil, }, } + } // ParseResponseHeaderComment parses comment for given `response header` comment string. + func (operation *Operation) ParseResponseHeaderComment(commentLine string, _ *ast.File) error { + matches := responsePattern.FindStringSubmatch(commentLine) + if len(matches) != 5 { + return fmt.Errorf("can not parse response comment \"%s\"", commentLine) + } header := newHeaderSpec(strings.Trim(matches[2], "{}"), strings.Trim(matches[4], "\"")) @@ -1064,182 +1738,282 @@ func (operation *Operation) ParseResponseHeaderComment(commentLine string, _ *as headerKey := strings.TrimSpace(matches[3]) if strings.EqualFold(matches[1], "all") { + if operation.Responses.Default != nil { + operation.Responses.Default.Headers[headerKey] = header + } if operation.Responses.StatusCodeResponses != nil { + for code, response := range operation.Responses.StatusCodeResponses { + response.Headers[headerKey] = header + operation.Responses.StatusCodeResponses[code] = response + } + } return nil + } for _, codeStr := range strings.Split(matches[1], ",") { + if strings.EqualFold(codeStr, defaultTag) { + if operation.Responses.Default != nil { + operation.Responses.Default.Headers[headerKey] = header + } continue + } code, err := strconv.Atoi(codeStr) + if err != nil { + return fmt.Errorf("can not parse response comment \"%s\"", commentLine) + } if operation.Responses.StatusCodeResponses != nil { + response, responseExist := operation.Responses.StatusCodeResponses[code] + if responseExist { + response.Headers[headerKey] = header operation.Responses.StatusCodeResponses[code] = response + } + } + } return nil + } var emptyResponsePattern = regexp.MustCompile(`([\w,]+)\s+"(.*)"`) // ParseEmptyResponseComment parse only comment out status code and description,eg: @Success 200 "it's ok". + func (operation *Operation) ParseEmptyResponseComment(commentLine string) error { + matches := emptyResponsePattern.FindStringSubmatch(commentLine) + if len(matches) != 3 { + return fmt.Errorf("can not parse response comment \"%s\"", commentLine) + } description := strings.Trim(matches[2], "\"") for _, codeStr := range strings.Split(matches[1], ",") { + if strings.EqualFold(codeStr, defaultTag) { + operation.DefaultResponse().WithDescription(description) continue + } code, err := strconv.Atoi(codeStr) + if err != nil { + return fmt.Errorf("can not parse response comment \"%s\"", commentLine) + } operation.AddResponse(code, spec.NewResponse().WithDescription(description)) + } return nil + } // ParseEmptyResponseOnly parse only comment out status code ,eg: @Success 200. + func (operation *Operation) ParseEmptyResponseOnly(commentLine string) error { + for _, codeStr := range strings.Split(commentLine, ",") { + if strings.EqualFold(codeStr, defaultTag) { + _ = operation.DefaultResponse() continue + } code, err := strconv.Atoi(codeStr) + if err != nil { + return fmt.Errorf("can not parse response comment \"%s\"", commentLine) + } operation.AddResponse(code, spec.NewResponse().WithDescription(http.StatusText(code))) + } return nil + } // DefaultResponse return the default response member pointer. + func (operation *Operation) DefaultResponse() *spec.Response { + if operation.Responses.Default == nil { + operation.Responses.Default = &spec.Response{ + ResponseProps: spec.ResponseProps{ + Description: "", - Headers: make(map[string]spec.Header), + + Headers: make(map[string]spec.Header), }, } + } return operation.Responses.Default + } // AddResponse add a response for a code. + func (operation *Operation) AddResponse(code int, response *spec.Response) { + if response.Headers == nil { + response.Headers = make(map[string]spec.Header) + } operation.Responses.StatusCodeResponses[code] = *response + } // createParameter returns swagger spec.Parameter for given paramType, description, paramName, schemaType, required. + func createParameter(paramType, description, paramName, objectType, schemaType string, required bool, enums []interface{}, collectionFormat string) spec.Parameter { + // //five possible parameter types. query, path, body, header, form + result := spec.Parameter{ + ParamProps: spec.ParamProps{ - Name: paramName, + + Name: paramName, + Description: description, - Required: required, - In: paramType, + + Required: required, + + In: paramType, }, } if paramType == "body" { + return result + } switch objectType { + case ARRAY: + result.Type = objectType + result.CollectionFormat = collectionFormat + result.Items = &spec.Items{ + CommonValidations: spec.CommonValidations{ + Enum: enums, }, + SimpleSchema: spec.SimpleSchema{ + Type: schemaType, }, } + case PRIMITIVE, OBJECT: + result.Type = schemaType + result.Enum = enums + } + return result + } func getCodeExampleForSummary(summaryName string, dirPath string) ([]byte, error) { + dirEntries, err := os.ReadDir(dirPath) + if err != nil { + return nil, err + } for _, entry := range dirEntries { + if entry.IsDir() { + continue + } fileName := entry.Name() if !strings.Contains(fileName, ".json") { + continue + } if strings.Contains(fileName, summaryName) { + fullPath := filepath.Join(dirPath, fileName) commentInfo, err := os.ReadFile(fullPath) + if err != nil { + return nil, fmt.Errorf("Failed to read code example file %s error: %s ", fullPath, err) + } return commentInfo, nil + } + } return nil, fmt.Errorf("unable to find code example file for tag %s in the given directory", summaryName) + } diff --git a/vendor/github.com/swaggo/swag/package.go b/vendor/github.com/swaggo/swag/package.go index 6c3129e..eab6eff 100644 --- a/vendor/github.com/swaggo/swag/package.go +++ b/vendor/github.com/swaggo/swag/package.go @@ -9,179 +9,326 @@ import ( ) // PackageDefinitions files and definition in a package. + type PackageDefinitions struct { + // files in this package, map key is file's relative path starting package path + Files map[string]*ast.File // definitions in this package, map key is typeName + TypeDefinitions map[string]*TypeSpecDef // const variables in this package, map key is the name + ConstTable map[string]*ConstVariable // const variables in order in this package + OrderedConst []*ConstVariable // package name + Name string // package path + Path string } // ConstVariableGlobalEvaluator an interface used to evaluate enums across packages + type ConstVariableGlobalEvaluator interface { EvaluateConstValue(pkg *PackageDefinitions, cv *ConstVariable, recursiveStack map[string]struct{}) (interface{}, ast.Expr) + EvaluateConstValueByName(file *ast.File, pkgPath, constVariableName string, recursiveStack map[string]struct{}) (interface{}, ast.Expr) + FindTypeSpec(typeName string, file *ast.File) *TypeSpecDef } // NewPackageDefinitions new a PackageDefinitions object + func NewPackageDefinitions(name, pkgPath string) *PackageDefinitions { + return &PackageDefinitions{ - Name: name, - Path: pkgPath, - Files: make(map[string]*ast.File), + + Name: name, + + Path: pkgPath, + + Files: make(map[string]*ast.File), + TypeDefinitions: make(map[string]*TypeSpecDef), - ConstTable: make(map[string]*ConstVariable), + + ConstTable: make(map[string]*ConstVariable), } + } // AddFile add a file + func (pkg *PackageDefinitions) AddFile(pkgPath string, file *ast.File) *PackageDefinitions { + pkg.Files[pkgPath] = file + return pkg + } // AddTypeSpec add a type spec. + func (pkg *PackageDefinitions) AddTypeSpec(name string, typeSpec *TypeSpecDef) *PackageDefinitions { + pkg.TypeDefinitions[name] = typeSpec + return pkg + } // AddConst add a const variable. + func (pkg *PackageDefinitions) AddConst(astFile *ast.File, valueSpec *ast.ValueSpec) *PackageDefinitions { + for i := 0; i < len(valueSpec.Names) && i < len(valueSpec.Values); i++ { + variable := &ConstVariable{ - Name: valueSpec.Names[i], - Type: valueSpec.Type, - Value: valueSpec.Values[i], + + Name: valueSpec.Names[i], + + Type: valueSpec.Type, + + Value: valueSpec.Values[i], + Comment: valueSpec.Comment, - File: astFile, + + File: astFile, } + pkg.ConstTable[valueSpec.Names[i].Name] = variable + pkg.OrderedConst = append(pkg.OrderedConst, variable) + } + return pkg + } func (pkg *PackageDefinitions) evaluateConstValue(file *ast.File, iota int, expr ast.Expr, globalEvaluator ConstVariableGlobalEvaluator, recursiveStack map[string]struct{}) (interface{}, ast.Expr) { + switch valueExpr := expr.(type) { + case *ast.Ident: + if valueExpr.Name == "iota" { + return iota, nil + } + if pkg.ConstTable != nil { + if cv, ok := pkg.ConstTable[valueExpr.Name]; ok { + return globalEvaluator.EvaluateConstValue(pkg, cv, recursiveStack) + } + } + case *ast.SelectorExpr: + pkgIdent, ok := valueExpr.X.(*ast.Ident) + if !ok { + return nil, nil + } + return globalEvaluator.EvaluateConstValueByName(file, pkgIdent.Name, valueExpr.Sel.Name, recursiveStack) + case *ast.BasicLit: + switch valueExpr.Kind { + case token.INT: + // handle underscored number, such as 1_000_000 + if strings.ContainsRune(valueExpr.Value, '_') { + valueExpr.Value = strings.Replace(valueExpr.Value, "_", "", -1) + } + if len(valueExpr.Value) >= 2 && valueExpr.Value[0] == '0' { + var start, base = 2, 8 + switch valueExpr.Value[1] { + case 'x', 'X': + //hex + base = 16 + case 'b', 'B': + //binary + base = 2 + default: + //octet + start = 1 + } + if x, err := strconv.ParseInt(valueExpr.Value[start:], base, 64); err == nil { + return int(x), nil + } else if x, err := strconv.ParseUint(valueExpr.Value[start:], base, 64); err == nil { + return x, nil + } else { + panic(err) + } + } //a basic literal integer is int type in default, or must have an explicit converting type in front + if x, err := strconv.ParseInt(valueExpr.Value, 10, 64); err == nil { + return int(x), nil + } else if x, err := strconv.ParseUint(valueExpr.Value, 10, 64); err == nil { + return x, nil + } else { + panic(err) + } + case token.STRING: + if valueExpr.Value[0] == '`' { + return valueExpr.Value[1 : len(valueExpr.Value)-1], nil + } + return EvaluateEscapedString(valueExpr.Value[1 : len(valueExpr.Value)-1]), nil + case token.CHAR: + return EvaluateEscapedChar(valueExpr.Value[1 : len(valueExpr.Value)-1]), nil + } + case *ast.UnaryExpr: + x, evalType := pkg.evaluateConstValue(file, iota, valueExpr.X, globalEvaluator, recursiveStack) + if x == nil { + return x, evalType + } + return EvaluateUnary(x, valueExpr.Op, evalType) + case *ast.BinaryExpr: + x, evalTypex := pkg.evaluateConstValue(file, iota, valueExpr.X, globalEvaluator, recursiveStack) + y, evalTypey := pkg.evaluateConstValue(file, iota, valueExpr.Y, globalEvaluator, recursiveStack) + if x == nil || y == nil { + return nil, nil + } + return EvaluateBinary(x, y, valueExpr.Op, evalTypex, evalTypey) + case *ast.ParenExpr: + return pkg.evaluateConstValue(file, iota, valueExpr.X, globalEvaluator, recursiveStack) + case *ast.CallExpr: + //data conversion + if len(valueExpr.Args) != 1 { + return nil, nil + } + arg := valueExpr.Args[0] + if ident, ok := valueExpr.Fun.(*ast.Ident); ok { + name := ident.Name + if name == "uintptr" { + name = "uint" + } + value, _ := pkg.evaluateConstValue(file, iota, arg, globalEvaluator, recursiveStack) + if IsGolangPrimitiveType(name) { + value = EvaluateDataConversion(value, name) + return value, nil + } else if name == "len" { + return reflect.ValueOf(value).Len(), nil + } + typeDef := globalEvaluator.FindTypeSpec(name, file) + if typeDef == nil { + return nil, nil + } + return value, valueExpr.Fun + } else if selector, ok := valueExpr.Fun.(*ast.SelectorExpr); ok { + typeDef := globalEvaluator.FindTypeSpec(fullTypeName(selector.X.(*ast.Ident).Name, selector.Sel.Name), file) + if typeDef == nil { + return nil, nil + } + return arg, typeDef.TypeSpec.Type + } + } + return nil, nil + } diff --git a/vendor/github.com/swaggo/swag/packages.go b/vendor/github.com/swaggo/swag/packages.go index 69a1b05..614797c 100644 --- a/vendor/github.com/swaggo/swag/packages.go +++ b/vendor/github.com/swaggo/swag/packages.go @@ -15,560 +15,979 @@ import ( ) // PackagesDefinitions map[package import path]*PackageDefinitions. + type PackagesDefinitions struct { - files map[*ast.File]*AstFileInfo - packages map[string]*PackageDefinitions + files map[*ast.File]*AstFileInfo + + packages map[string]*PackageDefinitions + uniqueDefinitions map[string]*TypeSpecDef - parseDependency ParseFlag - debug Debugger + + parseDependency ParseFlag + + debug Debugger } // NewPackagesDefinitions create object PackagesDefinitions. + func NewPackagesDefinitions() *PackagesDefinitions { + return &PackagesDefinitions{ - files: make(map[*ast.File]*AstFileInfo), - packages: make(map[string]*PackageDefinitions), + + files: make(map[*ast.File]*AstFileInfo), + + packages: make(map[string]*PackageDefinitions), + uniqueDefinitions: make(map[string]*TypeSpecDef), } + } // ParseFile parse a source file. + func (pkgDefs *PackagesDefinitions) ParseFile(packageDir, path string, src interface{}, flag ParseFlag) error { + // positions are relative to FileSet + fileSet := token.NewFileSet() + astFile, err := goparser.ParseFile(fileSet, path, src, goparser.ParseComments) + if err != nil { + return fmt.Errorf("failed to parse file %s, error:%+v", path, err) + } + return pkgDefs.collectAstFile(fileSet, packageDir, path, astFile, flag) + } // collectAstFile collect ast.file. + func (pkgDefs *PackagesDefinitions) collectAstFile(fileSet *token.FileSet, packageDir, path string, astFile *ast.File, flag ParseFlag) error { + if pkgDefs.files == nil { + pkgDefs.files = make(map[*ast.File]*AstFileInfo) + } if pkgDefs.packages == nil { + pkgDefs.packages = make(map[string]*PackageDefinitions) + } // return without storing the file if we lack a packageDir + if packageDir == "" { + return nil + } path, err := filepath.Abs(path) + if err != nil { + return err + } dependency, ok := pkgDefs.packages[packageDir] + if ok { + // return without storing the file if it already exists + _, exists := dependency.Files[path] + if exists { + return nil + } dependency.Files[path] = astFile + } else { + pkgDefs.packages[packageDir] = NewPackageDefinitions(astFile.Name.Name, packageDir).AddFile(path, astFile) + } pkgDefs.files[astFile] = &AstFileInfo{ - FileSet: fileSet, - File: astFile, - Path: path, + + FileSet: fileSet, + + File: astFile, + + Path: path, + PackagePath: packageDir, - ParseFlag: flag, + + ParseFlag: flag, } return nil + } // RangeFiles for range the collection of ast.File in alphabetic order. + func (pkgDefs *PackagesDefinitions) RangeFiles(handle func(info *AstFileInfo) error) error { + sortedFiles := make([]*AstFileInfo, 0, len(pkgDefs.files)) + for _, info := range pkgDefs.files { + // ignore package path prefix with 'vendor' or $GOROOT, + // because the router info of api will not be included these files. + if strings.HasPrefix(info.PackagePath, "vendor") || strings.HasPrefix(info.Path, runtime.GOROOT()) { + continue + } + sortedFiles = append(sortedFiles, info) + } sort.Slice(sortedFiles, func(i, j int) bool { + return strings.Compare(sortedFiles[i].Path, sortedFiles[j].Path) < 0 + }) for _, info := range sortedFiles { + err := handle(info) + if err != nil { + return err + } + } return nil + } // ParseTypes parse types + // @Return parsed definitions. + func (pkgDefs *PackagesDefinitions) ParseTypes() (map[*TypeSpecDef]*Schema, error) { + parsedSchemas := make(map[*TypeSpecDef]*Schema) + for astFile, info := range pkgDefs.files { + pkgDefs.parseTypesFromFile(astFile, info.PackagePath, parsedSchemas) + pkgDefs.parseFunctionScopedTypesFromFile(astFile, info.PackagePath, parsedSchemas) + } + pkgDefs.removeAllNotUniqueTypes() + pkgDefs.evaluateAllConstVariables() + pkgDefs.collectConstEnums(parsedSchemas) + return parsedSchemas, nil + } func (pkgDefs *PackagesDefinitions) parseTypesFromFile(astFile *ast.File, packagePath string, parsedSchemas map[*TypeSpecDef]*Schema) { + for _, astDeclaration := range astFile.Decls { + generalDeclaration, ok := astDeclaration.(*ast.GenDecl) + if !ok { + continue + } + if generalDeclaration.Tok == token.TYPE { + for _, astSpec := range generalDeclaration.Specs { + if typeSpec, ok := astSpec.(*ast.TypeSpec); ok { + typeSpecDef := &TypeSpecDef{ - PkgPath: packagePath, - File: astFile, + + PkgPath: packagePath, + + File: astFile, + TypeSpec: typeSpec, } if idt, ok := typeSpec.Type.(*ast.Ident); ok && IsGolangPrimitiveType(idt.Name) && parsedSchemas != nil { + parsedSchemas[typeSpecDef] = &Schema{ + PkgPath: typeSpecDef.PkgPath, - Name: astFile.Name.Name, - Schema: PrimitiveSchema(TransToValidSchemeType(idt.Name)), + + Name: astFile.Name.Name, + + Schema: PrimitiveSchema(TransToValidSchemeType(idt.Name)), } + } if pkgDefs.uniqueDefinitions == nil { + pkgDefs.uniqueDefinitions = make(map[string]*TypeSpecDef) + } fullName := typeSpecDef.TypeName() anotherTypeDef, ok := pkgDefs.uniqueDefinitions[fullName] + if ok { + if anotherTypeDef == nil { + typeSpecDef.NotUnique = true + fullName = typeSpecDef.TypeName() + pkgDefs.uniqueDefinitions[fullName] = typeSpecDef + } else if typeSpecDef.PkgPath != anotherTypeDef.PkgPath { + pkgDefs.uniqueDefinitions[fullName] = nil + anotherTypeDef.NotUnique = true + pkgDefs.uniqueDefinitions[anotherTypeDef.TypeName()] = anotherTypeDef + typeSpecDef.NotUnique = true + fullName = typeSpecDef.TypeName() + pkgDefs.uniqueDefinitions[fullName] = typeSpecDef + } + } else { + pkgDefs.uniqueDefinitions[fullName] = typeSpecDef + } if pkgDefs.packages[typeSpecDef.PkgPath] == nil { + pkgDefs.packages[typeSpecDef.PkgPath] = NewPackageDefinitions(astFile.Name.Name, typeSpecDef.PkgPath).AddTypeSpec(typeSpecDef.Name(), typeSpecDef) + } else if _, ok = pkgDefs.packages[typeSpecDef.PkgPath].TypeDefinitions[typeSpecDef.Name()]; !ok { + pkgDefs.packages[typeSpecDef.PkgPath].AddTypeSpec(typeSpecDef.Name(), typeSpecDef) + } + } + } + } else if generalDeclaration.Tok == token.CONST { + // collect consts + pkgDefs.collectConstVariables(astFile, packagePath, generalDeclaration) + } + } + } func (pkgDefs *PackagesDefinitions) parseFunctionScopedTypesFromFile(astFile *ast.File, packagePath string, parsedSchemas map[*TypeSpecDef]*Schema) { + for _, astDeclaration := range astFile.Decls { + funcDeclaration, ok := astDeclaration.(*ast.FuncDecl) + if ok && funcDeclaration.Body != nil { + for _, stmt := range funcDeclaration.Body.List { + if declStmt, ok := (stmt).(*ast.DeclStmt); ok { + if genDecl, ok := (declStmt.Decl).(*ast.GenDecl); ok && genDecl.Tok == token.TYPE { + for _, astSpec := range genDecl.Specs { + if typeSpec, ok := astSpec.(*ast.TypeSpec); ok { + typeSpecDef := &TypeSpecDef{ - PkgPath: packagePath, - File: astFile, - TypeSpec: typeSpec, + + PkgPath: packagePath, + + File: astFile, + + TypeSpec: typeSpec, + ParentSpec: astDeclaration, } if idt, ok := typeSpec.Type.(*ast.Ident); ok && IsGolangPrimitiveType(idt.Name) && parsedSchemas != nil { + parsedSchemas[typeSpecDef] = &Schema{ + PkgPath: typeSpecDef.PkgPath, - Name: astFile.Name.Name, - Schema: PrimitiveSchema(TransToValidSchemeType(idt.Name)), + + Name: astFile.Name.Name, + + Schema: PrimitiveSchema(TransToValidSchemeType(idt.Name)), } + } if pkgDefs.uniqueDefinitions == nil { + pkgDefs.uniqueDefinitions = make(map[string]*TypeSpecDef) + } fullName := typeSpecDef.TypeName() anotherTypeDef, ok := pkgDefs.uniqueDefinitions[fullName] + if ok { + if anotherTypeDef == nil { + typeSpecDef.NotUnique = true + fullName = typeSpecDef.TypeName() + pkgDefs.uniqueDefinitions[fullName] = typeSpecDef + } else if typeSpecDef.PkgPath != anotherTypeDef.PkgPath { + pkgDefs.uniqueDefinitions[fullName] = nil + anotherTypeDef.NotUnique = true + pkgDefs.uniqueDefinitions[anotherTypeDef.TypeName()] = anotherTypeDef + typeSpecDef.NotUnique = true + fullName = typeSpecDef.TypeName() + pkgDefs.uniqueDefinitions[fullName] = typeSpecDef + } + } else { + pkgDefs.uniqueDefinitions[fullName] = typeSpecDef + } if pkgDefs.packages[typeSpecDef.PkgPath] == nil { + pkgDefs.packages[typeSpecDef.PkgPath] = NewPackageDefinitions(astFile.Name.Name, typeSpecDef.PkgPath).AddTypeSpec(fullName, typeSpecDef) + } else if _, ok = pkgDefs.packages[typeSpecDef.PkgPath].TypeDefinitions[fullName]; !ok { + pkgDefs.packages[typeSpecDef.PkgPath].AddTypeSpec(fullName, typeSpecDef) + } + } + } } + } + } + } + } + } func (pkgDefs *PackagesDefinitions) collectConstVariables(astFile *ast.File, packagePath string, generalDeclaration *ast.GenDecl) { + pkg, ok := pkgDefs.packages[packagePath] + if !ok { + pkg = NewPackageDefinitions(astFile.Name.Name, packagePath) + pkgDefs.packages[packagePath] = pkg + } var lastValueSpec *ast.ValueSpec + for _, astSpec := range generalDeclaration.Specs { + valueSpec, ok := astSpec.(*ast.ValueSpec) + if !ok { + continue + } + if len(valueSpec.Names) == 1 && len(valueSpec.Values) == 1 { + lastValueSpec = valueSpec + } else if len(valueSpec.Names) == 1 && len(valueSpec.Values) == 0 && valueSpec.Type == nil && lastValueSpec != nil { + valueSpec.Type = lastValueSpec.Type + valueSpec.Values = lastValueSpec.Values + } + pkg.AddConst(astFile, valueSpec) + } + } func (pkgDefs *PackagesDefinitions) evaluateAllConstVariables() { + for _, pkg := range pkgDefs.packages { + for _, constVar := range pkg.OrderedConst { + pkgDefs.EvaluateConstValue(pkg, constVar, nil) + } + } + } // EvaluateConstValue evaluate a const variable. + func (pkgDefs *PackagesDefinitions) EvaluateConstValue(pkg *PackageDefinitions, cv *ConstVariable, recursiveStack map[string]struct{}) (interface{}, ast.Expr) { + if expr, ok := cv.Value.(ast.Expr); ok { + defer func() { + if err := recover(); err != nil { + if fi, ok := pkgDefs.files[cv.File]; ok { + pos := fi.FileSet.Position(cv.Name.NamePos) + pkgDefs.debug.Printf("warning: failed to evaluate const %s at %s:%d:%d, %v", cv.Name.Name, fi.Path, pos.Line, pos.Column, err) + } + } + }() + if recursiveStack == nil { + recursiveStack = make(map[string]struct{}) + } + fullConstName := fullTypeName(pkg.Path, cv.Name.Name) + if _, ok = recursiveStack[fullConstName]; ok { + return nil, nil + } + recursiveStack[fullConstName] = struct{}{} value, evalType := pkg.evaluateConstValue(cv.File, cv.Name.Obj.Data.(int), expr, pkgDefs, recursiveStack) + if cv.Type == nil && evalType != nil { + cv.Type = evalType + } + if value != nil { + cv.Value = value + } + return value, cv.Type + } + return cv.Value, cv.Type + } // EvaluateConstValueByName evaluate a const variable by name. + func (pkgDefs *PackagesDefinitions) EvaluateConstValueByName(file *ast.File, pkgName, constVariableName string, recursiveStack map[string]struct{}) (interface{}, ast.Expr) { + matchedPkgPaths, externalPkgPaths := pkgDefs.findPackagePathFromImports(pkgName, file) + for _, pkgPath := range matchedPkgPaths { + if pkg, ok := pkgDefs.packages[pkgPath]; ok { + if cv, ok := pkg.ConstTable[constVariableName]; ok { + return pkgDefs.EvaluateConstValue(pkg, cv, recursiveStack) + } + } + } + if pkgDefs.parseDependency > 0 { + for _, pkgPath := range externalPkgPaths { + if err := pkgDefs.loadExternalPackage(pkgPath); err == nil { + if pkg, ok := pkgDefs.packages[pkgPath]; ok { + if cv, ok := pkg.ConstTable[constVariableName]; ok { + return pkgDefs.EvaluateConstValue(pkg, cv, recursiveStack) + } + } + } + } + } + return nil, nil + } func (pkgDefs *PackagesDefinitions) collectConstEnums(parsedSchemas map[*TypeSpecDef]*Schema) { + for _, pkg := range pkgDefs.packages { + for _, constVar := range pkg.OrderedConst { + if constVar.Type == nil { + continue + } + ident, ok := constVar.Type.(*ast.Ident) + if !ok || IsGolangPrimitiveType(ident.Name) { + continue + } + typeDef, ok := pkg.TypeDefinitions[ident.Name] + if !ok { + continue + } //delete it from parsed schemas, and will parse it again + if _, ok = parsedSchemas[typeDef]; ok { + delete(parsedSchemas, typeDef) + } if typeDef.Enums == nil { + typeDef.Enums = make([]EnumValue, 0) + } name := constVar.Name.Name + if _, ok = constVar.Value.(ast.Expr); ok { + continue + } enumValue := EnumValue{ - key: name, + + key: name, + Value: constVar.Value, } + if constVar.Comment != nil && len(constVar.Comment.List) > 0 { + enumValue.Comment = constVar.Comment.List[0].Text + enumValue.Comment = strings.TrimPrefix(enumValue.Comment, "//") + enumValue.Comment = strings.TrimPrefix(enumValue.Comment, "/*") + enumValue.Comment = strings.TrimSuffix(enumValue.Comment, "*/") + enumValue.Comment = strings.TrimSpace(enumValue.Comment) + } + typeDef.Enums = append(typeDef.Enums, enumValue) + } + } + } func (pkgDefs *PackagesDefinitions) removeAllNotUniqueTypes() { + for key, ud := range pkgDefs.uniqueDefinitions { + if ud == nil { + delete(pkgDefs.uniqueDefinitions, key) + } + } + } func (pkgDefs *PackagesDefinitions) findTypeSpec(pkgPath string, typeName string) *TypeSpecDef { + if pkgDefs.packages == nil { + return nil + } pd, found := pkgDefs.packages[pkgPath] + if found { + typeSpec, ok := pd.TypeDefinitions[typeName] + if ok { + return typeSpec + } + } return nil + } func (pkgDefs *PackagesDefinitions) loadExternalPackage(importPath string) error { + cwd, err := os.Getwd() + if err != nil { + return err + } conf := loader.Config{ + ParserMode: goparser.ParseComments, - Cwd: cwd, + + Cwd: cwd, } conf.Import(importPath) loaderProgram, err := conf.Load() + if err != nil { + return err + } for _, info := range loaderProgram.AllPackages { + pkgPath := strings.TrimPrefix(info.Pkg.Path(), "vendor/") + for _, astFile := range info.Files { + pkgDefs.parseTypesFromFile(astFile, pkgPath, nil) + } + } return nil + } // findPackagePathFromImports finds out the package path of a package via ranging imports of an ast.File + // @pkg the name of the target package + // @file current ast.File in which to search imports + // @return the package paths of a package of @pkg. + func (pkgDefs *PackagesDefinitions) findPackagePathFromImports(pkg string, file *ast.File) (matchedPkgPaths, externalPkgPaths []string) { + if file == nil { + return + } if strings.ContainsRune(pkg, '.') { + pkg = strings.Split(pkg, ".")[0] + } matchLastPathPart := func(pkgPath string) bool { + paths := strings.Split(pkgPath, "/") + return paths[len(paths)-1] == pkg + } // prior to match named package + for _, imp := range file.Imports { + path := strings.Trim(imp.Path.Value, `"`) + if imp.Name != nil { + if imp.Name.Name == pkg { + // if name match, break loop and return + _, ok := pkgDefs.packages[path] + if ok { + matchedPkgPaths = []string{path} + externalPkgPaths = nil + } else { + externalPkgPaths = []string{path} + matchedPkgPaths = nil + } + break + } else if imp.Name.Name == "_" && len(pkg) > 0 { + //for unused types + pd, ok := pkgDefs.packages[path] + if ok { + if pd.Name == pkg { + matchedPkgPaths = append(matchedPkgPaths, path) + } + } else if matchLastPathPart(path) { + externalPkgPaths = append(externalPkgPaths, path) + } + } else if imp.Name.Name == "." && len(pkg) == 0 { + _, ok := pkgDefs.packages[path] + if ok { + matchedPkgPaths = append(matchedPkgPaths, path) + } else if len(pkg) == 0 || matchLastPathPart(path) { + externalPkgPaths = append(externalPkgPaths, path) + } + } + } else if pkgDefs.packages != nil && len(pkg) > 0 { + pd, ok := pkgDefs.packages[path] + if ok { + if pd.Name == pkg { + matchedPkgPaths = append(matchedPkgPaths, path) + } + } else if matchLastPathPart(path) { + externalPkgPaths = append(externalPkgPaths, path) + } + } + } if len(pkg) == 0 || file.Name.Name == pkg { + matchedPkgPaths = append(matchedPkgPaths, pkgDefs.files[file].PackagePath) + } return + } func (pkgDefs *PackagesDefinitions) findTypeSpecFromPackagePaths(matchedPkgPaths, externalPkgPaths []string, name string) (typeDef *TypeSpecDef) { + if pkgDefs.parseDependency > 0 { + for _, pkgPath := range externalPkgPaths { + if err := pkgDefs.loadExternalPackage(pkgPath); err == nil { + typeDef = pkgDefs.findTypeSpec(pkgPath, name) + if typeDef != nil { + return typeDef + } + } + } + } for _, pkgPath := range matchedPkgPaths { + typeDef = pkgDefs.findTypeSpec(pkgPath, name) + if typeDef != nil { + return typeDef + } + } return typeDef + } // FindTypeSpec finds out TypeSpecDef of a type by typeName + // @typeName the name of the target type, if it starts with a package name, find its own package path from imports on top of @file + // @file the ast.file in which @typeName is used + // @pkgPath the package path of @file. + func (pkgDefs *PackagesDefinitions) FindTypeSpec(typeName string, file *ast.File) *TypeSpecDef { + if IsGolangPrimitiveType(typeName) { + return nil + } if file == nil { // for test + return pkgDefs.uniqueDefinitions[typeName] + } parts := strings.Split(strings.Split(typeName, "[")[0], ".") + if len(parts) > 1 { + pkgPaths, externalPkgPaths := pkgDefs.findPackagePathFromImports(parts[0], file) + if len(externalPkgPaths) == 0 || pkgDefs.parseDependency == ParseNone { + typeDef, ok := pkgDefs.uniqueDefinitions[typeName] + if ok { + return typeDef + } + } + typeDef := pkgDefs.findTypeSpecFromPackagePaths(pkgPaths, externalPkgPaths, parts[1]) + return pkgDefs.parametrizeGenericType(file, typeDef, typeName) + } typeDef, ok := pkgDefs.uniqueDefinitions[fullTypeName(file.Name.Name, typeName)] + if ok { + return typeDef + } //in case that comment //@name renamed the type with a name without a dot + typeDef, ok = pkgDefs.uniqueDefinitions[typeName] + if ok { + return typeDef + } name := parts[0] + typeDef, ok = pkgDefs.uniqueDefinitions[fullTypeName(file.Name.Name, name)] + if !ok { + pkgPaths, externalPkgPaths := pkgDefs.findPackagePathFromImports("", file) + typeDef = pkgDefs.findTypeSpecFromPackagePaths(pkgPaths, externalPkgPaths, name) + } + return pkgDefs.parametrizeGenericType(file, typeDef, typeName) + } diff --git a/vendor/github.com/swaggo/swag/parser.go b/vendor/github.com/swaggo/swag/parser.go index 604f827..fc8865e 100644 --- a/vendor/github.com/swaggo/swag/parser.go +++ b/vendor/github.com/swaggo/swag/parser.go @@ -24,458 +24,747 @@ import ( ) const ( + // CamelCase indicates using CamelCase strategy for struct field. + CamelCase = "camelcase" // PascalCase indicates using PascalCase strategy for struct field. + PascalCase = "pascalcase" // SnakeCase indicates using SnakeCase strategy for struct field. + SnakeCase = "snakecase" - idAttr = "@id" - acceptAttr = "@accept" - produceAttr = "@produce" - paramAttr = "@param" - successAttr = "@success" - failureAttr = "@failure" - responseAttr = "@response" - headerAttr = "@header" - tagsAttr = "@tags" - routerAttr = "@router" - deprecatedRouterAttr = "@deprecatedrouter" - summaryAttr = "@summary" - deprecatedAttr = "@deprecated" - securityAttr = "@security" - titleAttr = "@title" - conNameAttr = "@contact.name" - conURLAttr = "@contact.url" - conEmailAttr = "@contact.email" - licNameAttr = "@license.name" - licURLAttr = "@license.url" - versionAttr = "@version" - descriptionAttr = "@description" + idAttr = "@id" + + acceptAttr = "@accept" + + produceAttr = "@produce" + + paramAttr = "@param" + + successAttr = "@success" + + failureAttr = "@failure" + + responseAttr = "@response" + + headerAttr = "@header" + + tagsAttr = "@tags" + + routerAttr = "@router" + + deprecatedRouterAttr = "@deprecatedrouter" + + summaryAttr = "@summary" + + deprecatedAttr = "@deprecated" + + securityAttr = "@security" + + titleAttr = "@title" + + conNameAttr = "@contact.name" + + conURLAttr = "@contact.url" + + conEmailAttr = "@contact.email" + + licNameAttr = "@license.name" + + licURLAttr = "@license.url" + + versionAttr = "@version" + + descriptionAttr = "@description" + descriptionMarkdownAttr = "@description.markdown" - secBasicAttr = "@securitydefinitions.basic" - secAPIKeyAttr = "@securitydefinitions.apikey" - secApplicationAttr = "@securitydefinitions.oauth2.application" - secImplicitAttr = "@securitydefinitions.oauth2.implicit" - secPasswordAttr = "@securitydefinitions.oauth2.password" - secAccessCodeAttr = "@securitydefinitions.oauth2.accesscode" - tosAttr = "@termsofservice" - extDocsDescAttr = "@externaldocs.description" - extDocsURLAttr = "@externaldocs.url" - xCodeSamplesAttr = "@x-codesamples" - scopeAttrPrefix = "@scope." - stateAttr = "@state" + + secBasicAttr = "@securitydefinitions.basic" + + secAPIKeyAttr = "@securitydefinitions.apikey" + + secApplicationAttr = "@securitydefinitions.oauth2.application" + + secImplicitAttr = "@securitydefinitions.oauth2.implicit" + + secPasswordAttr = "@securitydefinitions.oauth2.password" + + secAccessCodeAttr = "@securitydefinitions.oauth2.accesscode" + + tosAttr = "@termsofservice" + + extDocsDescAttr = "@externaldocs.description" + + extDocsURLAttr = "@externaldocs.url" + + xCodeSamplesAttr = "@x-codesamples" + + scopeAttrPrefix = "@scope." + + stateAttr = "@state" ) // ParseFlag determine what to parse + type ParseFlag int const ( + // ParseNone parse nothing + ParseNone ParseFlag = 0x00 + // ParseModels parse models + ParseModels = 0x01 + // ParseOperations parse operations + ParseOperations = 0x02 + // ParseAll parse operations and models + ParseAll = ParseOperations | ParseModels ) var ( + // ErrRecursiveParseStruct recursively parsing struct. + ErrRecursiveParseStruct = errors.New("recursively parsing struct") // ErrFuncTypeField field type is func. + ErrFuncTypeField = errors.New("field type is func") // ErrFailedConvertPrimitiveType Failed to convert for swag to interpretable type. + ErrFailedConvertPrimitiveType = errors.New("swag property: failed convert primitive type") // ErrSkippedField .swaggo specifies field should be skipped. + ErrSkippedField = errors.New("field is skipped by global overrides") ) var allMethod = map[string]struct{}{ - http.MethodGet: {}, - http.MethodPut: {}, - http.MethodPost: {}, - http.MethodDelete: {}, + + http.MethodGet: {}, + + http.MethodPut: {}, + + http.MethodPost: {}, + + http.MethodDelete: {}, + http.MethodOptions: {}, - http.MethodHead: {}, - http.MethodPatch: {}, + + http.MethodHead: {}, + + http.MethodPatch: {}, } // Parser implements a parser for Go source files. + type Parser struct { + // swagger represents the root document object for the API specification + swagger *spec.Swagger // packages store entities of APIs, definitions, file, package path etc. and their relations + packages *PackagesDefinitions // parsedSchemas store schemas which have been parsed from ast.TypeSpec + parsedSchemas map[*TypeSpecDef]*Schema // outputSchemas store schemas which will be export to swagger + outputSchemas map[*TypeSpecDef]*Schema // PropNamingStrategy naming strategy + PropNamingStrategy string // ParseVendor parse vendor folder + ParseVendor bool // ParseDependencies whether swag should be parse outside dependency folder: 0 none, 1 models, 2 operations, 3 all + ParseDependency ParseFlag // ParseInternal whether swag should parse internal packages + ParseInternal bool // Strict whether swag should error or warn when it detects cases which are most likely user errors + Strict bool // RequiredByDefault set validation required for all fields by default + RequiredByDefault bool // structStack stores full names of the structures that were already parsed or are being parsed now + structStack []*TypeSpecDef // markdownFileDir holds the path to the folder, where markdown files are stored + markdownFileDir string // codeExampleFilesDir holds path to the folder, where code example files are stored + codeExampleFilesDir string // collectionFormatInQuery set the default collectionFormat otherwise then 'csv' for array in query params + collectionFormatInQuery string // excludes excludes dirs and files in SearchDir + excludes map[string]struct{} // packagePrefix is a list of package path prefixes, packages that do not + // match any one of them will be excluded when searching. + packagePrefix []string // tells parser to include only specific extension + parseExtension string // debugging output goes here + debug Debugger // fieldParserFactory create FieldParser + fieldParserFactory FieldParserFactory // Overrides allows global replacements of types. A blank replacement will be skipped. + Overrides map[string]string // parseGoList whether swag use go list to parse dependency + parseGoList bool // tags to filter the APIs after + tags map[string]struct{} // HostState is the state of the host + HostState string } // FieldParserFactory create FieldParser. + type FieldParserFactory func(ps *Parser, field *ast.Field) FieldParser // FieldParser parse struct field. + type FieldParser interface { ShouldSkip() bool + FieldName() (string, error) + FormName() string + HeaderName() string + PathName() string + CustomSchema() (*spec.Schema, error) + ComplementSchema(schema *spec.Schema) error + IsRequired() (bool, error) } // Debugger is the interface that wraps the basic Printf method. + type Debugger interface { Printf(format string, v ...interface{}) } // New creates a new Parser with default properties. + func New(options ...func(*Parser)) *Parser { + parser := &Parser{ + swagger: &spec.Swagger{ + SwaggerProps: spec.SwaggerProps{ + Info: &spec.Info{ + InfoProps: spec.InfoProps{ + Contact: &spec.ContactInfo{}, + License: nil, }, + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{}, }, }, + Paths: &spec.Paths{ + Paths: make(map[string]spec.PathItem), + VendorExtensible: spec.VendorExtensible{ + Extensions: nil, }, }, - Definitions: make(map[string]spec.Schema), + + Definitions: make(map[string]spec.Schema), + SecurityDefinitions: make(map[string]*spec.SecurityScheme), }, + VendorExtensible: spec.VendorExtensible{ + Extensions: nil, }, }, - packages: NewPackagesDefinitions(), - debug: log.New(os.Stdout, "", log.LstdFlags), - parsedSchemas: make(map[*TypeSpecDef]*Schema), - outputSchemas: make(map[*TypeSpecDef]*Schema), - excludes: make(map[string]struct{}), - tags: make(map[string]struct{}), + + packages: NewPackagesDefinitions(), + + debug: log.New(os.Stdout, "", log.LstdFlags), + + parsedSchemas: make(map[*TypeSpecDef]*Schema), + + outputSchemas: make(map[*TypeSpecDef]*Schema), + + excludes: make(map[string]struct{}), + + tags: make(map[string]struct{}), + fieldParserFactory: newTagBaseFieldParser, - Overrides: make(map[string]string), + + Overrides: make(map[string]string), } for _, option := range options { + option(parser) + } parser.packages.debug = parser.debug return parser + } // SetParseDependency sets whether to parse the dependent packages. + func SetParseDependency(parseDependency int) func(*Parser) { + return func(p *Parser) { + p.ParseDependency = ParseFlag(parseDependency) + if p.packages != nil { + p.packages.parseDependency = p.ParseDependency + } + } + } // SetMarkdownFileDirectory sets the directory to search for markdown files. + func SetMarkdownFileDirectory(directoryPath string) func(*Parser) { + return func(p *Parser) { + p.markdownFileDir = directoryPath + } + } // SetCodeExamplesDirectory sets the directory to search for code example files. + func SetCodeExamplesDirectory(directoryPath string) func(*Parser) { + return func(p *Parser) { + p.codeExampleFilesDir = directoryPath + } + } // SetExcludedDirsAndFiles sets directories and files to be excluded when searching. + func SetExcludedDirsAndFiles(excludes string) func(*Parser) { + return func(p *Parser) { + for _, f := range strings.Split(excludes, ",") { + f = strings.TrimSpace(f) + if f != "" { + f = filepath.Clean(f) + p.excludes[f] = struct{}{} + } + } + } + } // SetPackagePrefix sets a list of package path prefixes from a comma-separated + // string, packages that do not match any one of them will be excluded when + // searching. + func SetPackagePrefix(packagePrefix string) func(*Parser) { + return func(p *Parser) { + for _, f := range strings.Split(packagePrefix, ",") { + f = strings.TrimSpace(f) + if f != "" { + p.packagePrefix = append(p.packagePrefix, f) + } + } + } + } // SetTags sets the tags to be included + func SetTags(include string) func(*Parser) { + return func(p *Parser) { + for _, f := range strings.Split(include, ",") { + f = strings.TrimSpace(f) + if f != "" { + p.tags[f] = struct{}{} + } + } + } + } // SetParseExtension parses only those operations which match given extension + func SetParseExtension(parseExtension string) func(*Parser) { + return func(p *Parser) { + p.parseExtension = parseExtension + } + } // SetStrict sets whether swag should error or warn when it detects cases which are most likely user errors. + func SetStrict(strict bool) func(*Parser) { + return func(p *Parser) { + p.Strict = strict + } + } // SetDebugger allows the use of user-defined implementations. + func SetDebugger(logger Debugger) func(parser *Parser) { + return func(p *Parser) { + if logger != nil { + p.debug = logger + } + } + } // SetFieldParserFactory allows the use of user-defined implementations. + func SetFieldParserFactory(factory FieldParserFactory) func(parser *Parser) { + return func(p *Parser) { + p.fieldParserFactory = factory + } + } // SetOverrides allows the use of user-defined global type overrides. + func SetOverrides(overrides map[string]string) func(parser *Parser) { + return func(p *Parser) { + for k, v := range overrides { + p.Overrides[k] = v + } + } + } // SetCollectionFormat set default collection format + func SetCollectionFormat(collectionFormat string) func(*Parser) { + return func(p *Parser) { + p.collectionFormatInQuery = collectionFormat + } + } // ParseUsingGoList sets whether swag use go list to parse dependency + func ParseUsingGoList(enabled bool) func(parser *Parser) { + return func(p *Parser) { + p.parseGoList = enabled + } + } // ParseAPI parses general api info for given searchDir and mainAPIFile. + func (parser *Parser) ParseAPI(searchDir string, mainAPIFile string, parseDepth int) error { + return parser.ParseAPIMultiSearchDir([]string{searchDir}, mainAPIFile, parseDepth) + } // skipPackageByPrefix returns true the given pkgpath does not match + // any user-defined package path prefixes. + func (parser *Parser) skipPackageByPrefix(pkgpath string) bool { + if len(parser.packagePrefix) == 0 { + return false + } + for _, prefix := range parser.packagePrefix { + if strings.HasPrefix(pkgpath, prefix) { + return false + } + } + return true + } // ParseAPIMultiSearchDir is like ParseAPI but for multiple search dirs. + func (parser *Parser) ParseAPIMultiSearchDir(searchDirs []string, mainAPIFile string, parseDepth int) error { + for _, searchDir := range searchDirs { + parser.debug.Printf("Generate general API Info, search dir:%s", searchDir) packageDir, err := getPkgName(searchDir) + if err != nil { + parser.debug.Printf("warning: failed to get package name in dir: %s, error: %s", searchDir, err.Error()) + } err = parser.getAllGoFileInfo(packageDir, searchDir) + if err != nil { + return err + } + } absMainAPIFilePath, err := filepath.Abs(filepath.Join(searchDirs[0], mainAPIFile)) + if err != nil { + return err + } // Use 'go list' command instead of depth.Resolve() + if parser.ParseDependency > 0 { + if parser.parseGoList { + pkgs, err := listPackages(context.Background(), filepath.Dir(absMainAPIFilePath), nil, "-deps") + if err != nil { + return fmt.Errorf("pkg %s cannot find all dependencies, %s", filepath.Dir(absMainAPIFilePath), err) + } length := len(pkgs) + for i := 0; i < length; i++ { + err := parser.getAllGoFileInfoFromDepsByList(pkgs[i], parser.ParseDependency) + if err != nil { + return err + } + } + } else { + var t depth.Tree + t.ResolveInternal = true + t.MaxDepth = parseDepth pkgName, err := getPkgName(filepath.Dir(absMainAPIFilePath)) + if err != nil { + return err + } err = t.Resolve(pkgName) + if err != nil { + return fmt.Errorf("pkg %s cannot find all dependencies, %s", pkgName, err) + } + for i := 0; i < len(t.Root.Deps); i++ { + err := parser.getAllGoFileInfoFromDeps(&t.Root.Deps[i], parser.ParseDependency) + if err != nil { + return err + } + } + } + } err = parser.ParseGeneralAPIInfo(absMainAPIFilePath) + if err != nil { + return err + } parser.parsedSchemas, err = parser.packages.ParseTypes() + if err != nil { + return err + } err = parser.packages.RangeFiles(parser.ParseRouterAPIInfo) + if err != nil { + return err + } return parser.checkOperationIDUniqueness() + } func getPkgName(searchDir string) (string, error) { + cmd := exec.Command("go", "list", "-f={{.ImportPath}}") + cmd.Dir = searchDir var stdout, stderr strings.Builder cmd.Stdout = &stdout + cmd.Stderr = &stderr if err := cmd.Run(); err != nil { + return "", fmt.Errorf("execute go list command, %s, stdout:%s, stderr:%s", err, stdout.String(), stderr.String()) + } outStr, _ := stdout.String(), stderr.String() if outStr[0] == '_' { // will shown like _/{GOPATH}/src/{YOUR_PACKAGE} when NOT enable GO MODULE. + outStr = strings.TrimPrefix(outStr, "_"+build.Default.GOPATH+"/src/") + } f := strings.Split(outStr, "\n") @@ -483,748 +772,1229 @@ func getPkgName(searchDir string) (string, error) { outStr = f[0] return outStr, nil + } // ParseGeneralAPIInfo parses general api info for given mainAPIFile path. + func (parser *Parser) ParseGeneralAPIInfo(mainAPIFile string) error { + fileTree, err := goparser.ParseFile(token.NewFileSet(), mainAPIFile, nil, goparser.ParseComments) + if err != nil { + return fmt.Errorf("cannot parse source files %s: %s", mainAPIFile, err) + } parser.swagger.Swagger = "2.0" for _, comment := range fileTree.Comments { + comments := strings.Split(comment.Text(), "\n") + if !isGeneralAPIComment(comments) { + continue + } err = parseGeneralAPIInfo(parser, comments) + if err != nil { + return err + } + } return nil + } func parseGeneralAPIInfo(parser *Parser, comments []string) error { + previousAttribute := "" // parsing classic meta data model + for line := 0; line < len(comments); line++ { + commentLine := comments[line] + commentLine = strings.TrimSpace(commentLine) + if len(commentLine) == 0 { + continue + } + fields := FieldsByAnySpace(commentLine, 2) attribute := fields[0] + var value string + if len(fields) > 1 { + value = fields[1] + } switch attr := strings.ToLower(attribute); attr { + case versionAttr, titleAttr, tosAttr, licNameAttr, licURLAttr, conNameAttr, conURLAttr, conEmailAttr: + setSwaggerInfo(parser.swagger, attr, value) + case descriptionAttr: + if previousAttribute == attribute { + parser.swagger.Info.Description += "\n" + value continue + } setSwaggerInfo(parser.swagger, attr, value) + case descriptionMarkdownAttr: + commentInfo, err := getMarkdownForTag("api", parser.markdownFileDir) + if err != nil { + return err + } setSwaggerInfo(parser.swagger, descriptionAttr, string(commentInfo)) case "@host": + parser.swagger.Host = value + case "@hoststate": + fields = FieldsByAnySpace(commentLine, 3) + if len(fields) != 3 { + return fmt.Errorf("%s needs 3 arguments", attribute) + } + if parser.HostState == fields[1] { + parser.swagger.Host = fields[2] + } + case "@basepath": + parser.swagger.BasePath = value case acceptAttr: + err := parser.ParseAcceptComment(value) + if err != nil { + return err + } + case produceAttr: + err := parser.ParseProduceComment(value) + if err != nil { + return err + } + case "@schemes": + parser.swagger.Schemes = strings.Split(value, " ") + case "@tag.name": + parser.swagger.Tags = append(parser.swagger.Tags, spec.Tag{ + TagProps: spec.TagProps{ + Name: value, }, }) + case "@tag.description": + tag := parser.swagger.Tags[len(parser.swagger.Tags)-1] + tag.TagProps.Description = value + replaceLastTag(parser.swagger.Tags, tag) + case "@tag.description.markdown": + tag := parser.swagger.Tags[len(parser.swagger.Tags)-1] commentInfo, err := getMarkdownForTag(tag.TagProps.Name, parser.markdownFileDir) + if err != nil { + return err + } tag.TagProps.Description = string(commentInfo) + replaceLastTag(parser.swagger.Tags, tag) + case "@tag.docs.url": + tag := parser.swagger.Tags[len(parser.swagger.Tags)-1] + tag.TagProps.ExternalDocs = &spec.ExternalDocumentation{ - URL: value, + + URL: value, + Description: "", } replaceLastTag(parser.swagger.Tags, tag) + case "@tag.docs.description": + tag := parser.swagger.Tags[len(parser.swagger.Tags)-1] + if tag.TagProps.ExternalDocs == nil { + return fmt.Errorf("%s needs to come after a @tags.docs.url", attribute) + } tag.TagProps.ExternalDocs.Description = value + replaceLastTag(parser.swagger.Tags, tag) case secBasicAttr, secAPIKeyAttr, secApplicationAttr, secImplicitAttr, secPasswordAttr, secAccessCodeAttr: + scheme, err := parseSecAttributes(attribute, comments, &line) + if err != nil { + return err + } parser.swagger.SecurityDefinitions[value] = scheme case securityAttr: + parser.swagger.Security = append(parser.swagger.Security, parseSecurity(value)) case "@query.collection.format": + parser.collectionFormatInQuery = TransToValidCollectionFormat(value) case extDocsDescAttr, extDocsURLAttr: + if parser.swagger.ExternalDocs == nil { + parser.swagger.ExternalDocs = new(spec.ExternalDocumentation) + } + switch attr { + case extDocsDescAttr: + parser.swagger.ExternalDocs.Description = value + case extDocsURLAttr: + parser.swagger.ExternalDocs.URL = value + } default: + if strings.HasPrefix(attribute, "@x-") { + extensionName := attribute[1:] extExistsInSecurityDef := false + // for each security definition + for _, v := range parser.swagger.SecurityDefinitions { + // check if extension exists + _, extExistsInSecurityDef = v.VendorExtensible.Extensions.GetString(extensionName) + // if it exists in at least one, then we stop iterating + if extExistsInSecurityDef { + break + } + } // if it is present on security def, don't add it again + if extExistsInSecurityDef { + break + } if len(value) == 0 { + return fmt.Errorf("annotation %s need a value", attribute) + } var valueJSON interface{} + err := json.Unmarshal([]byte(value), &valueJSON) + if err != nil { + return fmt.Errorf("annotation %s need a valid json value", attribute) + } if strings.Contains(extensionName, "logo") { + parser.swagger.Info.Extensions.Add(extensionName, valueJSON) + } else { + if parser.swagger.Extensions == nil { + parser.swagger.Extensions = make(map[string]interface{}) + } parser.swagger.Extensions[attribute[1:]] = valueJSON + } + } + } previousAttribute = attribute + } return nil + } func setSwaggerInfo(swagger *spec.Swagger, attribute, value string) { + switch attribute { + case versionAttr: + swagger.Info.Version = value + case titleAttr: + swagger.Info.Title = value + case tosAttr: + swagger.Info.TermsOfService = value + case descriptionAttr: + swagger.Info.Description = value + case conNameAttr: + swagger.Info.Contact.Name = value + case conEmailAttr: + swagger.Info.Contact.Email = value + case conURLAttr: + swagger.Info.Contact.URL = value + case licNameAttr: + swagger.Info.License = initIfEmpty(swagger.Info.License) + swagger.Info.License.Name = value + case licURLAttr: + swagger.Info.License = initIfEmpty(swagger.Info.License) + swagger.Info.License.URL = value + } + } func parseSecAttributes(context string, lines []string, index *int) (*spec.SecurityScheme, error) { + const ( - in = "@in" - name = "@name" - descriptionAttr = "@description" - tokenURL = "@tokenurl" + in = "@in" + + name = "@name" + + descriptionAttr = "@description" + + tokenURL = "@tokenurl" + authorizationURL = "@authorizationurl" ) var search []string attribute := strings.ToLower(FieldsByAnySpace(lines[*index], 2)[0]) + switch attribute { + case secBasicAttr: + return spec.BasicAuth(), nil + case secAPIKeyAttr: + search = []string{in, name} + case secApplicationAttr, secPasswordAttr: + search = []string{tokenURL} + case secImplicitAttr: + search = []string{authorizationURL} + case secAccessCodeAttr: + search = []string{tokenURL, authorizationURL} + } // For the first line we get the attributes in the context parameter, so we skip to the next one + *index++ attrMap, scopes := make(map[string]string), make(map[string]string) + extensions, description := make(map[string]interface{}), "" loopline: + for ; *index < len(lines); *index++ { + v := strings.TrimSpace(lines[*index]) + if len(v) == 0 { + continue + } fields := FieldsByAnySpace(v, 2) + securityAttr := strings.ToLower(fields[0]) + var value string + if len(fields) > 1 { + value = fields[1] + } for _, findterm := range search { + if securityAttr == findterm { + attrMap[securityAttr] = value + continue loopline + } + } if isExists, err := isExistsScope(securityAttr); err != nil { + return nil, err + } else if isExists { + scopes[securityAttr[len(scopeAttrPrefix):]] = value + continue + } if strings.HasPrefix(securityAttr, "@x-") { + // Add the custom attribute without the @ + extensions[securityAttr[1:]] = value + continue + } // Not mandatory field + if securityAttr == descriptionAttr { + description = value + } // next securityDefinitions + if strings.Index(securityAttr, "@securitydefinitions.") == 0 { + // Go back to the previous line and break + *index-- break + } + } if len(attrMap) != len(search) { + return nil, fmt.Errorf("%s is %v required", context, search) + } var scheme *spec.SecurityScheme switch attribute { + case secAPIKeyAttr: + scheme = spec.APIKeyAuth(attrMap[name], attrMap[in]) + case secApplicationAttr: + scheme = spec.OAuth2Application(attrMap[tokenURL]) + case secImplicitAttr: + scheme = spec.OAuth2Implicit(attrMap[authorizationURL]) + case secPasswordAttr: + scheme = spec.OAuth2Password(attrMap[tokenURL]) + case secAccessCodeAttr: + scheme = spec.OAuth2AccessToken(attrMap[authorizationURL], attrMap[tokenURL]) + } scheme.Description = description for extKey, extValue := range extensions { + scheme.AddExtension(extKey, extValue) + } for scope, scopeDescription := range scopes { + scheme.AddScope(scope, scopeDescription) + } return scheme, nil + } func parseSecurity(commentLine string) map[string][]string { + securityMap := make(map[string][]string) for _, securityOption := range strings.Split(commentLine, "||") { + securityOption = strings.TrimSpace(securityOption) left, right := strings.Index(securityOption, "["), strings.Index(securityOption, "]") if !(left == -1 && right == -1) { + scopes := securityOption[left+1 : right] var options []string for _, scope := range strings.Split(scopes, ",") { + options = append(options, strings.TrimSpace(scope)) + } securityKey := securityOption[0:left] + securityMap[securityKey] = append(securityMap[securityKey], options...) + } else { + securityKey := strings.TrimSpace(securityOption) + securityMap[securityKey] = []string{} + } + } return securityMap + } func initIfEmpty(license *spec.License) *spec.License { + if license == nil { + return new(spec.License) + } return license + } // ParseAcceptComment parses comment for given `accept` comment string. + func (parser *Parser) ParseAcceptComment(commentLine string) error { + return parseMimeTypeList(commentLine, &parser.swagger.Consumes, "%v accept type can't be accepted") + } // ParseProduceComment parses comment for given `produce` comment string. + func (parser *Parser) ParseProduceComment(commentLine string) error { + return parseMimeTypeList(commentLine, &parser.swagger.Produces, "%v produce type can't be accepted") + } func isGeneralAPIComment(comments []string) bool { + for _, commentLine := range comments { + commentLine = strings.TrimSpace(commentLine) + if len(commentLine) == 0 { + continue + } + attribute := strings.ToLower(FieldsByAnySpace(commentLine, 2)[0]) + switch attribute { + // The @summary, @router, @success, @failure annotation belongs to Operation + case summaryAttr, routerAttr, successAttr, failureAttr, responseAttr: + return false + } + } return true + } func getMarkdownForTag(tagName string, dirPath string) ([]byte, error) { + dirEntries, err := os.ReadDir(dirPath) + if err != nil { + return nil, err + } for _, entry := range dirEntries { + if entry.IsDir() { + continue + } fileName := entry.Name() if !strings.Contains(fileName, ".md") { + continue + } if strings.Contains(fileName, tagName) { + fullPath := filepath.Join(dirPath, fileName) commentInfo, err := os.ReadFile(fullPath) + if err != nil { + return nil, fmt.Errorf("Failed to read markdown file %s error: %s ", fullPath, err) + } return commentInfo, nil + } + } return nil, fmt.Errorf("Unable to find markdown file for tag %s in the given directory", tagName) + } func isExistsScope(scope string) (bool, error) { + s := strings.Fields(scope) + for _, v := range s { + if strings.HasPrefix(v, scopeAttrPrefix) { + if strings.Contains(v, ",") { + return false, fmt.Errorf("@scope can't use comma(,) get=" + v) + } + } + } return strings.HasPrefix(scope, scopeAttrPrefix), nil + } func getTagsFromComment(comment string) (tags []string) { + commentLine := strings.TrimSpace(strings.TrimLeft(comment, "/")) + if len(commentLine) == 0 { + return nil + } attribute := strings.Fields(commentLine)[0] + lineRemainder, lowerAttribute := strings.TrimSpace(commentLine[len(attribute):]), strings.ToLower(attribute) if lowerAttribute == tagsAttr { + for _, tag := range strings.Split(lineRemainder, ",") { + tags = append(tags, strings.TrimSpace(tag)) + } + } + return } func (parser *Parser) matchTags(comments []*ast.Comment) (match bool) { + if len(parser.tags) == 0 { + return true + } match = false + for _, comment := range comments { + for _, tag := range getTagsFromComment(comment.Text) { + if _, has := parser.tags["!"+tag]; has { + return false + } + if _, has := parser.tags[tag]; has { + match = true // keep iterating as it may contain a tag that is excluded + } + } + } if !match { + // If all tags are negation then we should return true + for key := range parser.tags { + if key[0] != '!' { + return false + } + } + } + return true + } func matchExtension(extensionToMatch string, comments []*ast.Comment) (match bool) { + if len(extensionToMatch) != 0 { + for _, comment := range comments { + commentLine := strings.TrimSpace(strings.TrimLeft(comment.Text, "/")) + fields := FieldsByAnySpace(commentLine, 2) + if len(fields) > 0 { + lowerAttribute := strings.ToLower(fields[0]) if lowerAttribute == fmt.Sprintf("@x-%s", strings.ToLower(extensionToMatch)) { + return true + } + } + } + return false + } + return true + } // ParseRouterAPIInfo parses router api info for given astFile. + func (parser *Parser) ParseRouterAPIInfo(fileInfo *AstFileInfo) error { + DeclsLoop: + for _, astDescription := range fileInfo.File.Decls { + if (fileInfo.ParseFlag & ParseOperations) == ParseNone { + continue + } + astDeclaration, ok := astDescription.(*ast.FuncDecl) + if ok && astDeclaration.Doc != nil && astDeclaration.Doc.List != nil { + if parser.matchTags(astDeclaration.Doc.List) && + matchExtension(parser.parseExtension, astDeclaration.Doc.List) { + // for per 'function' comment, create a new 'Operation' object + operation := NewOperation(parser, SetCodeExampleFilesDirectory(parser.codeExampleFilesDir)) + for _, comment := range astDeclaration.Doc.List { + err := operation.ParseComment(comment.Text, fileInfo.File) + if err != nil { + return fmt.Errorf("ParseComment error in file %s :%+v", fileInfo.Path, err) + } + if operation.State != "" && operation.State != parser.HostState { + continue DeclsLoop + } + } + err := processRouterOperation(parser, operation) + if err != nil { + return err + } + } + } + } return nil + } func refRouteMethodOp(item *spec.PathItem, method string) (op **spec.Operation) { + switch method { + case http.MethodGet: + op = &item.Get + case http.MethodPost: + op = &item.Post + case http.MethodDelete: + op = &item.Delete + case http.MethodPut: + op = &item.Put + case http.MethodPatch: + op = &item.Patch + case http.MethodHead: + op = &item.Head + case http.MethodOptions: + op = &item.Options + } return + } func processRouterOperation(parser *Parser, operation *Operation) error { + for _, routeProperties := range operation.RouterProperties { + var ( pathItem spec.PathItem - ok bool + + ok bool ) pathItem, ok = parser.swagger.Paths.Paths[routeProperties.Path] + if !ok { + pathItem = spec.PathItem{} + } op := refRouteMethodOp(&pathItem, routeProperties.HTTPMethod) // check if we already have an operation for this path and method + if *op != nil { + err := fmt.Errorf("route %s %s is declared multiple times", routeProperties.HTTPMethod, routeProperties.Path) + if parser.Strict { + return err + } parser.debug.Printf("warning: %s\n", err) + } if len(operation.RouterProperties) > 1 { + newOp := *operation + var validParams []spec.Parameter + for _, param := range newOp.Operation.OperationProps.Parameters { + if param.In == "path" && !strings.Contains(routeProperties.Path, param.Name) { + // This path param is not actually contained in the path, skip adding it to the final params + continue + } + validParams = append(validParams, param) + } + newOp.Operation.OperationProps.Parameters = validParams + *op = &newOp.Operation + } else { + *op = &operation.Operation + } if routeProperties.Deprecated { + (*op).Deprecated = routeProperties.Deprecated + } parser.swagger.Paths.Paths[routeProperties.Path] = pathItem + } return nil + } func convertFromSpecificToPrimitive(typeName string) (string, error) { + name := typeName + if strings.ContainsRune(name, '.') { + name = strings.Split(name, ".")[1] + } switch strings.ToUpper(name) { + case "TIME", "OBJECTID", "UUID": + return STRING, nil + case "DECIMAL": + return NUMBER, nil + } return typeName, ErrFailedConvertPrimitiveType + } func (parser *Parser) getTypeSchema(typeName string, file *ast.File, ref bool) (*spec.Schema, error) { + if override, ok := parser.Overrides[typeName]; ok { + parser.debug.Printf("Override detected for %s: using %s instead", typeName, override) + return parseObjectSchema(parser, override, file) + } if IsInterfaceLike(typeName) { + return &spec.Schema{}, nil + } + if IsGolangPrimitiveType(typeName) { + return PrimitiveSchema(TransToValidSchemeType(typeName)), nil + } schemaType, err := convertFromSpecificToPrimitive(typeName) + if err == nil { + return PrimitiveSchema(schemaType), nil + } typeSpecDef := parser.packages.FindTypeSpec(typeName, file) + if typeSpecDef == nil { + return nil, fmt.Errorf("cannot find type definition: %s", typeName) + } if override, ok := parser.Overrides[typeSpecDef.FullPath()]; ok { + if override == "" { + parser.debug.Printf("Override detected for %s: ignoring", typeSpecDef.FullPath()) return nil, ErrSkippedField + } parser.debug.Printf("Override detected for %s: using %s instead", typeSpecDef.FullPath(), override) separator := strings.LastIndex(override, ".") + if separator == -1 { + // treat as a swaggertype tag + parts := strings.Split(override, ",") return BuildCustomSchema(parts) + } typeSpecDef = parser.packages.findTypeSpec(override[0:separator], override[separator+1:]) + } schema, ok := parser.parsedSchemas[typeSpecDef] + if !ok { + var err error schema, err = parser.ParseDefinition(typeSpecDef) + if err != nil { + if err == ErrRecursiveParseStruct && ref { + return parser.getRefTypeSchema(typeSpecDef, schema), nil + } + return nil, fmt.Errorf("%s: %w", typeName, err) + } + } if ref { + if IsComplexSchema(schema.Schema) { + return parser.getRefTypeSchema(typeSpecDef, schema), nil + } + // if it is a simple schema, just return a copy + newSchema := *schema.Schema + return &newSchema, nil + } return schema.Schema, nil + } func (parser *Parser) getRefTypeSchema(typeSpecDef *TypeSpecDef, schema *Schema) *spec.Schema { + _, ok := parser.outputSchemas[typeSpecDef] + if !ok { + parser.swagger.Definitions[schema.Name] = spec.Schema{} if schema.Schema != nil { + parser.swagger.Definitions[schema.Name] = *schema.Schema + } parser.outputSchemas[typeSpecDef] = schema + } refSchema := RefSchema(schema.Name) return refSchema + } func (parser *Parser) isInStructStack(typeSpecDef *TypeSpecDef) bool { + for _, specDef := range parser.structStack { + if typeSpecDef == specDef { + return true + } + } return false + } // ParseDefinition parses given type spec that corresponds to the type under + // given name and package, and populates swagger schema definitions registry + // with a schema for the given type + func (parser *Parser) ParseDefinition(typeSpecDef *TypeSpecDef) (*Schema, error) { + typeName := typeSpecDef.TypeName() + schema, found := parser.parsedSchemas[typeSpecDef] + if found { + parser.debug.Printf("Skipping '%s', already parsed.", typeName) return schema, nil + } if parser.isInStructStack(typeSpecDef) { + parser.debug.Printf("Skipping '%s', recursion detected.", typeName) return &Schema{ - Name: typeName, + + Name: typeName, + PkgPath: typeSpecDef.PkgPath, - Schema: PrimitiveSchema(OBJECT), + + Schema: PrimitiveSchema(OBJECT), }, + ErrRecursiveParseStruct + } parser.structStack = append(parser.structStack, typeSpecDef) @@ -1232,429 +2002,700 @@ func (parser *Parser) ParseDefinition(typeSpecDef *TypeSpecDef) (*Schema, error) parser.debug.Printf("Generating %s", typeName) definition, err := parser.parseTypeExpr(typeSpecDef.File, typeSpecDef.TypeSpec.Type, false) + if err != nil { + parser.debug.Printf("Error parsing type definition '%s': %s", typeName, err) + return nil, err + } if definition.Description == "" { + fillDefinitionDescription(definition, typeSpecDef.File, typeSpecDef) + } if len(typeSpecDef.Enums) > 0 { + var varnames []string + var enumComments = make(map[string]string) + for _, value := range typeSpecDef.Enums { + definition.Enum = append(definition.Enum, value.Value) + varnames = append(varnames, value.key) + if len(value.Comment) > 0 { + enumComments[value.key] = value.Comment + } + } + if definition.Extensions == nil { + definition.Extensions = make(spec.Extensions) + } + definition.Extensions[enumVarNamesExtension] = varnames + if len(enumComments) > 0 { + definition.Extensions[enumCommentsExtension] = enumComments + } + } sch := Schema{ - Name: typeName, + + Name: typeName, + PkgPath: typeSpecDef.PkgPath, - Schema: definition, + + Schema: definition, } + parser.parsedSchemas[typeSpecDef] = &sch // update an empty schema as a result of recursion + s2, found := parser.outputSchemas[typeSpecDef] + if found { + parser.swagger.Definitions[s2.Name] = *definition + } return &sch, nil + } func fullTypeName(parts ...string) string { + return strings.Join(parts, ".") + } // fillDefinitionDescription additionally fills fields in definition (spec.Schema) + // TODO: If .go file contains many types, it may work for a long time + func fillDefinitionDescription(definition *spec.Schema, file *ast.File, typeSpecDef *TypeSpecDef) { + if file == nil { + return + } + for _, astDeclaration := range file.Decls { + generalDeclaration, ok := astDeclaration.(*ast.GenDecl) + if !ok || generalDeclaration.Tok != token.TYPE { + continue + } for _, astSpec := range generalDeclaration.Specs { + typeSpec, ok := astSpec.(*ast.TypeSpec) + if !ok || typeSpec != typeSpecDef.TypeSpec { + continue + } definition.Description = + extractDeclarationDescription(typeSpec.Doc, typeSpec.Comment, generalDeclaration.Doc) + } + } + } // extractDeclarationDescription gets first description + // from attribute descriptionAttr in commentGroups (ast.CommentGroup) + func extractDeclarationDescription(commentGroups ...*ast.CommentGroup) string { + var description string for _, commentGroup := range commentGroups { + if commentGroup == nil { + continue + } isHandlingDescription := false for _, comment := range commentGroup.List { + commentText := strings.TrimSpace(strings.TrimLeft(comment.Text, "/")) + if len(commentText) == 0 { + continue + } + attribute := FieldsByAnySpace(commentText, 2)[0] if strings.ToLower(attribute) != descriptionAttr { + if !isHandlingDescription { + continue + } break + } isHandlingDescription = true + description += " " + strings.TrimSpace(commentText[len(attribute):]) + } + } return strings.TrimLeft(description, " ") + } // parseTypeExpr parses given type expression that corresponds to the type under + // given name and package, and returns swagger schema for it. + func (parser *Parser) parseTypeExpr(file *ast.File, typeExpr ast.Expr, ref bool) (*spec.Schema, error) { + switch expr := typeExpr.(type) { + // type Foo interface{} + case *ast.InterfaceType: + return &spec.Schema{}, nil // type Foo struct {...} + case *ast.StructType: + return parser.parseStruct(file, expr.Fields) // type Foo Baz + case *ast.Ident: + return parser.getTypeSchema(expr.Name, file, ref) // type Foo *Baz + case *ast.StarExpr: + return parser.parseTypeExpr(file, expr.X, ref) // type Foo pkg.Bar + case *ast.SelectorExpr: + if xIdent, ok := expr.X.(*ast.Ident); ok { + return parser.getTypeSchema(fullTypeName(xIdent.Name, expr.Sel.Name), file, ref) + } + // type Foo []Baz + case *ast.ArrayType: + itemSchema, err := parser.parseTypeExpr(file, expr.Elt, true) + if err != nil { + return nil, err + } return spec.ArrayProperty(itemSchema), nil + // type Foo map[string]Bar + case *ast.MapType: + if _, ok := expr.Value.(*ast.InterfaceType); ok { + return spec.MapProperty(nil), nil + } + schema, err := parser.parseTypeExpr(file, expr.Value, true) + if err != nil { + return nil, err + } return spec.MapProperty(schema), nil case *ast.FuncType: + return nil, ErrFuncTypeField + // ... + } return parser.parseGenericTypeExpr(file, typeExpr) + } func (parser *Parser) parseStruct(file *ast.File, fields *ast.FieldList) (*spec.Schema, error) { + required, properties := make([]string, 0), make(map[string]spec.Schema) for _, field := range fields.List { + fieldProps, requiredFromAnon, err := parser.parseStructField(file, field) + if err != nil { + if errors.Is(err, ErrFuncTypeField) || errors.Is(err, ErrSkippedField) { + continue + } return nil, err + } if len(fieldProps) == 0 { + continue + } required = append(required, requiredFromAnon...) for k, v := range fieldProps { + properties[k] = v + } + } sort.Strings(required) return &spec.Schema{ + SchemaProps: spec.SchemaProps{ - Type: []string{OBJECT}, + + Type: []string{OBJECT}, + Properties: properties, - Required: required, + + Required: required, }, }, nil + } func (parser *Parser) parseStructField(file *ast.File, field *ast.Field) (map[string]spec.Schema, []string, error) { + if field.Tag != nil { + skip, ok := reflect.StructTag(strings.ReplaceAll(field.Tag.Value, "`", "")).Lookup("swaggerignore") + if ok && strings.EqualFold(skip, "true") { + return nil, nil, nil + } + } ps := parser.fieldParserFactory(parser, field) if ps.ShouldSkip() { + return nil, nil, nil + } fieldName, err := ps.FieldName() + if err != nil { + return nil, nil, err + } if fieldName == "" { + typeName, err := getFieldType(file, field.Type, nil) + if err != nil { + return nil, nil, fmt.Errorf("%s: %w", fieldName, err) + } schema, err := parser.getTypeSchema(typeName, file, false) + if err != nil { + return nil, nil, fmt.Errorf("%s: %w", fieldName, err) + } if len(schema.Type) > 0 && schema.Type[0] == OBJECT { + if len(schema.Properties) == 0 { + return nil, nil, nil + } properties := map[string]spec.Schema{} + for k, v := range schema.Properties { + properties[k] = v + } return properties, schema.SchemaProps.Required, nil + } + // for alias type of non-struct types ,such as array,map, etc. ignore field tag. + return map[string]spec.Schema{typeName: *schema}, nil, nil } schema, err := ps.CustomSchema() + if err != nil { + return nil, nil, fmt.Errorf("%s: %w", fieldName, err) + } if schema == nil { + typeName, err := getFieldType(file, field.Type, nil) + if err == nil { + // named type + schema, err = parser.getTypeSchema(typeName, file, true) + } else { + // unnamed type + schema, err = parser.parseTypeExpr(file, field.Type, false) + } if err != nil { + return nil, nil, fmt.Errorf("%s: %w", fieldName, err) + } + } err = ps.ComplementSchema(schema) + if err != nil { + return nil, nil, fmt.Errorf("%s: %w", fieldName, err) + } var tagRequired []string required, err := ps.IsRequired() + if err != nil { + return nil, nil, fmt.Errorf("%s: %w", fieldName, err) + } if required { + tagRequired = append(tagRequired, fieldName) + } if schema.Extensions == nil { + schema.Extensions = make(spec.Extensions) + } + if formName := ps.FormName(); len(formName) > 0 { + schema.Extensions["formData"] = formName + } + if headerName := ps.HeaderName(); len(headerName) > 0 { + schema.Extensions["header"] = headerName + } + if pathName := ps.PathName(); len(pathName) > 0 { + schema.Extensions["path"] = pathName + } return map[string]spec.Schema{fieldName: *schema}, tagRequired, nil + } func getFieldType(file *ast.File, field ast.Expr, genericParamTypeDefs map[string]*genericTypeSpec) (string, error) { + switch fieldType := field.(type) { + case *ast.Ident: + return fieldType.Name, nil + case *ast.SelectorExpr: + packageName, err := getFieldType(file, fieldType.X, genericParamTypeDefs) + if err != nil { + return "", err + } return fullTypeName(packageName, fieldType.Sel.Name), nil + case *ast.StarExpr: + fullName, err := getFieldType(file, fieldType.X, genericParamTypeDefs) + if err != nil { + return "", err + } return fullName, nil + default: + return getGenericFieldType(file, field, genericParamTypeDefs) + } + } func (parser *Parser) getUnderlyingSchema(schema *spec.Schema) *spec.Schema { + if schema == nil { + return nil + } if url := schema.Ref.GetURL(); url != nil { + if pos := strings.LastIndexByte(url.Fragment, '/'); pos >= 0 { + name := url.Fragment[pos+1:] + if schema, ok := parser.swagger.Definitions[name]; ok { + return &schema + } + } + } if len(schema.AllOf) > 0 { + merged := &spec.Schema{} + MergeSchema(merged, schema) + for _, s := range schema.AllOf { + MergeSchema(merged, parser.getUnderlyingSchema(&s)) + } + return merged + } + return nil + } // GetSchemaTypePath get path of schema type. + func (parser *Parser) GetSchemaTypePath(schema *spec.Schema, depth int) []string { + if schema == nil || depth == 0 { + return nil + } if underlying := parser.getUnderlyingSchema(schema); underlying != nil { + return parser.GetSchemaTypePath(underlying, depth) + } if len(schema.Type) > 0 { + switch schema.Type[0] { + case ARRAY: + depth-- s := []string{schema.Type[0]} return append(s, parser.GetSchemaTypePath(schema.Items.Schema, depth)...) + case OBJECT: + if schema.AdditionalProperties != nil && schema.AdditionalProperties.Schema != nil { + // for map + depth-- s := []string{schema.Type[0]} return append(s, parser.GetSchemaTypePath(schema.AdditionalProperties.Schema, depth)...) + } + } return []string{schema.Type[0]} + } return []string{ANY} + } func replaceLastTag(slice []spec.Tag, element spec.Tag) { + slice = append(slice[:len(slice)-1], element) + } // defineTypeOfExample example value define the type (object and array unsupported). + func defineTypeOfExample(schemaType, arrayType, exampleValue string) (interface{}, error) { + switch schemaType { + case STRING: + return exampleValue, nil + case NUMBER: + v, err := strconv.ParseFloat(exampleValue, 64) + if err != nil { + return nil, fmt.Errorf("example value %s can't convert to %s err: %s", exampleValue, schemaType, err) + } return v, nil + case INTEGER: + v, err := strconv.Atoi(exampleValue) + if err != nil { + return nil, fmt.Errorf("example value %s can't convert to %s err: %s", exampleValue, schemaType, err) + } return v, nil + case BOOLEAN: + v, err := strconv.ParseBool(exampleValue) + if err != nil { + return nil, fmt.Errorf("example value %s can't convert to %s err: %s", exampleValue, schemaType, err) + } return v, nil + case ARRAY: + values := strings.Split(exampleValue, ",") + result := make([]interface{}, 0) + for _, value := range values { + v, err := defineTypeOfExample(arrayType, "", value) + if err != nil { + return nil, err + } result = append(result, v) + } return result, nil + case OBJECT: + if arrayType == "" { + return nil, fmt.Errorf("%s is unsupported type in example value `%s`", schemaType, exampleValue) + } values := strings.Split(exampleValue, ",") @@ -1662,174 +2703,272 @@ func defineTypeOfExample(schemaType, arrayType, exampleValue string) (interface{ result := map[string]interface{}{} for _, value := range values { + mapData := strings.SplitN(value, ":", 2) if len(mapData) == 2 { + v, err := defineTypeOfExample(arrayType, "", mapData[1]) + if err != nil { + return nil, err + } result[mapData[0]] = v continue + } return nil, fmt.Errorf("example value %s should format: key:value", exampleValue) + } return result, nil + } return nil, fmt.Errorf("%s is unsupported type in example value %s", schemaType, exampleValue) + } // GetAllGoFileInfo gets all Go source files information for given searchDir. + func (parser *Parser) getAllGoFileInfo(packageDir, searchDir string) error { + if parser.skipPackageByPrefix(packageDir) { + return nil // ignored by user-defined package path prefixes + } + return filepath.Walk(searchDir, func(path string, f os.FileInfo, _ error) error { + err := parser.Skip(path, f) + if err != nil { + return err + } if f.IsDir() { + return nil + } relPath, err := filepath.Rel(searchDir, path) + if err != nil { + return err + } return parser.parseFile(filepath.ToSlash(filepath.Dir(filepath.Clean(filepath.Join(packageDir, relPath)))), path, nil, ParseAll) + }) + } func (parser *Parser) getAllGoFileInfoFromDeps(pkg *depth.Pkg, parseFlag ParseFlag) error { + ignoreInternal := pkg.Internal && !parser.ParseInternal + if ignoreInternal || !pkg.Resolved { // ignored internal and not resolved dependencies + return nil + } if pkg.Raw != nil && parser.skipPackageByPrefix(pkg.Raw.ImportPath) { + return nil // ignored by user-defined package path prefixes + } // Skip cgo + if pkg.Raw == nil && pkg.Name == "C" { + return nil + } srcDir := pkg.Raw.Dir files, err := os.ReadDir(srcDir) // only parsing files in the dir(don't contain sub dir files) + if err != nil { + return err + } for _, f := range files { + if f.IsDir() { + continue + } path := filepath.Join(srcDir, f.Name()) + if err := parser.parseFile(pkg.Name, path, nil, parseFlag); err != nil { + return err + } + } for i := 0; i < len(pkg.Deps); i++ { + if err := parser.getAllGoFileInfoFromDeps(&pkg.Deps[i], parseFlag); err != nil { + return err + } + } return nil + } func (parser *Parser) parseFile(packageDir, path string, src interface{}, flag ParseFlag) error { + if strings.HasSuffix(strings.ToLower(path), "_test.go") || filepath.Ext(path) != ".go" { + return nil + } return parser.packages.ParseFile(packageDir, path, src, flag) + } func (parser *Parser) checkOperationIDUniqueness() error { + // operationsIds contains all operationId annotations to check it's unique + operationsIds := make(map[string]string) for path, item := range parser.swagger.Paths.Paths { + var method, id string for method = range allMethod { + op := refRouteMethodOp(&item, method) + if *op != nil { + id = (**op).ID break + } + } if id == "" { + continue + } current := fmt.Sprintf("%s %s", method, path) previous, ok := operationsIds[id] + if ok { + return fmt.Errorf( + "duplicated @id annotation '%s' found in '%s', previously declared in: '%s'", + id, current, previous) + } operationsIds[id] = current + } return nil + } // Skip returns filepath.SkipDir error if match vendor and hidden folder. + func (parser *Parser) Skip(path string, f os.FileInfo) error { + return walkWith(parser.excludes, parser.ParseVendor)(path, f) + } func walkWith(excludes map[string]struct{}, parseVendor bool) func(path string, fileInfo os.FileInfo) error { + return func(path string, f os.FileInfo) error { + if f.IsDir() { + if !parseVendor && f.Name() == "vendor" || // ignore "vendor" + f.Name() == "docs" || // exclude docs + len(f.Name()) > 1 && f.Name()[0] == '.' && f.Name() != ".." { // exclude all hidden folder + return filepath.SkipDir + } if excludes != nil { + if _, ok := excludes[path]; ok { + return filepath.SkipDir + } + } + } return nil + } + } // GetSwagger returns *spec.Swagger which is the root document object for the API specification. + func (parser *Parser) GetSwagger() *spec.Swagger { + return parser.swagger + } // addTestType just for tests. + func (parser *Parser) addTestType(typename string) { + typeDef := &TypeSpecDef{} + parser.packages.uniqueDefinitions[typename] = typeDef + parser.parsedSchemas[typeDef] = &Schema{ + PkgPath: "", - Name: typename, - Schema: PrimitiveSchema(OBJECT), + + Name: typename, + + Schema: PrimitiveSchema(OBJECT), } + } diff --git a/vendor/github.com/swaggo/swag/schema.go b/vendor/github.com/swaggo/swag/schema.go index c78a435..85ef864 100644 --- a/vendor/github.com/swaggo/swag/schema.go +++ b/vendor/github.com/swaggo/swag/schema.go @@ -8,287 +8,508 @@ import ( ) const ( + // ARRAY represent a array value. + ARRAY = "array" + // OBJECT represent a object value. + OBJECT = "object" + // PRIMITIVE represent a primitive value. + PRIMITIVE = "primitive" + // BOOLEAN represent a boolean value. + BOOLEAN = "boolean" + // INTEGER represent a integer value. + INTEGER = "integer" + // NUMBER represent a number value. + NUMBER = "number" + // STRING represent a string value. + STRING = "string" + // FUNC represent a function value. + FUNC = "func" + // ERROR represent a error value. + ERROR = "error" + // INTERFACE represent a interface value. + INTERFACE = "interface{}" + // ANY represent a any value. + ANY = "any" + // NIL represent a empty value. + NIL = "nil" // IgnoreNameOverridePrefix Prepend to model to avoid renaming based on comment. + IgnoreNameOverridePrefix = '$' ) // CheckSchemaType checks if typeName is not a name of primitive type. + func CheckSchemaType(typeName string) error { + if !IsPrimitiveType(typeName) { + return fmt.Errorf("%s is not basic types", typeName) + } return nil + } // IsSimplePrimitiveType determine whether the type name is a simple primitive type. + func IsSimplePrimitiveType(typeName string) bool { + switch typeName { + case STRING, NUMBER, INTEGER, BOOLEAN: + return true + } return false + } // IsPrimitiveType determine whether the type name is a primitive type. + func IsPrimitiveType(typeName string) bool { + switch typeName { + case STRING, NUMBER, INTEGER, BOOLEAN, ARRAY, OBJECT, FUNC: + return true + } return false + } // IsInterfaceLike determines whether the swagger type name is an go named interface type like error type. + func IsInterfaceLike(typeName string) bool { + return typeName == ERROR || typeName == ANY + } // IsNumericType determines whether the swagger type name is a numeric type. + func IsNumericType(typeName string) bool { + return typeName == INTEGER || typeName == NUMBER + } // TransToValidSchemeType indicates type will transfer golang basic type to swagger supported type. + func TransToValidSchemeType(typeName string) string { + switch typeName { + case "uint", "int", "uint8", "int8", "uint16", "int16", "byte": + return INTEGER + case "uint32", "int32", "rune": + return INTEGER + case "uint64", "int64": + return INTEGER + case "float32", "float64": + return NUMBER + case "bool": + return BOOLEAN + case "string": + return STRING + } return typeName + } // IsGolangPrimitiveType determine whether the type name is a golang primitive type. + func IsGolangPrimitiveType(typeName string) bool { + switch typeName { + case "uint", + "int", + "uint8", + "int8", + "uint16", + "int16", + "byte", + "uint32", + "int32", + "rune", + "uint64", + "int64", + "float32", + "float64", + "bool", + "string": + return true + } return false + } // TransToValidCollectionFormat determine valid collection format. + func TransToValidCollectionFormat(format string) string { + switch format { + case "csv", "multi", "pipes", "tsv", "ssv": + return format + } return "" + } func ignoreNameOverride(name string) bool { + return len(name) != 0 && name[0] == IgnoreNameOverridePrefix + } // IsComplexSchema whether a schema is complex and should be a ref schema + func IsComplexSchema(schema *spec.Schema) bool { + // a enum type should be complex + if len(schema.Enum) > 0 { + return true + } // a deep array type is complex, how to determine deep? here more than 2 ,for example: [][]object,[][][]int + if len(schema.Type) > 2 { + return true + } //Object included, such as Object or []Object + for _, st := range schema.Type { + if st == OBJECT { + return true + } + } + return false + } // IsRefSchema whether a schema is a reference schema. + func IsRefSchema(schema *spec.Schema) bool { + return schema.Ref.Ref.GetURL() != nil + } // RefSchema build a reference schema. + func RefSchema(refType string) *spec.Schema { + return spec.RefSchema("#/definitions/" + refType) + } // PrimitiveSchema build a primitive schema. + func PrimitiveSchema(refType string) *spec.Schema { + return &spec.Schema{SchemaProps: spec.SchemaProps{Type: []string{refType}}} + } // BuildCustomSchema build custom schema specified by tag swaggertype. + func BuildCustomSchema(types []string) (*spec.Schema, error) { + if len(types) == 0 { + return nil, nil + } switch types[0] { + case PRIMITIVE: + if len(types) == 1 { + return nil, errors.New("need primitive type after primitive") + } return BuildCustomSchema(types[1:]) + case ARRAY: + if len(types) == 1 { + return nil, errors.New("need array item type after array") + } schema, err := BuildCustomSchema(types[1:]) + if err != nil { + return nil, err + } return spec.ArrayProperty(schema), nil + case OBJECT: + if len(types) == 1 { + return PrimitiveSchema(types[0]), nil + } schema, err := BuildCustomSchema(types[1:]) + if err != nil { + return nil, err + } return spec.MapProperty(schema), nil + default: + err := CheckSchemaType(types[0]) + if err != nil { + return nil, err + } return PrimitiveSchema(types[0]), nil + } + } // MergeSchema merge schemas + func MergeSchema(dst *spec.Schema, src *spec.Schema) *spec.Schema { + if len(src.Type) > 0 { + dst.Type = src.Type + } + if len(src.Properties) > 0 { + dst.Properties = src.Properties + } + if src.Items != nil { + dst.Items = src.Items + } + if src.AdditionalProperties != nil { + dst.AdditionalProperties = src.AdditionalProperties + } + if len(src.Description) > 0 { + dst.Description = src.Description + } + if src.Nullable { + dst.Nullable = src.Nullable + } + if len(src.Format) > 0 { + dst.Format = src.Format + } + if src.Default != nil { + dst.Default = src.Default + } + if src.Example != nil { + dst.Example = src.Example + } + if len(src.Extensions) > 0 { + dst.Extensions = src.Extensions + } + if src.Maximum != nil { + dst.Maximum = src.Maximum + } + if src.Minimum != nil { + dst.Minimum = src.Minimum + } + if src.ExclusiveMaximum { + dst.ExclusiveMaximum = src.ExclusiveMaximum + } + if src.ExclusiveMinimum { + dst.ExclusiveMinimum = src.ExclusiveMinimum + } + if src.MaxLength != nil { + dst.MaxLength = src.MaxLength + } + if src.MinLength != nil { + dst.MinLength = src.MinLength + } + if len(src.Pattern) > 0 { + dst.Pattern = src.Pattern + } + if src.MaxItems != nil { + dst.MaxItems = src.MaxItems + } + if src.MinItems != nil { + dst.MinItems = src.MinItems + } + if src.UniqueItems { + dst.UniqueItems = src.UniqueItems + } + if src.MultipleOf != nil { + dst.MultipleOf = src.MultipleOf + } + if len(src.Enum) > 0 { + dst.Enum = src.Enum + } + if len(src.Extensions) > 0 { + dst.Extensions = src.Extensions + } + if len(src.ExtraProps) > 0 { + dst.ExtraProps = src.ExtraProps + } + return dst + } diff --git a/vendor/github.com/swaggo/swag/spec.go b/vendor/github.com/swaggo/swag/spec.go index c18a365..32efb6a 100644 --- a/vendor/github.com/swaggo/swag/spec.go +++ b/vendor/github.com/swaggo/swag/spec.go @@ -8,57 +8,90 @@ import ( ) // Spec holds exported Swagger Info so clients can modify it. + type Spec struct { - Version string - Host string - BasePath string - Schemes []string - Title string - Description string + Version string + + Host string + + BasePath string + + Schemes []string + + Title string + + Description string + InfoInstanceName string - SwaggerTemplate string - LeftDelim string - RightDelim string + + SwaggerTemplate string + + LeftDelim string + + RightDelim string } // ReadDoc parses SwaggerTemplate into swagger document. + func (i *Spec) ReadDoc() string { + i.Description = strings.ReplaceAll(i.Description, "\n", "\\n") tpl := template.New("swagger_info").Funcs(template.FuncMap{ + "marshal": func(v interface{}) string { + a, _ := json.Marshal(v) return string(a) + }, + "escape": func(v interface{}) string { + // escape tabs + var str = strings.ReplaceAll(v.(string), "\t", "\\t") + // replace " with \", and if that results in \\", replace that with \\\" + str = strings.ReplaceAll(str, "\"", "\\\"") return strings.ReplaceAll(str, "\\\\\"", "\\\\\\\"") + }, }) if i.LeftDelim != "" && i.RightDelim != "" { + tpl = tpl.Delims(i.LeftDelim, i.RightDelim) + } parsed, err := tpl.Parse(i.SwaggerTemplate) + if err != nil { + return i.SwaggerTemplate + } var doc bytes.Buffer + if err = parsed.Execute(&doc, i); err != nil { + return i.SwaggerTemplate + } return doc.String() + } // InstanceName returns Spec instance name. + func (i *Spec) InstanceName() string { + return i.InfoInstanceName + } diff --git a/vendor/github.com/swaggo/swag/swagger.go b/vendor/github.com/swaggo/swag/swagger.go index 74c162c..fb4f4c3 100644 --- a/vendor/github.com/swaggo/swag/swagger.go +++ b/vendor/github.com/swaggo/swag/swagger.go @@ -7,66 +7,97 @@ import ( ) // Name is a unique name be used to register swag instance. + const Name = "swagger" var ( swaggerMu sync.RWMutex - swags map[string]Swagger + + swags map[string]Swagger ) // Swagger is an interface to read swagger document. + type Swagger interface { ReadDoc() string } // Register registers swagger for given name. + func Register(name string, swagger Swagger) { + swaggerMu.Lock() + defer swaggerMu.Unlock() if swagger == nil { + panic("swagger is nil") + } if swags == nil { + swags = make(map[string]Swagger) + } if _, ok := swags[name]; ok { + panic("Register called twice for swag: " + name) + } swags[name] = swagger + } // GetSwagger returns the swagger instance for given name. + // If not found, returns nil. + func GetSwagger(name string) Swagger { + swaggerMu.RLock() + defer swaggerMu.RUnlock() return swags[name] + } // ReadDoc reads swagger document. An optional name parameter can be passed to read a specific document. + // The default name is "swagger". + func ReadDoc(optionalName ...string) (string, error) { + swaggerMu.RLock() + defer swaggerMu.RUnlock() if swags == nil { + return "", errors.New("no swag has yet been registered") + } name := Name + if len(optionalName) != 0 && optionalName[0] != "" { + name = optionalName[0] + } swag, ok := swags[name] + if !ok { + return "", fmt.Errorf("no swag named \"%s\" was registered", name) + } return swag.ReadDoc(), nil + } diff --git a/vendor/github.com/swaggo/swag/types.go b/vendor/github.com/swaggo/swag/types.go index 0076a6b..aa17466 100644 --- a/vendor/github.com/swaggo/swag/types.go +++ b/vendor/github.com/swaggo/swag/types.go @@ -10,96 +10,156 @@ import ( ) // Schema parsed schema. + type Schema struct { - *spec.Schema // - PkgPath string // package import path used to rename Name of a definition int case of conflict - Name string // Name in definitions + *spec.Schema // + + PkgPath string // package import path used to rename Name of a definition int case of conflict + + Name string // Name in definitions + } // TypeSpecDef the whole information of a typeSpec. + type TypeSpecDef struct { + // ast file where TypeSpec is + File *ast.File // the TypeSpec of this type definition + TypeSpec *ast.TypeSpec Enums []EnumValue // path of package starting from under ${GOPATH}/src or from module path in go.mod - PkgPath string + + PkgPath string + ParentSpec ast.Decl NotUnique bool } // Name the name of the typeSpec. + func (t *TypeSpecDef) Name() string { + if t.TypeSpec != nil && t.TypeSpec.Name != nil { + return t.TypeSpec.Name.Name + } return "" + } // TypeName the type name of the typeSpec. + func (t *TypeSpecDef) TypeName() string { + if ignoreNameOverride(t.TypeSpec.Name.Name) { + return t.TypeSpec.Name.Name[1:] + } else if t.TypeSpec.Comment != nil { + // get alias from comment '// @name ' + const regexCaseInsensitive = "(?i)" + reTypeName, err := regexp.Compile(regexCaseInsensitive + `^@name\s+(\S+)`) + if err != nil { + panic(err) + } + for _, comment := range t.TypeSpec.Comment.List { + trimmedComment := strings.TrimSpace(strings.TrimLeft(comment.Text, "/")) + texts := reTypeName.FindStringSubmatch(trimmedComment) + if len(texts) > 1 { + return texts[1] + } + } + } var names []string + if t.NotUnique { + pkgPath := strings.Map(func(r rune) rune { + if r == '\\' || r == '/' || r == '.' { + return '_' + } + return r + }, t.PkgPath) + names = append(names, pkgPath) + } else if t.File != nil { + names = append(names, t.File.Name.Name) + } + if parentFun, ok := (t.ParentSpec).(*ast.FuncDecl); ok && parentFun != nil { + names = append(names, parentFun.Name.Name) + } + names = append(names, t.TypeSpec.Name.Name) + return fullTypeName(names...) + } // FullPath return the full path of the typeSpec. + func (t *TypeSpecDef) FullPath() string { + return t.PkgPath + "." + t.Name() + } // AstFileInfo information of an ast.File. + type AstFileInfo struct { + //FileSet the FileSet object which is used to parse this go source file + FileSet *token.FileSet // File ast.File + File *ast.File // Path the path of the ast.File + Path string // PackagePath package import path of the ast.File + PackagePath string // ParseFlag determine what to parse + ParseFlag ParseFlag } diff --git a/vendor/github.com/valyala/bytebufferpool/pool.go b/vendor/github.com/valyala/bytebufferpool/pool.go index 8bb4134..bd4acaf 100644 --- a/vendor/github.com/valyala/bytebufferpool/pool.go +++ b/vendor/github.com/valyala/bytebufferpool/pool.go @@ -8,26 +8,36 @@ import ( const ( minBitSize = 6 // 2**6=64 is a CPU cache line size - steps = 20 + + steps = 20 minSize = 1 << minBitSize + maxSize = 1 << (minBitSize + steps - 1) calibrateCallsThreshold = 42000 - maxPercentile = 0.95 + + maxPercentile = 0.95 ) // Pool represents byte buffer pool. + // + // Distinct pools may be used for distinct types of byte buffers. + // Properly determined byte buffer types with their own pools may help reducing + // memory waste. + type Pool struct { - calls [steps]uint64 + calls [steps]uint64 + calibrating uint64 defaultSize uint64 - maxSize uint64 + + maxSize uint64 pool sync.Pool } @@ -35,117 +45,193 @@ type Pool struct { var defaultPool Pool // Get returns an empty byte buffer from the pool. + // + // Got byte buffer may be returned to the pool via Put call. + // This reduces the number of memory allocations required for byte buffer + // management. + func Get() *ByteBuffer { return defaultPool.Get() } // Get returns new byte buffer with zero length. + // + // The byte buffer may be returned to the pool via Put after the use + // in order to minimize GC overhead. + func (p *Pool) Get() *ByteBuffer { + v := p.pool.Get() + if v != nil { + return v.(*ByteBuffer) + } + return &ByteBuffer{ + B: make([]byte, 0, atomic.LoadUint64(&p.defaultSize)), } + } // Put returns byte buffer to the pool. + // + // ByteBuffer.B mustn't be touched after returning it to the pool. + // Otherwise data races will occur. + func Put(b *ByteBuffer) { defaultPool.Put(b) } // Put releases byte buffer obtained via Get to the pool. + // + // The buffer mustn't be accessed after returning to the pool. + func (p *Pool) Put(b *ByteBuffer) { + idx := index(len(b.B)) if atomic.AddUint64(&p.calls[idx], 1) > calibrateCallsThreshold { + p.calibrate() + } maxSize := int(atomic.LoadUint64(&p.maxSize)) + if maxSize == 0 || cap(b.B) <= maxSize { + b.Reset() + p.pool.Put(b) + } + } func (p *Pool) calibrate() { + if !atomic.CompareAndSwapUint64(&p.calibrating, 0, 1) { + return + } a := make(callSizes, 0, steps) + var callsSum uint64 + for i := uint64(0); i < steps; i++ { + calls := atomic.SwapUint64(&p.calls[i], 0) + callsSum += calls + a = append(a, callSize{ + calls: calls, - size: minSize << i, + + size: minSize << i, }) + } + sort.Sort(a) defaultSize := a[0].size + maxSize := defaultSize maxSum := uint64(float64(callsSum) * maxPercentile) + callsSum = 0 + for i := 0; i < steps; i++ { + if callsSum > maxSum { + break + } + callsSum += a[i].calls + size := a[i].size + if size > maxSize { + maxSize = size + } + } atomic.StoreUint64(&p.defaultSize, defaultSize) + atomic.StoreUint64(&p.maxSize, maxSize) atomic.StoreUint64(&p.calibrating, 0) + } type callSize struct { calls uint64 - size uint64 + + size uint64 } type callSizes []callSize func (ci callSizes) Len() int { + return len(ci) + } func (ci callSizes) Less(i, j int) bool { + return ci[i].calls > ci[j].calls + } func (ci callSizes) Swap(i, j int) { + ci[i], ci[j] = ci[j], ci[i] + } func index(n int) int { + n-- + n >>= minBitSize + idx := 0 + for n > 0 { + n >>= 1 + idx++ + } + if idx >= steps { + idx = steps - 1 + } + return idx + } diff --git a/vendor/github.com/valyala/fasttemplate/template.go b/vendor/github.com/valyala/fasttemplate/template.go index c2df361..445097a 100644 --- a/vendor/github.com/valyala/fasttemplate/template.go +++ b/vendor/github.com/valyala/fasttemplate/template.go @@ -1,9 +1,15 @@ // Package fasttemplate implements simple and fast template library. + // + // Fasttemplate is faster than text/template, strings.Replace + // and strings.Replacer. + // + // Fasttemplate ideally fits for fast and simple placeholders' substitutions. + package fasttemplate import ( @@ -15,422 +21,763 @@ import ( ) // ExecuteFunc calls f on each template tag (placeholder) occurrence. + // + // Returns the number of bytes written to w. + // + // This function is optimized for constantly changing templates. + // Use Template.ExecuteFunc for frozen templates. + func ExecuteFunc(template, startTag, endTag string, w io.Writer, f TagFunc) (int64, error) { + s := unsafeString2Bytes(template) + a := unsafeString2Bytes(startTag) + b := unsafeString2Bytes(endTag) var nn int64 + var ni int + var err error + for { + n := bytes.Index(s, a) + if n < 0 { + break + } + ni, err = w.Write(s[:n]) + nn += int64(ni) + if err != nil { + return nn, err + } s = s[n+len(a):] + n = bytes.Index(s, b) + if n < 0 { + // cannot find end tag - just write it to the output. + ni, _ = w.Write(a) + nn += int64(ni) + break + } ni, err = f(w, unsafeBytes2String(s[:n])) + nn += int64(ni) + if err != nil { + return nn, err + } + s = s[n+len(b):] + } + ni, err = w.Write(s) + nn += int64(ni) return nn, err + } // Execute substitutes template tags (placeholders) with the corresponding + // values from the map m and writes the result to the given writer w. + // + // Substitution map m may contain values with the following types: + // - []byte - the fastest value type + // - string - convenient value type + // - TagFunc - flexible value type + // + // Returns the number of bytes written to w. + // + // This function is optimized for constantly changing templates. + // Use Template.Execute for frozen templates. + func Execute(template, startTag, endTag string, w io.Writer, m map[string]interface{}) (int64, error) { + return ExecuteFunc(template, startTag, endTag, w, func(w io.Writer, tag string) (int, error) { return stdTagFunc(w, tag, m) }) + } // ExecuteStd works the same way as Execute, but keeps the unknown placeholders. + // This can be used as a drop-in replacement for strings.Replacer + // + // Substitution map m may contain values with the following types: + // - []byte - the fastest value type + // - string - convenient value type + // - TagFunc - flexible value type + // + // Returns the number of bytes written to w. + // + // This function is optimized for constantly changing templates. + // Use Template.ExecuteStd for frozen templates. + func ExecuteStd(template, startTag, endTag string, w io.Writer, m map[string]interface{}) (int64, error) { + return ExecuteFunc(template, startTag, endTag, w, func(w io.Writer, tag string) (int, error) { return keepUnknownTagFunc(w, startTag, endTag, tag, m) }) + } // ExecuteFuncString calls f on each template tag (placeholder) occurrence + // and substitutes it with the data written to TagFunc's w. + // + // Returns the resulting string. + // + // This function is optimized for constantly changing templates. + // Use Template.ExecuteFuncString for frozen templates. + func ExecuteFuncString(template, startTag, endTag string, f TagFunc) string { + s, err := ExecuteFuncStringWithErr(template, startTag, endTag, f) + if err != nil { + panic(fmt.Sprintf("unexpected error: %s", err)) + } + return s + } // ExecuteFuncStringWithErr is nearly the same as ExecuteFuncString + // but when f returns an error, ExecuteFuncStringWithErr won't panic like ExecuteFuncString + // it just returns an empty string and the error f returned + func ExecuteFuncStringWithErr(template, startTag, endTag string, f TagFunc) (string, error) { + if n := bytes.Index(unsafeString2Bytes(template), unsafeString2Bytes(startTag)); n < 0 { + return template, nil + } bb := byteBufferPool.Get() + if _, err := ExecuteFunc(template, startTag, endTag, bb, f); err != nil { + bb.Reset() + byteBufferPool.Put(bb) + return "", err + } + s := string(bb.B) + bb.Reset() + byteBufferPool.Put(bb) + return s, nil + } var byteBufferPool bytebufferpool.Pool // ExecuteString substitutes template tags (placeholders) with the corresponding + // values from the map m and returns the result. + // + // Substitution map m may contain values with the following types: + // - []byte - the fastest value type + // - string - convenient value type + // - TagFunc - flexible value type + // + // This function is optimized for constantly changing templates. + // Use Template.ExecuteString for frozen templates. + func ExecuteString(template, startTag, endTag string, m map[string]interface{}) string { + return ExecuteFuncString(template, startTag, endTag, func(w io.Writer, tag string) (int, error) { return stdTagFunc(w, tag, m) }) + } // ExecuteStringStd works the same way as ExecuteString, but keeps the unknown placeholders. + // This can be used as a drop-in replacement for strings.Replacer + // + // Substitution map m may contain values with the following types: + // - []byte - the fastest value type + // - string - convenient value type + // - TagFunc - flexible value type + // + // This function is optimized for constantly changing templates. + // Use Template.ExecuteStringStd for frozen templates. + func ExecuteStringStd(template, startTag, endTag string, m map[string]interface{}) string { + return ExecuteFuncString(template, startTag, endTag, func(w io.Writer, tag string) (int, error) { return keepUnknownTagFunc(w, startTag, endTag, tag, m) }) + } // Template implements simple template engine, which can be used for fast + // tags' (aka placeholders) substitution. + type Template struct { template string - startTag string - endTag string - texts [][]byte - tags []string + startTag string + + endTag string + + texts [][]byte + + tags []string + byteBufferPool bytebufferpool.Pool } // New parses the given template using the given startTag and endTag + // as tag start and tag end. + // + // The returned template can be executed by concurrently running goroutines + // using Execute* methods. + // + // New panics if the given template cannot be parsed. Use NewTemplate instead + // if template may contain errors. + func New(template, startTag, endTag string) *Template { + t, err := NewTemplate(template, startTag, endTag) + if err != nil { + panic(err) + } + return t + } // NewTemplate parses the given template using the given startTag and endTag + // as tag start and tag end. + // + // The returned template can be executed by concurrently running goroutines + // using Execute* methods. + func NewTemplate(template, startTag, endTag string) (*Template, error) { + var t Template + err := t.Reset(template, startTag, endTag) + if err != nil { + return nil, err + } + return &t, nil + } // TagFunc can be used as a substitution value in the map passed to Execute*. + // Execute* functions pass tag (placeholder) name in 'tag' argument. + // + // TagFunc must be safe to call from concurrently running goroutines. + // + // TagFunc must write contents to w and return the number of bytes written. + type TagFunc func(w io.Writer, tag string) (int, error) // Reset resets the template t to new one defined by + // template, startTag and endTag. + // + // Reset allows Template object re-use. + // + // Reset may be called only if no other goroutines call t methods at the moment. + func (t *Template) Reset(template, startTag, endTag string) error { + // Keep these vars in t, so GC won't collect them and won't break + // vars derived via unsafe* + t.template = template + t.startTag = startTag + t.endTag = endTag + t.texts = t.texts[:0] + t.tags = t.tags[:0] if len(startTag) == 0 { + panic("startTag cannot be empty") + } + if len(endTag) == 0 { + panic("endTag cannot be empty") + } s := unsafeString2Bytes(template) + a := unsafeString2Bytes(startTag) + b := unsafeString2Bytes(endTag) tagsCount := bytes.Count(s, a) + if tagsCount == 0 { + return nil + } if tagsCount+1 > cap(t.texts) { + t.texts = make([][]byte, 0, tagsCount+1) + } + if tagsCount > cap(t.tags) { + t.tags = make([]string, 0, tagsCount) + } for { + n := bytes.Index(s, a) + if n < 0 { + t.texts = append(t.texts, s) + break + } + t.texts = append(t.texts, s[:n]) s = s[n+len(a):] + n = bytes.Index(s, b) + if n < 0 { + return fmt.Errorf("Cannot find end tag=%q in the template=%q starting from %q", endTag, template, s) + } t.tags = append(t.tags, unsafeBytes2String(s[:n])) + s = s[n+len(b):] + } return nil + } // ExecuteFunc calls f on each template tag (placeholder) occurrence. + // + // Returns the number of bytes written to w. + // + // This function is optimized for frozen templates. + // Use ExecuteFunc for constantly changing templates. + func (t *Template) ExecuteFunc(w io.Writer, f TagFunc) (int64, error) { + var nn int64 n := len(t.texts) - 1 + if n == -1 { + ni, err := w.Write(unsafeString2Bytes(t.template)) + return int64(ni), err + } for i := 0; i < n; i++ { + ni, err := w.Write(t.texts[i]) + nn += int64(ni) + if err != nil { + return nn, err + } ni, err = f(w, t.tags[i]) + nn += int64(ni) + if err != nil { + return nn, err + } + } + ni, err := w.Write(t.texts[n]) + nn += int64(ni) + return nn, err + } // Execute substitutes template tags (placeholders) with the corresponding + // values from the map m and writes the result to the given writer w. + // + // Substitution map m may contain values with the following types: + // - []byte - the fastest value type + // - string - convenient value type + // - TagFunc - flexible value type + // + // Returns the number of bytes written to w. + func (t *Template) Execute(w io.Writer, m map[string]interface{}) (int64, error) { + return t.ExecuteFunc(w, func(w io.Writer, tag string) (int, error) { return stdTagFunc(w, tag, m) }) + } // ExecuteStd works the same way as Execute, but keeps the unknown placeholders. + // This can be used as a drop-in replacement for strings.Replacer + // + // Substitution map m may contain values with the following types: + // - []byte - the fastest value type + // - string - convenient value type + // - TagFunc - flexible value type + // + // Returns the number of bytes written to w. + func (t *Template) ExecuteStd(w io.Writer, m map[string]interface{}) (int64, error) { + return t.ExecuteFunc(w, func(w io.Writer, tag string) (int, error) { return keepUnknownTagFunc(w, t.startTag, t.endTag, tag, m) }) + } // ExecuteFuncString calls f on each template tag (placeholder) occurrence + // and substitutes it with the data written to TagFunc's w. + // + // Returns the resulting string. + // + // This function is optimized for frozen templates. + // Use ExecuteFuncString for constantly changing templates. + func (t *Template) ExecuteFuncString(f TagFunc) string { + s, err := t.ExecuteFuncStringWithErr(f) + if err != nil { + panic(fmt.Sprintf("unexpected error: %s", err)) + } + return s + } // ExecuteFuncStringWithErr calls f on each template tag (placeholder) occurrence + // and substitutes it with the data written to TagFunc's w. + // + // Returns the resulting string. + // + // This function is optimized for frozen templates. + // Use ExecuteFuncString for constantly changing templates. + func (t *Template) ExecuteFuncStringWithErr(f TagFunc) (string, error) { + bb := t.byteBufferPool.Get() + if _, err := t.ExecuteFunc(bb, f); err != nil { + bb.Reset() + t.byteBufferPool.Put(bb) + return "", err + } + s := string(bb.Bytes()) + bb.Reset() + t.byteBufferPool.Put(bb) + return s, nil + } // ExecuteString substitutes template tags (placeholders) with the corresponding + // values from the map m and returns the result. + // + // Substitution map m may contain values with the following types: + // - []byte - the fastest value type + // - string - convenient value type + // - TagFunc - flexible value type + // + // This function is optimized for frozen templates. + // Use ExecuteString for constantly changing templates. + func (t *Template) ExecuteString(m map[string]interface{}) string { + return t.ExecuteFuncString(func(w io.Writer, tag string) (int, error) { return stdTagFunc(w, tag, m) }) + } // ExecuteStringStd works the same way as ExecuteString, but keeps the unknown placeholders. + // This can be used as a drop-in replacement for strings.Replacer + // + // Substitution map m may contain values with the following types: + // - []byte - the fastest value type + // - string - convenient value type + // - TagFunc - flexible value type + // + // This function is optimized for frozen templates. + // Use ExecuteStringStd for constantly changing templates. + func (t *Template) ExecuteStringStd(m map[string]interface{}) string { + return t.ExecuteFuncString(func(w io.Writer, tag string) (int, error) { return keepUnknownTagFunc(w, t.startTag, t.endTag, tag, m) }) + } func stdTagFunc(w io.Writer, tag string, m map[string]interface{}) (int, error) { + v := m[tag] + if v == nil { + return 0, nil + } + switch value := v.(type) { + case []byte: + return w.Write(value) + case string: + return w.Write([]byte(value)) + case TagFunc: + return value(w, tag) + default: + panic(fmt.Sprintf("tag=%q contains unexpected value type=%#v. Expected []byte, string or TagFunc", tag, v)) + } + } func keepUnknownTagFunc(w io.Writer, startTag, endTag, tag string, m map[string]interface{}) (int, error) { + v, ok := m[tag] + if !ok { + if _, err := w.Write(unsafeString2Bytes(startTag)); err != nil { + return 0, err + } + if _, err := w.Write(unsafeString2Bytes(tag)); err != nil { + return 0, err + } + if _, err := w.Write(unsafeString2Bytes(endTag)); err != nil { + return 0, err + } + return len(startTag) + len(tag) + len(endTag), nil + } + if v == nil { + return 0, nil + } + switch value := v.(type) { + case []byte: + return w.Write(value) + case string: + return w.Write([]byte(value)) + case TagFunc: + return value(w, tag) + default: + panic(fmt.Sprintf("tag=%q contains unexpected value type=%#v. Expected []byte, string or TagFunc", tag, v)) + } + } diff --git a/vendor/github.com/valyala/fasttemplate/unsafe.go b/vendor/github.com/valyala/fasttemplate/unsafe.go index 1d0bc9e..553a065 100644 --- a/vendor/github.com/valyala/fasttemplate/unsafe.go +++ b/vendor/github.com/valyala/fasttemplate/unsafe.go @@ -9,14 +9,23 @@ import ( ) func unsafeBytes2String(b []byte) string { + return *(*string)(unsafe.Pointer(&b)) + } func unsafeString2Bytes(s string) (b []byte) { + sh := (*reflect.StringHeader)(unsafe.Pointer(&s)) + bh := (*reflect.SliceHeader)(unsafe.Pointer(&b)) + bh.Data = sh.Data + bh.Cap = sh.Len + bh.Len = sh.Len + return b + } diff --git a/vendor/golang.org/x/crypto/acme/acme.go b/vendor/golang.org/x/crypto/acme/acme.go index aaafea2..c50c744 100644 --- a/vendor/golang.org/x/crypto/acme/acme.go +++ b/vendor/golang.org/x/crypto/acme/acme.go @@ -1,22 +1,39 @@ // Copyright 2015 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Package acme provides an implementation of the + // Automatic Certificate Management Environment (ACME) spec, + // most famously used by Let's Encrypt. + // + // The initial implementation of this package was based on an early version + // of the spec. The current implementation supports only the modern + // RFC 8555 but some of the old API surface remains for compatibility. + // While code using the old API will still compile, it will return an error. + // Note the deprecation comments to update your code. + // + // See https://tools.ietf.org/html/rfc8555 for the spec. + // + // Most common scenarios will want to use autocert subdirectory instead, + // which provides automatic access to certificates from Let's Encrypt + // and any other ACME-based CA. + package acme import ( @@ -44,775 +61,1398 @@ import ( ) const ( + // LetsEncryptURL is the Directory endpoint of Let's Encrypt CA. + LetsEncryptURL = "https://acme-v02.api.letsencrypt.org/directory" // ALPNProto is the ALPN protocol name used by a CA server when validating + // tls-alpn-01 challenges. + // + // Package users must ensure their servers can negotiate the ACME ALPN in + // order for tls-alpn-01 challenge verifications to succeed. + // See the crypto/tls package's Config.NextProtos field. + ALPNProto = "acme-tls/1" ) // idPeACMEIdentifier is the OID for the ACME extension for the TLS-ALPN challenge. + // https://tools.ietf.org/html/draft-ietf-acme-tls-alpn-05#section-5.1 + var idPeACMEIdentifier = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 31} const ( - maxChainLen = 5 // max depth and breadth of a certificate chain + maxChainLen = 5 // max depth and breadth of a certificate chain + maxCertSize = 1 << 20 // max size of a certificate, in DER bytes + // Used for decoding certs from application/pem-certificate-chain response, + // the default when in RFC mode. + maxCertChainSize = maxCertSize * maxChainLen // Max number of collected nonces kept in memory. + // Expect usual peak of 1 or 2. + maxNonces = 100 ) // Client is an ACME client. + // + // The only required field is Key. An example of creating a client with a new key + // is as follows: + // + // key, err := rsa.GenerateKey(rand.Reader, 2048) + // if err != nil { + // log.Fatal(err) + // } + // client := &Client{Key: key} + type Client struct { + // Key is the account key used to register with a CA and sign requests. + // Key.Public() must return a *rsa.PublicKey or *ecdsa.PublicKey. + // + // The following algorithms are supported: + // RS256, ES256, ES384 and ES512. + // See RFC 7518 for more details about the algorithms. + Key crypto.Signer // HTTPClient optionally specifies an HTTP client to use + // instead of http.DefaultClient. + HTTPClient *http.Client // DirectoryURL points to the CA directory endpoint. + // If empty, LetsEncryptURL is used. + // Mutating this value after a successful call of Client's Discover method + // will have no effect. + DirectoryURL string // RetryBackoff computes the duration after which the nth retry of a failed request + // should occur. The value of n for the first call on failure is 1. + // The values of r and resp are the request and response of the last failed attempt. + // If the returned value is negative or zero, no more retries are done and an error + // is returned to the caller of the original method. + // + // Requests which result in a 4xx client error are not retried, + // except for 400 Bad Request due to "bad nonce" errors and 429 Too Many Requests. + // + // If RetryBackoff is nil, a truncated exponential backoff algorithm + // with the ceiling of 10 seconds is used, where each subsequent retry n + // is done after either ("Retry-After" + jitter) or (2^n seconds + jitter), + // preferring the former if "Retry-After" header is found in the resp. + // The jitter is a random value up to 1 second. + RetryBackoff func(n int, r *http.Request, resp *http.Response) time.Duration // UserAgent is prepended to the User-Agent header sent to the ACME server, + // which by default is this package's name and version. + // + // Reusable libraries and tools in particular should set this value to be + // identifiable by the server, in case they are causing issues. + UserAgent string cacheMu sync.Mutex - dir *Directory // cached result of Client's Discover method + + dir *Directory // cached result of Client's Discover method + // KID is the key identifier provided by the CA. If not provided it will be + // retrieved from the CA by making a call to the registration endpoint. + KID KeyID noncesMu sync.Mutex - nonces map[string]struct{} // nonces collected from previous responses + + nonces map[string]struct{} // nonces collected from previous responses + } // accountKID returns a key ID associated with c.Key, the account identity + // provided by the CA during RFC based registration. + // It assumes c.Discover has already been called. + // + // accountKID requires at most one network roundtrip. + // It caches only successful result. + // + // When in pre-RFC mode or when c.getRegRFC responds with an error, accountKID + // returns noKeyID. + func (c *Client) accountKID(ctx context.Context) KeyID { + c.cacheMu.Lock() + defer c.cacheMu.Unlock() + if c.KID != noKeyID { + return c.KID + } + a, err := c.getRegRFC(ctx) + if err != nil { + return noKeyID + } + c.KID = KeyID(a.URI) + return c.KID + } var errPreRFC = errors.New("acme: server does not support the RFC 8555 version of ACME") // Discover performs ACME server discovery using c.DirectoryURL. + // + // It caches successful result. So, subsequent calls will not result in + // a network round-trip. This also means mutating c.DirectoryURL after successful call + // of this method will have no effect. + func (c *Client) Discover(ctx context.Context) (Directory, error) { + c.cacheMu.Lock() + defer c.cacheMu.Unlock() + if c.dir != nil { + return *c.dir, nil + } res, err := c.get(ctx, c.directoryURL(), wantStatus(http.StatusOK)) + if err != nil { + return Directory{}, err + } + defer res.Body.Close() + c.addNonce(res.Header) var v struct { - Reg string `json:"newAccount"` - Authz string `json:"newAuthz"` - Order string `json:"newOrder"` - Revoke string `json:"revokeCert"` - Nonce string `json:"newNonce"` + Reg string `json:"newAccount"` + + Authz string `json:"newAuthz"` + + Order string `json:"newOrder"` + + Revoke string `json:"revokeCert"` + + Nonce string `json:"newNonce"` + KeyChange string `json:"keyChange"` - Meta struct { - Terms string `json:"termsOfService"` - Website string `json:"website"` - CAA []string `json:"caaIdentities"` - ExternalAcct bool `json:"externalAccountRequired"` + + Meta struct { + Terms string `json:"termsOfService"` + + Website string `json:"website"` + + CAA []string `json:"caaIdentities"` + + ExternalAcct bool `json:"externalAccountRequired"` } } + if err := json.NewDecoder(res.Body).Decode(&v); err != nil { + return Directory{}, err + } + if v.Order == "" { + return Directory{}, errPreRFC + } + c.dir = &Directory{ - RegURL: v.Reg, - AuthzURL: v.Authz, - OrderURL: v.Order, - RevokeURL: v.Revoke, - NonceURL: v.Nonce, - KeyChangeURL: v.KeyChange, - Terms: v.Meta.Terms, - Website: v.Meta.Website, - CAA: v.Meta.CAA, + + RegURL: v.Reg, + + AuthzURL: v.Authz, + + OrderURL: v.Order, + + RevokeURL: v.Revoke, + + NonceURL: v.Nonce, + + KeyChangeURL: v.KeyChange, + + Terms: v.Meta.Terms, + + Website: v.Meta.Website, + + CAA: v.Meta.CAA, + ExternalAccountRequired: v.Meta.ExternalAcct, } + return *c.dir, nil + } func (c *Client) directoryURL() string { + if c.DirectoryURL != "" { + return c.DirectoryURL + } + return LetsEncryptURL + } // CreateCert was part of the old version of ACME. It is incompatible with RFC 8555. + // + // Deprecated: this was for the pre-RFC 8555 version of ACME. Callers should use CreateOrderCert. + func (c *Client) CreateCert(ctx context.Context, csr []byte, exp time.Duration, bundle bool) (der [][]byte, certURL string, err error) { + return nil, "", errPreRFC + } // FetchCert retrieves already issued certificate from the given url, in DER format. + // It retries the request until the certificate is successfully retrieved, + // context is cancelled by the caller or an error response is received. + // + // If the bundle argument is true, the returned value also contains the CA (issuer) + // certificate chain. + // + // FetchCert returns an error if the CA's response or chain was unreasonably large. + // Callers are encouraged to parse the returned value to ensure the certificate is valid + // and has expected features. + func (c *Client) FetchCert(ctx context.Context, url string, bundle bool) ([][]byte, error) { + if _, err := c.Discover(ctx); err != nil { + return nil, err + } + return c.fetchCertRFC(ctx, url, bundle) + } // RevokeCert revokes a previously issued certificate cert, provided in DER format. + // + // The key argument, used to sign the request, must be authorized + // to revoke the certificate. It's up to the CA to decide which keys are authorized. + // For instance, the key pair of the certificate may be authorized. + // If the key is nil, c.Key is used instead. + func (c *Client) RevokeCert(ctx context.Context, key crypto.Signer, cert []byte, reason CRLReasonCode) error { + if _, err := c.Discover(ctx); err != nil { + return err + } + return c.revokeCertRFC(ctx, key, cert, reason) + } // AcceptTOS always returns true to indicate the acceptance of a CA's Terms of Service + // during account registration. See Register method of Client for more details. + func AcceptTOS(tosURL string) bool { return true } // Register creates a new account with the CA using c.Key. + // It returns the registered account. The account acct is not modified. + // + // The registration may require the caller to agree to the CA's Terms of Service (TOS). + // If so, and the account has not indicated the acceptance of the terms (see Account for details), + // Register calls prompt with a TOS URL provided by the CA. Prompt should report + // whether the caller agrees to the terms. To always accept the terms, the caller can use AcceptTOS. + // + // When interfacing with an RFC-compliant CA, non-RFC 8555 fields of acct are ignored + // and prompt is called if Directory's Terms field is non-zero. + // Also see Error's Instance field for when a CA requires already registered accounts to agree + // to an updated Terms of Service. + func (c *Client) Register(ctx context.Context, acct *Account, prompt func(tosURL string) bool) (*Account, error) { + if c.Key == nil { + return nil, errors.New("acme: client.Key must be set to Register") + } + if _, err := c.Discover(ctx); err != nil { + return nil, err + } + return c.registerRFC(ctx, acct, prompt) + } // GetReg retrieves an existing account associated with c.Key. + // + // The url argument is a legacy artifact of the pre-RFC 8555 API + // and is ignored. + func (c *Client) GetReg(ctx context.Context, url string) (*Account, error) { + if _, err := c.Discover(ctx); err != nil { + return nil, err + } + return c.getRegRFC(ctx) + } // UpdateReg updates an existing registration. + // It returns an updated account copy. The provided account is not modified. + // + // The account's URI is ignored and the account URL associated with + // c.Key is used instead. + func (c *Client) UpdateReg(ctx context.Context, acct *Account) (*Account, error) { + if _, err := c.Discover(ctx); err != nil { + return nil, err + } + return c.updateRegRFC(ctx, acct) + } // AccountKeyRollover attempts to transition a client's account key to a new key. + // On success client's Key is updated which is not concurrency safe. + // On failure an error will be returned. + // The new key is already registered with the ACME provider if the following is true: + // - error is of type acme.Error + // - StatusCode should be 409 (Conflict) + // - Location header will have the KID of the associated account + // + // More about account key rollover can be found at + // https://tools.ietf.org/html/rfc8555#section-7.3.5. + func (c *Client) AccountKeyRollover(ctx context.Context, newKey crypto.Signer) error { + return c.accountKeyRollover(ctx, newKey) + } // Authorize performs the initial step in the pre-authorization flow, + // as opposed to order-based flow. + // The caller will then need to choose from and perform a set of returned + // challenges using c.Accept in order to successfully complete authorization. + // + // Once complete, the caller can use AuthorizeOrder which the CA + // should provision with the already satisfied authorization. + // For pre-RFC CAs, the caller can proceed directly to requesting a certificate + // using CreateCert method. + // + // If an authorization has been previously granted, the CA may return + // a valid authorization which has its Status field set to StatusValid. + // + // More about pre-authorization can be found at + // https://tools.ietf.org/html/rfc8555#section-7.4.1. + func (c *Client) Authorize(ctx context.Context, domain string) (*Authorization, error) { + return c.authorize(ctx, "dns", domain) + } // AuthorizeIP is the same as Authorize but requests IP address authorization. + // Clients which successfully obtain such authorization may request to issue + // a certificate for IP addresses. + // + // See the ACME spec extension for more details about IP address identifiers: + // https://tools.ietf.org/html/draft-ietf-acme-ip. + func (c *Client) AuthorizeIP(ctx context.Context, ipaddr string) (*Authorization, error) { + return c.authorize(ctx, "ip", ipaddr) + } func (c *Client) authorize(ctx context.Context, typ, val string) (*Authorization, error) { + if _, err := c.Discover(ctx); err != nil { + return nil, err + } type authzID struct { - Type string `json:"type"` + Type string `json:"type"` + Value string `json:"value"` } - req := struct { - Resource string `json:"resource"` - Identifier authzID `json:"identifier"` - }{ - Resource: "new-authz", - Identifier: authzID{Type: typ, Value: val}, - } - res, err := c.post(ctx, nil, c.dir.AuthzURL, req, wantStatus(http.StatusCreated)) - if err != nil { - return nil, err - } - defer res.Body.Close() - - var v wireAuthz - if err := json.NewDecoder(res.Body).Decode(&v); err != nil { - return nil, fmt.Errorf("acme: invalid response: %v", err) - } - if v.Status != StatusPending && v.Status != StatusValid { - return nil, fmt.Errorf("acme: unexpected status: %s", v.Status) - } - return v.authorization(res.Header.Get("Location")), nil -} - -// GetAuthorization retrieves an authorization identified by the given URL. -// -// If a caller needs to poll an authorization until its status is final, -// see the WaitAuthorization method. -func (c *Client) GetAuthorization(ctx context.Context, url string) (*Authorization, error) { - if _, err := c.Discover(ctx); err != nil { - return nil, err - } - - res, err := c.postAsGet(ctx, url, wantStatus(http.StatusOK)) - if err != nil { - return nil, err - } - defer res.Body.Close() - var v wireAuthz - if err := json.NewDecoder(res.Body).Decode(&v); err != nil { - return nil, fmt.Errorf("acme: invalid response: %v", err) - } - return v.authorization(url), nil -} - -// RevokeAuthorization relinquishes an existing authorization identified -// by the given URL. -// The url argument is an Authorization.URI value. -// -// If successful, the caller will be required to obtain a new authorization -// using the Authorize or AuthorizeOrder methods before being able to request -// a new certificate for the domain associated with the authorization. -// -// It does not revoke existing certificates. -func (c *Client) RevokeAuthorization(ctx context.Context, url string) error { - if _, err := c.Discover(ctx); err != nil { - return err - } req := struct { Resource string `json:"resource"` - Status string `json:"status"` - Delete bool `json:"delete"` + + Identifier authzID `json:"identifier"` }{ - Resource: "authz", - Status: "deactivated", - Delete: true, + + Resource: "new-authz", + + Identifier: authzID{Type: typ, Value: val}, } - res, err := c.post(ctx, nil, url, req, wantStatus(http.StatusOK)) + + res, err := c.post(ctx, nil, c.dir.AuthzURL, req, wantStatus(http.StatusCreated)) + if err != nil { - return err + + return nil, err + } + defer res.Body.Close() + + var v wireAuthz + + if err := json.NewDecoder(res.Body).Decode(&v); err != nil { + + return nil, fmt.Errorf("acme: invalid response: %v", err) + + } + + if v.Status != StatusPending && v.Status != StatusValid { + + return nil, fmt.Errorf("acme: unexpected status: %s", v.Status) + + } + + return v.authorization(res.Header.Get("Location")), nil + +} + +// GetAuthorization retrieves an authorization identified by the given URL. + +// + +// If a caller needs to poll an authorization until its status is final, + +// see the WaitAuthorization method. + +func (c *Client) GetAuthorization(ctx context.Context, url string) (*Authorization, error) { + + if _, err := c.Discover(ctx); err != nil { + + return nil, err + + } + + res, err := c.postAsGet(ctx, url, wantStatus(http.StatusOK)) + + if err != nil { + + return nil, err + + } + + defer res.Body.Close() + + var v wireAuthz + + if err := json.NewDecoder(res.Body).Decode(&v); err != nil { + + return nil, fmt.Errorf("acme: invalid response: %v", err) + + } + + return v.authorization(url), nil + +} + +// RevokeAuthorization relinquishes an existing authorization identified + +// by the given URL. + +// The url argument is an Authorization.URI value. + +// + +// If successful, the caller will be required to obtain a new authorization + +// using the Authorize or AuthorizeOrder methods before being able to request + +// a new certificate for the domain associated with the authorization. + +// + +// It does not revoke existing certificates. + +func (c *Client) RevokeAuthorization(ctx context.Context, url string) error { + + if _, err := c.Discover(ctx); err != nil { + + return err + + } + + req := struct { + Resource string `json:"resource"` + + Status string `json:"status"` + + Delete bool `json:"delete"` + }{ + + Resource: "authz", + + Status: "deactivated", + + Delete: true, + } + + res, err := c.post(ctx, nil, url, req, wantStatus(http.StatusOK)) + + if err != nil { + + return err + + } + + defer res.Body.Close() + return nil + } // WaitAuthorization polls an authorization at the given URL + // until it is in one of the final states, StatusValid or StatusInvalid, + // the ACME CA responded with a 4xx error code, or the context is done. + // + // It returns a non-nil Authorization only if its Status is StatusValid. + // In all other cases WaitAuthorization returns an error. + // If the Status is StatusInvalid, the returned error is of type *AuthorizationError. + func (c *Client) WaitAuthorization(ctx context.Context, url string) (*Authorization, error) { + if _, err := c.Discover(ctx); err != nil { + return nil, err + } + for { + res, err := c.postAsGet(ctx, url, wantStatus(http.StatusOK, http.StatusAccepted)) + if err != nil { + return nil, err + } var raw wireAuthz + err = json.NewDecoder(res.Body).Decode(&raw) + res.Body.Close() + switch { + case err != nil: + // Skip and retry. + case raw.Status == StatusValid: + return raw.authorization(url), nil + case raw.Status == StatusInvalid: + return nil, raw.error(url) + } // Exponential backoff is implemented in c.get above. + // This is just to prevent continuously hitting the CA + // while waiting for a final authorization status. + d := retryAfter(res.Header.Get("Retry-After")) + if d == 0 { + // Given that the fastest challenges TLS-SNI and HTTP-01 + // require a CA to make at least 1 network round trip + // and most likely persist a challenge state, + // this default delay seems reasonable. + d = time.Second + } + t := time.NewTimer(d) + select { + case <-ctx.Done(): + t.Stop() + return nil, ctx.Err() + case <-t.C: + // Retry. + } + } + } // GetChallenge retrieves the current status of an challenge. + // + // A client typically polls a challenge status using this method. + func (c *Client) GetChallenge(ctx context.Context, url string) (*Challenge, error) { + if _, err := c.Discover(ctx); err != nil { + return nil, err + } res, err := c.postAsGet(ctx, url, wantStatus(http.StatusOK, http.StatusAccepted)) + if err != nil { + return nil, err + } defer res.Body.Close() + v := wireChallenge{URI: url} + if err := json.NewDecoder(res.Body).Decode(&v); err != nil { + return nil, fmt.Errorf("acme: invalid response: %v", err) + } + return v.challenge(), nil + } // Accept informs the server that the client accepts one of its challenges + // previously obtained with c.Authorize. + // + // The server will then perform the validation asynchronously. + func (c *Client) Accept(ctx context.Context, chal *Challenge) (*Challenge, error) { + if _, err := c.Discover(ctx); err != nil { + return nil, err + } res, err := c.post(ctx, nil, chal.URI, json.RawMessage("{}"), wantStatus( - http.StatusOK, // according to the spec + + http.StatusOK, // according to the spec + http.StatusAccepted, // Let's Encrypt: see https://goo.gl/WsJ7VT (acme-divergences.md) + )) + if err != nil { + return nil, err + } + defer res.Body.Close() var v wireChallenge + if err := json.NewDecoder(res.Body).Decode(&v); err != nil { + return nil, fmt.Errorf("acme: invalid response: %v", err) + } + return v.challenge(), nil + } // DNS01ChallengeRecord returns a DNS record value for a dns-01 challenge response. + // A TXT record containing the returned value must be provisioned under + // "_acme-challenge" name of the domain being validated. + // + // The token argument is a Challenge.Token value. + func (c *Client) DNS01ChallengeRecord(token string) (string, error) { + ka, err := keyAuth(c.Key.Public(), token) + if err != nil { + return "", err + } + b := sha256.Sum256([]byte(ka)) + return base64.RawURLEncoding.EncodeToString(b[:]), nil + } // HTTP01ChallengeResponse returns the response for an http-01 challenge. + // Servers should respond with the value to HTTP requests at the URL path + // provided by HTTP01ChallengePath to validate the challenge and prove control + // over a domain name. + // + // The token argument is a Challenge.Token value. + func (c *Client) HTTP01ChallengeResponse(token string) (string, error) { + return keyAuth(c.Key.Public(), token) + } // HTTP01ChallengePath returns the URL path at which the response for an http-01 challenge + // should be provided by the servers. + // The response value can be obtained with HTTP01ChallengeResponse. + // + // The token argument is a Challenge.Token value. + func (c *Client) HTTP01ChallengePath(token string) string { + return "/.well-known/acme-challenge/" + token + } // TLSSNI01ChallengeCert creates a certificate for TLS-SNI-01 challenge response. + // + // Deprecated: This challenge type is unused in both draft-02 and RFC versions of the ACME spec. + func (c *Client) TLSSNI01ChallengeCert(token string, opt ...CertOption) (cert tls.Certificate, name string, err error) { + ka, err := keyAuth(c.Key.Public(), token) + if err != nil { + return tls.Certificate{}, "", err + } + b := sha256.Sum256([]byte(ka)) + h := hex.EncodeToString(b[:]) + name = fmt.Sprintf("%s.%s.acme.invalid", h[:32], h[32:]) + cert, err = tlsChallengeCert([]string{name}, opt) + if err != nil { + return tls.Certificate{}, "", err + } + return cert, name, nil + } // TLSSNI02ChallengeCert creates a certificate for TLS-SNI-02 challenge response. + // + // Deprecated: This challenge type is unused in both draft-02 and RFC versions of the ACME spec. + func (c *Client) TLSSNI02ChallengeCert(token string, opt ...CertOption) (cert tls.Certificate, name string, err error) { + b := sha256.Sum256([]byte(token)) + h := hex.EncodeToString(b[:]) + sanA := fmt.Sprintf("%s.%s.token.acme.invalid", h[:32], h[32:]) ka, err := keyAuth(c.Key.Public(), token) + if err != nil { + return tls.Certificate{}, "", err + } + b = sha256.Sum256([]byte(ka)) + h = hex.EncodeToString(b[:]) + sanB := fmt.Sprintf("%s.%s.ka.acme.invalid", h[:32], h[32:]) cert, err = tlsChallengeCert([]string{sanA, sanB}, opt) + if err != nil { + return tls.Certificate{}, "", err + } + return cert, sanA, nil + } // TLSALPN01ChallengeCert creates a certificate for TLS-ALPN-01 challenge response. + // Servers can present the certificate to validate the challenge and prove control + // over a domain name. For more details on TLS-ALPN-01 see + // https://tools.ietf.org/html/draft-shoemaker-acme-tls-alpn-00#section-3 + // + // The token argument is a Challenge.Token value. + // If a WithKey option is provided, its private part signs the returned cert, + // and the public part is used to specify the signee. + // If no WithKey option is provided, a new ECDSA key is generated using P-256 curve. + // + // The returned certificate is valid for the next 24 hours and must be presented only when + // the server name in the TLS ClientHello matches the domain, and the special acme-tls/1 ALPN protocol + // has been specified. + func (c *Client) TLSALPN01ChallengeCert(token, domain string, opt ...CertOption) (cert tls.Certificate, err error) { + ka, err := keyAuth(c.Key.Public(), token) + if err != nil { + return tls.Certificate{}, err + } + shasum := sha256.Sum256([]byte(ka)) + extValue, err := asn1.Marshal(shasum[:]) + if err != nil { + return tls.Certificate{}, err + } + acmeExtension := pkix.Extension{ - Id: idPeACMEIdentifier, + + Id: idPeACMEIdentifier, + Critical: true, - Value: extValue, + + Value: extValue, } tmpl := defaultTLSChallengeCertTemplate() var newOpt []CertOption + for _, o := range opt { + switch o := o.(type) { + case *certOptTemplate: + t := *(*x509.Certificate)(o) // shallow copy is ok + tmpl = &t + default: + newOpt = append(newOpt, o) + } + } + tmpl.ExtraExtensions = append(tmpl.ExtraExtensions, acmeExtension) + newOpt = append(newOpt, WithTemplate(tmpl)) + return tlsChallengeCert([]string{domain}, newOpt) + } // popNonce returns a nonce value previously stored with c.addNonce + // or fetches a fresh one from c.dir.NonceURL. + // If NonceURL is empty, it first tries c.directoryURL() and, failing that, + // the provided url. + func (c *Client) popNonce(ctx context.Context, url string) (string, error) { + c.noncesMu.Lock() + defer c.noncesMu.Unlock() + if len(c.nonces) == 0 { + if c.dir != nil && c.dir.NonceURL != "" { + return c.fetchNonce(ctx, c.dir.NonceURL) + } + dirURL := c.directoryURL() + v, err := c.fetchNonce(ctx, dirURL) + if err != nil && url != dirURL { + v, err = c.fetchNonce(ctx, url) + } + return v, err + } + var nonce string + for nonce = range c.nonces { + delete(c.nonces, nonce) + break + } + return nonce, nil + } // clearNonces clears any stored nonces + func (c *Client) clearNonces() { + c.noncesMu.Lock() + defer c.noncesMu.Unlock() + c.nonces = make(map[string]struct{}) + } // addNonce stores a nonce value found in h (if any) for future use. + func (c *Client) addNonce(h http.Header) { + v := nonceFromHeader(h) + if v == "" { + return + } + c.noncesMu.Lock() + defer c.noncesMu.Unlock() + if len(c.nonces) >= maxNonces { + return + } + if c.nonces == nil { + c.nonces = make(map[string]struct{}) + } + c.nonces[v] = struct{}{} + } func (c *Client) fetchNonce(ctx context.Context, url string) (string, error) { + r, err := http.NewRequest("HEAD", url, nil) + if err != nil { + return "", err + } + resp, err := c.doNoRetry(ctx, r) + if err != nil { + return "", err + } + defer resp.Body.Close() + nonce := nonceFromHeader(resp.Header) + if nonce == "" { + if resp.StatusCode > 299 { + return "", responseError(resp) + } + return "", errors.New("acme: nonce not found") + } + return nonce, nil + } func nonceFromHeader(h http.Header) string { + return h.Get("Replay-Nonce") + } // linkHeader returns URI-Reference values of all Link headers + // with relation-type rel. + // See https://tools.ietf.org/html/rfc5988#section-5 for details. + func linkHeader(h http.Header, rel string) []string { + var links []string + for _, v := range h["Link"] { + parts := strings.Split(v, ";") + for _, p := range parts { + p = strings.TrimSpace(p) + if !strings.HasPrefix(p, "rel=") { + continue + } + if v := strings.Trim(p[4:], `"`); v == rel { + links = append(links, strings.Trim(parts[0], "<>")) + } + } + } + return links + } // keyAuth generates a key authorization string for a given token. + func keyAuth(pub crypto.PublicKey, token string) (string, error) { + th, err := JWKThumbprint(pub) + if err != nil { + return "", err + } + return fmt.Sprintf("%s.%s", token, th), nil + } // defaultTLSChallengeCertTemplate is a template used to create challenge certs for TLS challenges. + func defaultTLSChallengeCertTemplate() *x509.Certificate { + return &x509.Certificate{ - SerialNumber: big.NewInt(1), - NotBefore: time.Now(), - NotAfter: time.Now().Add(24 * time.Hour), + + SerialNumber: big.NewInt(1), + + NotBefore: time.Now(), + + NotAfter: time.Now().Add(24 * time.Hour), + BasicConstraintsValid: true, - KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, - ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + + KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, + + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, } + } // tlsChallengeCert creates a temporary certificate for TLS-SNI challenges + // with the given SANs and auto-generated public/private key pair. + // The Subject Common Name is set to the first SAN to aid debugging. + // To create a cert with a custom key pair, specify WithKey option. + func tlsChallengeCert(san []string, opt []CertOption) (tls.Certificate, error) { + var key crypto.Signer + tmpl := defaultTLSChallengeCertTemplate() + for _, o := range opt { + switch o := o.(type) { + case *certOptKey: + if key != nil { + return tls.Certificate{}, errors.New("acme: duplicate key option") + } + key = o.key + case *certOptTemplate: + t := *(*x509.Certificate)(o) // shallow copy is ok + tmpl = &t + default: + // package's fault, if we let this happen: + panic(fmt.Sprintf("unsupported option type %T", o)) + } + } + if key == nil { + var err error + if key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader); err != nil { + return tls.Certificate{}, err + } + } + tmpl.DNSNames = san + if len(san) > 0 { + tmpl.Subject.CommonName = san[0] + } der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key) + if err != nil { + return tls.Certificate{}, err + } + return tls.Certificate{ + Certificate: [][]byte{der}, - PrivateKey: key, + + PrivateKey: key, }, nil + } // encodePEM returns b encoded as PEM with block of type typ. + func encodePEM(typ string, b []byte) []byte { + pb := &pem.Block{Type: typ, Bytes: b} + return pem.EncodeToMemory(pb) + } // timeNow is time.Now, except in tests which can mess with it. + var timeNow = time.Now diff --git a/vendor/golang.org/x/crypto/acme/autocert/autocert.go b/vendor/golang.org/x/crypto/acme/autocert/autocert.go index 6b4cdf4..9c3528a 100644 --- a/vendor/golang.org/x/crypto/acme/autocert/autocert.go +++ b/vendor/golang.org/x/crypto/acme/autocert/autocert.go @@ -1,11 +1,17 @@ // Copyright 2016 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Package autocert provides automatic access to certificates from Let's Encrypt + // and any other ACME-based CA. + // + // This package is a work in progress and makes no API stability promises. + package autocert import ( @@ -36,1163 +42,2112 @@ import ( ) // DefaultACMEDirectory is the default ACME Directory URL used when the Manager's Client is nil. + const DefaultACMEDirectory = "https://acme-v02.api.letsencrypt.org/directory" // createCertRetryAfter is how much time to wait before removing a failed state + // entry due to an unsuccessful createCert call. + // This is a variable instead of a const for testing. + // TODO: Consider making it configurable or an exp backoff? + var createCertRetryAfter = time.Minute // pseudoRand is safe for concurrent use. + var pseudoRand *lockedMathRand var errPreRFC = errors.New("autocert: ACME server doesn't support RFC 8555") func init() { + src := mathrand.NewSource(time.Now().UnixNano()) + pseudoRand = &lockedMathRand{rnd: mathrand.New(src)} + } // AcceptTOS is a Manager.Prompt function that always returns true to + // indicate acceptance of the CA's Terms of Service during account + // registration. + func AcceptTOS(tosURL string) bool { return true } // HostPolicy specifies which host names the Manager is allowed to respond to. + // It returns a non-nil error if the host should be rejected. + // The returned error is accessible via tls.Conn.Handshake and its callers. + // See Manager's HostPolicy field and GetCertificate method docs for more details. + type HostPolicy func(ctx context.Context, host string) error // HostWhitelist returns a policy where only the specified host names are allowed. + // Only exact matches are currently supported. Subdomains, regexp or wildcard + // will not match. + // + // Note that all hosts will be converted to Punycode via idna.Lookup.ToASCII so that + // Manager.GetCertificate can handle the Unicode IDN and mixedcase hosts correctly. + // Invalid hosts will be silently ignored. + func HostWhitelist(hosts ...string) HostPolicy { + whitelist := make(map[string]bool, len(hosts)) + for _, h := range hosts { + if h, err := idna.Lookup.ToASCII(h); err == nil { + whitelist[h] = true + } + } + return func(_ context.Context, host string) error { + if !whitelist[host] { + return fmt.Errorf("acme/autocert: host %q not configured in HostWhitelist", host) + } + return nil + } + } // defaultHostPolicy is used when Manager.HostPolicy is not set. + func defaultHostPolicy(context.Context, string) error { + return nil + } // Manager is a stateful certificate manager built on top of acme.Client. + // It obtains and refreshes certificates automatically using "tls-alpn-01" + // or "http-01" challenge types, as well as providing them to a TLS server + // via tls.Config. + // + // You must specify a cache implementation, such as DirCache, + // to reuse obtained certificates across program restarts. + // Otherwise your server is very likely to exceed the certificate + // issuer's request rate limits. + type Manager struct { + // Prompt specifies a callback function to conditionally accept a CA's Terms of Service (TOS). + // The registration may require the caller to agree to the CA's TOS. + // If so, Manager calls Prompt with a TOS URL provided by the CA. Prompt should report + // whether the caller agrees to the terms. + // + // To always accept the terms, the callers can use AcceptTOS. + Prompt func(tosURL string) bool // Cache optionally stores and retrieves previously-obtained certificates + // and other state. If nil, certs will only be cached for the lifetime of + // the Manager. Multiple Managers can share the same Cache. + // + // Using a persistent Cache, such as DirCache, is strongly recommended. + Cache Cache // HostPolicy controls which domains the Manager will attempt + // to retrieve new certificates for. It does not affect cached certs. + // + // If non-nil, HostPolicy is called before requesting a new cert. + // If nil, all hosts are currently allowed. This is not recommended, + // as it opens a potential attack where clients connect to a server + // by IP address and pretend to be asking for an incorrect host name. + // Manager will attempt to obtain a certificate for that host, incorrectly, + // eventually reaching the CA's rate limit for certificate requests + // and making it impossible to obtain actual certificates. + // + // See GetCertificate for more details. + HostPolicy HostPolicy // RenewBefore optionally specifies how early certificates should + // be renewed before they expire. + // + // If zero, they're renewed 30 days before expiration. + RenewBefore time.Duration // Client is used to perform low-level operations, such as account registration + // and requesting new certificates. + // + // If Client is nil, a zero-value acme.Client is used with DefaultACMEDirectory + // as the directory endpoint. + // If the Client.Key is nil, a new ECDSA P-256 key is generated and, + // if Cache is not nil, stored in cache. + // + // Mutating the field after the first call of GetCertificate method will have no effect. + Client *acme.Client // Email optionally specifies a contact email address. + // This is used by CAs, such as Let's Encrypt, to notify about problems + // with issued certificates. + // + // If the Client's account key is already registered, Email is not used. + Email string // ForceRSA used to make the Manager generate RSA certificates. It is now ignored. + // + // Deprecated: the Manager will request the correct type of certificate based + // on what each client supports. + ForceRSA bool // ExtraExtensions are used when generating a new CSR (Certificate Request), + // thus allowing customization of the resulting certificate. + // For instance, TLS Feature Extension (RFC 7633) can be used + // to prevent an OCSP downgrade attack. + // + // The field value is passed to crypto/x509.CreateCertificateRequest + // in the template's ExtraExtensions field as is. + ExtraExtensions []pkix.Extension // ExternalAccountBinding optionally represents an arbitrary binding to an + // account of the CA to which the ACME server is tied. + // See RFC 8555, Section 7.3.4 for more details. + ExternalAccountBinding *acme.ExternalAccountBinding clientMu sync.Mutex - client *acme.Client // initialized by acmeClient method + + client *acme.Client // initialized by acmeClient method stateMu sync.Mutex - state map[certKey]*certState + + state map[certKey]*certState // renewal tracks the set of domains currently running renewal timers. + renewalMu sync.Mutex - renewal map[certKey]*domainRenewal + + renewal map[certKey]*domainRenewal // challengeMu guards tryHTTP01, certTokens and httpTokens. + challengeMu sync.RWMutex + // tryHTTP01 indicates whether the Manager should try "http-01" challenge type + // during the authorization flow. + tryHTTP01 bool + // httpTokens contains response body values for http-01 challenges + // and is keyed by the URL path at which a challenge response is expected + // to be provisioned. + // The entries are stored for the duration of the authorization flow. + httpTokens map[string][]byte + // certTokens contains temporary certificates for tls-alpn-01 challenges + // and is keyed by the domain name which matches the ClientHello server name. + // The entries are stored for the duration of the authorization flow. + certTokens map[string]*tls.Certificate // nowFunc, if not nil, returns the current time. This may be set for + // testing purposes. + nowFunc func() time.Time } // certKey is the key by which certificates are tracked in state, renewal and cache. + type certKey struct { - domain string // without trailing dot - isRSA bool // RSA cert for legacy clients (as opposed to default ECDSA) - isToken bool // tls-based challenge token cert; key type is undefined regardless of isRSA + domain string // without trailing dot + + isRSA bool // RSA cert for legacy clients (as opposed to default ECDSA) + + isToken bool // tls-based challenge token cert; key type is undefined regardless of isRSA + } func (c certKey) String() string { + if c.isToken { + return c.domain + "+token" + } + if c.isRSA { + return c.domain + "+rsa" + } + return c.domain + } // TLSConfig creates a new TLS config suitable for net/http.Server servers, + // supporting HTTP/2 and the tls-alpn-01 ACME challenge type. + func (m *Manager) TLSConfig() *tls.Config { + return &tls.Config{ + GetCertificate: m.GetCertificate, + NextProtos: []string{ + "h2", "http/1.1", // enable HTTP/2 + acme.ALPNProto, // enable tls-alpn ACME challenges + }, } + } // GetCertificate implements the tls.Config.GetCertificate hook. + // It provides a TLS certificate for hello.ServerName host, including answering + // tls-alpn-01 challenges. + // All other fields of hello are ignored. + // + // If m.HostPolicy is non-nil, GetCertificate calls the policy before requesting + // a new cert. A non-nil error returned from m.HostPolicy halts TLS negotiation. + // The error is propagated back to the caller of GetCertificate and is user-visible. + // This does not affect cached certs. See HostPolicy field description for more details. + // + // If GetCertificate is used directly, instead of via Manager.TLSConfig, package users will + // also have to add acme.ALPNProto to NextProtos for tls-alpn-01, or use HTTPHandler for http-01. + func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) { + if m.Prompt == nil { + return nil, errors.New("acme/autocert: Manager.Prompt not set") + } name := hello.ServerName + if name == "" { + return nil, errors.New("acme/autocert: missing server name") + } + if !strings.Contains(strings.Trim(name, "."), ".") { + return nil, errors.New("acme/autocert: server name component count invalid") + } // Note that this conversion is necessary because some server names in the handshakes + // started by some clients (such as cURL) are not converted to Punycode, which will + // prevent us from obtaining certificates for them. In addition, we should also treat + // example.com and EXAMPLE.COM as equivalent and return the same certificate for them. + // Fortunately, this conversion also helped us deal with this kind of mixedcase problems. + // + // Due to the "σςΣ" problem (see https://unicode.org/faq/idn.html#22), we can't use + // idna.Punycode.ToASCII (or just idna.ToASCII) here. + name, err := idna.Lookup.ToASCII(name) + if err != nil { + return nil, errors.New("acme/autocert: server name contains invalid character") + } // In the worst-case scenario, the timeout needs to account for caching, host policy, + // domain ownership verification and certificate issuance. + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) + defer cancel() // Check whether this is a token cert requested for TLS-ALPN challenge. + if wantsTokenCert(hello) { + m.challengeMu.RLock() + defer m.challengeMu.RUnlock() + if cert := m.certTokens[name]; cert != nil { + return cert, nil + } + if cert, err := m.cacheGet(ctx, certKey{domain: name, isToken: true}); err == nil { + return cert, nil + } + // TODO: cache error results? + return nil, fmt.Errorf("acme/autocert: no token cert for %q", name) + } // regular domain + ck := certKey{ + domain: strings.TrimSuffix(name, "."), // golang.org/issue/18114 - isRSA: !supportsECDSA(hello), + + isRSA: !supportsECDSA(hello), } + cert, err := m.cert(ctx, ck) + if err == nil { + return cert, nil + } + if err != ErrCacheMiss { + return nil, err + } // first-time + if err := m.hostPolicy()(ctx, name); err != nil { + return nil, err + } + cert, err = m.createCert(ctx, ck) + if err != nil { + return nil, err + } + m.cachePut(ctx, ck, cert) + return cert, nil + } // wantsTokenCert reports whether a TLS request with SNI is made by a CA server + // for a challenge verification. + func wantsTokenCert(hello *tls.ClientHelloInfo) bool { + // tls-alpn-01 + if len(hello.SupportedProtos) == 1 && hello.SupportedProtos[0] == acme.ALPNProto { + return true + } + return false + } func supportsECDSA(hello *tls.ClientHelloInfo) bool { + // The "signature_algorithms" extension, if present, limits the key exchange + // algorithms allowed by the cipher suites. See RFC 5246, section 7.4.1.4.1. + if hello.SignatureSchemes != nil { + ecdsaOK := false + schemeLoop: + for _, scheme := range hello.SignatureSchemes { + const tlsECDSAWithSHA1 tls.SignatureScheme = 0x0203 // constant added in Go 1.10 + switch scheme { + case tlsECDSAWithSHA1, tls.ECDSAWithP256AndSHA256, + tls.ECDSAWithP384AndSHA384, tls.ECDSAWithP521AndSHA512: + ecdsaOK = true + break schemeLoop + } + } + if !ecdsaOK { + return false + } + } + if hello.SupportedCurves != nil { + ecdsaOK := false + for _, curve := range hello.SupportedCurves { + if curve == tls.CurveP256 { + ecdsaOK = true + break + } + } + if !ecdsaOK { + return false + } + } + for _, suite := range hello.CipherSuites { + switch suite { + case tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, + tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, + tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, + tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, + tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, + tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, + tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305: + return true + } + } + return false + } // HTTPHandler configures the Manager to provision ACME "http-01" challenge responses. + // It returns an http.Handler that responds to the challenges and must be + // running on port 80. If it receives a request that is not an ACME challenge, + // it delegates the request to the optional fallback handler. + // + // If fallback is nil, the returned handler redirects all GET and HEAD requests + // to the default TLS port 443 with 302 Found status code, preserving the original + // request path and query. It responds with 400 Bad Request to all other HTTP methods. + // The fallback is not protected by the optional HostPolicy. + // + // Because the fallback handler is run with unencrypted port 80 requests, + // the fallback should not serve TLS-only requests. + // + // If HTTPHandler is never called, the Manager will only use the "tls-alpn-01" + // challenge for domain verification. + func (m *Manager) HTTPHandler(fallback http.Handler) http.Handler { + m.challengeMu.Lock() + defer m.challengeMu.Unlock() + m.tryHTTP01 = true if fallback == nil { + fallback = http.HandlerFunc(handleHTTPRedirect) + } + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.HasPrefix(r.URL.Path, "/.well-known/acme-challenge/") { + fallback.ServeHTTP(w, r) + return + } + // A reasonable context timeout for cache and host policy only, + // because we don't wait for a new certificate issuance here. + ctx, cancel := context.WithTimeout(r.Context(), time.Minute) + defer cancel() + if err := m.hostPolicy()(ctx, r.Host); err != nil { + http.Error(w, err.Error(), http.StatusForbidden) + return + } + data, err := m.httpToken(ctx, r.URL.Path) + if err != nil { + http.Error(w, err.Error(), http.StatusNotFound) + return + } + w.Write(data) + }) + } func handleHTTPRedirect(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" && r.Method != "HEAD" { + http.Error(w, "Use HTTPS", http.StatusBadRequest) + return + } + target := "https://" + stripPort(r.Host) + r.URL.RequestURI() + http.Redirect(w, r, target, http.StatusFound) + } func stripPort(hostport string) string { + host, _, err := net.SplitHostPort(hostport) + if err != nil { + return hostport + } + return net.JoinHostPort(host, "443") + } // cert returns an existing certificate either from m.state or cache. + // If a certificate is found in cache but not in m.state, the latter will be filled + // with the cached value. + func (m *Manager) cert(ctx context.Context, ck certKey) (*tls.Certificate, error) { + m.stateMu.Lock() + if s, ok := m.state[ck]; ok { + m.stateMu.Unlock() + s.RLock() + defer s.RUnlock() + return s.tlscert() + } + defer m.stateMu.Unlock() + cert, err := m.cacheGet(ctx, ck) + if err != nil { + return nil, err + } + signer, ok := cert.PrivateKey.(crypto.Signer) + if !ok { + return nil, errors.New("acme/autocert: private key cannot sign") + } + if m.state == nil { + m.state = make(map[certKey]*certState) + } + s := &certState{ - key: signer, + + key: signer, + cert: cert.Certificate, + leaf: cert.Leaf, } + m.state[ck] = s + m.startRenew(ck, s.key, s.leaf.NotAfter) + return cert, nil + } // cacheGet always returns a valid certificate, or an error otherwise. + // If a cached certificate exists but is not valid, ErrCacheMiss is returned. + func (m *Manager) cacheGet(ctx context.Context, ck certKey) (*tls.Certificate, error) { + if m.Cache == nil { + return nil, ErrCacheMiss + } + data, err := m.Cache.Get(ctx, ck.String()) + if err != nil { + return nil, err + } // private + priv, pub := pem.Decode(data) + if priv == nil || !strings.Contains(priv.Type, "PRIVATE") { + return nil, ErrCacheMiss + } + privKey, err := parsePrivateKey(priv.Bytes) + if err != nil { + return nil, err + } // public + var pubDER [][]byte + for len(pub) > 0 { + var b *pem.Block + b, pub = pem.Decode(pub) + if b == nil { + break + } + pubDER = append(pubDER, b.Bytes) + } + if len(pub) > 0 { + // Leftover content not consumed by pem.Decode. Corrupt. Ignore. + return nil, ErrCacheMiss + } // verify and create TLS cert + leaf, err := validCert(ck, pubDER, privKey, m.now()) + if err != nil { + return nil, ErrCacheMiss + } + tlscert := &tls.Certificate{ + Certificate: pubDER, - PrivateKey: privKey, - Leaf: leaf, + + PrivateKey: privKey, + + Leaf: leaf, } + return tlscert, nil + } func (m *Manager) cachePut(ctx context.Context, ck certKey, tlscert *tls.Certificate) error { + if m.Cache == nil { + return nil + } // contains PEM-encoded data + var buf bytes.Buffer // private + switch key := tlscert.PrivateKey.(type) { + case *ecdsa.PrivateKey: + if err := encodeECDSAKey(&buf, key); err != nil { + return err + } + case *rsa.PrivateKey: + b := x509.MarshalPKCS1PrivateKey(key) + pb := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: b} + if err := pem.Encode(&buf, pb); err != nil { + return err + } + default: + return errors.New("acme/autocert: unknown private key type") + } // public + for _, b := range tlscert.Certificate { + pb := &pem.Block{Type: "CERTIFICATE", Bytes: b} + if err := pem.Encode(&buf, pb); err != nil { + return err + } + } return m.Cache.Put(ctx, ck.String(), buf.Bytes()) + } func encodeECDSAKey(w io.Writer, key *ecdsa.PrivateKey) error { + b, err := x509.MarshalECPrivateKey(key) + if err != nil { + return err + } + pb := &pem.Block{Type: "EC PRIVATE KEY", Bytes: b} + return pem.Encode(w, pb) + } // createCert starts the domain ownership verification and returns a certificate + // for that domain upon success. + // + // If the domain is already being verified, it waits for the existing verification to complete. + // Either way, createCert blocks for the duration of the whole process. + func (m *Manager) createCert(ctx context.Context, ck certKey) (*tls.Certificate, error) { + // TODO: maybe rewrite this whole piece using sync.Once + state, err := m.certState(ck) + if err != nil { + return nil, err + } + // state may exist if another goroutine is already working on it + // in which case just wait for it to finish + if !state.locked { + state.RLock() + defer state.RUnlock() + return state.tlscert() + } // We are the first; state is locked. + // Unblock the readers when domain ownership is verified + // and we got the cert or the process failed. + defer state.Unlock() + state.locked = false der, leaf, err := m.authorizedCert(ctx, state.key, ck) + if err != nil { + // Remove the failed state after some time, + // making the manager call createCert again on the following TLS hello. + didRemove := testDidRemoveState // The lifetime of this timer is untracked, so copy mutable local state to avoid races. + time.AfterFunc(createCertRetryAfter, func() { + defer didRemove(ck) + m.stateMu.Lock() + defer m.stateMu.Unlock() + // Verify the state hasn't changed and it's still invalid + // before deleting. + s, ok := m.state[ck] + if !ok { + return + } + if _, err := validCert(ck, s.cert, s.key, m.now()); err == nil { + return + } + delete(m.state, ck) + }) + return nil, err + } + state.cert = der + state.leaf = leaf + m.startRenew(ck, state.key, state.leaf.NotAfter) + return state.tlscert() + } // certState returns a new or existing certState. + // If a new certState is returned, state.exist is false and the state is locked. + // The returned error is non-nil only in the case where a new state could not be created. + func (m *Manager) certState(ck certKey) (*certState, error) { + m.stateMu.Lock() + defer m.stateMu.Unlock() + if m.state == nil { + m.state = make(map[certKey]*certState) + } + // existing state + if state, ok := m.state[ck]; ok { + return state, nil + } // new locked state + var ( err error + key crypto.Signer ) + if ck.isRSA { + key, err = rsa.GenerateKey(rand.Reader, 2048) + } else { + key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + } + if err != nil { + return nil, err + } state := &certState{ - key: key, + + key: key, + locked: true, } + state.Lock() // will be unlocked by m.certState caller + m.state[ck] = state + return state, nil + } // authorizedCert starts the domain ownership verification process and requests a new cert upon success. + // The key argument is the certificate private key. + func (m *Manager) authorizedCert(ctx context.Context, key crypto.Signer, ck certKey) (der [][]byte, leaf *x509.Certificate, err error) { + csr, err := certRequest(key, ck.domain, m.ExtraExtensions) + if err != nil { + return nil, nil, err + } client, err := m.acmeClient(ctx) + if err != nil { + return nil, nil, err + } + dir, err := client.Discover(ctx) + if err != nil { + return nil, nil, err + } + if dir.OrderURL == "" { + return nil, nil, errPreRFC + } o, err := m.verifyRFC(ctx, client, ck.domain) + if err != nil { + return nil, nil, err + } + chain, _, err := client.CreateOrderCert(ctx, o.FinalizeURL, csr, true) + if err != nil { + return nil, nil, err + } leaf, err = validCert(ck, chain, key, m.now()) + if err != nil { + return nil, nil, err + } + return chain, leaf, nil + } // verifyRFC runs the identifier (domain) order-based authorization flow for RFC compliant CAs + // using each applicable ACME challenge type. + func (m *Manager) verifyRFC(ctx context.Context, client *acme.Client, domain string) (*acme.Order, error) { + // Try each supported challenge type starting with a new order each time. + // The nextTyp index of the next challenge type to try is shared across + // all order authorizations: if we've tried a challenge type once and it didn't work, + // it will most likely not work on another order's authorization either. + challengeTypes := m.supportedChallengeTypes() + nextTyp := 0 // challengeTypes index + AuthorizeOrderLoop: + for { + o, err := client.AuthorizeOrder(ctx, acme.DomainIDs(domain)) + if err != nil { + return nil, err + } + // Remove all hanging authorizations to reduce rate limit quotas + // after we're done. + defer func(urls []string) { + go m.deactivatePendingAuthz(urls) + }(o.AuthzURLs) // Check if there's actually anything we need to do. + switch o.Status { + case acme.StatusReady: + // Already authorized. + return o, nil + case acme.StatusPending: + // Continue normal Order-based flow. + default: + return nil, fmt.Errorf("acme/autocert: invalid new order status %q; order URL: %q", o.Status, o.URI) + } // Satisfy all pending authorizations. + for _, zurl := range o.AuthzURLs { + z, err := client.GetAuthorization(ctx, zurl) + if err != nil { + return nil, err + } + if z.Status != acme.StatusPending { + // We are interested only in pending authorizations. + continue + } + // Pick the next preferred challenge. + var chal *acme.Challenge + for chal == nil && nextTyp < len(challengeTypes) { + chal = pickChallenge(challengeTypes[nextTyp], z.Challenges) + nextTyp++ + } + if chal == nil { + return nil, fmt.Errorf("acme/autocert: unable to satisfy %q for domain %q: no viable challenge type found", z.URI, domain) + } + // Respond to the challenge and wait for validation result. + cleanup, err := m.fulfill(ctx, client, chal, domain) + if err != nil { + continue AuthorizeOrderLoop + } + defer cleanup() + if _, err := client.Accept(ctx, chal); err != nil { + continue AuthorizeOrderLoop + } + if _, err := client.WaitAuthorization(ctx, z.URI); err != nil { + continue AuthorizeOrderLoop + } + } // All authorizations are satisfied. + // Wait for the CA to update the order status. + o, err = client.WaitOrder(ctx, o.URI) + if err != nil { + continue AuthorizeOrderLoop + } + return o, nil + } + } func pickChallenge(typ string, chal []*acme.Challenge) *acme.Challenge { + for _, c := range chal { + if c.Type == typ { + return c + } + } + return nil + } func (m *Manager) supportedChallengeTypes() []string { + m.challengeMu.RLock() + defer m.challengeMu.RUnlock() + typ := []string{"tls-alpn-01"} + if m.tryHTTP01 { + typ = append(typ, "http-01") + } + return typ + } // deactivatePendingAuthz relinquishes all authorizations identified by the elements + // of the provided uri slice which are in "pending" state. + // It ignores revocation errors. + // + // deactivatePendingAuthz takes no context argument and instead runs with its own + // "detached" context because deactivations are done in a goroutine separate from + // that of the main issuance or renewal flow. + func (m *Manager) deactivatePendingAuthz(uri []string) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) + defer cancel() + client, err := m.acmeClient(ctx) + if err != nil { + return + } + for _, u := range uri { + z, err := client.GetAuthorization(ctx, u) + if err == nil && z.Status == acme.StatusPending { + client.RevokeAuthorization(ctx, u) + } + } + } // fulfill provisions a response to the challenge chal. + // The cleanup is non-nil only if provisioning succeeded. + func (m *Manager) fulfill(ctx context.Context, client *acme.Client, chal *acme.Challenge, domain string) (cleanup func(), err error) { + switch chal.Type { + case "tls-alpn-01": + cert, err := client.TLSALPN01ChallengeCert(chal.Token, domain) + if err != nil { + return nil, err + } + m.putCertToken(ctx, domain, &cert) + return func() { go m.deleteCertToken(domain) }, nil + case "http-01": + resp, err := client.HTTP01ChallengeResponse(chal.Token) + if err != nil { + return nil, err + } + p := client.HTTP01ChallengePath(chal.Token) + m.putHTTPToken(ctx, p, resp) + return func() { go m.deleteHTTPToken(p) }, nil + } + return nil, fmt.Errorf("acme/autocert: unknown challenge type %q", chal.Type) + } // putCertToken stores the token certificate with the specified name + // in both m.certTokens map and m.Cache. + func (m *Manager) putCertToken(ctx context.Context, name string, cert *tls.Certificate) { + m.challengeMu.Lock() + defer m.challengeMu.Unlock() + if m.certTokens == nil { + m.certTokens = make(map[string]*tls.Certificate) + } + m.certTokens[name] = cert + m.cachePut(ctx, certKey{domain: name, isToken: true}, cert) + } // deleteCertToken removes the token certificate with the specified name + // from both m.certTokens map and m.Cache. + func (m *Manager) deleteCertToken(name string) { + m.challengeMu.Lock() + defer m.challengeMu.Unlock() + delete(m.certTokens, name) + if m.Cache != nil { + ck := certKey{domain: name, isToken: true} + m.Cache.Delete(context.Background(), ck.String()) + } + } // httpToken retrieves an existing http-01 token value from an in-memory map + // or the optional cache. + func (m *Manager) httpToken(ctx context.Context, tokenPath string) ([]byte, error) { + m.challengeMu.RLock() + defer m.challengeMu.RUnlock() + if v, ok := m.httpTokens[tokenPath]; ok { + return v, nil + } + if m.Cache == nil { + return nil, fmt.Errorf("acme/autocert: no token at %q", tokenPath) + } + return m.Cache.Get(ctx, httpTokenCacheKey(tokenPath)) + } // putHTTPToken stores an http-01 token value using tokenPath as key + // in both in-memory map and the optional Cache. + // + // It ignores any error returned from Cache.Put. + func (m *Manager) putHTTPToken(ctx context.Context, tokenPath, val string) { + m.challengeMu.Lock() + defer m.challengeMu.Unlock() + if m.httpTokens == nil { + m.httpTokens = make(map[string][]byte) + } + b := []byte(val) + m.httpTokens[tokenPath] = b + if m.Cache != nil { + m.Cache.Put(ctx, httpTokenCacheKey(tokenPath), b) + } + } // deleteHTTPToken removes an http-01 token value from both in-memory map + // and the optional Cache, ignoring any error returned from the latter. + // + // If m.Cache is non-nil, it blocks until Cache.Delete returns without a timeout. + func (m *Manager) deleteHTTPToken(tokenPath string) { + m.challengeMu.Lock() + defer m.challengeMu.Unlock() + delete(m.httpTokens, tokenPath) + if m.Cache != nil { + m.Cache.Delete(context.Background(), httpTokenCacheKey(tokenPath)) + } + } // httpTokenCacheKey returns a key at which an http-01 token value may be stored + // in the Manager's optional Cache. + func httpTokenCacheKey(tokenPath string) string { + return path.Base(tokenPath) + "+http-01" + } // startRenew starts a cert renewal timer loop, one per domain. + // + // The loop is scheduled in two cases: + // - a cert was fetched from cache for the first time (wasn't in m.state) + // - a new cert was created by m.createCert + // + // The key argument is a certificate private key. + // The exp argument is the cert expiration time (NotAfter). + func (m *Manager) startRenew(ck certKey, key crypto.Signer, exp time.Time) { + m.renewalMu.Lock() + defer m.renewalMu.Unlock() + if m.renewal[ck] != nil { + // another goroutine is already on it + return + } + if m.renewal == nil { + m.renewal = make(map[certKey]*domainRenewal) + } + dr := &domainRenewal{m: m, ck: ck, key: key} + m.renewal[ck] = dr + dr.start(exp) + } // stopRenew stops all currently running cert renewal timers. + // The timers are not restarted during the lifetime of the Manager. + func (m *Manager) stopRenew() { + m.renewalMu.Lock() + defer m.renewalMu.Unlock() + for name, dr := range m.renewal { + delete(m.renewal, name) + dr.stop() + } + } func (m *Manager) accountKey(ctx context.Context) (crypto.Signer, error) { + const keyName = "acme_account+key" // Previous versions of autocert stored the value under a different key. + const legacyKeyName = "acme_account.key" genKey := func() (*ecdsa.PrivateKey, error) { + return ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + } if m.Cache == nil { + return genKey() + } data, err := m.Cache.Get(ctx, keyName) + if err == ErrCacheMiss { + data, err = m.Cache.Get(ctx, legacyKeyName) + } + if err == ErrCacheMiss { + key, err := genKey() + if err != nil { + return nil, err + } + var buf bytes.Buffer + if err := encodeECDSAKey(&buf, key); err != nil { + return nil, err + } + if err := m.Cache.Put(ctx, keyName, buf.Bytes()); err != nil { + return nil, err + } + return key, nil + } + if err != nil { + return nil, err + } priv, _ := pem.Decode(data) + if priv == nil || !strings.Contains(priv.Type, "PRIVATE") { + return nil, errors.New("acme/autocert: invalid account key found in cache") + } + return parsePrivateKey(priv.Bytes) + } func (m *Manager) acmeClient(ctx context.Context) (*acme.Client, error) { + m.clientMu.Lock() + defer m.clientMu.Unlock() + if m.client != nil { + return m.client, nil + } client := m.Client + if client == nil { + client = &acme.Client{DirectoryURL: DefaultACMEDirectory} + } + if client.Key == nil { + var err error + client.Key, err = m.accountKey(ctx) + if err != nil { + return nil, err + } + } + if client.UserAgent == "" { + client.UserAgent = "autocert" + } + var contact []string + if m.Email != "" { + contact = []string{"mailto:" + m.Email} + } + a := &acme.Account{Contact: contact, ExternalAccountBinding: m.ExternalAccountBinding} + _, err := client.Register(ctx, a, m.Prompt) + if err == nil || isAccountAlreadyExist(err) { + m.client = client + err = nil + } + return m.client, err + } // isAccountAlreadyExist reports whether the err, as returned from acme.Client.Register, + // indicates the account has already been registered. + func isAccountAlreadyExist(err error) bool { + if err == acme.ErrAccountAlreadyExists { + return true + } + ae, ok := err.(*acme.Error) + return ok && ae.StatusCode == http.StatusConflict + } func (m *Manager) hostPolicy() HostPolicy { + if m.HostPolicy != nil { + return m.HostPolicy + } + return defaultHostPolicy + } func (m *Manager) renewBefore() time.Duration { + if m.RenewBefore > renewJitter { + return m.RenewBefore + } + return 720 * time.Hour // 30 days + } func (m *Manager) now() time.Time { + if m.nowFunc != nil { + return m.nowFunc() + } + return time.Now() + } // certState is ready when its mutex is unlocked for reading. + type certState struct { sync.RWMutex - locked bool // locked for read/write - key crypto.Signer // private key for cert - cert [][]byte // DER encoding - leaf *x509.Certificate // parsed cert[0]; always non-nil if cert != nil + + locked bool // locked for read/write + + key crypto.Signer // private key for cert + + cert [][]byte // DER encoding + + leaf *x509.Certificate // parsed cert[0]; always non-nil if cert != nil + } // tlscert creates a tls.Certificate from s.key and s.cert. + // Callers should wrap it in s.RLock() and s.RUnlock(). + func (s *certState) tlscert() (*tls.Certificate, error) { + if s.key == nil { + return nil, errors.New("acme/autocert: missing signer") + } + if len(s.cert) == 0 { + return nil, errors.New("acme/autocert: missing certificate") + } + return &tls.Certificate{ - PrivateKey: s.key, + + PrivateKey: s.key, + Certificate: s.cert, - Leaf: s.leaf, + + Leaf: s.leaf, }, nil + } // certRequest generates a CSR for the given common name. + func certRequest(key crypto.Signer, name string, ext []pkix.Extension) ([]byte, error) { + req := &x509.CertificateRequest{ - Subject: pkix.Name{CommonName: name}, - DNSNames: []string{name}, + + Subject: pkix.Name{CommonName: name}, + + DNSNames: []string{name}, + ExtraExtensions: ext, } + return x509.CreateCertificateRequest(rand.Reader, req, key) + } // 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. + // + // Inspired by parsePrivateKey in crypto/tls/tls.go. + func parsePrivateKey(der []byte) (crypto.Signer, error) { + if key, err := x509.ParsePKCS1PrivateKey(der); err == nil { + return key, nil + } + if key, err := x509.ParsePKCS8PrivateKey(der); err == nil { + switch key := key.(type) { + case *rsa.PrivateKey: + return key, nil + case *ecdsa.PrivateKey: + return key, nil + default: + return nil, errors.New("acme/autocert: unknown private key type in PKCS#8 wrapping") + } + } + if key, err := x509.ParseECPrivateKey(der); err == nil { + return key, nil + } return nil, errors.New("acme/autocert: failed to parse private key") + } // validCert parses a cert chain provided as der argument and verifies the leaf and der[0] + // correspond to the private key, the domain and key type match, and expiration dates + // are valid. It doesn't do any revocation checking. + // + // The returned value is the verified leaf cert. + func validCert(ck certKey, der [][]byte, key crypto.Signer, now time.Time) (leaf *x509.Certificate, err error) { + // parse public part(s) + var n int + for _, b := range der { + n += len(b) + } + pub := make([]byte, n) + n = 0 + for _, b := range der { + n += copy(pub[n:], b) + } + x509Cert, err := x509.ParseCertificates(pub) + if err != nil || len(x509Cert) == 0 { + return nil, errors.New("acme/autocert: no public key found") + } + // verify the leaf is not expired and matches the domain name + leaf = x509Cert[0] + if now.Before(leaf.NotBefore) { + return nil, errors.New("acme/autocert: certificate is not valid yet") + } + if now.After(leaf.NotAfter) { + return nil, errors.New("acme/autocert: expired certificate") + } + if err := leaf.VerifyHostname(ck.domain); err != nil { + return nil, err + } + // renew certificates revoked by Let's Encrypt in January 2022 + if isRevokedLetsEncrypt(leaf) { + return nil, errors.New("acme/autocert: certificate was probably revoked by Let's Encrypt") + } + // ensure the leaf corresponds to the private key and matches the certKey type + switch pub := leaf.PublicKey.(type) { + case *rsa.PublicKey: + prv, ok := key.(*rsa.PrivateKey) + if !ok { + return nil, errors.New("acme/autocert: private key type does not match public key type") + } + if pub.N.Cmp(prv.N) != 0 { + return nil, errors.New("acme/autocert: private key does not match public key") + } + if !ck.isRSA && !ck.isToken { + return nil, errors.New("acme/autocert: key type does not match expected value") + } + case *ecdsa.PublicKey: + prv, ok := key.(*ecdsa.PrivateKey) + if !ok { + return nil, errors.New("acme/autocert: private key type does not match public key type") + } + if pub.X.Cmp(prv.X) != 0 || pub.Y.Cmp(prv.Y) != 0 { + return nil, errors.New("acme/autocert: private key does not match public key") + } + if ck.isRSA && !ck.isToken { + return nil, errors.New("acme/autocert: key type does not match expected value") + } + default: + return nil, errors.New("acme/autocert: unknown public key algorithm") + } + return leaf, nil + } // https://community.letsencrypt.org/t/2022-01-25-issue-with-tls-alpn-01-validation-method/170450 + var letsEncryptFixDeployTime = time.Date(2022, time.January, 26, 00, 48, 0, 0, time.UTC) // isRevokedLetsEncrypt returns whether the certificate is likely to be part of + // a batch of certificates revoked by Let's Encrypt in January 2022. This check + // can be safely removed from May 2022. + func isRevokedLetsEncrypt(cert *x509.Certificate) bool { + O := cert.Issuer.Organization + return len(O) == 1 && O[0] == "Let's Encrypt" && + cert.NotBefore.Before(letsEncryptFixDeployTime) + } type lockedMathRand struct { sync.Mutex + rnd *mathrand.Rand } func (r *lockedMathRand) int63n(max int64) int64 { + r.Lock() + n := r.rnd.Int63n(max) + r.Unlock() + return n + } // For easier testing. + var ( + // Called when a state is removed. + testDidRemoveState = func(certKey) {} ) diff --git a/vendor/golang.org/x/crypto/acme/autocert/cache.go b/vendor/golang.org/x/crypto/acme/autocert/cache.go index 758ab12..6cf395b 100644 --- a/vendor/golang.org/x/crypto/acme/autocert/cache.go +++ b/vendor/golang.org/x/crypto/acme/autocert/cache.go @@ -1,5 +1,7 @@ // Copyright 2016 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package autocert @@ -12,124 +14,222 @@ import ( ) // ErrCacheMiss is returned when a certificate is not found in cache. + var ErrCacheMiss = errors.New("acme/autocert: certificate cache miss") // Cache is used by Manager to store and retrieve previously obtained certificates + // and other account data as opaque blobs. + // + // Cache implementations should not rely on the key naming pattern. Keys can + // include any printable ASCII characters, except the following: \/:*?"<>| + type Cache interface { + // Get returns a certificate data for the specified key. + // If there's no such key, Get returns ErrCacheMiss. + Get(ctx context.Context, key string) ([]byte, error) // Put stores the data in the cache under the specified key. + // Underlying implementations may use any data storage format, + // as long as the reverse operation, Get, results in the original data. + Put(ctx context.Context, key string, data []byte) error // Delete removes a certificate data from the cache under the specified key. + // If there's no such key in the cache, Delete returns nil. + Delete(ctx context.Context, key string) error } // DirCache implements Cache using a directory on the local filesystem. + // If the directory does not exist, it will be created with 0700 permissions. + type DirCache string // Get reads a certificate data from the specified file name. + func (d DirCache) Get(ctx context.Context, name string) ([]byte, error) { + name = filepath.Join(string(d), filepath.Clean("/"+name)) + var ( data []byte - err error + + err error + done = make(chan struct{}) ) + go func() { + data, err = os.ReadFile(name) + close(done) + }() + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-done: + } + if os.IsNotExist(err) { + return nil, ErrCacheMiss + } + return data, err + } // Put writes the certificate data to the specified file name. + // The file will be created with 0600 permissions. + func (d DirCache) Put(ctx context.Context, name string, data []byte) error { + if err := os.MkdirAll(string(d), 0700); err != nil { + return err + } done := make(chan struct{}) + var err error + go func() { + defer close(done) + var tmp string + if tmp, err = d.writeTempFile(name, data); err != nil { + return + } + defer os.Remove(tmp) + select { + case <-ctx.Done(): + // Don't overwrite the file if the context was canceled. + default: + newName := filepath.Join(string(d), filepath.Clean("/"+name)) + err = os.Rename(tmp, newName) + } + }() + select { + case <-ctx.Done(): + return ctx.Err() + case <-done: + } + return err + } // Delete removes the specified file name. + func (d DirCache) Delete(ctx context.Context, name string) error { + name = filepath.Join(string(d), filepath.Clean("/"+name)) + var ( - err error + err error + done = make(chan struct{}) ) + go func() { + err = os.Remove(name) + close(done) + }() + select { + case <-ctx.Done(): + return ctx.Err() + case <-done: + } + if err != nil && !os.IsNotExist(err) { + return err + } + return nil + } // writeTempFile writes b to a temporary file, closes the file and returns its path. + func (d DirCache) writeTempFile(prefix string, b []byte) (name string, reterr error) { + // TempFile uses 0600 permissions + f, err := os.CreateTemp(string(d), prefix) + if err != nil { + return "", err + } + defer func() { + if reterr != nil { + os.Remove(f.Name()) + } + }() + if _, err := f.Write(b); err != nil { + f.Close() + return "", err + } + return f.Name(), f.Close() + } diff --git a/vendor/golang.org/x/crypto/acme/autocert/listener.go b/vendor/golang.org/x/crypto/acme/autocert/listener.go index 9d62f8c..9c90864 100644 --- a/vendor/golang.org/x/crypto/acme/autocert/listener.go +++ b/vendor/golang.org/x/crypto/acme/autocert/listener.go @@ -1,5 +1,7 @@ // Copyright 2017 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package autocert @@ -15,141 +17,255 @@ import ( ) // NewListener returns a net.Listener that listens on the standard TLS + // port (443) on all interfaces and returns *tls.Conn connections with + // LetsEncrypt certificates for the provided domain or domains. + // + // It enables one-line HTTPS servers: + // + // log.Fatal(http.Serve(autocert.NewListener("example.com"), handler)) + // + // NewListener is a convenience function for a common configuration. + // More complex or custom configurations can use the autocert.Manager + // type instead. + // + // Use of this function implies acceptance of the LetsEncrypt Terms of + // Service. If domains is not empty, the provided domains are passed + // to HostWhitelist. If domains is empty, the listener will do + // LetsEncrypt challenges for any requested domain, which is not + // recommended. + // + // Certificates are cached in a "golang-autocert" directory under an + // operating system-specific cache or temp directory. This may not + // be suitable for servers spanning multiple machines. + // + // The returned listener uses a *tls.Config that enables HTTP/2, and + // should only be used with servers that support HTTP/2. + // + // The returned Listener also enables TCP keep-alives on the accepted + // connections. The returned *tls.Conn are returned before their TLS + // handshake has completed. + func NewListener(domains ...string) net.Listener { + m := &Manager{ + Prompt: AcceptTOS, } + if len(domains) > 0 { + m.HostPolicy = HostWhitelist(domains...) + } + dir := cacheDir() + if err := os.MkdirAll(dir, 0700); err != nil { + log.Printf("warning: autocert.NewListener not using a cache: %v", err) + } else { + m.Cache = DirCache(dir) + } + return m.Listener() + } // Listener listens on the standard TLS port (443) on all interfaces + // and returns a net.Listener returning *tls.Conn connections. + // + // The returned listener uses a *tls.Config that enables HTTP/2, and + // should only be used with servers that support HTTP/2. + // + // The returned Listener also enables TCP keep-alives on the accepted + // connections. The returned *tls.Conn are returned before their TLS + // handshake has completed. + // + // Unlike NewListener, it is the caller's responsibility to initialize + // the Manager m's Prompt, Cache, HostPolicy, and other desired options. + func (m *Manager) Listener() net.Listener { + ln := &listener{ + conf: m.TLSConfig(), } + ln.tcpListener, ln.tcpListenErr = net.Listen("tcp", ":443") + return ln + } type listener struct { conf *tls.Config - tcpListener net.Listener + tcpListener net.Listener + tcpListenErr error } func (ln *listener) Accept() (net.Conn, error) { + if ln.tcpListenErr != nil { + return nil, ln.tcpListenErr + } + conn, err := ln.tcpListener.Accept() + if err != nil { + return nil, err + } + tcpConn := conn.(*net.TCPConn) // Because Listener is a convenience function, help out with + // this too. This is not possible for the caller to set once + // we return a *tcp.Conn wrapping an inaccessible net.Conn. + // If callers don't want this, they can do things the manual + // way and tweak as needed. But this is what net/http does + // itself, so copy that. If net/http changes, we can change + // here too. + tcpConn.SetKeepAlive(true) + tcpConn.SetKeepAlivePeriod(3 * time.Minute) return tls.Server(tcpConn, ln.conf), nil + } func (ln *listener) Addr() net.Addr { + if ln.tcpListener != nil { + return ln.tcpListener.Addr() + } + // net.Listen failed. Return something non-nil in case callers + // call Addr before Accept: + return &net.TCPAddr{IP: net.IP{0, 0, 0, 0}, Port: 443} + } func (ln *listener) Close() error { + if ln.tcpListenErr != nil { + return ln.tcpListenErr + } + return ln.tcpListener.Close() + } func homeDir() string { + if runtime.GOOS == "windows" { + return os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH") + } + if h := os.Getenv("HOME"); h != "" { + return h + } + return "/" + } func cacheDir() string { + const base = "golang-autocert" + switch runtime.GOOS { + case "darwin": + return filepath.Join(homeDir(), "Library", "Caches", base) + case "windows": + for _, ev := range []string{"APPDATA", "CSIDL_APPDATA", "TEMP", "TMP"} { + if v := os.Getenv(ev); v != "" { + return filepath.Join(v, base) + } + } + // Worst case: + return filepath.Join(homeDir(), base) + } + if xdg := os.Getenv("XDG_CACHE_HOME"); xdg != "" { + return filepath.Join(xdg, base) + } + return filepath.Join(homeDir(), ".cache", base) + } diff --git a/vendor/golang.org/x/crypto/acme/autocert/renewal.go b/vendor/golang.org/x/crypto/acme/autocert/renewal.go index 0df7da7..48b01e9 100644 --- a/vendor/golang.org/x/crypto/acme/autocert/renewal.go +++ b/vendor/golang.org/x/crypto/acme/autocert/renewal.go @@ -1,5 +1,7 @@ // Copyright 2016 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package autocert @@ -12,145 +14,262 @@ import ( ) // renewJitter is the maximum deviation from Manager.RenewBefore. + const renewJitter = time.Hour // domainRenewal tracks the state used by the periodic timers + // renewing a single domain's cert. + type domainRenewal struct { - m *Manager - ck certKey + m *Manager + + ck certKey + key crypto.Signer - timerMu sync.Mutex - timer *time.Timer + timerMu sync.Mutex + + timer *time.Timer + timerClose chan struct{} // if non-nil, renew closes this channel (and nils out the timer fields) instead of running + } // start starts a cert renewal timer at the time + // defined by the certificate expiration time exp. + // + // If the timer is already started, calling start is a noop. + func (dr *domainRenewal) start(exp time.Time) { + dr.timerMu.Lock() + defer dr.timerMu.Unlock() + if dr.timer != nil { + return + } + dr.timer = time.AfterFunc(dr.next(exp), dr.renew) + } // stop stops the cert renewal timer and waits for any in-flight calls to renew + // to complete. If the timer is already stopped, calling stop is a noop. + func (dr *domainRenewal) stop() { + dr.timerMu.Lock() + defer dr.timerMu.Unlock() + for { + if dr.timer == nil { + return + } + if dr.timer.Stop() { + dr.timer = nil + return + } else { + // dr.timer fired, and we acquired dr.timerMu before the renew callback did. + // (We know this because otherwise the renew callback would have reset dr.timer!) + timerClose := make(chan struct{}) + dr.timerClose = timerClose + dr.timerMu.Unlock() + <-timerClose + dr.timerMu.Lock() + } + } + } // renew is called periodically by a timer. + // The first renew call is kicked off by dr.start. + func (dr *domainRenewal) renew() { + dr.timerMu.Lock() + defer dr.timerMu.Unlock() + if dr.timerClose != nil { + close(dr.timerClose) + dr.timer, dr.timerClose = nil, nil + return + } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) + defer cancel() + // TODO: rotate dr.key at some point? + next, err := dr.do(ctx) + if err != nil { + next = renewJitter / 2 + next += time.Duration(pseudoRand.int63n(int64(next))) + } + testDidRenewLoop(next, err) + dr.timer = time.AfterFunc(next, dr.renew) + } // updateState locks and replaces the relevant Manager.state item with the given + // state. It additionally updates dr.key with the given state's key. + func (dr *domainRenewal) updateState(state *certState) { + dr.m.stateMu.Lock() + defer dr.m.stateMu.Unlock() + dr.key = state.key + dr.m.state[dr.ck] = state + } // do is similar to Manager.createCert but it doesn't lock a Manager.state item. + // Instead, it requests a new certificate independently and, upon success, + // replaces dr.m.state item with a new one and updates cache for the given domain. + // + // It may lock and update the Manager.state if the expiration date of the currently + // cached cert is far enough in the future. + // + // The returned value is a time interval after which the renewal should occur again. + func (dr *domainRenewal) do(ctx context.Context) (time.Duration, error) { + // a race is likely unavoidable in a distributed environment + // but we try nonetheless + if tlscert, err := dr.m.cacheGet(ctx, dr.ck); err == nil { + next := dr.next(tlscert.Leaf.NotAfter) + if next > dr.m.renewBefore()+renewJitter { + signer, ok := tlscert.PrivateKey.(crypto.Signer) + if ok { + state := &certState{ - key: signer, + + key: signer, + cert: tlscert.Certificate, + leaf: tlscert.Leaf, } + dr.updateState(state) + return next, nil + } + } + } der, leaf, err := dr.m.authorizedCert(ctx, dr.key, dr.ck) + if err != nil { + return 0, err + } + state := &certState{ - key: dr.key, + + key: dr.key, + cert: der, + leaf: leaf, } + tlscert, err := state.tlscert() + if err != nil { + return 0, err + } + if err := dr.m.cachePut(ctx, dr.ck, tlscert); err != nil { + return 0, err + } + dr.updateState(state) + return dr.next(leaf.NotAfter), nil + } func (dr *domainRenewal) next(expiry time.Time) time.Duration { + d := expiry.Sub(dr.m.now()) - dr.m.renewBefore() + // add a bit of randomness to renew deadline + n := pseudoRand.int63n(int64(renewJitter)) + d -= time.Duration(n) + if d < 0 { + return 0 + } + return d + } var testDidRenewLoop = func(next time.Duration, err error) {} diff --git a/vendor/golang.org/x/crypto/acme/http.go b/vendor/golang.org/x/crypto/acme/http.go index 58836e5..9bebd5a 100644 --- a/vendor/golang.org/x/crypto/acme/http.go +++ b/vendor/golang.org/x/crypto/acme/http.go @@ -1,5 +1,7 @@ // Copyright 2018 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package acme @@ -21,305 +23,568 @@ import ( ) // retryTimer encapsulates common logic for retrying unsuccessful requests. + // It is not safe for concurrent use. + type retryTimer struct { + // backoffFn provides backoff delay sequence for retries. + // See Client.RetryBackoff doc comment. + backoffFn func(n int, r *http.Request, res *http.Response) time.Duration + // n is the current retry attempt. + n int } func (t *retryTimer) inc() { + t.n++ + } // backoff pauses the current goroutine as described in Client.RetryBackoff. + func (t *retryTimer) backoff(ctx context.Context, r *http.Request, res *http.Response) error { + d := t.backoffFn(t.n, r, res) + if d <= 0 { + return fmt.Errorf("acme: no more retries for %s; tried %d time(s)", r.URL, t.n) + } + wakeup := time.NewTimer(d) + defer wakeup.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-wakeup.C: + return nil + } + } func (c *Client) retryTimer() *retryTimer { + f := c.RetryBackoff + if f == nil { + f = defaultBackoff + } + return &retryTimer{backoffFn: f} + } // defaultBackoff provides default Client.RetryBackoff implementation + // using a truncated exponential backoff algorithm, + // as described in Client.RetryBackoff. + // + // The n argument is always bounded between 1 and 30. + // The returned value is always greater than 0. + func defaultBackoff(n int, r *http.Request, res *http.Response) time.Duration { + const max = 10 * time.Second + var jitter time.Duration + if x, err := rand.Int(rand.Reader, big.NewInt(1000)); err == nil { + // Set the minimum to 1ms to avoid a case where + // an invalid Retry-After value is parsed into 0 below, + // resulting in the 0 returned value which would unintentionally + // stop the retries. + jitter = (1 + time.Duration(x.Int64())) * time.Millisecond + } + if v, ok := res.Header["Retry-After"]; ok { + return retryAfter(v[0]) + jitter + } if n < 1 { + n = 1 + } + if n > 30 { + n = 30 + } + d := time.Duration(1< max { + return max + } + return d + } // retryAfter parses a Retry-After HTTP header value, + // trying to convert v into an int (seconds) or use http.ParseTime otherwise. + // It returns zero value if v cannot be parsed. + func retryAfter(v string) time.Duration { + if i, err := strconv.Atoi(v); err == nil { + return time.Duration(i) * time.Second + } + t, err := http.ParseTime(v) + if err != nil { + return 0 + } + return t.Sub(timeNow()) + } // resOkay is a function that reports whether the provided response is okay. + // It is expected to keep the response body unread. + type resOkay func(*http.Response) bool // wantStatus returns a function which reports whether the code + // matches the status code of a response. + func wantStatus(codes ...int) resOkay { + return func(res *http.Response) bool { + for _, code := range codes { + if code == res.StatusCode { + return true + } + } + return false + } + } // get issues an unsigned GET request to the specified URL. + // It returns a non-error value only when ok reports true. + // + // get retries unsuccessful attempts according to c.RetryBackoff + // until the context is done or a non-retriable error is received. + func (c *Client) get(ctx context.Context, url string, ok resOkay) (*http.Response, error) { + retry := c.retryTimer() + for { + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return nil, err + } + res, err := c.doNoRetry(ctx, req) + switch { + case err != nil: + return nil, err + case ok(res): + return res, nil + case isRetriable(res.StatusCode): + retry.inc() + resErr := responseError(res) + res.Body.Close() + // Ignore the error value from retry.backoff + // and return the one from last retry, as received from the CA. + if retry.backoff(ctx, req, res) != nil { + return nil, resErr + } + default: + defer res.Body.Close() + return nil, responseError(res) + } + } + } // postAsGet is POST-as-GET, a replacement for GET in RFC 8555 + // as described in https://tools.ietf.org/html/rfc8555#section-6.3. + // It makes a POST request in KID form with zero JWS payload. + // See nopayload doc comments in jws.go. + func (c *Client) postAsGet(ctx context.Context, url string, ok resOkay) (*http.Response, error) { + return c.post(ctx, nil, url, noPayload, ok) + } // post issues a signed POST request in JWS format using the provided key + // to the specified URL. If key is nil, c.Key is used instead. + // It returns a non-error value only when ok reports true. + // + // post retries unsuccessful attempts according to c.RetryBackoff + // until the context is done or a non-retriable error is received. + // It uses postNoRetry to make individual requests. + func (c *Client) post(ctx context.Context, key crypto.Signer, url string, body interface{}, ok resOkay) (*http.Response, error) { + retry := c.retryTimer() + for { + res, req, err := c.postNoRetry(ctx, key, url, body) + if err != nil { + return nil, err + } + if ok(res) { + return res, nil + } + resErr := responseError(res) + res.Body.Close() + switch { + // Check for bad nonce before isRetriable because it may have been returned + // with an unretriable response code such as 400 Bad Request. + case isBadNonce(resErr): + // Consider any previously stored nonce values to be invalid. + c.clearNonces() + case !isRetriable(res.StatusCode): + return nil, resErr + } + retry.inc() + // Ignore the error value from retry.backoff + // and return the one from last retry, as received from the CA. + if err := retry.backoff(ctx, req, res); err != nil { + return nil, resErr + } + } + } // postNoRetry signs the body with the given key and POSTs it to the provided url. + // It is used by c.post to retry unsuccessful attempts. + // The body argument must be JSON-serializable. + // + // If key argument is nil, c.Key is used to sign the request. + // If key argument is nil and c.accountKID returns a non-zero keyID, + // the request is sent in KID form. Otherwise, JWK form is used. + // + // In practice, when interfacing with RFC-compliant CAs most requests are sent in KID form + // and JWK is used only when KID is unavailable: new account endpoint and certificate + // revocation requests authenticated by a cert key. + // See jwsEncodeJSON for other details. + func (c *Client) postNoRetry(ctx context.Context, key crypto.Signer, url string, body interface{}) (*http.Response, *http.Request, error) { + kid := noKeyID + if key == nil { + if c.Key == nil { + return nil, nil, errors.New("acme: Client.Key must be populated to make POST requests") + } + key = c.Key + kid = c.accountKID(ctx) + } + nonce, err := c.popNonce(ctx, url) + if err != nil { + return nil, nil, err + } + b, err := jwsEncodeJSON(body, key, kid, nonce, url) + if err != nil { + return nil, nil, err + } + req, err := http.NewRequest("POST", url, bytes.NewReader(b)) + if err != nil { + return nil, nil, err + } + req.Header.Set("Content-Type", "application/jose+json") + res, err := c.doNoRetry(ctx, req) + if err != nil { + return nil, nil, err + } + c.addNonce(res.Header) + return res, req, nil + } // doNoRetry issues a request req, replacing its context (if any) with ctx. + func (c *Client) doNoRetry(ctx context.Context, req *http.Request) (*http.Response, error) { + req.Header.Set("User-Agent", c.userAgent()) + res, err := c.httpClient().Do(req.WithContext(ctx)) + if err != nil { + select { + case <-ctx.Done(): + // Prefer the unadorned context error. + // (The acme package had tests assuming this, previously from ctxhttp's + // behavior, predating net/http supporting contexts natively) + // TODO(bradfitz): reconsider this in the future. But for now this + // requires no test updates. + return nil, ctx.Err() + default: + return nil, err + } + } + return res, nil + } func (c *Client) httpClient() *http.Client { + if c.HTTPClient != nil { + return c.HTTPClient + } + return http.DefaultClient + } // packageVersion is the version of the module that contains this package, for + // sending as part of the User-Agent header. It's set in version_go112.go. + var packageVersion string // userAgent returns the User-Agent header value. It includes the package name, + // the module version (if available), and the c.UserAgent value (if set). + func (c *Client) userAgent() string { + ua := "golang.org/x/crypto/acme" + if packageVersion != "" { + ua += "@" + packageVersion + } + if c.UserAgent != "" { + ua = c.UserAgent + " " + ua + } + return ua + } // isBadNonce reports whether err is an ACME "badnonce" error. + func isBadNonce(err error) bool { + // According to the spec badNonce is urn:ietf:params:acme:error:badNonce. + // However, ACME servers in the wild return their versions of the error. + // See https://tools.ietf.org/html/draft-ietf-acme-acme-02#section-5.4 + // and https://github.com/letsencrypt/boulder/blob/0e07eacb/docs/acme-divergences.md#section-66. + ae, ok := err.(*Error) + return ok && strings.HasSuffix(strings.ToLower(ae.ProblemType), ":badnonce") + } // isRetriable reports whether a request can be retried + // based on the response status code. + // + // Note that a "bad nonce" error is returned with a non-retriable 400 Bad Request code. + // Callers should parse the response and check with isBadNonce. + func isRetriable(code int) bool { + return code <= 399 || code >= 500 || code == http.StatusTooManyRequests + } // responseError creates an error of Error type from resp. + func responseError(resp *http.Response) error { + // don't care if ReadAll returns an error: + // json.Unmarshal will fail in that case anyway + b, _ := io.ReadAll(resp.Body) + e := &wireError{Status: resp.StatusCode} + if err := json.Unmarshal(b, e); err != nil { + // this is not a regular error response: + // populate detail with anything we received, + // e.Status will already contain HTTP response code value + e.Detail = string(b) + if e.Detail == "" { + e.Detail = resp.Status + } + } + return e.error(resp.Header) + } diff --git a/vendor/golang.org/x/crypto/acme/jws.go b/vendor/golang.org/x/crypto/acme/jws.go index b38828d..c71df94 100644 --- a/vendor/golang.org/x/crypto/acme/jws.go +++ b/vendor/golang.org/x/crypto/acme/jws.go @@ -1,5 +1,7 @@ // Copyright 2015 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package acme @@ -21,237 +23,431 @@ import ( ) // KeyID is the account key identity provided by a CA during registration. + type KeyID string // noKeyID indicates that jwsEncodeJSON should compute and use JWK instead of a KID. + // See jwsEncodeJSON for details. + const noKeyID = KeyID("") // noPayload indicates jwsEncodeJSON will encode zero-length octet string + // in a JWS request. This is called POST-as-GET in RFC 8555 and is used to make + // authenticated GET requests via POSTing with an empty payload. + // See https://tools.ietf.org/html/rfc8555#section-6.3 for more details. + const noPayload = "" // noNonce indicates that the nonce should be omitted from the protected header. + // See jwsEncodeJSON for details. + const noNonce = "" // jsonWebSignature can be easily serialized into a JWS following + // https://tools.ietf.org/html/rfc7515#section-3.2. + type jsonWebSignature struct { Protected string `json:"protected"` - Payload string `json:"payload"` - Sig string `json:"signature"` + + Payload string `json:"payload"` + + Sig string `json:"signature"` } // jwsEncodeJSON signs claimset using provided key and a nonce. + // The result is serialized in JSON format containing either kid or jwk + // fields based on the provided KeyID value. + // + // The claimset is marshalled using json.Marshal unless it is a string. + // In which case it is inserted directly into the message. + // + // If kid is non-empty, its quoted value is inserted in the protected header + // as "kid" field value. Otherwise, JWK is computed using jwkEncode and inserted + // as "jwk" field value. The "jwk" and "kid" fields are mutually exclusive. + // + // If nonce is non-empty, its quoted value is inserted in the protected header. + // + // See https://tools.ietf.org/html/rfc7515#section-7. + func jwsEncodeJSON(claimset interface{}, key crypto.Signer, kid KeyID, nonce, url string) ([]byte, error) { + if key == nil { + return nil, errors.New("nil key") + } + alg, sha := jwsHasher(key.Public()) + if alg == "" || !sha.Available() { + return nil, ErrUnsupportedKey + } + headers := struct { - Alg string `json:"alg"` - KID string `json:"kid,omitempty"` - JWK json.RawMessage `json:"jwk,omitempty"` - Nonce string `json:"nonce,omitempty"` - URL string `json:"url"` + Alg string `json:"alg"` + + KID string `json:"kid,omitempty"` + + JWK json.RawMessage `json:"jwk,omitempty"` + + Nonce string `json:"nonce,omitempty"` + + URL string `json:"url"` }{ - Alg: alg, + + Alg: alg, + Nonce: nonce, - URL: url, + + URL: url, } + switch kid { + case noKeyID: + jwk, err := jwkEncode(key.Public()) + if err != nil { + return nil, err + } + headers.JWK = json.RawMessage(jwk) + default: + headers.KID = string(kid) + } + phJSON, err := json.Marshal(headers) + if err != nil { + return nil, err + } + phead := base64.RawURLEncoding.EncodeToString([]byte(phJSON)) + var payload string + if val, ok := claimset.(string); ok { + payload = val + } else { + cs, err := json.Marshal(claimset) + if err != nil { + return nil, err + } + payload = base64.RawURLEncoding.EncodeToString(cs) + } + hash := sha.New() + hash.Write([]byte(phead + "." + payload)) + sig, err := jwsSign(key, sha, hash.Sum(nil)) + if err != nil { + return nil, err + } + enc := jsonWebSignature{ + Protected: phead, - Payload: payload, - Sig: base64.RawURLEncoding.EncodeToString(sig), + + Payload: payload, + + Sig: base64.RawURLEncoding.EncodeToString(sig), } + return json.Marshal(&enc) + } // jwsWithMAC creates and signs a JWS using the given key and the HS256 + // algorithm. kid and url are included in the protected header. rawPayload + // should not be base64-URL-encoded. + func jwsWithMAC(key []byte, kid, url string, rawPayload []byte) (*jsonWebSignature, error) { + if len(key) == 0 { + return nil, errors.New("acme: cannot sign JWS with an empty MAC key") + } + header := struct { Algorithm string `json:"alg"` - KID string `json:"kid"` - URL string `json:"url,omitempty"` + + KID string `json:"kid"` + + URL string `json:"url,omitempty"` }{ + // Only HMAC-SHA256 is supported. + Algorithm: "HS256", - KID: kid, - URL: url, + + KID: kid, + + URL: url, } + rawProtected, err := json.Marshal(header) + if err != nil { + return nil, err + } + protected := base64.RawURLEncoding.EncodeToString(rawProtected) + payload := base64.RawURLEncoding.EncodeToString(rawPayload) h := hmac.New(sha256.New, key) + if _, err := h.Write([]byte(protected + "." + payload)); err != nil { + return nil, err + } + mac := h.Sum(nil) return &jsonWebSignature{ + Protected: protected, - Payload: payload, - Sig: base64.RawURLEncoding.EncodeToString(mac), + + Payload: payload, + + Sig: base64.RawURLEncoding.EncodeToString(mac), }, nil + } // jwkEncode encodes public part of an RSA or ECDSA key into a JWK. + // The result is also suitable for creating a JWK thumbprint. + // https://tools.ietf.org/html/rfc7517 + func jwkEncode(pub crypto.PublicKey) (string, error) { + switch pub := pub.(type) { + case *rsa.PublicKey: + // https://tools.ietf.org/html/rfc7518#section-6.3.1 + n := pub.N + e := big.NewInt(int64(pub.E)) + // Field order is important. + // See https://tools.ietf.org/html/rfc7638#section-3.3 for details. + return fmt.Sprintf(`{"e":"%s","kty":"RSA","n":"%s"}`, + base64.RawURLEncoding.EncodeToString(e.Bytes()), + base64.RawURLEncoding.EncodeToString(n.Bytes()), ), nil + case *ecdsa.PublicKey: + // https://tools.ietf.org/html/rfc7518#section-6.2.1 + p := pub.Curve.Params() + n := p.BitSize / 8 + if p.BitSize%8 != 0 { + n++ + } + x := pub.X.Bytes() + if n > len(x) { + x = append(make([]byte, n-len(x)), x...) + } + y := pub.Y.Bytes() + if n > len(y) { + y = append(make([]byte, n-len(y)), y...) + } + // Field order is important. + // See https://tools.ietf.org/html/rfc7638#section-3.3 for details. + return fmt.Sprintf(`{"crv":"%s","kty":"EC","x":"%s","y":"%s"}`, + p.Name, + base64.RawURLEncoding.EncodeToString(x), + base64.RawURLEncoding.EncodeToString(y), ), nil + } + return "", ErrUnsupportedKey + } // jwsSign signs the digest using the given key. + // The hash is unused for ECDSA keys. + func jwsSign(key crypto.Signer, hash crypto.Hash, digest []byte) ([]byte, error) { + switch pub := key.Public().(type) { + case *rsa.PublicKey: + return key.Sign(rand.Reader, digest, hash) + case *ecdsa.PublicKey: + sigASN1, err := key.Sign(rand.Reader, digest, hash) + if err != nil { + return nil, err + } var rs struct{ R, S *big.Int } + if _, err := asn1.Unmarshal(sigASN1, &rs); err != nil { + return nil, err + } rb, sb := rs.R.Bytes(), rs.S.Bytes() + size := pub.Params().BitSize / 8 + if size%8 > 0 { + size++ + } + sig := make([]byte, size*2) + copy(sig[size-len(rb):], rb) + copy(sig[size*2-len(sb):], sb) + return sig, nil + } + return nil, ErrUnsupportedKey + } // jwsHasher indicates suitable JWS algorithm name and a hash function + // to use for signing a digest with the provided key. + // It returns ("", 0) if the key is not supported. + func jwsHasher(pub crypto.PublicKey) (string, crypto.Hash) { + switch pub := pub.(type) { + case *rsa.PublicKey: + return "RS256", crypto.SHA256 + case *ecdsa.PublicKey: + switch pub.Params().Name { + case "P-256": + return "ES256", crypto.SHA256 + case "P-384": + return "ES384", crypto.SHA384 + case "P-521": + return "ES512", crypto.SHA512 + } + } + return "", 0 + } // JWKThumbprint creates a JWK thumbprint out of pub + // as specified in https://tools.ietf.org/html/rfc7638. + func JWKThumbprint(pub crypto.PublicKey) (string, error) { + jwk, err := jwkEncode(pub) + if err != nil { + return "", err + } + b := sha256.Sum256([]byte(jwk)) + return base64.RawURLEncoding.EncodeToString(b[:]), nil + } diff --git a/vendor/golang.org/x/crypto/acme/rfc8555.go b/vendor/golang.org/x/crypto/acme/rfc8555.go index 3152e53..a2ad89a 100644 --- a/vendor/golang.org/x/crypto/acme/rfc8555.go +++ b/vendor/golang.org/x/crypto/acme/rfc8555.go @@ -1,5 +1,7 @@ // Copyright 2019 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package acme @@ -18,459 +20,827 @@ import ( ) // DeactivateReg permanently disables an existing account associated with c.Key. + // A deactivated account can no longer request certificate issuance or access + // resources related to the account, such as orders or authorizations. + // + // It only works with CAs implementing RFC 8555. + func (c *Client) DeactivateReg(ctx context.Context) error { + if _, err := c.Discover(ctx); err != nil { // required by c.accountKID + return err + } + url := string(c.accountKID(ctx)) + if url == "" { + return ErrNoAccount + } + req := json.RawMessage(`{"status": "deactivated"}`) + res, err := c.post(ctx, nil, url, req, wantStatus(http.StatusOK)) + if err != nil { + return err + } + res.Body.Close() + return nil + } // registerRFC is equivalent to c.Register but for CAs implementing RFC 8555. + // It expects c.Discover to have already been called. + func (c *Client) registerRFC(ctx context.Context, acct *Account, prompt func(tosURL string) bool) (*Account, error) { + c.cacheMu.Lock() // guard c.kid access + defer c.cacheMu.Unlock() req := struct { - TermsAgreed bool `json:"termsOfServiceAgreed,omitempty"` - Contact []string `json:"contact,omitempty"` + TermsAgreed bool `json:"termsOfServiceAgreed,omitempty"` + + Contact []string `json:"contact,omitempty"` + ExternalAccountBinding *jsonWebSignature `json:"externalAccountBinding,omitempty"` }{ + Contact: acct.Contact, } + if c.dir.Terms != "" { + req.TermsAgreed = prompt(c.dir.Terms) + } // set 'externalAccountBinding' field if requested + if acct.ExternalAccountBinding != nil { + eabJWS, err := c.encodeExternalAccountBinding(acct.ExternalAccountBinding) + if err != nil { + return nil, fmt.Errorf("acme: failed to encode external account binding: %v", err) + } + req.ExternalAccountBinding = eabJWS + } res, err := c.post(ctx, c.Key, c.dir.RegURL, req, wantStatus( - http.StatusOK, // account with this key already registered + + http.StatusOK, // account with this key already registered + http.StatusCreated, // new account created + )) + if err != nil { + return nil, err + } defer res.Body.Close() + a, err := responseAccount(res) + if err != nil { + return nil, err + } + // Cache Account URL even if we return an error to the caller. + // It is by all means a valid and usable "kid" value for future requests. + c.KID = KeyID(a.URI) + if res.StatusCode == http.StatusOK { + return nil, ErrAccountAlreadyExists + } + return a, nil + } // encodeExternalAccountBinding will encode an external account binding stanza + // as described in https://tools.ietf.org/html/rfc8555#section-7.3.4. + func (c *Client) encodeExternalAccountBinding(eab *ExternalAccountBinding) (*jsonWebSignature, error) { + jwk, err := jwkEncode(c.Key.Public()) + if err != nil { + return nil, err + } + return jwsWithMAC(eab.Key, eab.KID, c.dir.RegURL, []byte(jwk)) + } // updateRegRFC is equivalent to c.UpdateReg but for CAs implementing RFC 8555. + // It expects c.Discover to have already been called. + func (c *Client) updateRegRFC(ctx context.Context, a *Account) (*Account, error) { + url := string(c.accountKID(ctx)) + if url == "" { + return nil, ErrNoAccount + } + req := struct { Contact []string `json:"contact,omitempty"` }{ + Contact: a.Contact, } + res, err := c.post(ctx, nil, url, req, wantStatus(http.StatusOK)) + if err != nil { + return nil, err + } + defer res.Body.Close() + return responseAccount(res) + } // getRegRFC is equivalent to c.GetReg but for CAs implementing RFC 8555. + // It expects c.Discover to have already been called. + func (c *Client) getRegRFC(ctx context.Context) (*Account, error) { + req := json.RawMessage(`{"onlyReturnExisting": true}`) + res, err := c.post(ctx, c.Key, c.dir.RegURL, req, wantStatus(http.StatusOK)) + if e, ok := err.(*Error); ok && e.ProblemType == "urn:ietf:params:acme:error:accountDoesNotExist" { + return nil, ErrNoAccount + } + if err != nil { + return nil, err + } defer res.Body.Close() + return responseAccount(res) + } func responseAccount(res *http.Response) (*Account, error) { + var v struct { - Status string + Status string + Contact []string - Orders string + + Orders string } + if err := json.NewDecoder(res.Body).Decode(&v); err != nil { + return nil, fmt.Errorf("acme: invalid account response: %v", err) + } + return &Account{ - URI: res.Header.Get("Location"), - Status: v.Status, - Contact: v.Contact, + + URI: res.Header.Get("Location"), + + Status: v.Status, + + Contact: v.Contact, + OrdersURL: v.Orders, }, nil + } // accountKeyRollover attempts to perform account key rollover. + // On success it will change client.Key to the new key. + func (c *Client) accountKeyRollover(ctx context.Context, newKey crypto.Signer) error { + dir, err := c.Discover(ctx) // Also required by c.accountKID + if err != nil { + return err + } + kid := c.accountKID(ctx) + if kid == noKeyID { + return ErrNoAccount + } + oldKey, err := jwkEncode(c.Key.Public()) + if err != nil { + return err + } + payload := struct { - Account string `json:"account"` - OldKey json.RawMessage `json:"oldKey"` + Account string `json:"account"` + + OldKey json.RawMessage `json:"oldKey"` }{ + Account: string(kid), - OldKey: json.RawMessage(oldKey), + + OldKey: json.RawMessage(oldKey), } + inner, err := jwsEncodeJSON(payload, newKey, noKeyID, noNonce, dir.KeyChangeURL) + if err != nil { + return err + } res, err := c.post(ctx, nil, dir.KeyChangeURL, base64.RawURLEncoding.EncodeToString(inner), wantStatus(http.StatusOK)) + if err != nil { + return err + } + defer res.Body.Close() + c.Key = newKey + return nil + } // AuthorizeOrder initiates the order-based application for certificate issuance, + // as opposed to pre-authorization in Authorize. + // It is only supported by CAs implementing RFC 8555. + // + // The caller then needs to fetch each authorization with GetAuthorization, + // identify those with StatusPending status and fulfill a challenge using Accept. + // Once all authorizations are satisfied, the caller will typically want to poll + // order status using WaitOrder until it's in StatusReady state. + // To finalize the order and obtain a certificate, the caller submits a CSR with CreateOrderCert. + func (c *Client) AuthorizeOrder(ctx context.Context, id []AuthzID, opt ...OrderOption) (*Order, error) { + dir, err := c.Discover(ctx) + if err != nil { + return nil, err + } req := struct { Identifiers []wireAuthzID `json:"identifiers"` - NotBefore string `json:"notBefore,omitempty"` - NotAfter string `json:"notAfter,omitempty"` + + NotBefore string `json:"notBefore,omitempty"` + + NotAfter string `json:"notAfter,omitempty"` }{} + for _, v := range id { + req.Identifiers = append(req.Identifiers, wireAuthzID{ - Type: v.Type, + + Type: v.Type, + Value: v.Value, }) + } + for _, o := range opt { + switch o := o.(type) { + case orderNotBeforeOpt: + req.NotBefore = time.Time(o).Format(time.RFC3339) + case orderNotAfterOpt: + req.NotAfter = time.Time(o).Format(time.RFC3339) + default: + // Package's fault if we let this happen. + panic(fmt.Sprintf("unsupported order option type %T", o)) + } + } res, err := c.post(ctx, nil, dir.OrderURL, req, wantStatus(http.StatusCreated)) + if err != nil { + return nil, err + } + defer res.Body.Close() + return responseOrder(res) + } // GetOrder retrives an order identified by the given URL. + // For orders created with AuthorizeOrder, the url value is Order.URI. + // + // If a caller needs to poll an order until its status is final, + // see the WaitOrder method. + func (c *Client) GetOrder(ctx context.Context, url string) (*Order, error) { + if _, err := c.Discover(ctx); err != nil { + return nil, err + } res, err := c.postAsGet(ctx, url, wantStatus(http.StatusOK)) + if err != nil { + return nil, err + } + defer res.Body.Close() + return responseOrder(res) + } // WaitOrder polls an order from the given URL until it is in one of the final states, + // StatusReady, StatusValid or StatusInvalid, the CA responded with a non-retryable error + // or the context is done. + // + // It returns a non-nil Order only if its Status is StatusReady or StatusValid. + // In all other cases WaitOrder returns an error. + // If the Status is StatusInvalid, the returned error is of type *OrderError. + func (c *Client) WaitOrder(ctx context.Context, url string) (*Order, error) { + if _, err := c.Discover(ctx); err != nil { + return nil, err + } + for { + res, err := c.postAsGet(ctx, url, wantStatus(http.StatusOK)) + if err != nil { + return nil, err + } + o, err := responseOrder(res) + res.Body.Close() + switch { + case err != nil: + // Skip and retry. + case o.Status == StatusInvalid: + return nil, &OrderError{OrderURL: o.URI, Status: o.Status} + case o.Status == StatusReady || o.Status == StatusValid: + return o, nil + } d := retryAfter(res.Header.Get("Retry-After")) + if d == 0 { + // Default retry-after. + // Same reasoning as in WaitAuthorization. + d = time.Second + } + t := time.NewTimer(d) + select { + case <-ctx.Done(): + t.Stop() + return nil, ctx.Err() + case <-t.C: + // Retry. + } + } + } func responseOrder(res *http.Response) (*Order, error) { + var v struct { - Status string - Expires time.Time - Identifiers []wireAuthzID - NotBefore time.Time - NotAfter time.Time - Error *wireError + Status string + + Expires time.Time + + Identifiers []wireAuthzID + + NotBefore time.Time + + NotAfter time.Time + + Error *wireError + Authorizations []string - Finalize string - Certificate string + + Finalize string + + Certificate string } + if err := json.NewDecoder(res.Body).Decode(&v); err != nil { + return nil, fmt.Errorf("acme: error reading order: %v", err) + } + o := &Order{ - URI: res.Header.Get("Location"), - Status: v.Status, - Expires: v.Expires, - NotBefore: v.NotBefore, - NotAfter: v.NotAfter, - AuthzURLs: v.Authorizations, + + URI: res.Header.Get("Location"), + + Status: v.Status, + + Expires: v.Expires, + + NotBefore: v.NotBefore, + + NotAfter: v.NotAfter, + + AuthzURLs: v.Authorizations, + FinalizeURL: v.Finalize, - CertURL: v.Certificate, + + CertURL: v.Certificate, } + for _, id := range v.Identifiers { + o.Identifiers = append(o.Identifiers, AuthzID{Type: id.Type, Value: id.Value}) + } + if v.Error != nil { + o.Error = v.Error.error(nil /* headers */) + } + return o, nil + } // CreateOrderCert submits the CSR (Certificate Signing Request) to a CA at the specified URL. + // The URL is the FinalizeURL field of an Order created with AuthorizeOrder. + // + // If the bundle argument is true, the returned value also contain the CA (issuer) + // certificate chain. Otherwise, only a leaf certificate is returned. + // The returned URL can be used to re-fetch the certificate using FetchCert. + // + // This method is only supported by CAs implementing RFC 8555. See CreateCert for pre-RFC CAs. + // + // CreateOrderCert returns an error if the CA's response is unreasonably large. + // Callers are encouraged to parse the returned value to ensure the certificate is valid and has the expected features. + func (c *Client) CreateOrderCert(ctx context.Context, url string, csr []byte, bundle bool) (der [][]byte, certURL string, err error) { + if _, err := c.Discover(ctx); err != nil { // required by c.accountKID + return nil, "", err + } // RFC describes this as "finalize order" request. + req := struct { CSR string `json:"csr"` }{ + CSR: base64.RawURLEncoding.EncodeToString(csr), } + res, err := c.post(ctx, nil, url, req, wantStatus(http.StatusOK)) + if err != nil { + return nil, "", err + } + defer res.Body.Close() + o, err := responseOrder(res) + if err != nil { + return nil, "", err + } // Wait for CA to issue the cert if they haven't. + if o.Status != StatusValid { + o, err = c.WaitOrder(ctx, o.URI) + } + if err != nil { + return nil, "", err + } + // The only acceptable status post finalize and WaitOrder is "valid". + if o.Status != StatusValid { + return nil, "", &OrderError{OrderURL: o.URI, Status: o.Status} + } + crt, err := c.fetchCertRFC(ctx, o.CertURL, bundle) + return crt, o.CertURL, err + } // fetchCertRFC downloads issued certificate from the given URL. + // It expects the CA to respond with PEM-encoded certificate chain. + // + // The URL argument is the CertURL field of Order. + func (c *Client) fetchCertRFC(ctx context.Context, url string, bundle bool) ([][]byte, error) { + res, err := c.postAsGet(ctx, url, wantStatus(http.StatusOK)) + if err != nil { + return nil, err + } + defer res.Body.Close() // Get all the bytes up to a sane maximum. + // Account very roughly for base64 overhead. + const max = maxCertChainSize + maxCertChainSize/33 + b, err := io.ReadAll(io.LimitReader(res.Body, max+1)) + if err != nil { + return nil, fmt.Errorf("acme: fetch cert response stream: %v", err) + } + if len(b) > max { + return nil, errors.New("acme: certificate chain is too big") + } // Decode PEM chain. + var chain [][]byte + for { + var p *pem.Block + p, b = pem.Decode(b) + if p == nil { + break + } + if p.Type != "CERTIFICATE" { + return nil, fmt.Errorf("acme: invalid PEM cert type %q", p.Type) + } chain = append(chain, p.Bytes) + if !bundle { + return chain, nil + } + if len(chain) > maxChainLen { + return nil, errors.New("acme: certificate chain is too long") + } + } + if len(chain) == 0 { + return nil, errors.New("acme: certificate chain is empty") + } + return chain, nil + } // sends a cert revocation request in either JWK form when key is non-nil or KID form otherwise. + func (c *Client) revokeCertRFC(ctx context.Context, key crypto.Signer, cert []byte, reason CRLReasonCode) error { + req := &struct { - Cert string `json:"certificate"` - Reason int `json:"reason"` + Cert string `json:"certificate"` + + Reason int `json:"reason"` }{ - Cert: base64.RawURLEncoding.EncodeToString(cert), + + Cert: base64.RawURLEncoding.EncodeToString(cert), + Reason: int(reason), } + res, err := c.post(ctx, key, c.dir.RevokeURL, req, wantStatus(http.StatusOK)) + if err != nil { + if isAlreadyRevoked(err) { + // Assume it is not an error to revoke an already revoked cert. + return nil + } + return err + } + defer res.Body.Close() + return nil + } func isAlreadyRevoked(err error) bool { + e, ok := err.(*Error) + return ok && e.ProblemType == "urn:ietf:params:acme:error:alreadyRevoked" + } // ListCertAlternates retrieves any alternate certificate chain URLs for the + // given certificate chain URL. These alternate URLs can be passed to FetchCert + // in order to retrieve the alternate certificate chains. + // + // If there are no alternate issuer certificate chains, a nil slice will be + // returned. + func (c *Client) ListCertAlternates(ctx context.Context, url string) ([]string, error) { + if _, err := c.Discover(ctx); err != nil { // required by c.accountKID + return nil, err + } res, err := c.postAsGet(ctx, url, wantStatus(http.StatusOK)) + if err != nil { + return nil, err + } + defer res.Body.Close() // We don't need the body but we need to discard it so we don't end up + // preventing keep-alive + if _, err := io.Copy(io.Discard, res.Body); err != nil { + return nil, fmt.Errorf("acme: cert alternates response stream: %v", err) + } + alts := linkHeader(res.Header, "alternate") + return alts, nil + } diff --git a/vendor/golang.org/x/crypto/acme/types.go b/vendor/golang.org/x/crypto/acme/types.go index 4888726..73d609a 100644 --- a/vendor/golang.org/x/crypto/acme/types.go +++ b/vendor/golang.org/x/crypto/acme/types.go @@ -1,5 +1,7 @@ // Copyright 2016 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package acme @@ -15,367 +17,603 @@ import ( ) // ACME status values of Account, Order, Authorization and Challenge objects. + // See https://tools.ietf.org/html/rfc8555#section-7.1.6 for details. + const ( StatusDeactivated = "deactivated" - StatusExpired = "expired" - StatusInvalid = "invalid" - StatusPending = "pending" - StatusProcessing = "processing" - StatusReady = "ready" - StatusRevoked = "revoked" - StatusUnknown = "unknown" - StatusValid = "valid" + + StatusExpired = "expired" + + StatusInvalid = "invalid" + + StatusPending = "pending" + + StatusProcessing = "processing" + + StatusReady = "ready" + + StatusRevoked = "revoked" + + StatusUnknown = "unknown" + + StatusValid = "valid" ) // CRLReasonCode identifies the reason for a certificate revocation. + type CRLReasonCode int // CRL reason codes as defined in RFC 5280. + const ( - CRLReasonUnspecified CRLReasonCode = 0 - CRLReasonKeyCompromise CRLReasonCode = 1 - CRLReasonCACompromise CRLReasonCode = 2 - CRLReasonAffiliationChanged CRLReasonCode = 3 - CRLReasonSuperseded CRLReasonCode = 4 + CRLReasonUnspecified CRLReasonCode = 0 + + CRLReasonKeyCompromise CRLReasonCode = 1 + + CRLReasonCACompromise CRLReasonCode = 2 + + CRLReasonAffiliationChanged CRLReasonCode = 3 + + CRLReasonSuperseded CRLReasonCode = 4 + CRLReasonCessationOfOperation CRLReasonCode = 5 - CRLReasonCertificateHold CRLReasonCode = 6 - CRLReasonRemoveFromCRL CRLReasonCode = 8 - CRLReasonPrivilegeWithdrawn CRLReasonCode = 9 - CRLReasonAACompromise CRLReasonCode = 10 + + CRLReasonCertificateHold CRLReasonCode = 6 + + CRLReasonRemoveFromCRL CRLReasonCode = 8 + + CRLReasonPrivilegeWithdrawn CRLReasonCode = 9 + + CRLReasonAACompromise CRLReasonCode = 10 ) var ( + // ErrUnsupportedKey is returned when an unsupported key type is encountered. + ErrUnsupportedKey = errors.New("acme: unknown key type; only RSA and ECDSA are supported") // ErrAccountAlreadyExists indicates that the Client's key has already been registered + // with the CA. It is returned by Register method. + ErrAccountAlreadyExists = errors.New("acme: account already exists") // ErrNoAccount indicates that the Client's key has not been registered with the CA. + ErrNoAccount = errors.New("acme: account does not exist") ) // A Subproblem describes an ACME subproblem as reported in an Error. + type Subproblem struct { + // Type is a URI reference that identifies the problem type, + // typically in a "urn:acme:error:xxx" form. + Type string + // Detail is a human-readable explanation specific to this occurrence of the problem. + Detail string + // Instance indicates a URL that the client should direct a human user to visit + // in order for instructions on how to agree to the updated Terms of Service. + // In such an event CA sets StatusCode to 403, Type to + // "urn:ietf:params:acme:error:userActionRequired", and adds a Link header with relation + // "terms-of-service" containing the latest TOS URL. + Instance string + // Identifier may contain the ACME identifier that the error is for. + Identifier *AuthzID } func (sp Subproblem) String() string { + str := fmt.Sprintf("%s: ", sp.Type) + if sp.Identifier != nil { + str += fmt.Sprintf("[%s: %s] ", sp.Identifier.Type, sp.Identifier.Value) + } + str += sp.Detail + return str + } // Error is an ACME error, defined in Problem Details for HTTP APIs doc + // http://tools.ietf.org/html/draft-ietf-appsawg-http-problem. + type Error struct { + // StatusCode is The HTTP status code generated by the origin server. + StatusCode int + // ProblemType is a URI reference that identifies the problem type, + // typically in a "urn:acme:error:xxx" form. + ProblemType string + // Detail is a human-readable explanation specific to this occurrence of the problem. + Detail string + // Instance indicates a URL that the client should direct a human user to visit + // in order for instructions on how to agree to the updated Terms of Service. + // In such an event CA sets StatusCode to 403, ProblemType to + // "urn:ietf:params:acme:error:userActionRequired" and a Link header with relation + // "terms-of-service" containing the latest TOS URL. + Instance string + // Header is the original server error response headers. + // It may be nil. + Header http.Header + // Subproblems may contain more detailed information about the individual problems + // that caused the error. This field is only sent by RFC 8555 compatible ACME + // servers. Defined in RFC 8555 Section 6.7.1. + Subproblems []Subproblem } func (e *Error) Error() string { + str := fmt.Sprintf("%d %s: %s", e.StatusCode, e.ProblemType, e.Detail) + if len(e.Subproblems) > 0 { + str += fmt.Sprintf("; subproblems:") + for _, sp := range e.Subproblems { + str += fmt.Sprintf("\n\t%s", sp) + } + } + return str + } // AuthorizationError indicates that an authorization for an identifier + // did not succeed. + // It contains all errors from Challenge items of the failed Authorization. + type AuthorizationError struct { + // URI uniquely identifies the failed Authorization. + URI string // Identifier is an AuthzID.Value of the failed Authorization. + Identifier string // Errors is a collection of non-nil error values of Challenge items + // of the failed Authorization. + Errors []error } func (a *AuthorizationError) Error() string { + e := make([]string, len(a.Errors)) + for i, err := range a.Errors { + e[i] = err.Error() + } if a.Identifier != "" { + return fmt.Sprintf("acme: authorization error for %s: %s", a.Identifier, strings.Join(e, "; ")) + } return fmt.Sprintf("acme: authorization error: %s", strings.Join(e, "; ")) + } // OrderError is returned from Client's order related methods. + // It indicates the order is unusable and the clients should start over with + // AuthorizeOrder. + // + // The clients can still fetch the order object from CA using GetOrder + // to inspect its state. + type OrderError struct { OrderURL string - Status string + + Status string } func (oe *OrderError) Error() string { + return fmt.Sprintf("acme: order %s status: %s", oe.OrderURL, oe.Status) + } // RateLimit reports whether err represents a rate limit error and + // any Retry-After duration returned by the server. + // + // See the following for more details on rate limiting: + // https://tools.ietf.org/html/draft-ietf-acme-acme-05#section-5.6 + func RateLimit(err error) (time.Duration, bool) { + e, ok := err.(*Error) + if !ok { + return 0, false + } + // Some CA implementations may return incorrect values. + // Use case-insensitive comparison. + if !strings.HasSuffix(strings.ToLower(e.ProblemType), ":ratelimited") { + return 0, false + } + if e.Header == nil { + return 0, true + } + return retryAfter(e.Header.Get("Retry-After")), true + } // Account is a user account. It is associated with a private key. + // Non-RFC 8555 fields are empty when interfacing with a compliant CA. + type Account struct { + // URI is the account unique ID, which is also a URL used to retrieve + // account data from the CA. + // When interfacing with RFC 8555-compliant CAs, URI is the "kid" field + // value in JWS signed requests. + URI string // Contact is a slice of contact info used during registration. + // See https://tools.ietf.org/html/rfc8555#section-7.3 for supported + // formats. + Contact []string // Status indicates current account status as returned by the CA. + // Possible values are StatusValid, StatusDeactivated, and StatusRevoked. + Status string // OrdersURL is a URL from which a list of orders submitted by this account + // can be fetched. + OrdersURL string // The terms user has agreed to. + // A value not matching CurrentTerms indicates that the user hasn't agreed + // to the actual Terms of Service of the CA. + // + // It is non-RFC 8555 compliant. Package users can store the ToS they agree to + // during Client's Register call in the prompt callback function. + AgreedTerms string // Actual terms of a CA. + // + // It is non-RFC 8555 compliant. Use Directory's Terms field. + // When a CA updates their terms and requires an account agreement, + // a URL at which instructions to do so is available in Error's Instance field. + CurrentTerms string // Authz is the authorization URL used to initiate a new authz flow. + // + // It is non-RFC 8555 compliant. Use Directory's AuthzURL or OrderURL. + Authz string // Authorizations is a URI from which a list of authorizations + // granted to this account can be fetched via a GET request. + // + // It is non-RFC 8555 compliant and is obsoleted by OrdersURL. + Authorizations string // Certificates is a URI from which a list of certificates + // issued for this account can be fetched via a GET request. + // + // It is non-RFC 8555 compliant and is obsoleted by OrdersURL. + Certificates string // ExternalAccountBinding represents an arbitrary binding to an account of + // the CA which the ACME server is tied to. + // See https://tools.ietf.org/html/rfc8555#section-7.3.4 for more details. + ExternalAccountBinding *ExternalAccountBinding } // ExternalAccountBinding contains the data needed to form a request with + // an external account binding. + // See https://tools.ietf.org/html/rfc8555#section-7.3.4 for more details. + type ExternalAccountBinding struct { + // KID is the Key ID of the symmetric MAC key that the CA provides to + // identify an external account from ACME. + KID string // Key is the bytes of the symmetric key that the CA provides to identify + // the account. Key must correspond to the KID. + Key []byte } func (e *ExternalAccountBinding) String() string { + return fmt.Sprintf("&{KID: %q, Key: redacted}", e.KID) + } // Directory is ACME server discovery data. + // See https://tools.ietf.org/html/rfc8555#section-7.1.1 for more details. + type Directory struct { + // NonceURL indicates an endpoint where to fetch fresh nonce values from. + NonceURL string // RegURL is an account endpoint URL, allowing for creating new accounts. + // Pre-RFC 8555 CAs also allow modifying existing accounts at this URL. + RegURL string // OrderURL is used to initiate the certificate issuance flow + // as described in RFC 8555. + OrderURL string // AuthzURL is used to initiate identifier pre-authorization flow. + // Empty string indicates the flow is unsupported by the CA. + AuthzURL string // CertURL is a new certificate issuance endpoint URL. + // It is non-RFC 8555 compliant and is obsoleted by OrderURL. + CertURL string // RevokeURL is used to initiate a certificate revocation flow. + RevokeURL string // KeyChangeURL allows to perform account key rollover flow. + KeyChangeURL string // Term is a URI identifying the current terms of service. + Terms string // Website is an HTTP or HTTPS URL locating a website + // providing more information about the ACME server. + Website string // CAA consists of lowercase hostname elements, which the ACME server + // recognises as referring to itself for the purposes of CAA record validation + // as defined in RFC 6844. + CAA []string // ExternalAccountRequired indicates that the CA requires for all account-related + // requests to include external account binding information. + ExternalAccountRequired bool } // Order represents a client's request for a certificate. + // It tracks the request flow progress through to issuance. + type Order struct { + // URI uniquely identifies an order. + URI string // Status represents the current status of the order. + // It indicates which action the client should take. + // + // Possible values are StatusPending, StatusReady, StatusProcessing, StatusValid and StatusInvalid. + // Pending means the CA does not believe that the client has fulfilled the requirements. + // Ready indicates that the client has fulfilled all the requirements and can submit a CSR + // to obtain a certificate. This is done with Client's CreateOrderCert. + // Processing means the certificate is being issued. + // Valid indicates the CA has issued the certificate. It can be downloaded + // from the Order's CertURL. This is done with Client's FetchCert. + // Invalid means the certificate will not be issued. Users should consider this order + // abandoned. + Status string // Expires is the timestamp after which CA considers this order invalid. + Expires time.Time // Identifiers contains all identifier objects which the order pertains to. + Identifiers []AuthzID // NotBefore is the requested value of the notBefore field in the certificate. + NotBefore time.Time // NotAfter is the requested value of the notAfter field in the certificate. + NotAfter time.Time // AuthzURLs represents authorizations to complete before a certificate + // for identifiers specified in the order can be issued. + // It also contains unexpired authorizations that the client has completed + // in the past. + // + // Authorization objects can be fetched using Client's GetAuthorization method. + // + // The required authorizations are dictated by CA policies. + // There may not be a 1:1 relationship between the identifiers and required authorizations. + // Required authorizations can be identified by their StatusPending status. + // + // For orders in the StatusValid or StatusInvalid state these are the authorizations + // which were completed. + AuthzURLs []string // FinalizeURL is the endpoint at which a CSR is submitted to obtain a certificate + // once all the authorizations are satisfied. + FinalizeURL string // CertURL points to the certificate that has been issued in response to this order. + CertURL string // The error that occurred while processing the order as received from a CA, if any. + Error *Error } // OrderOption allows customizing Client.AuthorizeOrder call. + type OrderOption interface { privateOrderOpt() } // WithOrderNotBefore sets order's NotBefore field. + func WithOrderNotBefore(t time.Time) OrderOption { + return orderNotBeforeOpt(t) + } // WithOrderNotAfter sets order's NotAfter field. + func WithOrderNotAfter(t time.Time) OrderOption { + return orderNotAfterOpt(t) + } type orderNotBeforeOpt time.Time @@ -387,210 +625,343 @@ type orderNotAfterOpt time.Time func (orderNotAfterOpt) privateOrderOpt() {} // Authorization encodes an authorization response. + type Authorization struct { + // URI uniquely identifies a authorization. + URI string // Status is the current status of an authorization. + // Possible values are StatusPending, StatusValid, StatusInvalid, StatusDeactivated, + // StatusExpired and StatusRevoked. + Status string // Identifier is what the account is authorized to represent. + Identifier AuthzID // The timestamp after which the CA considers the authorization invalid. + Expires time.Time // Wildcard is true for authorizations of a wildcard domain name. + Wildcard bool // Challenges that the client needs to fulfill in order to prove possession + // of the identifier (for pending authorizations). + // For valid authorizations, the challenge that was validated. + // For invalid authorizations, the challenge that was attempted and failed. + // + // RFC 8555 compatible CAs require users to fuflfill only one of the challenges. + Challenges []*Challenge // A collection of sets of challenges, each of which would be sufficient + // to prove possession of the identifier. + // Clients must complete a set of challenges that covers at least one set. + // Challenges are identified by their indices in the challenges array. + // If this field is empty, the client needs to complete all challenges. + // + // This field is unused in RFC 8555. + Combinations [][]int } // AuthzID is an identifier that an account is authorized to represent. + type AuthzID struct { - Type string // The type of identifier, "dns" or "ip". + Type string // The type of identifier, "dns" or "ip". + Value string // The identifier itself, e.g. "example.org". + } // DomainIDs creates a slice of AuthzID with "dns" identifier type. + func DomainIDs(names ...string) []AuthzID { + a := make([]AuthzID, len(names)) + for i, v := range names { + a[i] = AuthzID{Type: "dns", Value: v} + } + return a + } // IPIDs creates a slice of AuthzID with "ip" identifier type. + // Each element of addr is textual form of an address as defined + // in RFC 1123 Section 2.1 for IPv4 and in RFC 5952 Section 4 for IPv6. + func IPIDs(addr ...string) []AuthzID { + a := make([]AuthzID, len(addr)) + for i, v := range addr { + a[i] = AuthzID{Type: "ip", Value: v} + } + return a + } // wireAuthzID is ACME JSON representation of authorization identifier objects. + type wireAuthzID struct { - Type string `json:"type"` + Type string `json:"type"` + Value string `json:"value"` } // wireAuthz is ACME JSON representation of Authorization objects. + type wireAuthz struct { - Identifier wireAuthzID - Status string - Expires time.Time - Wildcard bool - Challenges []wireChallenge + Identifier wireAuthzID + + Status string + + Expires time.Time + + Wildcard bool + + Challenges []wireChallenge + Combinations [][]int - Error *wireError + + Error *wireError } func (z *wireAuthz) authorization(uri string) *Authorization { + a := &Authorization{ - URI: uri, - Status: z.Status, - Identifier: AuthzID{Type: z.Identifier.Type, Value: z.Identifier.Value}, - Expires: z.Expires, - Wildcard: z.Wildcard, - Challenges: make([]*Challenge, len(z.Challenges)), + + URI: uri, + + Status: z.Status, + + Identifier: AuthzID{Type: z.Identifier.Type, Value: z.Identifier.Value}, + + Expires: z.Expires, + + Wildcard: z.Wildcard, + + Challenges: make([]*Challenge, len(z.Challenges)), + Combinations: z.Combinations, // shallow copy + } + for i, v := range z.Challenges { + a.Challenges[i] = v.challenge() + } + return a + } func (z *wireAuthz) error(uri string) *AuthorizationError { + err := &AuthorizationError{ - URI: uri, + + URI: uri, + Identifier: z.Identifier.Value, } if z.Error != nil { + err.Errors = append(err.Errors, z.Error.error(nil)) + } for _, raw := range z.Challenges { + if raw.Error != nil { + err.Errors = append(err.Errors, raw.Error.error(nil)) + } + } return err + } // Challenge encodes a returned CA challenge. + // Its Error field may be non-nil if the challenge is part of an Authorization + // with StatusInvalid. + type Challenge struct { + // Type is the challenge type, e.g. "http-01", "tls-alpn-01", "dns-01". + Type string // URI is where a challenge response can be posted to. + URI string // Token is a random value that uniquely identifies the challenge. + Token string // Status identifies the status of this challenge. + // In RFC 8555, possible values are StatusPending, StatusProcessing, StatusValid, + // and StatusInvalid. + Status string // Validated is the time at which the CA validated this challenge. + // Always zero value in pre-RFC 8555. + Validated time.Time // Error indicates the reason for an authorization failure + // when this challenge was used. + // The type of a non-nil value is *Error. + Error error } // wireChallenge is ACME JSON challenge representation. + type wireChallenge struct { - URL string `json:"url"` // RFC - URI string `json:"uri"` // pre-RFC - Type string - Token string - Status string + URL string `json:"url"` // RFC + + URI string `json:"uri"` // pre-RFC + + Type string + + Token string + + Status string + Validated time.Time - Error *wireError + + Error *wireError } func (c *wireChallenge) challenge() *Challenge { + v := &Challenge{ - URI: c.URL, - Type: c.Type, - Token: c.Token, + + URI: c.URL, + + Type: c.Type, + + Token: c.Token, + Status: c.Status, } + if v.URI == "" { + v.URI = c.URI // c.URL was empty; use legacy + } + if v.Status == "" { + v.Status = StatusPending + } + if c.Error != nil { + v.Error = c.Error.error(nil) + } + return v + } // wireError is a subset of fields of the Problem Details object + // as described in https://tools.ietf.org/html/rfc7807#section-3.1. + type wireError struct { - Status int - Type string - Detail string - Instance string + Status int + + Type string + + Detail string + + Instance string + Subproblems []Subproblem } func (e *wireError) error(h http.Header) *Error { + err := &Error{ - StatusCode: e.Status, + + StatusCode: e.Status, + ProblemType: e.Type, - Detail: e.Detail, - Instance: e.Instance, - Header: h, + + Detail: e.Detail, + + Instance: e.Instance, + + Header: h, + Subproblems: e.Subproblems, } + return err + } // CertOption is an optional argument type for the TLS ChallengeCert methods for + // customizing a temporary certificate for TLS-based challenges. + type CertOption interface { privateCertOpt() } // WithKey creates an option holding a private/public key pair. + // The private part signs a certificate, and the public part represents the signee. + func WithKey(key crypto.Signer) CertOption { + return &certOptKey{key} + } type certOptKey struct { @@ -600,13 +971,21 @@ type certOptKey struct { func (*certOptKey) privateCertOpt() {} // WithTemplate creates an option for specifying a certificate template. + // See x509.CreateCertificate for template usage details. + // + // In TLS ChallengeCert methods, the template is also used as parent, + // resulting in a self-signed certificate. + // The DNSNames field of t is always overwritten for tls-sni challenge certs. + func WithTemplate(t *x509.Certificate) CertOption { + return (*certOptTemplate)(t) + } type certOptTemplate x509.Certificate diff --git a/vendor/golang.org/x/crypto/bcrypt/bcrypt.go b/vendor/golang.org/x/crypto/bcrypt/bcrypt.go index 5577c0f..2e37fdf 100644 --- a/vendor/golang.org/x/crypto/bcrypt/bcrypt.go +++ b/vendor/golang.org/x/crypto/bcrypt/bcrypt.go @@ -1,12 +1,17 @@ // Copyright 2011 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Package bcrypt implements Provos and Mazières's bcrypt adaptive hashing + // algorithm. See http://www.usenix.org/event/usenix99/provos/provos.pdf + package bcrypt // import "golang.org/x/crypto/bcrypt" // The code is a port of Provos and Mazières's C implementation. + import ( "crypto/rand" "crypto/subtle" @@ -19,286 +24,483 @@ import ( ) const ( - MinCost int = 4 // the minimum allowable cost as passed in to GenerateFromPassword - MaxCost int = 31 // the maximum allowable cost as passed in to GenerateFromPassword + MinCost int = 4 // the minimum allowable cost as passed in to GenerateFromPassword + + MaxCost int = 31 // the maximum allowable cost as passed in to GenerateFromPassword + DefaultCost int = 10 // the cost that will actually be set if a cost below MinCost is passed into GenerateFromPassword + ) // The error returned from CompareHashAndPassword when a password and hash do + // not match. + var ErrMismatchedHashAndPassword = errors.New("crypto/bcrypt: hashedPassword is not the hash of the given password") // The error returned from CompareHashAndPassword when a hash is too short to + // be a bcrypt hash. + var ErrHashTooShort = errors.New("crypto/bcrypt: hashedSecret too short to be a bcrypted password") // The error returned from CompareHashAndPassword when a hash was created with + // a bcrypt algorithm newer than this implementation. + type HashVersionTooNewError byte func (hv HashVersionTooNewError) Error() string { + return fmt.Sprintf("crypto/bcrypt: bcrypt algorithm version '%c' requested is newer than current version '%c'", byte(hv), majorVersion) + } // The error returned from CompareHashAndPassword when a hash starts with something other than '$' + type InvalidHashPrefixError byte func (ih InvalidHashPrefixError) Error() string { + return fmt.Sprintf("crypto/bcrypt: bcrypt hashes must start with '$', but hashedSecret started with '%c'", byte(ih)) + } type InvalidCostError int func (ic InvalidCostError) Error() string { + return fmt.Sprintf("crypto/bcrypt: cost %d is outside allowed range (%d,%d)", int(ic), MinCost, MaxCost) + } const ( - majorVersion = '2' - minorVersion = 'a' - maxSaltSize = 16 + majorVersion = '2' + + minorVersion = 'a' + + maxSaltSize = 16 + maxCryptedHashSize = 23 - encodedSaltSize = 22 - encodedHashSize = 31 - minHashSize = 59 + + encodedSaltSize = 22 + + encodedHashSize = 31 + + minHashSize = 59 ) // magicCipherData is an IV for the 64 Blowfish encryption calls in + // bcrypt(). It's the string "OrpheanBeholderScryDoubt" in big-endian bytes. + var magicCipherData = []byte{ + 0x4f, 0x72, 0x70, 0x68, + 0x65, 0x61, 0x6e, 0x42, + 0x65, 0x68, 0x6f, 0x6c, + 0x64, 0x65, 0x72, 0x53, + 0x63, 0x72, 0x79, 0x44, + 0x6f, 0x75, 0x62, 0x74, } type hashed struct { - hash []byte - salt []byte - cost int // allowed range is MinCost to MaxCost + hash []byte + + salt []byte + + cost int // allowed range is MinCost to MaxCost + major byte + minor byte } // ErrPasswordTooLong is returned when the password passed to + // GenerateFromPassword is too long (i.e. > 72 bytes). + var ErrPasswordTooLong = errors.New("bcrypt: password length exceeds 72 bytes") // GenerateFromPassword returns the bcrypt hash of the password at the given + // cost. If the cost given is less than MinCost, the cost will be set to + // DefaultCost, instead. Use CompareHashAndPassword, as defined in this package, + // to compare the returned hashed password with its cleartext version. + // GenerateFromPassword does not accept passwords longer than 72 bytes, which + // is the longest password bcrypt will operate on. + func GenerateFromPassword(password []byte, cost int) ([]byte, error) { + if len(password) > 72 { + return nil, ErrPasswordTooLong + } + p, err := newFromPassword(password, cost) + if err != nil { + return nil, err + } + return p.Hash(), nil + } // CompareHashAndPassword compares a bcrypt hashed password with its possible + // plaintext equivalent. Returns nil on success, or an error on failure. + func CompareHashAndPassword(hashedPassword, password []byte) error { + p, err := newFromHash(hashedPassword) + if err != nil { + return err + } otherHash, err := bcrypt(password, p.cost, p.salt) + if err != nil { + return err + } otherP := &hashed{otherHash, p.salt, p.cost, p.major, p.minor} + if subtle.ConstantTimeCompare(p.Hash(), otherP.Hash()) == 1 { + return nil + } return ErrMismatchedHashAndPassword + } // Cost returns the hashing cost used to create the given hashed + // password. When, in the future, the hashing cost of a password system needs + // to be increased in order to adjust for greater computational power, this + // function allows one to establish which passwords need to be updated. + func Cost(hashedPassword []byte) (int, error) { + p, err := newFromHash(hashedPassword) + if err != nil { + return 0, err + } + return p.cost, nil + } func newFromPassword(password []byte, cost int) (*hashed, error) { + if cost < MinCost { + cost = DefaultCost + } + p := new(hashed) + p.major = majorVersion + p.minor = minorVersion err := checkCost(cost) + if err != nil { + return nil, err + } + p.cost = cost unencodedSalt := make([]byte, maxSaltSize) + _, err = io.ReadFull(rand.Reader, unencodedSalt) + if err != nil { + return nil, err + } p.salt = base64Encode(unencodedSalt) + hash, err := bcrypt(password, p.cost, p.salt) + if err != nil { + return nil, err + } + p.hash = hash + return p, err + } func newFromHash(hashedSecret []byte) (*hashed, error) { + if len(hashedSecret) < minHashSize { + return nil, ErrHashTooShort + } + p := new(hashed) + n, err := p.decodeVersion(hashedSecret) + if err != nil { + return nil, err + } + hashedSecret = hashedSecret[n:] + n, err = p.decodeCost(hashedSecret) + if err != nil { + return nil, err + } + hashedSecret = hashedSecret[n:] // The "+2" is here because we'll have to append at most 2 '=' to the salt + // when base64 decoding it in expensiveBlowfishSetup(). + p.salt = make([]byte, encodedSaltSize, encodedSaltSize+2) + copy(p.salt, hashedSecret[:encodedSaltSize]) hashedSecret = hashedSecret[encodedSaltSize:] + p.hash = make([]byte, len(hashedSecret)) + copy(p.hash, hashedSecret) return p, nil + } func bcrypt(password []byte, cost int, salt []byte) ([]byte, error) { + cipherData := make([]byte, len(magicCipherData)) + copy(cipherData, magicCipherData) c, err := expensiveBlowfishSetup(password, uint32(cost), salt) + if err != nil { + return nil, err + } for i := 0; i < 24; i += 8 { + for j := 0; j < 64; j++ { + c.Encrypt(cipherData[i:i+8], cipherData[i:i+8]) + } + } // Bug compatibility with C bcrypt implementations. We only encode 23 of + // the 24 bytes encrypted. + hsh := base64Encode(cipherData[:maxCryptedHashSize]) + return hsh, nil + } func expensiveBlowfishSetup(key []byte, cost uint32, salt []byte) (*blowfish.Cipher, error) { + csalt, err := base64Decode(salt) + if err != nil { + return nil, err + } // Bug compatibility with C bcrypt implementations. They use the trailing + // NULL in the key string during expansion. + // We copy the key to prevent changing the underlying array. + ckey := append(key[:len(key):len(key)], 0) c, err := blowfish.NewSaltedCipher(ckey, csalt) + if err != nil { + return nil, err + } var i, rounds uint64 + rounds = 1 << cost + for i = 0; i < rounds; i++ { + blowfish.ExpandKey(ckey, c) + blowfish.ExpandKey(csalt, c) + } return c, nil + } func (p *hashed) Hash() []byte { + arr := make([]byte, 60) + arr[0] = '$' + arr[1] = p.major + n := 2 + if p.minor != 0 { + arr[2] = p.minor + n = 3 + } + arr[n] = '$' + n++ + copy(arr[n:], []byte(fmt.Sprintf("%02d", p.cost))) + n += 2 + arr[n] = '$' + n++ + copy(arr[n:], p.salt) + n += encodedSaltSize + copy(arr[n:], p.hash) + n += encodedHashSize + return arr[:n] + } func (p *hashed) decodeVersion(sbytes []byte) (int, error) { + if sbytes[0] != '$' { + return -1, InvalidHashPrefixError(sbytes[0]) + } + if sbytes[1] > majorVersion { + return -1, HashVersionTooNewError(sbytes[1]) + } + p.major = sbytes[1] + n := 3 + if sbytes[2] != '$' { + p.minor = sbytes[2] + n++ + } + return n, nil + } // sbytes should begin where decodeVersion left off. + func (p *hashed) decodeCost(sbytes []byte) (int, error) { + cost, err := strconv.Atoi(string(sbytes[0:2])) + if err != nil { + return -1, err + } + err = checkCost(cost) + if err != nil { + return -1, err + } + p.cost = cost + return 3, nil + } func (p *hashed) String() string { + return fmt.Sprintf("&{hash: %#v, salt: %#v, cost: %d, major: %c, minor: %c}", string(p.hash), p.salt, p.cost, p.major, p.minor) + } func checkCost(cost int) error { + if cost < MinCost || cost > MaxCost { + return InvalidCostError(cost) + } + return nil + } diff --git a/vendor/golang.org/x/net/http/httpguts/guts.go b/vendor/golang.org/x/net/http/httpguts/guts.go index e6cd0ce..7d903ee 100644 --- a/vendor/golang.org/x/net/http/httpguts/guts.go +++ b/vendor/golang.org/x/net/http/httpguts/guts.go @@ -1,12 +1,19 @@ // Copyright 2018 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Package httpguts provides functions implementing various details + // of the HTTP specification. + // + // This package is shared by the standard library (which vendors it) + // and x/net/http2. It comes with no API stability promise. + package httpguts import ( @@ -15,36 +22,66 @@ import ( ) // ValidTrailerHeader reports whether name is a valid header field name to appear + // in trailers. + // See RFC 7230, Section 4.1.2 + func ValidTrailerHeader(name string) bool { + name = textproto.CanonicalMIMEHeaderKey(name) + if strings.HasPrefix(name, "If-") || badTrailer[name] { + return false + } + return true + } var badTrailer = map[string]bool{ - "Authorization": true, - "Cache-Control": true, - "Connection": true, - "Content-Encoding": true, - "Content-Length": true, - "Content-Range": true, - "Content-Type": true, - "Expect": true, - "Host": true, - "Keep-Alive": true, - "Max-Forwards": true, - "Pragma": true, - "Proxy-Authenticate": true, + + "Authorization": true, + + "Cache-Control": true, + + "Connection": true, + + "Content-Encoding": true, + + "Content-Length": true, + + "Content-Range": true, + + "Content-Type": true, + + "Expect": true, + + "Host": true, + + "Keep-Alive": true, + + "Max-Forwards": true, + + "Pragma": true, + + "Proxy-Authenticate": true, + "Proxy-Authorization": true, - "Proxy-Connection": true, - "Range": true, - "Realm": true, - "Te": true, - "Trailer": true, - "Transfer-Encoding": true, - "Www-Authenticate": true, + + "Proxy-Connection": true, + + "Range": true, + + "Realm": true, + + "Te": true, + + "Trailer": true, + + "Transfer-Encoding": true, + + "Www-Authenticate": true, } diff --git a/vendor/golang.org/x/net/http/httpguts/httplex.go b/vendor/golang.org/x/net/http/httpguts/httplex.go index 9b4de94..6c4588a 100644 --- a/vendor/golang.org/x/net/http/httpguts/httplex.go +++ b/vendor/golang.org/x/net/http/httpguts/httplex.go @@ -1,5 +1,7 @@ // Copyright 2016 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package httpguts @@ -13,335 +15,628 @@ import ( ) var isTokenTable = [256]bool{ - '!': true, - '#': true, - '$': true, - '%': true, - '&': true, + + '!': true, + + '#': true, + + '$': true, + + '%': true, + + '&': true, + '\'': true, - '*': true, - '+': true, - '-': true, - '.': true, - '0': true, - '1': true, - '2': true, - '3': true, - '4': true, - '5': true, - '6': true, - '7': true, - '8': true, - '9': true, - 'A': true, - 'B': true, - 'C': true, - 'D': true, - 'E': true, - 'F': true, - 'G': true, - 'H': true, - 'I': true, - 'J': true, - 'K': true, - 'L': true, - 'M': true, - 'N': true, - 'O': true, - 'P': true, - 'Q': true, - 'R': true, - 'S': true, - 'T': true, - 'U': true, - 'W': true, - 'V': true, - 'X': true, - 'Y': true, - 'Z': true, - '^': true, - '_': true, - '`': true, - 'a': true, - 'b': true, - 'c': true, - 'd': true, - 'e': true, - 'f': true, - 'g': true, - 'h': true, - 'i': true, - 'j': true, - 'k': true, - 'l': true, - 'm': true, - 'n': true, - 'o': true, - 'p': true, - 'q': true, - 'r': true, - 's': true, - 't': true, - 'u': true, - 'v': true, - 'w': true, - 'x': true, - 'y': true, - 'z': true, - '|': true, - '~': true, + + '*': true, + + '+': true, + + '-': true, + + '.': true, + + '0': true, + + '1': true, + + '2': true, + + '3': true, + + '4': true, + + '5': true, + + '6': true, + + '7': true, + + '8': true, + + '9': true, + + 'A': true, + + 'B': true, + + 'C': true, + + 'D': true, + + 'E': true, + + 'F': true, + + 'G': true, + + 'H': true, + + 'I': true, + + 'J': true, + + 'K': true, + + 'L': true, + + 'M': true, + + 'N': true, + + 'O': true, + + 'P': true, + + 'Q': true, + + 'R': true, + + 'S': true, + + 'T': true, + + 'U': true, + + 'W': true, + + 'V': true, + + 'X': true, + + 'Y': true, + + 'Z': true, + + '^': true, + + '_': true, + + '`': true, + + 'a': true, + + 'b': true, + + 'c': true, + + 'd': true, + + 'e': true, + + 'f': true, + + 'g': true, + + 'h': true, + + 'i': true, + + 'j': true, + + 'k': true, + + 'l': true, + + 'm': true, + + 'n': true, + + 'o': true, + + 'p': true, + + 'q': true, + + 'r': true, + + 's': true, + + 't': true, + + 'u': true, + + 'v': true, + + 'w': true, + + 'x': true, + + 'y': true, + + 'z': true, + + '|': true, + + '~': true, } func IsTokenRune(r rune) bool { + return r < utf8.RuneSelf && isTokenTable[byte(r)] + } // HeaderValuesContainsToken reports whether any string in values + // contains the provided token, ASCII case-insensitively. + func HeaderValuesContainsToken(values []string, token string) bool { + for _, v := range values { + if headerValueContainsToken(v, token) { + return true + } + } + return false + } // isOWS reports whether b is an optional whitespace byte, as defined + // by RFC 7230 section 3.2.3. + func isOWS(b byte) bool { return b == ' ' || b == '\t' } // trimOWS returns x with all optional whitespace removes from the + // beginning and end. + func trimOWS(x string) string { + // TODO: consider using strings.Trim(x, " \t") instead, + // if and when it's fast enough. See issue 10292. + // But this ASCII-only code will probably always beat UTF-8 + // aware code. + for len(x) > 0 && isOWS(x[0]) { + x = x[1:] + } + for len(x) > 0 && isOWS(x[len(x)-1]) { + x = x[:len(x)-1] + } + return x + } // headerValueContainsToken reports whether v (assumed to be a + // 0#element, in the ABNF extension described in RFC 7230 section 7) + // contains token amongst its comma-separated tokens, ASCII + // case-insensitively. + func headerValueContainsToken(v string, token string) bool { + for comma := strings.IndexByte(v, ','); comma != -1; comma = strings.IndexByte(v, ',') { + if tokenEqual(trimOWS(v[:comma]), token) { + return true + } + v = v[comma+1:] + } + return tokenEqual(trimOWS(v), token) + } // lowerASCII returns the ASCII lowercase version of b. + func lowerASCII(b byte) byte { + if 'A' <= b && b <= 'Z' { + return b + ('a' - 'A') + } + return b + } // tokenEqual reports whether t1 and t2 are equal, ASCII case-insensitively. + func tokenEqual(t1, t2 string) bool { + if len(t1) != len(t2) { + return false + } + for i, b := range t1 { + if b >= utf8.RuneSelf { + // No UTF-8 or non-ASCII allowed in tokens. + return false + } + if lowerASCII(byte(b)) != lowerASCII(t2[i]) { + return false + } + } + return true + } // isLWS reports whether b is linear white space, according + // to http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2 + // + // LWS = [CRLF] 1*( SP | HT ) + func isLWS(b byte) bool { return b == ' ' || b == '\t' } // isCTL reports whether b is a control byte, according + // to http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2 + // + // CTL = + func isCTL(b byte) bool { + const del = 0x7f // a CTL + return b < ' ' || b == del + } // ValidHeaderFieldName reports whether v is a valid HTTP/1.x header name. + // HTTP/2 imposes the additional restriction that uppercase ASCII + // letters are not allowed. + // + // RFC 7230 says: + // + // header-field = field-name ":" OWS field-value OWS + // field-name = token + // token = 1*tchar + // tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / + // "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA + func ValidHeaderFieldName(v string) bool { + if len(v) == 0 { + return false + } + for i := 0; i < len(v); i++ { + if !isTokenTable[v[i]] { + return false + } + } + return true + } // ValidHostHeader reports whether h is a valid host header. + func ValidHostHeader(h string) bool { + // The latest spec is actually this: + // + // http://tools.ietf.org/html/rfc7230#section-5.4 + // Host = uri-host [ ":" port ] + // + // Where uri-host is: + // http://tools.ietf.org/html/rfc3986#section-3.2.2 + // + // But we're going to be much more lenient for now and just + // search for any byte that's not a valid byte in any of those + // expressions. + for i := 0; i < len(h); i++ { + if !validHostByte[h[i]] { + return false + } + } + return true + } // See the validHostHeader comment. + var validHostByte = [256]bool{ + '0': true, '1': true, '2': true, '3': true, '4': true, '5': true, '6': true, '7': true, + '8': true, '9': true, 'a': true, 'b': true, 'c': true, 'd': true, 'e': true, 'f': true, 'g': true, 'h': true, + 'i': true, 'j': true, 'k': true, 'l': true, 'm': true, 'n': true, 'o': true, 'p': true, + 'q': true, 'r': true, 's': true, 't': true, 'u': true, 'v': true, 'w': true, 'x': true, + 'y': true, 'z': true, 'A': true, 'B': true, 'C': true, 'D': true, 'E': true, 'F': true, 'G': true, 'H': true, + 'I': true, 'J': true, 'K': true, 'L': true, 'M': true, 'N': true, 'O': true, 'P': true, + 'Q': true, 'R': true, 'S': true, 'T': true, 'U': true, 'V': true, 'W': true, 'X': true, + 'Y': true, 'Z': true, - '!': true, // sub-delims - '$': true, // sub-delims - '%': true, // pct-encoded (and used in IPv6 zones) - '&': true, // sub-delims - '(': true, // sub-delims - ')': true, // sub-delims - '*': true, // sub-delims - '+': true, // sub-delims - ',': true, // sub-delims - '-': true, // unreserved - '.': true, // unreserved - ':': true, // IPv6address + Host expression's optional port - ';': true, // sub-delims - '=': true, // sub-delims - '[': true, + '!': true, // sub-delims + + '$': true, // sub-delims + + '%': true, // pct-encoded (and used in IPv6 zones) + + '&': true, // sub-delims + + '(': true, // sub-delims + + ')': true, // sub-delims + + '*': true, // sub-delims + + '+': true, // sub-delims + + ',': true, // sub-delims + + '-': true, // unreserved + + '.': true, // unreserved + + ':': true, // IPv6address + Host expression's optional port + + ';': true, // sub-delims + + '=': true, // sub-delims + + '[': true, + '\'': true, // sub-delims - ']': true, - '_': true, // unreserved - '~': true, // unreserved + + ']': true, + + '_': true, // unreserved + + '~': true, // unreserved + } // ValidHeaderFieldValue reports whether v is a valid "field-value" according to + // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 : + // + // message-header = field-name ":" [ field-value ] + // field-value = *( field-content | LWS ) + // field-content = + // + // http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2 : + // + // TEXT = + // LWS = [CRLF] 1*( SP | HT ) + // CTL = + // + // RFC 7230 says: + // + // field-value = *( field-content / obs-fold ) + // obj-fold = N/A to http2, and deprecated + // field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + // field-vchar = VCHAR / obs-text + // obs-text = %x80-FF + // VCHAR = "any visible [USASCII] character" + // + // http2 further says: "Similarly, HTTP/2 allows header field values + // that are not valid. While most of the values that can be encoded + // will not alter header field parsing, carriage return (CR, ASCII + // 0xd), line feed (LF, ASCII 0xa), and the zero character (NUL, ASCII + // 0x0) might be exploited by an attacker if they are translated + // verbatim. Any request or response that contains a character not + // permitted in a header field value MUST be treated as malformed + // (Section 8.1.2.6). Valid characters are defined by the + // field-content ABNF rule in Section 3.2 of [RFC7230]." + // + // This function does not (yet?) properly handle the rejection of + // strings that begin or end with SP or HTAB. + func ValidHeaderFieldValue(v string) bool { + for i := 0; i < len(v); i++ { + b := v[i] + if isCTL(b) && !isLWS(b) { + return false + } + } + return true + } func isASCII(s string) bool { + for i := 0; i < len(s); i++ { + if s[i] >= utf8.RuneSelf { + return false + } + } + return true + } // PunycodeHostPort returns the IDNA Punycode version + // of the provided "host" or "host:port" string. + func PunycodeHostPort(v string) (string, error) { + if isASCII(v) { + return v, nil + } host, port, err := net.SplitHostPort(v) + if err != nil { + // The input 'v' argument was just a "host" argument, + // without a port. This error should not be returned + // to the caller. + host = v + port = "" + } + host, err = idna.ToASCII(host) + if err != nil { + // Non-UTF-8? Not representable in Punycode, in any + // case. + return "", err + } + if port == "" { + return host, nil + } + return net.JoinHostPort(host, port), nil + } diff --git a/vendor/golang.org/x/net/http2/client_conn_pool.go b/vendor/golang.org/x/net/http2/client_conn_pool.go index 780968d..1b75b23 100644 --- a/vendor/golang.org/x/net/http2/client_conn_pool.go +++ b/vendor/golang.org/x/net/http2/client_conn_pool.go @@ -1,5 +1,7 @@ // Copyright 2015 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Transport code's client connection pooling. @@ -15,297 +17,531 @@ import ( ) // ClientConnPool manages a pool of HTTP/2 client connections. + type ClientConnPool interface { + // GetClientConn returns a specific HTTP/2 connection (usually + // a TLS-TCP connection) to an HTTP/2 server. On success, the + // returned ClientConn accounts for the upcoming RoundTrip + // call, so the caller should not omit it. If the caller needs + // to, ClientConn.RoundTrip can be called with a bogus + // new(http.Request) to release the stream reservation. + GetClientConn(req *http.Request, addr string) (*ClientConn, error) + MarkDead(*ClientConn) } // clientConnPoolIdleCloser is the interface implemented by ClientConnPool + // implementations which can close their idle connections. + type clientConnPoolIdleCloser interface { ClientConnPool + closeIdleConnections() } var ( _ clientConnPoolIdleCloser = (*clientConnPool)(nil) + _ clientConnPoolIdleCloser = noDialClientConnPool{} ) // TODO: use singleflight for dialing and addConnCalls? + type clientConnPool struct { t *Transport mu sync.Mutex // TODO: maybe switch to RWMutex + // TODO: add support for sharing conns based on cert names + // (e.g. share conn for googleapis.com and appspot.com) - conns map[string][]*ClientConn // key is host:port - dialing map[string]*dialCall // currently in-flight dials - keys map[*ClientConn][]string + + conns map[string][]*ClientConn // key is host:port + + dialing map[string]*dialCall // currently in-flight dials + + keys map[*ClientConn][]string + addConnCalls map[string]*addConnCall // in-flight addConnIfNeeded calls + } func (p *clientConnPool) GetClientConn(req *http.Request, addr string) (*ClientConn, error) { + return p.getClientConn(req, addr, dialOnMiss) + } const ( - dialOnMiss = true + dialOnMiss = true + noDialOnMiss = false ) func (p *clientConnPool) getClientConn(req *http.Request, addr string, dialOnMiss bool) (*ClientConn, error) { + // TODO(dneil): Dial a new connection when t.DisableKeepAlives is set? + if isConnectionCloseRequest(req) && dialOnMiss { + // It gets its own connection. + traceGetConn(req, addr) + const singleUse = true + cc, err := p.t.dialClientConn(req.Context(), addr, singleUse) + if err != nil { + return nil, err + } + return cc, nil + } + for { + p.mu.Lock() + for _, cc := range p.conns[addr] { + if cc.ReserveNewRequest() { + // When a connection is presented to us by the net/http package, + // the GetConn hook has already been called. + // Don't call it a second time here. + if !cc.getConnCalled { + traceGetConn(req, addr) + } + cc.getConnCalled = false + p.mu.Unlock() + return cc, nil + } + } + if !dialOnMiss { + p.mu.Unlock() + return nil, ErrNoCachedConn + } + traceGetConn(req, addr) + call := p.getStartDialLocked(req.Context(), addr) + p.mu.Unlock() + <-call.done + if shouldRetryDial(call, req) { + continue + } + cc, err := call.res, call.err + if err != nil { + return nil, err + } + if cc.ReserveNewRequest() { + return cc, nil + } + } + } // dialCall is an in-flight Transport dial call to a host. + type dialCall struct { _ incomparable + p *clientConnPool + // the context associated with the request + // that created this dialCall - ctx context.Context + + ctx context.Context + done chan struct{} // closed when done - res *ClientConn // valid after done is closed - err error // valid after done is closed + + res *ClientConn // valid after done is closed + + err error // valid after done is closed + } // requires p.mu is held. + func (p *clientConnPool) getStartDialLocked(ctx context.Context, addr string) *dialCall { + if call, ok := p.dialing[addr]; ok { + // A dial is already in-flight. Don't start another. + return call + } + call := &dialCall{p: p, done: make(chan struct{}), ctx: ctx} + if p.dialing == nil { + p.dialing = make(map[string]*dialCall) + } + p.dialing[addr] = call + go call.dial(call.ctx, addr) + return call + } // run in its own goroutine. + func (c *dialCall) dial(ctx context.Context, addr string) { + const singleUse = false // shared conn + c.res, c.err = c.p.t.dialClientConn(ctx, addr, singleUse) c.p.mu.Lock() + delete(c.p.dialing, addr) + if c.err == nil { + c.p.addConnLocked(addr, c.res) + } + c.p.mu.Unlock() close(c.done) + } // addConnIfNeeded makes a NewClientConn out of c if a connection for key doesn't + // already exist. It coalesces concurrent calls with the same key. + // This is used by the http1 Transport code when it creates a new connection. Because + // the http1 Transport doesn't de-dup TCP dials to outbound hosts (because it doesn't know + // the protocol), it can get into a situation where it has multiple TLS connections. + // This code decides which ones live or die. + // The return value used is whether c was used. + // c is never closed. + func (p *clientConnPool) addConnIfNeeded(key string, t *Transport, c *tls.Conn) (used bool, err error) { + p.mu.Lock() + for _, cc := range p.conns[key] { + if cc.CanTakeNewRequest() { + p.mu.Unlock() + return false, nil + } + } + call, dup := p.addConnCalls[key] + if !dup { + if p.addConnCalls == nil { + p.addConnCalls = make(map[string]*addConnCall) + } + call = &addConnCall{ - p: p, + + p: p, + done: make(chan struct{}), } + p.addConnCalls[key] = call + go call.run(t, key, c) + } + p.mu.Unlock() <-call.done + if call.err != nil { + return false, call.err + } + return !dup, nil + } type addConnCall struct { - _ incomparable - p *clientConnPool + _ incomparable + + p *clientConnPool + done chan struct{} // closed when done - err error + + err error } func (c *addConnCall) run(t *Transport, key string, tc *tls.Conn) { + cc, err := t.NewClientConn(tc) p := c.p + p.mu.Lock() + if err != nil { + c.err = err + } else { + cc.getConnCalled = true // already called by the net/http package + p.addConnLocked(key, cc) + } + delete(p.addConnCalls, key) + p.mu.Unlock() + close(c.done) + } // p.mu must be held + func (p *clientConnPool) addConnLocked(key string, cc *ClientConn) { + for _, v := range p.conns[key] { + if v == cc { + return + } + } + if p.conns == nil { + p.conns = make(map[string][]*ClientConn) + } + if p.keys == nil { + p.keys = make(map[*ClientConn][]string) + } + p.conns[key] = append(p.conns[key], cc) + p.keys[cc] = append(p.keys[cc], key) + } func (p *clientConnPool) MarkDead(cc *ClientConn) { + p.mu.Lock() + defer p.mu.Unlock() + for _, key := range p.keys[cc] { + vv, ok := p.conns[key] + if !ok { + continue + } + newList := filterOutClientConn(vv, cc) + if len(newList) > 0 { + p.conns[key] = newList + } else { + delete(p.conns, key) + } + } + delete(p.keys, cc) + } func (p *clientConnPool) closeIdleConnections() { + p.mu.Lock() + defer p.mu.Unlock() + // TODO: don't close a cc if it was just added to the pool + // milliseconds ago and has never been used. There's currently + // a small race window with the HTTP/1 Transport's integration + // where it can add an idle conn just before using it, and + // somebody else can concurrently call CloseIdleConns and + // break some caller's RoundTrip. + for _, vv := range p.conns { + for _, cc := range vv { + cc.closeIfIdle() + } + } + } func filterOutClientConn(in []*ClientConn, exclude *ClientConn) []*ClientConn { + out := in[:0] + for _, v := range in { + if v != exclude { + out = append(out, v) + } + } + // If we filtered it out, zero out the last item to prevent + // the GC from seeing it. + if len(in) != len(out) { + in[len(in)-1] = nil + } + return out + } // noDialClientConnPool is an implementation of http2.ClientConnPool + // which never dials. We let the HTTP/1.1 client dial and use its TLS + // connection instead. + type noDialClientConnPool struct{ *clientConnPool } func (p noDialClientConnPool) GetClientConn(req *http.Request, addr string) (*ClientConn, error) { + return p.getClientConn(req, addr, noDialOnMiss) + } // shouldRetryDial reports whether the current request should + // retry dialing after the call finished unsuccessfully, for example + // if the dial was canceled because of a context cancellation or + // deadline expiry. + func shouldRetryDial(call *dialCall, req *http.Request) bool { + if call.err == nil { + // No error, no need to retry + return false + } + if call.ctx == req.Context() { + // If the call has the same context as the request, the dial + // should not be retried, since any cancellation will have come + // from this request. + return false + } + if !errors.Is(call.err, context.Canceled) && !errors.Is(call.err, context.DeadlineExceeded) { + // If the call error is not because of a context cancellation or a deadline expiry, + // the dial should not be retried. + return false + } + // Only retry if the error is a context cancellation error or deadline expiry + // and the context associated with the call was canceled or expired. + return call.ctx.Err() != nil + } diff --git a/vendor/golang.org/x/net/http2/databuffer.go b/vendor/golang.org/x/net/http2/databuffer.go index e6f55cb..10e1215 100644 --- a/vendor/golang.org/x/net/http2/databuffer.go +++ b/vendor/golang.org/x/net/http2/databuffer.go @@ -1,5 +1,7 @@ // Copyright 2014 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package http2 @@ -11,139 +13,255 @@ import ( ) // Buffer chunks are allocated from a pool to reduce pressure on GC. + // The maximum wasted space per dataBuffer is 2x the largest size class, + // which happens when the dataBuffer has multiple chunks and there is + // one unread byte in both the first and last chunks. We use a few size + // classes to minimize overheads for servers that typically receive very + // small request bodies. + // + // TODO: Benchmark to determine if the pools are necessary. The GC may have + // improved enough that we can instead allocate chunks like this: + // make([]byte, max(16<<10, expectedBytesRemaining)) + var dataChunkPools = [...]sync.Pool{ + {New: func() interface{} { return new([1 << 10]byte) }}, + {New: func() interface{} { return new([2 << 10]byte) }}, + {New: func() interface{} { return new([4 << 10]byte) }}, + {New: func() interface{} { return new([8 << 10]byte) }}, + {New: func() interface{} { return new([16 << 10]byte) }}, } func getDataBufferChunk(size int64) []byte { + switch { + case size <= 1<<10: + return dataChunkPools[0].Get().(*[1 << 10]byte)[:] + case size <= 2<<10: + return dataChunkPools[1].Get().(*[2 << 10]byte)[:] + case size <= 4<<10: + return dataChunkPools[2].Get().(*[4 << 10]byte)[:] + case size <= 8<<10: + return dataChunkPools[3].Get().(*[8 << 10]byte)[:] + default: + return dataChunkPools[4].Get().(*[16 << 10]byte)[:] + } + } func putDataBufferChunk(p []byte) { + switch len(p) { + case 1 << 10: + dataChunkPools[0].Put((*[1 << 10]byte)(p)) + case 2 << 10: + dataChunkPools[1].Put((*[2 << 10]byte)(p)) + case 4 << 10: + dataChunkPools[2].Put((*[4 << 10]byte)(p)) + case 8 << 10: + dataChunkPools[3].Put((*[8 << 10]byte)(p)) + case 16 << 10: + dataChunkPools[4].Put((*[16 << 10]byte)(p)) + default: + panic(fmt.Sprintf("unexpected buffer len=%v", len(p))) + } + } // dataBuffer is an io.ReadWriter backed by a list of data chunks. + // Each dataBuffer is used to read DATA frames on a single stream. + // The buffer is divided into chunks so the server can limit the + // total memory used by a single connection without limiting the + // request body size on any single stream. + type dataBuffer struct { - chunks [][]byte - r int // next byte to read is chunks[0][r] - w int // next byte to write is chunks[len(chunks)-1][w] - size int // total buffered bytes + chunks [][]byte + + r int // next byte to read is chunks[0][r] + + w int // next byte to write is chunks[len(chunks)-1][w] + + size int // total buffered bytes + expected int64 // we expect at least this many bytes in future Write calls (ignored if <= 0) + } var errReadEmpty = errors.New("read from empty dataBuffer") // Read copies bytes from the buffer into p. + // It is an error to read when no data is available. + func (b *dataBuffer) Read(p []byte) (int, error) { + if b.size == 0 { + return 0, errReadEmpty + } + var ntotal int + for len(p) > 0 && b.size > 0 { + readFrom := b.bytesFromFirstChunk() + n := copy(p, readFrom) + p = p[n:] + ntotal += n + b.r += n + b.size -= n + // If the first chunk has been consumed, advance to the next chunk. + if b.r == len(b.chunks[0]) { + putDataBufferChunk(b.chunks[0]) + end := len(b.chunks) - 1 + copy(b.chunks[:end], b.chunks[1:]) + b.chunks[end] = nil + b.chunks = b.chunks[:end] + b.r = 0 + } + } + return ntotal, nil + } func (b *dataBuffer) bytesFromFirstChunk() []byte { + if len(b.chunks) == 1 { + return b.chunks[0][b.r:b.w] + } + return b.chunks[0][b.r:] + } // Len returns the number of bytes of the unread portion of the buffer. + func (b *dataBuffer) Len() int { + return b.size + } // Write appends p to the buffer. + func (b *dataBuffer) Write(p []byte) (int, error) { + ntotal := len(p) + for len(p) > 0 { + // If the last chunk is empty, allocate a new chunk. Try to allocate + // enough to fully copy p plus any additional bytes we expect to + // receive. However, this may allocate less than len(p). + want := int64(len(p)) + if b.expected > want { + want = b.expected + } + chunk := b.lastChunkOrAlloc(want) + n := copy(chunk[b.w:], p) + p = p[n:] + b.w += n + b.size += n + b.expected -= int64(n) + } + return ntotal, nil + } func (b *dataBuffer) lastChunkOrAlloc(want int64) []byte { + if len(b.chunks) != 0 { + last := b.chunks[len(b.chunks)-1] + if b.w < len(last) { + return last + } + } + chunk := getDataBufferChunk(want) + b.chunks = append(b.chunks, chunk) + b.w = 0 + return chunk + } diff --git a/vendor/golang.org/x/net/http2/errors.go b/vendor/golang.org/x/net/http2/errors.go index f2067da..a6893bf 100644 --- a/vendor/golang.org/x/net/http2/errors.go +++ b/vendor/golang.org/x/net/http2/errors.go @@ -1,5 +1,7 @@ // Copyright 2014 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package http2 @@ -10,136 +12,216 @@ import ( ) // An ErrCode is an unsigned 32-bit error code as defined in the HTTP/2 spec. + type ErrCode uint32 const ( - ErrCodeNo ErrCode = 0x0 - ErrCodeProtocol ErrCode = 0x1 - ErrCodeInternal ErrCode = 0x2 - ErrCodeFlowControl ErrCode = 0x3 - ErrCodeSettingsTimeout ErrCode = 0x4 - ErrCodeStreamClosed ErrCode = 0x5 - ErrCodeFrameSize ErrCode = 0x6 - ErrCodeRefusedStream ErrCode = 0x7 - ErrCodeCancel ErrCode = 0x8 - ErrCodeCompression ErrCode = 0x9 - ErrCodeConnect ErrCode = 0xa - ErrCodeEnhanceYourCalm ErrCode = 0xb + ErrCodeNo ErrCode = 0x0 + + ErrCodeProtocol ErrCode = 0x1 + + ErrCodeInternal ErrCode = 0x2 + + ErrCodeFlowControl ErrCode = 0x3 + + ErrCodeSettingsTimeout ErrCode = 0x4 + + ErrCodeStreamClosed ErrCode = 0x5 + + ErrCodeFrameSize ErrCode = 0x6 + + ErrCodeRefusedStream ErrCode = 0x7 + + ErrCodeCancel ErrCode = 0x8 + + ErrCodeCompression ErrCode = 0x9 + + ErrCodeConnect ErrCode = 0xa + + ErrCodeEnhanceYourCalm ErrCode = 0xb + ErrCodeInadequateSecurity ErrCode = 0xc - ErrCodeHTTP11Required ErrCode = 0xd + + ErrCodeHTTP11Required ErrCode = 0xd ) var errCodeName = map[ErrCode]string{ - ErrCodeNo: "NO_ERROR", - ErrCodeProtocol: "PROTOCOL_ERROR", - ErrCodeInternal: "INTERNAL_ERROR", - ErrCodeFlowControl: "FLOW_CONTROL_ERROR", - ErrCodeSettingsTimeout: "SETTINGS_TIMEOUT", - ErrCodeStreamClosed: "STREAM_CLOSED", - ErrCodeFrameSize: "FRAME_SIZE_ERROR", - ErrCodeRefusedStream: "REFUSED_STREAM", - ErrCodeCancel: "CANCEL", - ErrCodeCompression: "COMPRESSION_ERROR", - ErrCodeConnect: "CONNECT_ERROR", - ErrCodeEnhanceYourCalm: "ENHANCE_YOUR_CALM", + + ErrCodeNo: "NO_ERROR", + + ErrCodeProtocol: "PROTOCOL_ERROR", + + ErrCodeInternal: "INTERNAL_ERROR", + + ErrCodeFlowControl: "FLOW_CONTROL_ERROR", + + ErrCodeSettingsTimeout: "SETTINGS_TIMEOUT", + + ErrCodeStreamClosed: "STREAM_CLOSED", + + ErrCodeFrameSize: "FRAME_SIZE_ERROR", + + ErrCodeRefusedStream: "REFUSED_STREAM", + + ErrCodeCancel: "CANCEL", + + ErrCodeCompression: "COMPRESSION_ERROR", + + ErrCodeConnect: "CONNECT_ERROR", + + ErrCodeEnhanceYourCalm: "ENHANCE_YOUR_CALM", + ErrCodeInadequateSecurity: "INADEQUATE_SECURITY", - ErrCodeHTTP11Required: "HTTP_1_1_REQUIRED", + + ErrCodeHTTP11Required: "HTTP_1_1_REQUIRED", } func (e ErrCode) String() string { + if s, ok := errCodeName[e]; ok { + return s + } + return fmt.Sprintf("unknown error code 0x%x", uint32(e)) + } func (e ErrCode) stringToken() string { + if s, ok := errCodeName[e]; ok { + return s + } + return fmt.Sprintf("ERR_UNKNOWN_%d", uint32(e)) + } // ConnectionError is an error that results in the termination of the + // entire connection. + type ConnectionError ErrCode func (e ConnectionError) Error() string { return fmt.Sprintf("connection error: %s", ErrCode(e)) } // StreamError is an error that only affects one stream within an + // HTTP/2 connection. + type StreamError struct { StreamID uint32 - Code ErrCode - Cause error // optional additional detail + + Code ErrCode + + Cause error // optional additional detail + } // errFromPeer is a sentinel error value for StreamError.Cause to + // indicate that the StreamError was sent from the peer over the wire + // and wasn't locally generated in the Transport. + var errFromPeer = errors.New("received from peer") func streamError(id uint32, code ErrCode) StreamError { + return StreamError{StreamID: id, Code: code} + } func (e StreamError) Error() string { + if e.Cause != nil { + return fmt.Sprintf("stream error: stream ID %d; %v; %v", e.StreamID, e.Code, e.Cause) + } + return fmt.Sprintf("stream error: stream ID %d; %v", e.StreamID, e.Code) + } // 6.9.1 The Flow Control Window + // "If a sender receives a WINDOW_UPDATE that causes a flow control + // window to exceed this maximum it MUST terminate either the stream + // or the connection, as appropriate. For streams, [...]; for the + // connection, a GOAWAY frame with a FLOW_CONTROL_ERROR code." + type goAwayFlowError struct{} func (goAwayFlowError) Error() string { return "connection exceeded flow control window size" } // connError represents an HTTP/2 ConnectionError error code, along + // with a string (for debugging) explaining why. + // + // Errors of this type are only returned by the frame parser functions + // and converted into ConnectionError(Code), after stashing away + // the Reason into the Framer's errDetail field, accessible via + // the (*Framer).ErrorDetail method. + type connError struct { - Code ErrCode // the ConnectionError error code - Reason string // additional reason + Code ErrCode // the ConnectionError error code + + Reason string // additional reason + } func (e connError) Error() string { + return fmt.Sprintf("http2: connection error: %v: %v", e.Code, e.Reason) + } type pseudoHeaderError string func (e pseudoHeaderError) Error() string { + return fmt.Sprintf("invalid pseudo-header %q", string(e)) + } type duplicatePseudoHeaderError string func (e duplicatePseudoHeaderError) Error() string { + return fmt.Sprintf("duplicate pseudo-header %q", string(e)) + } type headerFieldNameError string func (e headerFieldNameError) Error() string { + return fmt.Sprintf("invalid header field name %q", string(e)) + } type headerFieldValueError string func (e headerFieldValueError) Error() string { + return fmt.Sprintf("invalid header field value for %q", string(e)) + } var ( errMixPseudoHeaderTypes = errors.New("mix of request and response pseudo headers") - errPseudoAfterRegular = errors.New("pseudo header field after regular") + + errPseudoAfterRegular = errors.New("pseudo header field after regular") ) diff --git a/vendor/golang.org/x/net/http2/frame.go b/vendor/golang.org/x/net/http2/frame.go index 105c3b2..dc9a143 100644 --- a/vendor/golang.org/x/net/http2/frame.go +++ b/vendor/golang.org/x/net/http2/frame.go @@ -1,5 +1,7 @@ // Copyright 2014 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package http2 @@ -23,396 +25,660 @@ const frameHeaderLen = 9 var padZeros = make([]byte, 255) // zeros for padding // A FrameType is a registered frame type as defined in + // https://httpwg.org/specs/rfc7540.html#rfc.section.11.2 + type FrameType uint8 const ( - FrameData FrameType = 0x0 - FrameHeaders FrameType = 0x1 - FramePriority FrameType = 0x2 - FrameRSTStream FrameType = 0x3 - FrameSettings FrameType = 0x4 - FramePushPromise FrameType = 0x5 - FramePing FrameType = 0x6 - FrameGoAway FrameType = 0x7 + FrameData FrameType = 0x0 + + FrameHeaders FrameType = 0x1 + + FramePriority FrameType = 0x2 + + FrameRSTStream FrameType = 0x3 + + FrameSettings FrameType = 0x4 + + FramePushPromise FrameType = 0x5 + + FramePing FrameType = 0x6 + + FrameGoAway FrameType = 0x7 + FrameWindowUpdate FrameType = 0x8 + FrameContinuation FrameType = 0x9 ) var frameName = map[FrameType]string{ - FrameData: "DATA", - FrameHeaders: "HEADERS", - FramePriority: "PRIORITY", - FrameRSTStream: "RST_STREAM", - FrameSettings: "SETTINGS", - FramePushPromise: "PUSH_PROMISE", - FramePing: "PING", - FrameGoAway: "GOAWAY", + + FrameData: "DATA", + + FrameHeaders: "HEADERS", + + FramePriority: "PRIORITY", + + FrameRSTStream: "RST_STREAM", + + FrameSettings: "SETTINGS", + + FramePushPromise: "PUSH_PROMISE", + + FramePing: "PING", + + FrameGoAway: "GOAWAY", + FrameWindowUpdate: "WINDOW_UPDATE", + FrameContinuation: "CONTINUATION", } func (t FrameType) String() string { + if s, ok := frameName[t]; ok { + return s + } + return fmt.Sprintf("UNKNOWN_FRAME_TYPE_%d", uint8(t)) + } // Flags is a bitmask of HTTP/2 flags. + // The meaning of flags varies depending on the frame type. + type Flags uint8 // Has reports whether f contains all (0 or more) flags in v. + func (f Flags) Has(v Flags) bool { + return (f & v) == v + } // Frame-specific FrameHeader flag bits. + const ( + // Data Frame + FlagDataEndStream Flags = 0x1 - FlagDataPadded Flags = 0x8 + + FlagDataPadded Flags = 0x8 // Headers Frame - FlagHeadersEndStream Flags = 0x1 + + FlagHeadersEndStream Flags = 0x1 + FlagHeadersEndHeaders Flags = 0x4 - FlagHeadersPadded Flags = 0x8 - FlagHeadersPriority Flags = 0x20 + + FlagHeadersPadded Flags = 0x8 + + FlagHeadersPriority Flags = 0x20 // Settings Frame + FlagSettingsAck Flags = 0x1 // Ping Frame + FlagPingAck Flags = 0x1 // Continuation Frame + FlagContinuationEndHeaders Flags = 0x4 FlagPushPromiseEndHeaders Flags = 0x4 - FlagPushPromisePadded Flags = 0x8 + + FlagPushPromisePadded Flags = 0x8 ) var flagName = map[FrameType]map[Flags]string{ + FrameData: { + FlagDataEndStream: "END_STREAM", - FlagDataPadded: "PADDED", + + FlagDataPadded: "PADDED", }, + FrameHeaders: { - FlagHeadersEndStream: "END_STREAM", + + FlagHeadersEndStream: "END_STREAM", + FlagHeadersEndHeaders: "END_HEADERS", - FlagHeadersPadded: "PADDED", - FlagHeadersPriority: "PRIORITY", + + FlagHeadersPadded: "PADDED", + + FlagHeadersPriority: "PRIORITY", }, + FrameSettings: { + FlagSettingsAck: "ACK", }, + FramePing: { + FlagPingAck: "ACK", }, + FrameContinuation: { + FlagContinuationEndHeaders: "END_HEADERS", }, + FramePushPromise: { + FlagPushPromiseEndHeaders: "END_HEADERS", - FlagPushPromisePadded: "PADDED", + + FlagPushPromisePadded: "PADDED", }, } // a frameParser parses a frame given its FrameHeader and payload + // bytes. The length of payload will always equal fh.Length (which + // might be 0). + type frameParser func(fc *frameCache, fh FrameHeader, countError func(string), payload []byte) (Frame, error) var frameParsers = map[FrameType]frameParser{ - FrameData: parseDataFrame, - FrameHeaders: parseHeadersFrame, - FramePriority: parsePriorityFrame, - FrameRSTStream: parseRSTStreamFrame, - FrameSettings: parseSettingsFrame, - FramePushPromise: parsePushPromise, - FramePing: parsePingFrame, - FrameGoAway: parseGoAwayFrame, + + FrameData: parseDataFrame, + + FrameHeaders: parseHeadersFrame, + + FramePriority: parsePriorityFrame, + + FrameRSTStream: parseRSTStreamFrame, + + FrameSettings: parseSettingsFrame, + + FramePushPromise: parsePushPromise, + + FramePing: parsePingFrame, + + FrameGoAway: parseGoAwayFrame, + FrameWindowUpdate: parseWindowUpdateFrame, + FrameContinuation: parseContinuationFrame, } func typeFrameParser(t FrameType) frameParser { + if f := frameParsers[t]; f != nil { + return f + } + return parseUnknownFrame + } // A FrameHeader is the 9 byte header of all HTTP/2 frames. + // + // See https://httpwg.org/specs/rfc7540.html#FrameHeader + type FrameHeader struct { valid bool // caller can access []byte fields in the Frame // Type is the 1 byte frame type. There are ten standard frame + // types, but extension frame types may be written by WriteRawFrame + // and will be returned by ReadFrame (as UnknownFrame). + Type FrameType // Flags are the 1 byte of 8 potential bit flags per frame. + // They are specific to the frame type. + Flags Flags // Length is the length of the frame, not including the 9 byte header. + // The maximum size is one byte less than 16MB (uint24), but only + // frames up to 16KB are allowed without peer agreement. + Length uint32 // StreamID is which stream this frame is for. Certain frames + // are not stream-specific, in which case this field is 0. + StreamID uint32 } // Header returns h. It exists so FrameHeaders can be embedded in other + // specific frame types and implement the Frame interface. + func (h FrameHeader) Header() FrameHeader { return h } func (h FrameHeader) String() string { + var buf bytes.Buffer + buf.WriteString("[FrameHeader ") + h.writeDebug(&buf) + buf.WriteByte(']') + return buf.String() + } func (h FrameHeader) writeDebug(buf *bytes.Buffer) { + buf.WriteString(h.Type.String()) + if h.Flags != 0 { + buf.WriteString(" flags=") + set := 0 + for i := uint8(0); i < 8; i++ { + if h.Flags&(1< 1 { + buf.WriteByte('|') + } + name := flagName[h.Type][Flags(1<>24), + byte(streamID>>16), + byte(streamID>>8), + byte(streamID)) + } func (f *Framer) endWrite() error { + // Now that we know the final size, fill in the FrameHeader in + // the space previously reserved for it. Abuse append. + length := len(f.wbuf) - frameHeaderLen + if length >= (1 << 24) { + return ErrFrameTooLarge + } + _ = append(f.wbuf[:0], + byte(length>>16), + byte(length>>8), + byte(length)) + if f.logWrites { + f.logWrite() + } n, err := f.w.Write(f.wbuf) + if err == nil && n != len(f.wbuf) { + err = io.ErrShortWrite + } + return err + } func (f *Framer) logWrite() { + if f.debugFramer == nil { + f.debugFramerBuf = new(bytes.Buffer) + f.debugFramer = NewFramer(nil, f.debugFramerBuf) + f.debugFramer.logReads = false // we log it ourselves, saying "wrote" below + // Let us read anything, even if we accidentally wrote it + // in the wrong order: + f.debugFramer.AllowIllegalReads = true + } + f.debugFramerBuf.Write(f.wbuf) + fr, err := f.debugFramer.ReadFrame() + if err != nil { + f.debugWriteLoggerf("http2: Framer %p: failed to decode just-written frame", f) + return + } + f.debugWriteLoggerf("http2: Framer %p: wrote %v", f, summarizeFrame(fr)) + } -func (f *Framer) writeByte(v byte) { f.wbuf = append(f.wbuf, v) } -func (f *Framer) writeBytes(v []byte) { f.wbuf = append(f.wbuf, v...) } +func (f *Framer) writeByte(v byte) { f.wbuf = append(f.wbuf, v) } + +func (f *Framer) writeBytes(v []byte) { f.wbuf = append(f.wbuf, v...) } + func (f *Framer) writeUint16(v uint16) { f.wbuf = append(f.wbuf, byte(v>>8), byte(v)) } + func (f *Framer) writeUint32(v uint32) { + f.wbuf = append(f.wbuf, byte(v>>24), byte(v>>16), byte(v>>8), byte(v)) + } const ( minMaxFrameSize = 1 << 14 - maxFrameSize = 1<<24 - 1 + + maxFrameSize = 1<<24 - 1 ) // SetReuseFrames allows the Framer to reuse Frames. + // If called on a Framer, Frames returned by calls to ReadFrame are only + // valid until the next call to ReadFrame. + func (fr *Framer) SetReuseFrames() { + if fr.frameCache != nil { + return + } + fr.frameCache = &frameCache{} + } type frameCache struct { @@ -420,993 +686,1770 @@ type frameCache struct { } func (fc *frameCache) getDataFrame() *DataFrame { + if fc == nil { + return &DataFrame{} + } + return &fc.dataFrame + } // NewFramer returns a Framer that writes frames to w and reads them from r. + func NewFramer(w io.Writer, r io.Reader) *Framer { + fr := &Framer{ - w: w, - r: r, - countError: func(string) {}, - logReads: logFrameReads, - logWrites: logFrameWrites, - debugReadLoggerf: log.Printf, + + w: w, + + r: r, + + countError: func(string) {}, + + logReads: logFrameReads, + + logWrites: logFrameWrites, + + debugReadLoggerf: log.Printf, + debugWriteLoggerf: log.Printf, } + fr.getReadBuf = func(size uint32) []byte { + if cap(fr.readBuf) >= int(size) { + return fr.readBuf[:size] + } + fr.readBuf = make([]byte, size) + return fr.readBuf + } + fr.SetMaxReadFrameSize(maxFrameSize) + return fr + } // SetMaxReadFrameSize sets the maximum size of a frame + // that will be read by a subsequent call to ReadFrame. + // It is the caller's responsibility to advertise this + // limit with a SETTINGS frame. + func (fr *Framer) SetMaxReadFrameSize(v uint32) { + if v > maxFrameSize { + v = maxFrameSize + } + fr.maxReadSize = v + } // ErrorDetail returns a more detailed error of the last error + // returned by Framer.ReadFrame. For instance, if ReadFrame + // returns a StreamError with code PROTOCOL_ERROR, ErrorDetail + // will say exactly what was invalid. ErrorDetail is not guaranteed + // to return a non-nil value and like the rest of the http2 package, + // its return value is not protected by an API compatibility promise. + // ErrorDetail is reset after the next call to ReadFrame. + func (fr *Framer) ErrorDetail() error { + return fr.errDetail + } // ErrFrameTooLarge is returned from Framer.ReadFrame when the peer + // sends a frame that is larger than declared with SetMaxReadFrameSize. + var ErrFrameTooLarge = errors.New("http2: frame too large") // terminalReadFrameError reports whether err is an unrecoverable + // error from ReadFrame and no other frames should be read. + func terminalReadFrameError(err error) bool { + if _, ok := err.(StreamError); ok { + return false + } + return err != nil + } // ReadFrame reads a single frame. The returned Frame is only valid + // until the next call to ReadFrame. + // + // If the frame is larger than previously set with SetMaxReadFrameSize, the + // returned error is ErrFrameTooLarge. Other errors may be of type + // ConnectionError, StreamError, or anything else from the underlying + // reader. + // + // If ReadFrame returns an error and a non-nil Frame, the Frame's StreamID + // indicates the stream responsible for the error. + func (fr *Framer) ReadFrame() (Frame, error) { + fr.errDetail = nil + if fr.lastFrame != nil { + fr.lastFrame.invalidate() + } + fh, err := readFrameHeader(fr.headerBuf[:], fr.r) + if err != nil { + return nil, err + } + if fh.Length > fr.maxReadSize { + return nil, ErrFrameTooLarge + } + payload := fr.getReadBuf(fh.Length) + if _, err := io.ReadFull(fr.r, payload); err != nil { + return nil, err + } + f, err := typeFrameParser(fh.Type)(fr.frameCache, fh, fr.countError, payload) + if err != nil { + if ce, ok := err.(connError); ok { + return nil, fr.connError(ce.Code, ce.Reason) + } + return nil, err + } + if err := fr.checkFrameOrder(f); err != nil { + return nil, err + } + if fr.logReads { + fr.debugReadLoggerf("http2: Framer %p: read %v", fr, summarizeFrame(f)) + } + if fh.Type == FrameHeaders && fr.ReadMetaHeaders != nil { + return fr.readMetaFrame(f.(*HeadersFrame)) + } + return f, nil + } // connError returns ConnectionError(code) but first + // stashes away a public reason to the caller can optionally relay it + // to the peer before hanging up on them. This might help others debug + // their implementations. + func (fr *Framer) connError(code ErrCode, reason string) error { + fr.errDetail = errors.New(reason) + return ConnectionError(code) + } // checkFrameOrder reports an error if f is an invalid frame to return + // next from ReadFrame. Mostly it checks whether HEADERS and + // CONTINUATION frames are contiguous. + func (fr *Framer) checkFrameOrder(f Frame) error { + last := fr.lastFrame + fr.lastFrame = f + if fr.AllowIllegalReads { + return nil + } fh := f.Header() + if fr.lastHeaderStream != 0 { + if fh.Type != FrameContinuation { + return fr.connError(ErrCodeProtocol, + fmt.Sprintf("got %s for stream %d; expected CONTINUATION following %s for stream %d", + fh.Type, fh.StreamID, + last.Header().Type, fr.lastHeaderStream)) + } + if fh.StreamID != fr.lastHeaderStream { + return fr.connError(ErrCodeProtocol, + fmt.Sprintf("got CONTINUATION for stream %d; expected stream %d", + fh.StreamID, fr.lastHeaderStream)) + } + } else if fh.Type == FrameContinuation { + return fr.connError(ErrCodeProtocol, fmt.Sprintf("unexpected CONTINUATION for stream %d", fh.StreamID)) + } switch fh.Type { + case FrameHeaders, FrameContinuation: + if fh.Flags.Has(FlagHeadersEndHeaders) { + fr.lastHeaderStream = 0 + } else { + fr.lastHeaderStream = fh.StreamID + } + } return nil + } // A DataFrame conveys arbitrary, variable-length sequences of octets + // associated with a stream. + // See https://httpwg.org/specs/rfc7540.html#rfc.section.6.1 + type DataFrame struct { FrameHeader + data []byte } func (f *DataFrame) StreamEnded() bool { + return f.FrameHeader.Flags.Has(FlagDataEndStream) + } // Data returns the frame's data octets, not including any padding + // size byte or padding suffix bytes. + // The caller must not retain the returned memory past the next + // call to ReadFrame. + func (f *DataFrame) Data() []byte { + f.checkValid() + return f.data + } func parseDataFrame(fc *frameCache, fh FrameHeader, countError func(string), payload []byte) (Frame, error) { + if fh.StreamID == 0 { + // DATA frames MUST be associated with a stream. If a + // DATA frame is received whose stream identifier + // field is 0x0, the recipient MUST respond with a + // connection error (Section 5.4.1) of type + // PROTOCOL_ERROR. + countError("frame_data_stream_0") + return nil, connError{ErrCodeProtocol, "DATA frame with stream ID 0"} + } + f := fc.getDataFrame() + f.FrameHeader = fh var padSize byte + if fh.Flags.Has(FlagDataPadded) { + var err error + payload, padSize, err = readByte(payload) + if err != nil { + countError("frame_data_pad_byte_short") + return nil, err + } + } + if int(padSize) > len(payload) { + // If the length of the padding is greater than the + // length of the frame payload, the recipient MUST + // treat this as a connection error. + // Filed: https://github.com/http2/http2-spec/issues/610 + countError("frame_data_pad_too_big") + return nil, connError{ErrCodeProtocol, "pad size larger than data payload"} + } + f.data = payload[:len(payload)-int(padSize)] + return f, nil + } var ( - errStreamID = errors.New("invalid stream ID") + errStreamID = errors.New("invalid stream ID") + errDepStreamID = errors.New("invalid dependent stream ID") - errPadLength = errors.New("pad length too large") - errPadBytes = errors.New("padding bytes must all be zeros unless AllowIllegalWrites is enabled") + + errPadLength = errors.New("pad length too large") + + errPadBytes = errors.New("padding bytes must all be zeros unless AllowIllegalWrites is enabled") ) func validStreamIDOrZero(streamID uint32) bool { + return streamID&(1<<31) == 0 + } func validStreamID(streamID uint32) bool { + return streamID != 0 && streamID&(1<<31) == 0 + } // WriteData writes a DATA frame. + // + // It will perform exactly one Write to the underlying Writer. + // It is the caller's responsibility not to violate the maximum frame size + // and to not call other Write methods concurrently. + func (f *Framer) WriteData(streamID uint32, endStream bool, data []byte) error { + return f.WriteDataPadded(streamID, endStream, data, nil) + } // WriteDataPadded writes a DATA frame with optional padding. + // + // If pad is nil, the padding bit is not sent. + // The length of pad must not exceed 255 bytes. + // The bytes of pad must all be zero, unless f.AllowIllegalWrites is set. + // + // It will perform exactly one Write to the underlying Writer. + // It is the caller's responsibility not to violate the maximum frame size + // and to not call other Write methods concurrently. + func (f *Framer) WriteDataPadded(streamID uint32, endStream bool, data, pad []byte) error { + if err := f.startWriteDataPadded(streamID, endStream, data, pad); err != nil { + return err + } + return f.endWrite() + } // startWriteDataPadded is WriteDataPadded, but only writes the frame to the Framer's internal buffer. + // The caller should call endWrite to flush the frame to the underlying writer. + func (f *Framer) startWriteDataPadded(streamID uint32, endStream bool, data, pad []byte) error { + if !validStreamID(streamID) && !f.AllowIllegalWrites { + return errStreamID + } + if len(pad) > 0 { + if len(pad) > 255 { + return errPadLength + } + if !f.AllowIllegalWrites { + for _, b := range pad { + if b != 0 { + // "Padding octets MUST be set to zero when sending." + return errPadBytes + } + } + } + } + var flags Flags + if endStream { + flags |= FlagDataEndStream + } + if pad != nil { + flags |= FlagDataPadded + } + f.startWrite(FrameData, flags, streamID) + if pad != nil { + f.wbuf = append(f.wbuf, byte(len(pad))) + } + f.wbuf = append(f.wbuf, data...) + f.wbuf = append(f.wbuf, pad...) + return nil + } // A SettingsFrame conveys configuration parameters that affect how + // endpoints communicate, such as preferences and constraints on peer + // behavior. + // + // See https://httpwg.org/specs/rfc7540.html#SETTINGS + type SettingsFrame struct { FrameHeader + p []byte } func parseSettingsFrame(_ *frameCache, fh FrameHeader, countError func(string), p []byte) (Frame, error) { + if fh.Flags.Has(FlagSettingsAck) && fh.Length > 0 { + // When this (ACK 0x1) bit is set, the payload of the + // SETTINGS frame MUST be empty. Receipt of a + // SETTINGS frame with the ACK flag set and a length + // field value other than 0 MUST be treated as a + // connection error (Section 5.4.1) of type + // FRAME_SIZE_ERROR. + countError("frame_settings_ack_with_length") + return nil, ConnectionError(ErrCodeFrameSize) + } + if fh.StreamID != 0 { + // SETTINGS frames always apply to a connection, + // never a single stream. The stream identifier for a + // SETTINGS frame MUST be zero (0x0). If an endpoint + // receives a SETTINGS frame whose stream identifier + // field is anything other than 0x0, the endpoint MUST + // respond with a connection error (Section 5.4.1) of + // type PROTOCOL_ERROR. + countError("frame_settings_has_stream") + return nil, ConnectionError(ErrCodeProtocol) + } + if len(p)%6 != 0 { + countError("frame_settings_mod_6") + // Expecting even number of 6 byte settings. + return nil, ConnectionError(ErrCodeFrameSize) + } + f := &SettingsFrame{FrameHeader: fh, p: p} + if v, ok := f.Value(SettingInitialWindowSize); ok && v > (1<<31)-1 { + countError("frame_settings_window_size_too_big") + // Values above the maximum flow control window size of 2^31 - 1 MUST + // be treated as a connection error (Section 5.4.1) of type + // FLOW_CONTROL_ERROR. + return nil, ConnectionError(ErrCodeFlowControl) + } + return f, nil + } func (f *SettingsFrame) IsAck() bool { + return f.FrameHeader.Flags.Has(FlagSettingsAck) + } func (f *SettingsFrame) Value(id SettingID) (v uint32, ok bool) { + f.checkValid() + for i := 0; i < f.NumSettings(); i++ { + if s := f.Setting(i); s.ID == id { + return s.Val, true + } + } + return 0, false + } // Setting returns the setting from the frame at the given 0-based index. + // The index must be >= 0 and less than f.NumSettings(). + func (f *SettingsFrame) Setting(i int) Setting { + buf := f.p + return Setting{ - ID: SettingID(binary.BigEndian.Uint16(buf[i*6 : i*6+2])), + + ID: SettingID(binary.BigEndian.Uint16(buf[i*6 : i*6+2])), + Val: binary.BigEndian.Uint32(buf[i*6+2 : i*6+6]), } + } func (f *SettingsFrame) NumSettings() int { return len(f.p) / 6 } // HasDuplicates reports whether f contains any duplicate setting IDs. + func (f *SettingsFrame) HasDuplicates() bool { + num := f.NumSettings() + if num == 0 { + return false + } + // If it's small enough (the common case), just do the n^2 + // thing and avoid a map allocation. + if num < 10 { + for i := 0; i < num; i++ { + idi := f.Setting(i).ID + for j := i + 1; j < num; j++ { + idj := f.Setting(j).ID + if idi == idj { + return true + } + } + } + return false + } + seen := map[SettingID]bool{} + for i := 0; i < num; i++ { + id := f.Setting(i).ID + if seen[id] { + return true + } + seen[id] = true + } + return false + } // ForeachSetting runs fn for each setting. + // It stops and returns the first error. + func (f *SettingsFrame) ForeachSetting(fn func(Setting) error) error { + f.checkValid() + for i := 0; i < f.NumSettings(); i++ { + if err := fn(f.Setting(i)); err != nil { + return err + } + } + return nil + } // WriteSettings writes a SETTINGS frame with zero or more settings + // specified and the ACK bit not set. + // + // It will perform exactly one Write to the underlying Writer. + // It is the caller's responsibility to not call other Write methods concurrently. + func (f *Framer) WriteSettings(settings ...Setting) error { + f.startWrite(FrameSettings, 0, 0) + for _, s := range settings { + f.writeUint16(uint16(s.ID)) + f.writeUint32(s.Val) + } + return f.endWrite() + } // WriteSettingsAck writes an empty SETTINGS frame with the ACK bit set. + // + // It will perform exactly one Write to the underlying Writer. + // It is the caller's responsibility to not call other Write methods concurrently. + func (f *Framer) WriteSettingsAck() error { + f.startWrite(FrameSettings, FlagSettingsAck, 0) + return f.endWrite() + } // A PingFrame is a mechanism for measuring a minimal round trip time + // from the sender, as well as determining whether an idle connection + // is still functional. + // See https://httpwg.org/specs/rfc7540.html#rfc.section.6.7 + type PingFrame struct { FrameHeader + Data [8]byte } func (f *PingFrame) IsAck() bool { return f.Flags.Has(FlagPingAck) } func parsePingFrame(_ *frameCache, fh FrameHeader, countError func(string), payload []byte) (Frame, error) { + if len(payload) != 8 { + countError("frame_ping_length") + return nil, ConnectionError(ErrCodeFrameSize) + } + if fh.StreamID != 0 { + countError("frame_ping_has_stream") + return nil, ConnectionError(ErrCodeProtocol) + } + f := &PingFrame{FrameHeader: fh} + copy(f.Data[:], payload) + return f, nil + } func (f *Framer) WritePing(ack bool, data [8]byte) error { + var flags Flags + if ack { + flags = FlagPingAck + } + f.startWrite(FramePing, flags, 0) + f.writeBytes(data[:]) + return f.endWrite() + } // A GoAwayFrame informs the remote peer to stop creating streams on this connection. + // See https://httpwg.org/specs/rfc7540.html#rfc.section.6.8 + type GoAwayFrame struct { FrameHeader + LastStreamID uint32 - ErrCode ErrCode - debugData []byte + + ErrCode ErrCode + + debugData []byte } // DebugData returns any debug data in the GOAWAY frame. Its contents + // are not defined. + // The caller must not retain the returned memory past the next + // call to ReadFrame. + func (f *GoAwayFrame) DebugData() []byte { + f.checkValid() + return f.debugData + } func parseGoAwayFrame(_ *frameCache, fh FrameHeader, countError func(string), p []byte) (Frame, error) { + if fh.StreamID != 0 { + countError("frame_goaway_has_stream") + return nil, ConnectionError(ErrCodeProtocol) + } + if len(p) < 8 { + countError("frame_goaway_short") + return nil, ConnectionError(ErrCodeFrameSize) + } + return &GoAwayFrame{ - FrameHeader: fh, + + FrameHeader: fh, + LastStreamID: binary.BigEndian.Uint32(p[:4]) & (1<<31 - 1), - ErrCode: ErrCode(binary.BigEndian.Uint32(p[4:8])), - debugData: p[8:], + + ErrCode: ErrCode(binary.BigEndian.Uint32(p[4:8])), + + debugData: p[8:], }, nil + } func (f *Framer) WriteGoAway(maxStreamID uint32, code ErrCode, debugData []byte) error { + f.startWrite(FrameGoAway, 0, 0) + f.writeUint32(maxStreamID & (1<<31 - 1)) + f.writeUint32(uint32(code)) + f.writeBytes(debugData) + return f.endWrite() + } // An UnknownFrame is the frame type returned when the frame type is unknown + // or no specific frame type parser exists. + type UnknownFrame struct { FrameHeader + p []byte } // Payload returns the frame's payload (after the header). It is not + // valid to call this method after a subsequent call to + // Framer.ReadFrame, nor is it valid to retain the returned slice. + // The memory is owned by the Framer and is invalidated when the next + // frame is read. + func (f *UnknownFrame) Payload() []byte { + f.checkValid() + return f.p + } func parseUnknownFrame(_ *frameCache, fh FrameHeader, countError func(string), p []byte) (Frame, error) { + return &UnknownFrame{fh, p}, nil + } // A WindowUpdateFrame is used to implement flow control. + // See https://httpwg.org/specs/rfc7540.html#rfc.section.6.9 + type WindowUpdateFrame struct { FrameHeader + Increment uint32 // never read with high bit set + } func parseWindowUpdateFrame(_ *frameCache, fh FrameHeader, countError func(string), p []byte) (Frame, error) { + if len(p) != 4 { + countError("frame_windowupdate_bad_len") + return nil, ConnectionError(ErrCodeFrameSize) + } + inc := binary.BigEndian.Uint32(p[:4]) & 0x7fffffff // mask off high reserved bit + if inc == 0 { + // A receiver MUST treat the receipt of a + // WINDOW_UPDATE frame with an flow control window + // increment of 0 as a stream error (Section 5.4.2) of + // type PROTOCOL_ERROR; errors on the connection flow + // control window MUST be treated as a connection + // error (Section 5.4.1). + if fh.StreamID == 0 { + countError("frame_windowupdate_zero_inc_conn") + return nil, ConnectionError(ErrCodeProtocol) + } + countError("frame_windowupdate_zero_inc_stream") + return nil, streamError(fh.StreamID, ErrCodeProtocol) + } + return &WindowUpdateFrame{ + FrameHeader: fh, - Increment: inc, + + Increment: inc, }, nil + } // WriteWindowUpdate writes a WINDOW_UPDATE frame. + // The increment value must be between 1 and 2,147,483,647, inclusive. + // If the Stream ID is zero, the window update applies to the + // connection as a whole. + func (f *Framer) WriteWindowUpdate(streamID, incr uint32) error { + // "The legal range for the increment to the flow control window is 1 to 2^31-1 (2,147,483,647) octets." + if (incr < 1 || incr > 2147483647) && !f.AllowIllegalWrites { + return errors.New("illegal window increment value") + } + f.startWrite(FrameWindowUpdate, 0, streamID) + f.writeUint32(incr) + return f.endWrite() + } // A HeadersFrame is used to open a stream and additionally carries a + // header block fragment. + type HeadersFrame struct { FrameHeader // Priority is set if FlagHeadersPriority is set in the FrameHeader. + Priority PriorityParam headerFragBuf []byte // not owned + } func (f *HeadersFrame) HeaderBlockFragment() []byte { + f.checkValid() + return f.headerFragBuf + } func (f *HeadersFrame) HeadersEnded() bool { + return f.FrameHeader.Flags.Has(FlagHeadersEndHeaders) + } func (f *HeadersFrame) StreamEnded() bool { + return f.FrameHeader.Flags.Has(FlagHeadersEndStream) + } func (f *HeadersFrame) HasPriority() bool { + return f.FrameHeader.Flags.Has(FlagHeadersPriority) + } func parseHeadersFrame(_ *frameCache, fh FrameHeader, countError func(string), p []byte) (_ Frame, err error) { + hf := &HeadersFrame{ + FrameHeader: fh, } + if fh.StreamID == 0 { + // HEADERS frames MUST be associated with a stream. If a HEADERS frame + // is received whose stream identifier field is 0x0, the recipient MUST + // respond with a connection error (Section 5.4.1) of type + // PROTOCOL_ERROR. + countError("frame_headers_zero_stream") + return nil, connError{ErrCodeProtocol, "HEADERS frame with stream ID 0"} + } + var padLength uint8 + if fh.Flags.Has(FlagHeadersPadded) { + if p, padLength, err = readByte(p); err != nil { + countError("frame_headers_pad_short") + return + } + } + if fh.Flags.Has(FlagHeadersPriority) { + var v uint32 + p, v, err = readUint32(p) + if err != nil { + countError("frame_headers_prio_short") + return nil, err + } + hf.Priority.StreamDep = v & 0x7fffffff + hf.Priority.Exclusive = (v != hf.Priority.StreamDep) // high bit was set + p, hf.Priority.Weight, err = readByte(p) + if err != nil { + countError("frame_headers_prio_weight_short") + return nil, err + } + } + if len(p)-int(padLength) < 0 { + countError("frame_headers_pad_too_big") + return nil, streamError(fh.StreamID, ErrCodeProtocol) + } + hf.headerFragBuf = p[:len(p)-int(padLength)] + return hf, nil + } // HeadersFrameParam are the parameters for writing a HEADERS frame. + type HeadersFrameParam struct { + // StreamID is the required Stream ID to initiate. + StreamID uint32 + // BlockFragment is part (or all) of a Header Block. + BlockFragment []byte // EndStream indicates that the header block is the last that + // the endpoint will send for the identified stream. Setting + // this flag causes the stream to enter one of "half closed" + // states. + EndStream bool // EndHeaders indicates that this frame contains an entire + // header block and is not followed by any + // CONTINUATION frames. + EndHeaders bool // PadLength is the optional number of bytes of zeros to add + // to this frame. + PadLength uint8 // Priority, if non-zero, includes stream priority information + // in the HEADER frame. + Priority PriorityParam } // WriteHeaders writes a single HEADERS frame. + // + // This is a low-level header writing method. Encoding headers and + // splitting them into any necessary CONTINUATION frames is handled + // elsewhere. + // + // It will perform exactly one Write to the underlying Writer. + // It is the caller's responsibility to not call other Write methods concurrently. + func (f *Framer) WriteHeaders(p HeadersFrameParam) error { + if !validStreamID(p.StreamID) && !f.AllowIllegalWrites { + return errStreamID + } + var flags Flags + if p.PadLength != 0 { + flags |= FlagHeadersPadded + } + if p.EndStream { + flags |= FlagHeadersEndStream + } + if p.EndHeaders { + flags |= FlagHeadersEndHeaders + } + if !p.Priority.IsZero() { + flags |= FlagHeadersPriority + } + f.startWrite(FrameHeaders, flags, p.StreamID) + if p.PadLength != 0 { + f.writeByte(p.PadLength) + } + if !p.Priority.IsZero() { + v := p.Priority.StreamDep + if !validStreamIDOrZero(v) && !f.AllowIllegalWrites { + return errDepStreamID + } + if p.Priority.Exclusive { + v |= 1 << 31 + } + f.writeUint32(v) + f.writeByte(p.Priority.Weight) + } + f.wbuf = append(f.wbuf, p.BlockFragment...) + f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...) + return f.endWrite() + } // A PriorityFrame specifies the sender-advised priority of a stream. + // See https://httpwg.org/specs/rfc7540.html#rfc.section.6.3 + type PriorityFrame struct { FrameHeader + PriorityParam } // PriorityParam are the stream prioritzation parameters. + type PriorityParam struct { + // StreamDep is a 31-bit stream identifier for the + // stream that this stream depends on. Zero means no + // dependency. + StreamDep uint32 // Exclusive is whether the dependency is exclusive. + Exclusive bool // Weight is the stream's zero-indexed weight. It should be + // set together with StreamDep, or neither should be set. Per + // the spec, "Add one to the value to obtain a weight between + // 1 and 256." + Weight uint8 } func (p PriorityParam) IsZero() bool { + return p == PriorityParam{} + } func parsePriorityFrame(_ *frameCache, fh FrameHeader, countError func(string), payload []byte) (Frame, error) { + if fh.StreamID == 0 { + countError("frame_priority_zero_stream") + return nil, connError{ErrCodeProtocol, "PRIORITY frame with stream ID 0"} + } + if len(payload) != 5 { + countError("frame_priority_bad_length") + return nil, connError{ErrCodeFrameSize, fmt.Sprintf("PRIORITY frame payload size was %d; want 5", len(payload))} + } + v := binary.BigEndian.Uint32(payload[:4]) + streamID := v & 0x7fffffff // mask off high bit + return &PriorityFrame{ + FrameHeader: fh, + PriorityParam: PriorityParam{ - Weight: payload[4], + + Weight: payload[4], + StreamDep: streamID, + Exclusive: streamID != v, // was high bit set? + }, }, nil + } // WritePriority writes a PRIORITY frame. + // + // It will perform exactly one Write to the underlying Writer. + // It is the caller's responsibility to not call other Write methods concurrently. + func (f *Framer) WritePriority(streamID uint32, p PriorityParam) error { + if !validStreamID(streamID) && !f.AllowIllegalWrites { + return errStreamID + } + if !validStreamIDOrZero(p.StreamDep) { + return errDepStreamID + } + f.startWrite(FramePriority, 0, streamID) + v := p.StreamDep + if p.Exclusive { + v |= 1 << 31 + } + f.writeUint32(v) + f.writeByte(p.Weight) + return f.endWrite() + } // A RSTStreamFrame allows for abnormal termination of a stream. + // See https://httpwg.org/specs/rfc7540.html#rfc.section.6.4 + type RSTStreamFrame struct { FrameHeader + ErrCode ErrCode } func parseRSTStreamFrame(_ *frameCache, fh FrameHeader, countError func(string), p []byte) (Frame, error) { + if len(p) != 4 { + countError("frame_rststream_bad_len") + return nil, ConnectionError(ErrCodeFrameSize) + } + if fh.StreamID == 0 { + countError("frame_rststream_zero_stream") + return nil, ConnectionError(ErrCodeProtocol) + } + return &RSTStreamFrame{fh, ErrCode(binary.BigEndian.Uint32(p[:4]))}, nil + } // WriteRSTStream writes a RST_STREAM frame. + // + // It will perform exactly one Write to the underlying Writer. + // It is the caller's responsibility to not call other Write methods concurrently. + func (f *Framer) WriteRSTStream(streamID uint32, code ErrCode) error { + if !validStreamID(streamID) && !f.AllowIllegalWrites { + return errStreamID + } + f.startWrite(FrameRSTStream, 0, streamID) + f.writeUint32(uint32(code)) + return f.endWrite() + } // A ContinuationFrame is used to continue a sequence of header block fragments. + // See https://httpwg.org/specs/rfc7540.html#rfc.section.6.10 + type ContinuationFrame struct { FrameHeader + headerFragBuf []byte } func parseContinuationFrame(_ *frameCache, fh FrameHeader, countError func(string), p []byte) (Frame, error) { + if fh.StreamID == 0 { + countError("frame_continuation_zero_stream") + return nil, connError{ErrCodeProtocol, "CONTINUATION frame with stream ID 0"} + } + return &ContinuationFrame{fh, p}, nil + } func (f *ContinuationFrame) HeaderBlockFragment() []byte { + f.checkValid() + return f.headerFragBuf + } func (f *ContinuationFrame) HeadersEnded() bool { + return f.FrameHeader.Flags.Has(FlagContinuationEndHeaders) + } // WriteContinuation writes a CONTINUATION frame. + // + // It will perform exactly one Write to the underlying Writer. + // It is the caller's responsibility to not call other Write methods concurrently. + func (f *Framer) WriteContinuation(streamID uint32, endHeaders bool, headerBlockFragment []byte) error { + if !validStreamID(streamID) && !f.AllowIllegalWrites { + return errStreamID + } + var flags Flags + if endHeaders { + flags |= FlagContinuationEndHeaders + } + f.startWrite(FrameContinuation, flags, streamID) + f.wbuf = append(f.wbuf, headerBlockFragment...) + return f.endWrite() + } // A PushPromiseFrame is used to initiate a server stream. + // See https://httpwg.org/specs/rfc7540.html#rfc.section.6.6 + type PushPromiseFrame struct { FrameHeader - PromiseID uint32 + + PromiseID uint32 + headerFragBuf []byte // not owned + } func (f *PushPromiseFrame) HeaderBlockFragment() []byte { + f.checkValid() + return f.headerFragBuf + } func (f *PushPromiseFrame) HeadersEnded() bool { + return f.FrameHeader.Flags.Has(FlagPushPromiseEndHeaders) + } func parsePushPromise(_ *frameCache, fh FrameHeader, countError func(string), p []byte) (_ Frame, err error) { + pp := &PushPromiseFrame{ + FrameHeader: fh, } + if pp.StreamID == 0 { + // PUSH_PROMISE frames MUST be associated with an existing, + // peer-initiated stream. The stream identifier of a + // PUSH_PROMISE frame indicates the stream it is associated + // with. If the stream identifier field specifies the value + // 0x0, a recipient MUST respond with a connection error + // (Section 5.4.1) of type PROTOCOL_ERROR. + countError("frame_pushpromise_zero_stream") + return nil, ConnectionError(ErrCodeProtocol) + } + // The PUSH_PROMISE frame includes optional padding. + // Padding fields and flags are identical to those defined for DATA frames + var padLength uint8 + if fh.Flags.Has(FlagPushPromisePadded) { + if p, padLength, err = readByte(p); err != nil { + countError("frame_pushpromise_pad_short") + return + } + } p, pp.PromiseID, err = readUint32(p) + if err != nil { + countError("frame_pushpromise_promiseid_short") + return + } + pp.PromiseID = pp.PromiseID & (1<<31 - 1) if int(padLength) > len(p) { + // like the DATA frame, error out if padding is longer than the body. + countError("frame_pushpromise_pad_too_big") + return nil, ConnectionError(ErrCodeProtocol) + } + pp.headerFragBuf = p[:len(p)-int(padLength)] + return pp, nil + } // PushPromiseParam are the parameters for writing a PUSH_PROMISE frame. + type PushPromiseParam struct { + // StreamID is the required Stream ID to initiate. + StreamID uint32 // PromiseID is the required Stream ID which this + // Push Promises + PromiseID uint32 // BlockFragment is part (or all) of a Header Block. + BlockFragment []byte // EndHeaders indicates that this frame contains an entire + // header block and is not followed by any + // CONTINUATION frames. + EndHeaders bool // PadLength is the optional number of bytes of zeros to add + // to this frame. + PadLength uint8 } // WritePushPromise writes a single PushPromise Frame. + // + // As with Header Frames, This is the low level call for writing + // individual frames. Continuation frames are handled elsewhere. + // + // It will perform exactly one Write to the underlying Writer. + // It is the caller's responsibility to not call other Write methods concurrently. + func (f *Framer) WritePushPromise(p PushPromiseParam) error { + if !validStreamID(p.StreamID) && !f.AllowIllegalWrites { + return errStreamID + } + var flags Flags + if p.PadLength != 0 { + flags |= FlagPushPromisePadded + } + if p.EndHeaders { + flags |= FlagPushPromiseEndHeaders + } + f.startWrite(FramePushPromise, flags, p.StreamID) + if p.PadLength != 0 { + f.writeByte(p.PadLength) + } + if !validStreamID(p.PromiseID) && !f.AllowIllegalWrites { + return errStreamID + } + f.writeUint32(p.PromiseID) + f.wbuf = append(f.wbuf, p.BlockFragment...) + f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...) + return f.endWrite() + } // WriteRawFrame writes a raw frame. This can be used to write + // extension frames unknown to this package. + func (f *Framer) WriteRawFrame(t FrameType, flags Flags, streamID uint32, payload []byte) error { + f.startWrite(t, flags, streamID) + f.writeBytes(payload) + return f.endWrite() + } func readByte(p []byte) (remain []byte, b byte, err error) { + if len(p) == 0 { + return nil, 0, io.ErrUnexpectedEOF + } + return p[1:], p[0], nil + } func readUint32(p []byte) (remain []byte, v uint32, err error) { + if len(p) < 4 { + return nil, 0, io.ErrUnexpectedEOF + } + return p[4:], binary.BigEndian.Uint32(p[:4]), nil + } type streamEnder interface { @@ -1419,273 +2462,497 @@ type headersEnder interface { type headersOrContinuation interface { headersEnder + HeaderBlockFragment() []byte } // A MetaHeadersFrame is the representation of one HEADERS frame and + // zero or more contiguous CONTINUATION frames and the decoding of + // their HPACK-encoded contents. + // + // This type of frame does not appear on the wire and is only returned + // by the Framer when Framer.ReadMetaHeaders is set. + type MetaHeadersFrame struct { *HeadersFrame // Fields are the fields contained in the HEADERS and + // CONTINUATION frames. The underlying slice is owned by the + // Framer and must not be retained after the next call to + // ReadFrame. + // + // Fields are guaranteed to be in the correct http2 order and + // not have unknown pseudo header fields or invalid header + // field names or values. Required pseudo header fields may be + // missing, however. Use the MetaHeadersFrame.Pseudo accessor + // method access pseudo headers. + Fields []hpack.HeaderField // Truncated is whether the max header list size limit was hit + // and Fields is incomplete. The hpack decoder state is still + // valid, however. + Truncated bool } // PseudoValue returns the given pseudo header field's value. + // The provided pseudo field should not contain the leading colon. + func (mh *MetaHeadersFrame) PseudoValue(pseudo string) string { + for _, hf := range mh.Fields { + if !hf.IsPseudo() { + return "" + } + if hf.Name[1:] == pseudo { + return hf.Value + } + } + return "" + } // RegularFields returns the regular (non-pseudo) header fields of mh. + // The caller does not own the returned slice. + func (mh *MetaHeadersFrame) RegularFields() []hpack.HeaderField { + for i, hf := range mh.Fields { + if !hf.IsPseudo() { + return mh.Fields[i:] + } + } + return nil + } // PseudoFields returns the pseudo header fields of mh. + // The caller does not own the returned slice. + func (mh *MetaHeadersFrame) PseudoFields() []hpack.HeaderField { + for i, hf := range mh.Fields { + if !hf.IsPseudo() { + return mh.Fields[:i] + } + } + return mh.Fields + } func (mh *MetaHeadersFrame) checkPseudos() error { + var isRequest, isResponse bool + pf := mh.PseudoFields() + for i, hf := range pf { + switch hf.Name { + case ":method", ":path", ":scheme", ":authority": + isRequest = true + case ":status": + isResponse = true + default: + return pseudoHeaderError(hf.Name) + } + // Check for duplicates. + // This would be a bad algorithm, but N is 4. + // And this doesn't allocate. + for _, hf2 := range pf[:i] { + if hf.Name == hf2.Name { + return duplicatePseudoHeaderError(hf.Name) + } + } + } + if isRequest && isResponse { + return errMixPseudoHeaderTypes + } + return nil + } func (fr *Framer) maxHeaderStringLen() int { + v := int(fr.maxHeaderListSize()) + if v < 0 { + // If maxHeaderListSize overflows an int, use no limit (0). + return 0 + } + return v + } // readMetaFrame returns 0 or more CONTINUATION frames from fr and + // merge them into the provided hf and returns a MetaHeadersFrame + // with the decoded hpack values. + func (fr *Framer) readMetaFrame(hf *HeadersFrame) (Frame, error) { + if fr.AllowIllegalReads { + return nil, errors.New("illegal use of AllowIllegalReads with ReadMetaHeaders") + } + mh := &MetaHeadersFrame{ + HeadersFrame: hf, } + var remainSize = fr.maxHeaderListSize() + var sawRegular bool var invalid error // pseudo header field errors + hdec := fr.ReadMetaHeaders + hdec.SetEmitEnabled(true) + hdec.SetMaxStringLength(fr.maxHeaderStringLen()) + hdec.SetEmitFunc(func(hf hpack.HeaderField) { + if VerboseLogs && fr.logReads { + fr.debugReadLoggerf("http2: decoded hpack field %+v", hf) + } + if !httpguts.ValidHeaderFieldValue(hf.Value) { + // Don't include the value in the error, because it may be sensitive. + invalid = headerFieldValueError(hf.Name) + } + isPseudo := strings.HasPrefix(hf.Name, ":") + if isPseudo { + if sawRegular { + invalid = errPseudoAfterRegular + } + } else { + sawRegular = true + if !validWireHeaderFieldName(hf.Name) { + invalid = headerFieldNameError(hf.Name) + } + } if invalid != nil { + hdec.SetEmitEnabled(false) + return + } size := hf.Size() + if size > remainSize { + hdec.SetEmitEnabled(false) + mh.Truncated = true + remainSize = 0 + return + } + remainSize -= size mh.Fields = append(mh.Fields, hf) + }) + // Lose reference to MetaHeadersFrame: + defer hdec.SetEmitFunc(func(hf hpack.HeaderField) {}) var hc headersOrContinuation = hf + for { + frag := hc.HeaderBlockFragment() // Avoid parsing large amounts of headers that we will then discard. + // If the sender exceeds the max header list size by too much, + // skip parsing the fragment and close the connection. + // + // "Too much" is either any CONTINUATION frame after we've already + // exceeded the max header list size (in which case remainSize is 0), + // or a frame whose encoded size is more than twice the remaining + // header list bytes we're willing to accept. + if int64(len(frag)) > int64(2*remainSize) { + if VerboseLogs { + log.Printf("http2: header list too large") + } + // It would be nice to send a RST_STREAM before sending the GOAWAY, + // but the structure of the server's frame writer makes this difficult. + return mh, ConnectionError(ErrCodeProtocol) + } // Also close the connection after any CONTINUATION frame following an + // invalid header, since we stop tracking the size of the headers after + // an invalid one. + if invalid != nil { + if VerboseLogs { + log.Printf("http2: invalid header: %v", invalid) + } + // It would be nice to send a RST_STREAM before sending the GOAWAY, + // but the structure of the server's frame writer makes this difficult. + return mh, ConnectionError(ErrCodeProtocol) + } if _, err := hdec.Write(frag); err != nil { + return mh, ConnectionError(ErrCodeCompression) + } if hc.HeadersEnded() { + break + } + if f, err := fr.ReadFrame(); err != nil { + return nil, err + } else { + hc = f.(*ContinuationFrame) // guaranteed by checkFrameOrder + } + } mh.HeadersFrame.headerFragBuf = nil + mh.HeadersFrame.invalidate() if err := hdec.Close(); err != nil { + return mh, ConnectionError(ErrCodeCompression) + } + if invalid != nil { + fr.errDetail = invalid + if VerboseLogs { + log.Printf("http2: invalid header: %v", invalid) + } + return nil, StreamError{mh.StreamID, ErrCodeProtocol, invalid} + } + if err := mh.checkPseudos(); err != nil { + fr.errDetail = err + if VerboseLogs { + log.Printf("http2: invalid pseudo headers: %v", err) + } + return nil, StreamError{mh.StreamID, ErrCodeProtocol, err} + } + return mh, nil + } func summarizeFrame(f Frame) string { + var buf bytes.Buffer + f.Header().writeDebug(&buf) + switch f := f.(type) { + case *SettingsFrame: + n := 0 + f.ForeachSetting(func(s Setting) error { + n++ + if n == 1 { + buf.WriteString(", settings:") + } + fmt.Fprintf(&buf, " %v=%v,", s.ID, s.Val) + return nil + }) + if n > 0 { + buf.Truncate(buf.Len() - 1) // remove trailing comma + } + case *DataFrame: + data := f.Data() + const max = 256 + if len(data) > max { + data = data[:max] + } + fmt.Fprintf(&buf, " data=%q", data) + if len(f.Data()) > max { + fmt.Fprintf(&buf, " (%d bytes omitted)", len(f.Data())-max) + } + case *WindowUpdateFrame: + if f.StreamID == 0 { + buf.WriteString(" (conn)") + } + fmt.Fprintf(&buf, " incr=%v", f.Increment) + case *PingFrame: + fmt.Fprintf(&buf, " ping=%q", f.Data[:]) + case *GoAwayFrame: + fmt.Fprintf(&buf, " LastStreamID=%v ErrCode=%v Debug=%q", + f.LastStreamID, f.ErrCode, f.debugData) + case *RSTStreamFrame: + fmt.Fprintf(&buf, " ErrCode=%v", f.ErrCode) + } + return buf.String() + } diff --git a/vendor/golang.org/x/net/http2/gotrack.go b/vendor/golang.org/x/net/http2/gotrack.go index 9933c9f..f050ca0 100644 --- a/vendor/golang.org/x/net/http2/gotrack.go +++ b/vendor/golang.org/x/net/http2/gotrack.go @@ -1,8 +1,11 @@ // Copyright 2014 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Defensive debug-only utility to track that functions run on the + // goroutine that they're supposed to. package http2 @@ -22,149 +25,258 @@ var DebugGoroutines = os.Getenv("DEBUG_HTTP2_GOROUTINES") == "1" type goroutineLock uint64 func newGoroutineLock() goroutineLock { + if !DebugGoroutines { + return 0 + } + return goroutineLock(curGoroutineID()) + } func (g goroutineLock) check() { + if !DebugGoroutines { + return + } + if curGoroutineID() != uint64(g) { + panic("running on the wrong goroutine") + } + } func (g goroutineLock) checkNotOn() { + if !DebugGoroutines { + return + } + if curGoroutineID() == uint64(g) { + panic("running on the wrong goroutine") + } + } var goroutineSpace = []byte("goroutine ") func curGoroutineID() uint64 { + bp := littleBuf.Get().(*[]byte) + defer littleBuf.Put(bp) + b := *bp + b = b[:runtime.Stack(b, false)] + // Parse the 4707 out of "goroutine 4707 [" + b = bytes.TrimPrefix(b, goroutineSpace) + i := bytes.IndexByte(b, ' ') + if i < 0 { + panic(fmt.Sprintf("No space found in %q", b)) + } + b = b[:i] + n, err := parseUintBytes(b, 10, 64) + if err != nil { + panic(fmt.Sprintf("Failed to parse goroutine ID out of %q: %v", b, err)) + } + return n + } var littleBuf = sync.Pool{ + New: func() interface{} { + buf := make([]byte, 64) + return &buf + }, } // parseUintBytes is like strconv.ParseUint, but using a []byte. + func parseUintBytes(s []byte, base int, bitSize int) (n uint64, err error) { + var cutoff, maxVal uint64 if bitSize == 0 { + bitSize = int(strconv.IntSize) + } s0 := s + switch { + case len(s) < 1: + err = strconv.ErrSyntax + goto Error case 2 <= base && base <= 36: + // valid base; nothing to do case base == 0: + // Look for octal, hex prefix. + switch { + case s[0] == '0' && len(s) > 1 && (s[1] == 'x' || s[1] == 'X'): + base = 16 + s = s[2:] + if len(s) < 1 { + err = strconv.ErrSyntax + goto Error + } + case s[0] == '0': + base = 8 + default: + base = 10 + } default: + err = errors.New("invalid base " + strconv.Itoa(base)) + goto Error + } n = 0 + cutoff = cutoff64(base) + maxVal = 1<= base { + n = 0 + err = strconv.ErrSyntax + goto Error + } if n >= cutoff { + // n*base overflows + n = 1<<64 - 1 + err = strconv.ErrRange + goto Error + } + n *= uint64(base) n1 := n + uint64(v) + if n1 < n || n1 > maxVal { + // n+v overflows + n = 1<<64 - 1 + err = strconv.ErrRange + goto Error + } + n = n1 + } return n, nil Error: + return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err} + } // Return the first number n such that n*base >= 1<<64. + func cutoff64(base int) uint64 { + if base < 2 { + return 0 + } + return (1<<64-1)/uint64(base) + 1 + } diff --git a/vendor/golang.org/x/net/http2/h2c/h2c.go b/vendor/golang.org/x/net/http2/h2c/h2c.go index 2d6bf86..388f332 100644 --- a/vendor/golang.org/x/net/http2/h2c/h2c.go +++ b/vendor/golang.org/x/net/http2/h2c/h2c.go @@ -1,11 +1,17 @@ // Copyright 2018 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Package h2c implements the unencrypted "h2c" form of HTTP/2. + // + // The h2c protocol is the non-TLS version of HTTP/2 which is not available from + // net/http or golang.org/x/net/http2. + package h2c import ( @@ -31,210 +37,374 @@ var ( ) func init() { + e := os.Getenv("GODEBUG") + if strings.Contains(e, "http2debug=1") || strings.Contains(e, "http2debug=2") { + http2VerboseLogs = true + } + } // h2cHandler is a Handler which implements h2c by hijacking the HTTP/1 traffic + // that should be h2c traffic. There are two ways to begin a h2c connection + // (RFC 7540 Section 3.2 and 3.4): (1) Starting with Prior Knowledge - this + // works by starting an h2c connection with a string of bytes that is valid + // HTTP/1, but unlikely to occur in practice and (2) Upgrading from HTTP/1 to + // h2c - this works by using the HTTP/1 Upgrade header to request an upgrade to + // h2c. When either of those situations occur we hijack the HTTP/1 connection, + // convert it to an HTTP/2 connection and pass the net.Conn to http2.ServeConn. + type h2cHandler struct { Handler http.Handler - s *http2.Server + + s *http2.Server } // NewHandler returns an http.Handler that wraps h, intercepting any h2c + // traffic. If a request is an h2c connection, it's hijacked and redirected to + // s.ServeConn. Otherwise the returned Handler just forwards requests to h. This + // works because h2c is designed to be parseable as valid HTTP/1, but ignored by + // any HTTP server that does not handle h2c. Therefore we leverage the HTTP/1 + // compatible parts of the Go http library to parse and recognize h2c requests. + // Once a request is recognized as h2c, we hijack the connection and convert it + // to an HTTP/2 connection which is understandable to s.ServeConn. (s.ServeConn + // understands HTTP/2 except for the h2c part of it.) + // + // The first request on an h2c connection is read entirely into memory before + // the Handler is called. To limit the memory consumed by this request, wrap + // the result of NewHandler in an http.MaxBytesHandler. + func NewHandler(h http.Handler, s *http2.Server) http.Handler { + return &h2cHandler{ + Handler: h, - s: s, + + s: s, } + } // extractServer extracts existing http.Server instance from http.Request or create an empty http.Server + func extractServer(r *http.Request) *http.Server { + server, ok := r.Context().Value(http.ServerContextKey).(*http.Server) + if ok { + return server + } + return new(http.Server) + } // ServeHTTP implement the h2c support that is enabled by h2c.GetH2CHandler. + func (s h2cHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Handle h2c with prior knowledge (RFC 7540 Section 3.4) + if r.Method == "PRI" && len(r.Header) == 0 && r.URL.Path == "*" && r.Proto == "HTTP/2.0" { + if http2VerboseLogs { + log.Print("h2c: attempting h2c with prior knowledge.") + } + conn, err := initH2CWithPriorKnowledge(w) + if err != nil { + if http2VerboseLogs { + log.Printf("h2c: error h2c with prior knowledge: %v", err) + } + return + } + defer conn.Close() + s.s.ServeConn(conn, &http2.ServeConnOpts{ - Context: r.Context(), - BaseConfig: extractServer(r), - Handler: s.Handler, + + Context: r.Context(), + + BaseConfig: extractServer(r), + + Handler: s.Handler, + SawClientPreface: true, }) + return + } + // Handle Upgrade to h2c (RFC 7540 Section 3.2) + if isH2CUpgrade(r.Header) { + conn, settings, err := h2cUpgrade(w, r) + if err != nil { + if http2VerboseLogs { + log.Printf("h2c: error h2c upgrade: %v", err) + } + w.WriteHeader(http.StatusInternalServerError) + return + } + defer conn.Close() + s.s.ServeConn(conn, &http2.ServeConnOpts{ - Context: r.Context(), - BaseConfig: extractServer(r), - Handler: s.Handler, + + Context: r.Context(), + + BaseConfig: extractServer(r), + + Handler: s.Handler, + UpgradeRequest: r, - Settings: settings, + + Settings: settings, }) + return + } + s.Handler.ServeHTTP(w, r) + return + } // initH2CWithPriorKnowledge implements creating a h2c connection with prior + // knowledge (Section 3.4) and creates a net.Conn suitable for http2.ServeConn. + // All we have to do is look for the client preface that is suppose to be part + // of the body, and reforward the client preface on the net.Conn this function + // creates. + func initH2CWithPriorKnowledge(w http.ResponseWriter) (net.Conn, error) { + hijacker, ok := w.(http.Hijacker) + if !ok { + return nil, errors.New("h2c: connection does not support Hijack") + } + conn, rw, err := hijacker.Hijack() + if err != nil { + return nil, err + } const expectedBody = "SM\r\n\r\n" buf := make([]byte, len(expectedBody)) + n, err := io.ReadFull(rw, buf) + if err != nil { + return nil, fmt.Errorf("h2c: error reading client preface: %s", err) + } if string(buf[:n]) == expectedBody { + return newBufConn(conn, rw), nil + } conn.Close() + return nil, errors.New("h2c: invalid client preface") + } // h2cUpgrade establishes a h2c connection using the HTTP/1 upgrade (Section 3.2). + func h2cUpgrade(w http.ResponseWriter, r *http.Request) (_ net.Conn, settings []byte, err error) { + settings, err = getH2Settings(r.Header) + if err != nil { + return nil, nil, err + } + hijacker, ok := w.(http.Hijacker) + if !ok { + return nil, nil, errors.New("h2c: connection does not support Hijack") + } body, err := io.ReadAll(r.Body) + if err != nil { + return nil, nil, err + } + r.Body = io.NopCloser(bytes.NewBuffer(body)) conn, rw, err := hijacker.Hijack() + if err != nil { + return nil, nil, err + } rw.Write([]byte("HTTP/1.1 101 Switching Protocols\r\n" + + "Connection: Upgrade\r\n" + + "Upgrade: h2c\r\n\r\n")) + return newBufConn(conn, rw), settings, nil + } // isH2CUpgrade returns true if the header properly request an upgrade to h2c + // as specified by Section 3.2. + func isH2CUpgrade(h http.Header) bool { + return httpguts.HeaderValuesContainsToken(h[textproto.CanonicalMIMEHeaderKey("Upgrade")], "h2c") && + httpguts.HeaderValuesContainsToken(h[textproto.CanonicalMIMEHeaderKey("Connection")], "HTTP2-Settings") + } // getH2Settings returns the settings in the HTTP2-Settings header. + func getH2Settings(h http.Header) ([]byte, error) { + vals, ok := h[textproto.CanonicalMIMEHeaderKey("HTTP2-Settings")] + if !ok { + return nil, errors.New("missing HTTP2-Settings header") + } + if len(vals) != 1 { + return nil, fmt.Errorf("expected 1 HTTP2-Settings. Got: %v", vals) + } + settings, err := base64.RawURLEncoding.DecodeString(vals[0]) + if err != nil { + return nil, err + } + return settings, nil + } func newBufConn(conn net.Conn, rw *bufio.ReadWriter) net.Conn { + rw.Flush() + if rw.Reader.Buffered() == 0 { + // If there's no buffered data to be read, + // we can just discard the bufio.ReadWriter. + return conn + } + return &bufConn{conn, rw.Reader} + } // bufConn wraps a net.Conn, but reads drain the bufio.Reader first. + type bufConn struct { net.Conn + *bufio.Reader } func (c *bufConn) Read(p []byte) (int, error) { + if c.Reader == nil { + return c.Conn.Read(p) + } + n := c.Reader.Buffered() + if n == 0 { + c.Reader = nil + return c.Conn.Read(p) + } + if n < len(p) { + p = p[:n] + } + return c.Reader.Read(p) + } diff --git a/vendor/golang.org/x/net/http2/headermap.go b/vendor/golang.org/x/net/http2/headermap.go index 149b3dd..cb80434 100644 --- a/vendor/golang.org/x/net/http2/headermap.go +++ b/vendor/golang.org/x/net/http2/headermap.go @@ -1,5 +1,7 @@ // Copyright 2014 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package http2 @@ -10,96 +12,179 @@ import ( ) var ( - commonBuildOnce sync.Once + commonBuildOnce sync.Once + commonLowerHeader map[string]string // Go-Canonical-Case -> lower-case + commonCanonHeader map[string]string // lower-case -> Go-Canonical-Case + ) func buildCommonHeaderMapsOnce() { + commonBuildOnce.Do(buildCommonHeaderMaps) + } func buildCommonHeaderMaps() { + common := []string{ + "accept", + "accept-charset", + "accept-encoding", + "accept-language", + "accept-ranges", + "age", + "access-control-allow-credentials", + "access-control-allow-headers", + "access-control-allow-methods", + "access-control-allow-origin", + "access-control-expose-headers", + "access-control-max-age", + "access-control-request-headers", + "access-control-request-method", + "allow", + "authorization", + "cache-control", + "content-disposition", + "content-encoding", + "content-language", + "content-length", + "content-location", + "content-range", + "content-type", + "cookie", + "date", + "etag", + "expect", + "expires", + "from", + "host", + "if-match", + "if-modified-since", + "if-none-match", + "if-unmodified-since", + "last-modified", + "link", + "location", + "max-forwards", + "origin", + "proxy-authenticate", + "proxy-authorization", + "range", + "referer", + "refresh", + "retry-after", + "server", + "set-cookie", + "strict-transport-security", + "trailer", + "transfer-encoding", + "user-agent", + "vary", + "via", + "www-authenticate", + "x-forwarded-for", + "x-forwarded-proto", } + commonLowerHeader = make(map[string]string, len(common)) + commonCanonHeader = make(map[string]string, len(common)) + for _, v := range common { + chk := http.CanonicalHeaderKey(v) + commonLowerHeader[chk] = v + commonCanonHeader[v] = chk + } + } func lowerHeader(v string) (lower string, ascii bool) { + buildCommonHeaderMapsOnce() + if s, ok := commonLowerHeader[v]; ok { + return s, true + } + return asciiToLower(v) + } func canonicalHeader(v string) string { + buildCommonHeaderMapsOnce() + if s, ok := commonCanonHeader[v]; ok { + return s + } + return http.CanonicalHeaderKey(v) + } diff --git a/vendor/golang.org/x/net/http2/hpack/hpack.go b/vendor/golang.org/x/net/http2/hpack/hpack.go index 7a1d976..e64f1ab 100644 --- a/vendor/golang.org/x/net/http2/hpack/hpack.go +++ b/vendor/golang.org/x/net/http2/hpack/hpack.go @@ -1,11 +1,17 @@ // Copyright 2014 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Package hpack implements HPACK, a compression format for + // efficiently representing HTTP header fields in the context of HTTP/2. + // + // See http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-09 + package hpack import ( @@ -15,509 +21,903 @@ import ( ) // A DecodingError is something the spec defines as a decoding error. + type DecodingError struct { Err error } func (de DecodingError) Error() string { + return fmt.Sprintf("decoding error: %v", de.Err) + } // An InvalidIndexError is returned when an encoder references a table + // entry before the static table or after the end of the dynamic table. + type InvalidIndexError int func (e InvalidIndexError) Error() string { + return fmt.Sprintf("invalid indexed representation index %d", int(e)) + } // A HeaderField is a name-value pair. Both the name and value are + // treated as opaque sequences of octets. + type HeaderField struct { Name, Value string // Sensitive means that this header field should never be + // indexed. + Sensitive bool } // IsPseudo reports whether the header field is an http2 pseudo header. + // That is, it reports whether it starts with a colon. + // It is not otherwise guaranteed to be a valid pseudo header field, + // though. + func (hf HeaderField) IsPseudo() bool { + return len(hf.Name) != 0 && hf.Name[0] == ':' + } func (hf HeaderField) String() string { + var suffix string + if hf.Sensitive { + suffix = " (sensitive)" + } + return fmt.Sprintf("header field %q = %q%s", hf.Name, hf.Value, suffix) + } // Size returns the size of an entry per RFC 7541 section 4.1. + func (hf HeaderField) Size() uint32 { + // https://httpwg.org/specs/rfc7541.html#rfc.section.4.1 + // "The size of the dynamic table is the sum of the size of + // its entries. The size of an entry is the sum of its name's + // length in octets (as defined in Section 5.2), its value's + // length in octets (see Section 5.2), plus 32. The size of + // an entry is calculated using the length of the name and + // value without any Huffman encoding applied." // This can overflow if somebody makes a large HeaderField + // Name and/or Value by hand, but we don't care, because that + // won't happen on the wire because the encoding doesn't allow + // it. + return uint32(len(hf.Name) + len(hf.Value) + 32) + } // A Decoder is the decoding context for incremental processing of + // header blocks. + type Decoder struct { dynTab dynamicTable - emit func(f HeaderField) + + emit func(f HeaderField) emitEnabled bool // whether calls to emit are enabled - maxStrLen int // 0 means unlimited + + maxStrLen int // 0 means unlimited // buf is the unparsed buffer. It's only written to + // saveBuf if it was truncated in the middle of a header + // block. Because it's usually not owned, we can only + // process it under Write. + buf []byte // not owned; only valid during Write // saveBuf is previous data passed to Write which we weren't able + // to fully parse before. Unlike buf, we own this data. + saveBuf bytes.Buffer firstField bool // processing the first field of the header block + } // NewDecoder returns a new decoder with the provided maximum dynamic + // table size. The emitFunc will be called for each valid field + // parsed, in the same goroutine as calls to Write, before Write returns. + func NewDecoder(maxDynamicTableSize uint32, emitFunc func(f HeaderField)) *Decoder { + d := &Decoder{ - emit: emitFunc, + + emit: emitFunc, + emitEnabled: true, - firstField: true, + + firstField: true, } + d.dynTab.table.init() + d.dynTab.allowedMaxSize = maxDynamicTableSize + d.dynTab.setMaxSize(maxDynamicTableSize) + return d + } // ErrStringLength is returned by Decoder.Write when the max string length + // (as configured by Decoder.SetMaxStringLength) would be violated. + var ErrStringLength = errors.New("hpack: string too long") // SetMaxStringLength sets the maximum size of a HeaderField name or + // value string. If a string exceeds this length (even after any + // decompression), Write will return ErrStringLength. + // A value of 0 means unlimited and is the default from NewDecoder. + func (d *Decoder) SetMaxStringLength(n int) { + d.maxStrLen = n + } // SetEmitFunc changes the callback used when new header fields + // are decoded. + // It must be non-nil. It does not affect EmitEnabled. + func (d *Decoder) SetEmitFunc(emitFunc func(f HeaderField)) { + d.emit = emitFunc + } // SetEmitEnabled controls whether the emitFunc provided to NewDecoder + // should be called. The default is true. + // + // This facility exists to let servers enforce MAX_HEADER_LIST_SIZE + // while still decoding and keeping in-sync with decoder state, but + // without doing unnecessary decompression or generating unnecessary + // garbage for header fields past the limit. + func (d *Decoder) SetEmitEnabled(v bool) { d.emitEnabled = v } // EmitEnabled reports whether calls to the emitFunc provided to NewDecoder + // are currently enabled. The default is true. + func (d *Decoder) EmitEnabled() bool { return d.emitEnabled } // TODO: add method *Decoder.Reset(maxSize, emitFunc) to let callers re-use Decoders and their + // underlying buffers for garbage reasons. func (d *Decoder) SetMaxDynamicTableSize(v uint32) { + d.dynTab.setMaxSize(v) + } // SetAllowedMaxDynamicTableSize sets the upper bound that the encoded + // stream (via dynamic table size updates) may set the maximum size + // to. + func (d *Decoder) SetAllowedMaxDynamicTableSize(v uint32) { + d.dynTab.allowedMaxSize = v + } type dynamicTable struct { + // https://httpwg.org/specs/rfc7541.html#rfc.section.2.3.2 - table headerFieldTable - size uint32 // in bytes - maxSize uint32 // current maxSize + + table headerFieldTable + + size uint32 // in bytes + + maxSize uint32 // current maxSize + allowedMaxSize uint32 // maxSize may go up to this, inclusive + } func (dt *dynamicTable) setMaxSize(v uint32) { + dt.maxSize = v + dt.evict() + } func (dt *dynamicTable) add(f HeaderField) { + dt.table.addEntry(f) + dt.size += f.Size() + dt.evict() + } // If we're too big, evict old stuff. + func (dt *dynamicTable) evict() { + var n int + for dt.size > dt.maxSize && n < dt.table.len() { + dt.size -= dt.table.ents[n].Size() + n++ + } + dt.table.evictOldest(n) + } func (d *Decoder) maxTableIndex() int { + // This should never overflow. RFC 7540 Section 6.5.2 limits the size of + // the dynamic table to 2^32 bytes, where each entry will occupy more than + // one byte. Further, the staticTable has a fixed, small length. + return d.dynTab.table.len() + staticTable.len() + } func (d *Decoder) at(i uint64) (hf HeaderField, ok bool) { + // See Section 2.3.3. + if i == 0 { + return + } + if i <= uint64(staticTable.len()) { + return staticTable.ents[i-1], true + } + if i > uint64(d.maxTableIndex()) { + return + } + // In the dynamic table, newer entries have lower indices. + // However, dt.ents[0] is the oldest entry. Hence, dt.ents is + // the reversed dynamic table. + dt := d.dynTab.table + return dt.ents[dt.len()-(int(i)-staticTable.len())], true + } // DecodeFull decodes an entire block. + // + // TODO: remove this method and make it incremental later? This is + // easier for debugging now. + func (d *Decoder) DecodeFull(p []byte) ([]HeaderField, error) { + var hf []HeaderField + saveFunc := d.emit + defer func() { d.emit = saveFunc }() + d.emit = func(f HeaderField) { hf = append(hf, f) } + if _, err := d.Write(p); err != nil { + return nil, err + } + if err := d.Close(); err != nil { + return nil, err + } + return hf, nil + } // Close declares that the decoding is complete and resets the Decoder + // to be reused again for a new header block. If there is any remaining + // data in the decoder's buffer, Close returns an error. + func (d *Decoder) Close() error { + if d.saveBuf.Len() > 0 { + d.saveBuf.Reset() + return DecodingError{errors.New("truncated headers")} + } + d.firstField = true + return nil + } func (d *Decoder) Write(p []byte) (n int, err error) { + if len(p) == 0 { + // Prevent state machine CPU attacks (making us redo + // work up to the point of finding out we don't have + // enough data) + return + } + // Only copy the data if we have to. Optimistically assume + // that p will contain a complete header block. + if d.saveBuf.Len() == 0 { + d.buf = p + } else { + d.saveBuf.Write(p) + d.buf = d.saveBuf.Bytes() + d.saveBuf.Reset() + } for len(d.buf) > 0 { + err = d.parseHeaderFieldRepr() + if err == errNeedMore { + // Extra paranoia, making sure saveBuf won't + // get too large. All the varint and string + // reading code earlier should already catch + // overlong things and return ErrStringLength, + // but keep this as a last resort. + const varIntOverhead = 8 // conservative + if d.maxStrLen != 0 && int64(len(d.buf)) > 2*(int64(d.maxStrLen)+varIntOverhead) { + return 0, ErrStringLength + } + d.saveBuf.Write(d.buf) + return len(p), nil + } + d.firstField = false + if err != nil { + break + } + } + return len(p), err + } // errNeedMore is an internal sentinel error value that means the + // buffer is truncated and we need to read more data before we can + // continue parsing. + var errNeedMore = errors.New("need more data") type indexType int const ( indexedTrue indexType = iota + indexedFalse + indexedNever ) -func (v indexType) indexed() bool { return v == indexedTrue } +func (v indexType) indexed() bool { return v == indexedTrue } + func (v indexType) sensitive() bool { return v == indexedNever } // returns errNeedMore if there isn't enough data available. + // any other error is fatal. + // consumes d.buf iff it returns nil. + // precondition: must be called with len(d.buf) > 0 + func (d *Decoder) parseHeaderFieldRepr() error { + b := d.buf[0] + switch { + case b&128 != 0: + // Indexed representation. + // High bit set? + // https://httpwg.org/specs/rfc7541.html#rfc.section.6.1 + return d.parseFieldIndexed() + case b&192 == 64: + // 6.2.1 Literal Header Field with Incremental Indexing + // 0b10xxxxxx: top two bits are 10 + // https://httpwg.org/specs/rfc7541.html#rfc.section.6.2.1 + return d.parseFieldLiteral(6, indexedTrue) + case b&240 == 0: + // 6.2.2 Literal Header Field without Indexing + // 0b0000xxxx: top four bits are 0000 + // https://httpwg.org/specs/rfc7541.html#rfc.section.6.2.2 + return d.parseFieldLiteral(4, indexedFalse) + case b&240 == 16: + // 6.2.3 Literal Header Field never Indexed + // 0b0001xxxx: top four bits are 0001 + // https://httpwg.org/specs/rfc7541.html#rfc.section.6.2.3 + return d.parseFieldLiteral(4, indexedNever) + case b&224 == 32: + // 6.3 Dynamic Table Size Update + // Top three bits are '001'. + // https://httpwg.org/specs/rfc7541.html#rfc.section.6.3 + return d.parseDynamicTableSizeUpdate() + } return DecodingError{errors.New("invalid encoding")} + } // (same invariants and behavior as parseHeaderFieldRepr) + func (d *Decoder) parseFieldIndexed() error { + buf := d.buf + idx, buf, err := readVarInt(7, buf) + if err != nil { + return err + } + hf, ok := d.at(idx) + if !ok { + return DecodingError{InvalidIndexError(idx)} + } + d.buf = buf + return d.callEmit(HeaderField{Name: hf.Name, Value: hf.Value}) + } // (same invariants and behavior as parseHeaderFieldRepr) + func (d *Decoder) parseFieldLiteral(n uint8, it indexType) error { + buf := d.buf + nameIdx, buf, err := readVarInt(n, buf) + if err != nil { + return err + } var hf HeaderField + wantStr := d.emitEnabled || it.indexed() + var undecodedName undecodedString + if nameIdx > 0 { + ihf, ok := d.at(nameIdx) + if !ok { + return DecodingError{InvalidIndexError(nameIdx)} + } + hf.Name = ihf.Name + } else { + undecodedName, buf, err = d.readString(buf) + if err != nil { + return err + } + } + undecodedValue, buf, err := d.readString(buf) + if err != nil { + return err + } + if wantStr { + if nameIdx <= 0 { + hf.Name, err = d.decodeString(undecodedName) + if err != nil { + return err + } + } + hf.Value, err = d.decodeString(undecodedValue) + if err != nil { + return err + } + } + d.buf = buf + if it.indexed() { + d.dynTab.add(hf) + } + hf.Sensitive = it.sensitive() + return d.callEmit(hf) + } func (d *Decoder) callEmit(hf HeaderField) error { + if d.maxStrLen != 0 { + if len(hf.Name) > d.maxStrLen || len(hf.Value) > d.maxStrLen { + return ErrStringLength + } + } + if d.emitEnabled { + d.emit(hf) + } + return nil + } // (same invariants and behavior as parseHeaderFieldRepr) + func (d *Decoder) parseDynamicTableSizeUpdate() error { + // RFC 7541, sec 4.2: This dynamic table size update MUST occur at the + // beginning of the first header block following the change to the dynamic table size. + if !d.firstField && d.dynTab.size > 0 { + return DecodingError{errors.New("dynamic table size update MUST occur at the beginning of a header block")} + } buf := d.buf + size, buf, err := readVarInt(5, buf) + if err != nil { + return err + } + if size > uint64(d.dynTab.allowedMaxSize) { + return DecodingError{errors.New("dynamic table size update too large")} + } + d.dynTab.setMaxSize(uint32(size)) + d.buf = buf + return nil + } var errVarintOverflow = DecodingError{errors.New("varint integer overflow")} // readVarInt reads an unsigned variable length integer off the + // beginning of p. n is the parameter as described in + // https://httpwg.org/specs/rfc7541.html#rfc.section.5.1. + // + // n must always be between 1 and 8. + // + // The returned remain buffer is either a smaller suffix of p, or err != nil. + // The error is errNeedMore if p doesn't contain a complete integer. + func readVarInt(n byte, p []byte) (i uint64, remain []byte, err error) { + if n < 1 || n > 8 { + panic("bad n") + } + if len(p) == 0 { + return 0, p, errNeedMore + } + i = uint64(p[0]) + if n < 8 { + i &= (1 << uint64(n)) - 1 + } + if i < (1< 0 { + b := p[0] + p = p[1:] + i += uint64(b&127) << m + if b&128 == 0 { + return i, p, nil + } + m += 7 + if m >= 63 { // TODO: proper overflow check. making this up. + return 0, origP, errVarintOverflow + } + } + return 0, origP, errNeedMore + } // readString reads an hpack string from p. + // + // It returns a reference to the encoded string data to permit deferring decode costs + // until after the caller verifies all data is present. + func (d *Decoder) readString(p []byte) (u undecodedString, remain []byte, err error) { + if len(p) == 0 { + return u, p, errNeedMore + } + isHuff := p[0]&128 != 0 + strLen, p, err := readVarInt(7, p) + if err != nil { + return u, p, err + } + if d.maxStrLen != 0 && strLen > uint64(d.maxStrLen) { + // Returning an error here means Huffman decoding errors + // for non-indexed strings past the maximum string length + // are ignored, but the server is returning an error anyway + // and because the string is not indexed the error will not + // affect the decoding state. + return u, nil, ErrStringLength + } + if uint64(len(p)) < strLen { + return u, p, errNeedMore + } + u.isHuff = isHuff + u.b = p[:strLen] + return u, p[strLen:], nil + } type undecodedString struct { isHuff bool - b []byte + + b []byte } func (d *Decoder) decodeString(u undecodedString) (string, error) { + if !u.isHuff { + return string(u.b), nil + } + buf := bufPool.Get().(*bytes.Buffer) + buf.Reset() // don't trust others + var s string + err := huffmanDecode(buf, d.maxStrLen, u.b) + if err == nil { + s = buf.String() + } + buf.Reset() // be nice to GC + bufPool.Put(buf) + return s, err + } diff --git a/vendor/golang.org/x/net/http2/hpack/huffman.go b/vendor/golang.org/x/net/http2/hpack/huffman.go index 20d083a..2a1b52e 100644 --- a/vendor/golang.org/x/net/http2/hpack/huffman.go +++ b/vendor/golang.org/x/net/http2/hpack/huffman.go @@ -1,5 +1,7 @@ // Copyright 2014 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package hpack @@ -12,215 +14,384 @@ import ( ) var bufPool = sync.Pool{ + New: func() interface{} { return new(bytes.Buffer) }, } // HuffmanDecode decodes the string in v and writes the expanded + // result to w, returning the number of bytes written to w and the + // Write call's return value. At most one Write call is made. + func HuffmanDecode(w io.Writer, v []byte) (int, error) { + buf := bufPool.Get().(*bytes.Buffer) + buf.Reset() + defer bufPool.Put(buf) + if err := huffmanDecode(buf, 0, v); err != nil { + return 0, err + } + return w.Write(buf.Bytes()) + } // HuffmanDecodeToString decodes the string in v. + func HuffmanDecodeToString(v []byte) (string, error) { + buf := bufPool.Get().(*bytes.Buffer) + buf.Reset() + defer bufPool.Put(buf) + if err := huffmanDecode(buf, 0, v); err != nil { + return "", err + } + return buf.String(), nil + } // ErrInvalidHuffman is returned for errors found decoding + // Huffman-encoded strings. + var ErrInvalidHuffman = errors.New("hpack: invalid Huffman-encoded data") // huffmanDecode decodes v to buf. + // If maxLen is greater than 0, attempts to write more to buf than + // maxLen bytes will return ErrStringLength. + func huffmanDecode(buf *bytes.Buffer, maxLen int, v []byte) error { + rootHuffmanNode := getRootHuffmanNode() + n := rootHuffmanNode + // cur is the bit buffer that has not been fed into n. + // cbits is the number of low order bits in cur that are valid. + // sbits is the number of bits of the symbol prefix being decoded. + cur, cbits, sbits := uint(0), uint8(0), uint8(0) + for _, b := range v { + cur = cur<<8 | uint(b) + cbits += 8 + sbits += 8 + for cbits >= 8 { + idx := byte(cur >> (cbits - 8)) + n = n.children[idx] + if n == nil { + return ErrInvalidHuffman + } + if n.children == nil { + if maxLen != 0 && buf.Len() == maxLen { + return ErrStringLength + } + buf.WriteByte(n.sym) + cbits -= n.codeLen + n = rootHuffmanNode + sbits = cbits + } else { + cbits -= 8 + } + } + } + for cbits > 0 { + n = n.children[byte(cur<<(8-cbits))] + if n == nil { + return ErrInvalidHuffman + } + if n.children != nil || n.codeLen > cbits { + break + } + if maxLen != 0 && buf.Len() == maxLen { + return ErrStringLength + } + buf.WriteByte(n.sym) + cbits -= n.codeLen + n = rootHuffmanNode + sbits = cbits + } + if sbits > 7 { + // Either there was an incomplete symbol, or overlong padding. + // Both are decoding errors per RFC 7541 section 5.2. + return ErrInvalidHuffman + } + if mask := uint(1< 8 { + codeLen -= 8 + i := uint8(code >> codeLen) + if cur.children[i] == nil { + cur.children[i] = newInternalNode() + } + cur = cur.children[i] + } + shift := 8 - codeLen + start, end := int(uint8(code<= 32 { - n %= 32 // Normally would be -= 32 but %= 32 informs compiler 0 <= n <= 31 for upcoming shift + + n %= 32 // Normally would be -= 32 but %= 32 informs compiler 0 <= n <= 31 for upcoming shift + y := uint32(x >> n) // Compiler doesn't combine memory writes if y isn't uint32 + dst = append(dst, byte(y>>24), byte(y>>16), byte(y>>8), byte(y)) + } + } + // Add padding bits if necessary + if over := n % 8; over > 0 { + const ( - eosCode = 0x3fffffff - eosNBits = 30 + eosCode = 0x3fffffff + + eosNBits = 30 + eosPadByte = eosCode >> (eosNBits - 8) ) + pad := 8 - over + x = (x << pad) | (eosPadByte >> over) + n += pad // 8 now divides into n exactly + } + // n in (0, 8, 16, 24, 32) + switch n / 8 { + case 0: + return dst + case 1: + return append(dst, byte(x)) + case 2: + y := uint16(x) + return append(dst, byte(y>>8), byte(y)) + case 3: + y := uint16(x >> 8) + return append(dst, byte(y>>8), byte(y), byte(x)) + } + // case 4: + y := uint32(x) + return append(dst, byte(y>>24), byte(y>>16), byte(y>>8), byte(y)) + } // HuffmanEncodeLength returns the number of bytes required to encode + // s in Huffman codes. The result is round up to byte boundary. + func HuffmanEncodeLength(s string) uint64 { + n := uint64(0) + for i := 0; i < len(s); i++ { + n += uint64(huffmanCodeLen[s[i]]) + } + return (n + 7) / 8 + } diff --git a/vendor/golang.org/x/net/http2/http2.go b/vendor/golang.org/x/net/http2/http2.go index 6f2df28..5ce9bc1 100644 --- a/vendor/golang.org/x/net/http2/http2.go +++ b/vendor/golang.org/x/net/http2/http2.go @@ -1,18 +1,31 @@ // Copyright 2014 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Package http2 implements the HTTP/2 protocol. + // + // This package is low-level and intended to be used directly by very + // few people. Most users will use it indirectly through the automatic + // use by the net/http package (from Go 1.6 and later). + // For use in earlier Go versions see ConfigureServer. (Transport support + // requires Go 1.6 or later) + // + // See https://http2.github.io/ for more information on HTTP/2. + // + // See https://http2.golang.org/ for a test server running this code. + package http2 // import "golang.org/x/net/http2" import ( @@ -31,38 +44,59 @@ import ( ) var ( - VerboseLogs bool + VerboseLogs bool + logFrameWrites bool - logFrameReads bool - inTests bool + + logFrameReads bool + + inTests bool ) func init() { + e := os.Getenv("GODEBUG") + if strings.Contains(e, "http2debug=1") { + VerboseLogs = true + } + if strings.Contains(e, "http2debug=2") { + VerboseLogs = true + logFrameWrites = true + logFrameReads = true + } + } const ( + // ClientPreface is the string that must be sent by new + // connections from clients. + ClientPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" // SETTINGS_MAX_FRAME_SIZE default + // https://httpwg.org/specs/rfc7540.html#rfc.section.6.5.2 + initialMaxFrameSize = 16384 // NextProtoTLS is the NPN/ALPN protocol negotiated during + // HTTP/2's TLS setup. + NextProtoTLS = "h2" // https://httpwg.org/specs/rfc7540.html#SettingValues + initialHeaderTableSize = 4096 initialWindowSize = 65535 // 6.9.2 Initial Flow Control Window Size @@ -77,250 +111,422 @@ var ( type streamState int // HTTP/2 stream states. + // + // See http://tools.ietf.org/html/rfc7540#section-5.1. + // + // For simplicity, the server code merges "reserved (local)" into + // "half-closed (remote)". This is one less state transition to track. + // The only downside is that we send PUSH_PROMISEs slightly less + // liberally than allowable. More discussion here: + // https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html + // + // "reserved (remote)" is omitted since the client code does not + // support server push. + const ( stateIdle streamState = iota + stateOpen + stateHalfClosedLocal + stateHalfClosedRemote + stateClosed ) var stateName = [...]string{ - stateIdle: "Idle", - stateOpen: "Open", - stateHalfClosedLocal: "HalfClosedLocal", + + stateIdle: "Idle", + + stateOpen: "Open", + + stateHalfClosedLocal: "HalfClosedLocal", + stateHalfClosedRemote: "HalfClosedRemote", - stateClosed: "Closed", + + stateClosed: "Closed", } func (st streamState) String() string { + return stateName[st] + } // Setting is a setting parameter: which setting it is, and its value. + type Setting struct { + // ID is which setting is being set. + // See https://httpwg.org/specs/rfc7540.html#SettingFormat + ID SettingID // Val is the value. + Val uint32 } func (s Setting) String() string { + return fmt.Sprintf("[%v = %d]", s.ID, s.Val) + } // Valid reports whether the setting is valid. + func (s Setting) Valid() error { + // Limits and error codes from 6.5.2 Defined SETTINGS Parameters + switch s.ID { + case SettingEnablePush: + if s.Val != 1 && s.Val != 0 { + return ConnectionError(ErrCodeProtocol) + } + case SettingInitialWindowSize: + if s.Val > 1<<31-1 { + return ConnectionError(ErrCodeFlowControl) + } + case SettingMaxFrameSize: + if s.Val < 16384 || s.Val > 1<<24-1 { + return ConnectionError(ErrCodeProtocol) + } + } + return nil + } // A SettingID is an HTTP/2 setting as defined in + // https://httpwg.org/specs/rfc7540.html#iana-settings + type SettingID uint16 const ( - SettingHeaderTableSize SettingID = 0x1 - SettingEnablePush SettingID = 0x2 + SettingHeaderTableSize SettingID = 0x1 + + SettingEnablePush SettingID = 0x2 + SettingMaxConcurrentStreams SettingID = 0x3 - SettingInitialWindowSize SettingID = 0x4 - SettingMaxFrameSize SettingID = 0x5 - SettingMaxHeaderListSize SettingID = 0x6 + + SettingInitialWindowSize SettingID = 0x4 + + SettingMaxFrameSize SettingID = 0x5 + + SettingMaxHeaderListSize SettingID = 0x6 ) var settingName = map[SettingID]string{ - SettingHeaderTableSize: "HEADER_TABLE_SIZE", - SettingEnablePush: "ENABLE_PUSH", + + SettingHeaderTableSize: "HEADER_TABLE_SIZE", + + SettingEnablePush: "ENABLE_PUSH", + SettingMaxConcurrentStreams: "MAX_CONCURRENT_STREAMS", - SettingInitialWindowSize: "INITIAL_WINDOW_SIZE", - SettingMaxFrameSize: "MAX_FRAME_SIZE", - SettingMaxHeaderListSize: "MAX_HEADER_LIST_SIZE", + + SettingInitialWindowSize: "INITIAL_WINDOW_SIZE", + + SettingMaxFrameSize: "MAX_FRAME_SIZE", + + SettingMaxHeaderListSize: "MAX_HEADER_LIST_SIZE", } func (s SettingID) String() string { + if v, ok := settingName[s]; ok { + return v + } + return fmt.Sprintf("UNKNOWN_SETTING_%d", uint16(s)) + } // validWireHeaderFieldName reports whether v is a valid header field + // name (key). See httpguts.ValidHeaderName for the base rules. + // + // Further, http2 says: + // + // "Just as in HTTP/1.x, header field names are strings of ASCII + // characters that are compared in a case-insensitive + // fashion. However, header field names MUST be converted to + // lowercase prior to their encoding in HTTP/2. " + func validWireHeaderFieldName(v string) bool { + if len(v) == 0 { + return false + } + for _, r := range v { + if !httpguts.IsTokenRune(r) { + return false + } + if 'A' <= r && r <= 'Z' { + return false + } + } + return true + } func httpCodeString(code int) string { + switch code { + case 200: + return "200" + case 404: + return "404" + } + return strconv.Itoa(code) + } // from pkg io + type stringWriter interface { WriteString(s string) (n int, err error) } // A gate lets two goroutines coordinate their activities. + type gate chan struct{} func (g gate) Done() { g <- struct{}{} } + func (g gate) Wait() { <-g } // A closeWaiter is like a sync.WaitGroup but only goes 1 to 0 (open to closed). + type closeWaiter chan struct{} // Init makes a closeWaiter usable. + // It exists because so a closeWaiter value can be placed inside a + // larger struct and have the Mutex and Cond's memory in the same + // allocation. + func (cw *closeWaiter) Init() { + *cw = make(chan struct{}) + } // Close marks the closeWaiter as closed and unblocks any waiters. + func (cw closeWaiter) Close() { + close(cw) + } // Wait waits for the closeWaiter to become closed. + func (cw closeWaiter) Wait() { + <-cw + } // bufferedWriter is a buffered writer that writes to w. + // Its buffered writer is lazily allocated as needed, to minimize + // idle memory usage with many connections. + type bufferedWriter struct { - _ incomparable - w io.Writer // immutable + _ incomparable + + w io.Writer // immutable + bw *bufio.Writer // non-nil when data is buffered + } func newBufferedWriter(w io.Writer) *bufferedWriter { + return &bufferedWriter{w: w} + } // bufWriterPoolBufferSize is the size of bufio.Writer's + // buffers created using bufWriterPool. + // + // TODO: pick a less arbitrary value? this is a bit under + // (3 x typical 1500 byte MTU) at least. Other than that, + // not much thought went into it. + const bufWriterPoolBufferSize = 4 << 10 var bufWriterPool = sync.Pool{ + New: func() interface{} { + return bufio.NewWriterSize(nil, bufWriterPoolBufferSize) + }, } func (w *bufferedWriter) Available() int { + if w.bw == nil { + return bufWriterPoolBufferSize + } + return w.bw.Available() + } func (w *bufferedWriter) Write(p []byte) (n int, err error) { + if w.bw == nil { + bw := bufWriterPool.Get().(*bufio.Writer) + bw.Reset(w.w) + w.bw = bw + } + return w.bw.Write(p) + } func (w *bufferedWriter) Flush() error { + bw := w.bw + if bw == nil { + return nil + } + err := bw.Flush() + bw.Reset(nil) + bufWriterPool.Put(bw) + w.bw = nil + return err + } func mustUint31(v int32) uint32 { + if v < 0 || v > 2147483647 { + panic("out of range") + } + return uint32(v) + } // bodyAllowedForStatus reports whether a given response status code + // permits a body. See RFC 7230, section 3.3. + func bodyAllowedForStatus(status int) bool { + switch { + case status >= 100 && status <= 199: + return false + case status == 204: + return false + case status == 304: + return false + } + return true + } type httpError struct { - _ incomparable - msg string + _ incomparable + + msg string + timeout bool } -func (e *httpError) Error() string { return e.msg } -func (e *httpError) Timeout() bool { return e.timeout } +func (e *httpError) Error() string { return e.msg } + +func (e *httpError) Timeout() bool { return e.timeout } + func (e *httpError) Temporary() bool { return true } var errTimeout error = &httpError{msg: "http2: timeout awaiting response headers", timeout: true} @@ -333,53 +539,93 @@ var sorterPool = sync.Pool{New: func() interface{} { return new(sorter) }} type sorter struct { v []string // owned by sorter + } -func (s *sorter) Len() int { return len(s.v) } -func (s *sorter) Swap(i, j int) { s.v[i], s.v[j] = s.v[j], s.v[i] } +func (s *sorter) Len() int { return len(s.v) } + +func (s *sorter) Swap(i, j int) { s.v[i], s.v[j] = s.v[j], s.v[i] } + func (s *sorter) Less(i, j int) bool { return s.v[i] < s.v[j] } // Keys returns the sorted keys of h. + // + // The returned slice is only valid until s used again or returned to + // its pool. + func (s *sorter) Keys(h http.Header) []string { + keys := s.v[:0] + for k := range h { + keys = append(keys, k) + } + s.v = keys + sort.Sort(s) + return keys + } func (s *sorter) SortStrings(ss []string) { + // Our sorter works on s.v, which sorter owns, so + // stash it away while we sort the user's buffer. + save := s.v + s.v = ss + sort.Sort(s) + s.v = save + } // validPseudoPath reports whether v is a valid :path pseudo-header + // value. It must be either: + // + // - a non-empty string starting with '/' + // - the string '*', for OPTIONS requests. + // + // For now this is only used a quick check for deciding when to clean + // up Opaque URLs before sending requests from the Transport. + // See golang.org/issue/16847 + // + // We used to enforce that the path also didn't start with "//", but + // Google's GFE accepts such paths and Chrome sends them, so ignore + // that part of the spec. See golang.org/issue/19103. + func validPseudoPath(v string) bool { + return (len(v) > 0 && v[0] == '/') || v == "*" + } // incomparable is a zero-width, non-comparable type. Adding it to a struct + // makes that struct also non-comparable, and generally doesn't add + // any size (as long as it's first). + type incomparable [0]func() diff --git a/vendor/golang.org/x/net/http2/pipe.go b/vendor/golang.org/x/net/http2/pipe.go index 3b9f06b..30f053d 100644 --- a/vendor/golang.org/x/net/http2/pipe.go +++ b/vendor/golang.org/x/net/http2/pipe.go @@ -1,5 +1,7 @@ // Copyright 2014 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package http2 @@ -11,174 +13,314 @@ import ( ) // pipe is a goroutine-safe io.Reader/io.Writer pair. It's like + // io.Pipe except there are no PipeReader/PipeWriter halves, and the + // underlying buffer is an interface. (io.Pipe is always unbuffered) + type pipe struct { - mu sync.Mutex - c sync.Cond // c.L lazily initialized to &p.mu - b pipeBuffer // nil when done reading - unread int // bytes unread when done - err error // read error once empty. non-nil means closed. - breakErr error // immediate read error (caller doesn't see rest of b) - donec chan struct{} // closed on error - readFn func() // optional code to run in Read before error + mu sync.Mutex + + c sync.Cond // c.L lazily initialized to &p.mu + + b pipeBuffer // nil when done reading + + unread int // bytes unread when done + + err error // read error once empty. non-nil means closed. + + breakErr error // immediate read error (caller doesn't see rest of b) + + donec chan struct{} // closed on error + + readFn func() // optional code to run in Read before error + } type pipeBuffer interface { Len() int + io.Writer + io.Reader } // setBuffer initializes the pipe buffer. + // It has no effect if the pipe is already closed. + func (p *pipe) setBuffer(b pipeBuffer) { + p.mu.Lock() + defer p.mu.Unlock() + if p.err != nil || p.breakErr != nil { + return + } + p.b = b + } func (p *pipe) Len() int { + p.mu.Lock() + defer p.mu.Unlock() + if p.b == nil { + return p.unread + } + return p.b.Len() + } // Read waits until data is available and copies bytes + // from the buffer into p. + func (p *pipe) Read(d []byte) (n int, err error) { + p.mu.Lock() + defer p.mu.Unlock() + if p.c.L == nil { + p.c.L = &p.mu + } + for { + if p.breakErr != nil { + return 0, p.breakErr + } + if p.b != nil && p.b.Len() > 0 { + return p.b.Read(d) + } + if p.err != nil { + if p.readFn != nil { - p.readFn() // e.g. copy trailers + + p.readFn() // e.g. copy trailers + p.readFn = nil // not sticky like p.err + } + p.b = nil + return 0, p.err + } + p.c.Wait() + } + } var ( - errClosedPipeWrite = errors.New("write on closed buffer") + errClosedPipeWrite = errors.New("write on closed buffer") + errUninitializedPipeWrite = errors.New("write on uninitialized buffer") ) // Write copies bytes from p into the buffer and wakes a reader. + // It is an error to write more data than the buffer can hold. + func (p *pipe) Write(d []byte) (n int, err error) { + p.mu.Lock() + defer p.mu.Unlock() + if p.c.L == nil { + p.c.L = &p.mu + } + defer p.c.Signal() + if p.err != nil || p.breakErr != nil { + return 0, errClosedPipeWrite + } + // pipe.setBuffer is never invoked, leaving the buffer uninitialized. + // We shouldn't try to write to an uninitialized pipe, + // but returning an error is better than panicking. + if p.b == nil { + return 0, errUninitializedPipeWrite + } + return p.b.Write(d) + } // CloseWithError causes the next Read (waking up a current blocked + // Read if needed) to return the provided err after all data has been + // read. + // + // The error must be non-nil. + func (p *pipe) CloseWithError(err error) { p.closeWithError(&p.err, err, nil) } // BreakWithError causes the next Read (waking up a current blocked + // Read if needed) to return the provided err immediately, without + // waiting for unread data. + func (p *pipe) BreakWithError(err error) { p.closeWithError(&p.breakErr, err, nil) } // closeWithErrorAndCode is like CloseWithError but also sets some code to run + // in the caller's goroutine before returning the error. + func (p *pipe) closeWithErrorAndCode(err error, fn func()) { p.closeWithError(&p.err, err, fn) } func (p *pipe) closeWithError(dst *error, err error, fn func()) { + if err == nil { + panic("err must be non-nil") + } + p.mu.Lock() + defer p.mu.Unlock() + if p.c.L == nil { + p.c.L = &p.mu + } + defer p.c.Signal() + if *dst != nil { + // Already been done. + return + } + p.readFn = fn + if dst == &p.breakErr { + if p.b != nil { + p.unread += p.b.Len() + } + p.b = nil + } + *dst = err + p.closeDoneLocked() + } // requires p.mu be held. + func (p *pipe) closeDoneLocked() { + if p.donec == nil { + return + } + // Close if unclosed. This isn't racy since we always + // hold p.mu while closing. + select { + case <-p.donec: + default: + close(p.donec) + } + } // Err returns the error (if any) first set by BreakWithError or CloseWithError. + func (p *pipe) Err() error { + p.mu.Lock() + defer p.mu.Unlock() + if p.breakErr != nil { + return p.breakErr + } + return p.err + } // Done returns a channel which is closed if and when this pipe is closed + // with CloseWithError. + func (p *pipe) Done() <-chan struct{} { + p.mu.Lock() + defer p.mu.Unlock() + if p.donec == nil { + p.donec = make(chan struct{}) + if p.err != nil || p.breakErr != nil { + // Already hit an error. + p.closeDoneLocked() + } + } + return p.donec + } diff --git a/vendor/golang.org/x/net/http2/server.go b/vendor/golang.org/x/net/http2/server.go index c5d0810..2ec894b 100644 --- a/vendor/golang.org/x/net/http2/server.go +++ b/vendor/golang.org/x/net/http2/server.go @@ -1,26 +1,45 @@ // Copyright 2014 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // TODO: turn off the serve goroutine when idle, so + // an idle conn only has the readFrames goroutine active. (which could + // also be optimized probably to pin less memory in crypto/tls). This + // would involve tracking when the serve goroutine is active (atomic + // int32 read/CAS probably?) and starting it up when frames arrive, + // and shutting it down when all handlers exit. the occasional PING + // packets could use time.AfterFunc to call sc.wakeStartServeLoop() + // (which is a no-op if already running) and then queue the PING write + // as normal. The serve loop would then exit in most cases (if no + // Handlers running) and not be woken up again until the PING packet + // returns. // TODO (maybe): add a mechanism for Handlers to going into + // half-closed-local mode (rw.(io.Closer) test?) but not exit their + // handler, and continue to be able to read from the + // Request.Body. This would be a somewhat semantic change from HTTP/1 + // (or at least what we expose in net/http), so I'd probably want to + // add it there too. For now, this package says that returning from + // the Handler ServeHTTP function means you're both done reading and + // done writing, without a way to stop just one or the other. package http2 @@ -52,3231 +71,5831 @@ import ( ) const ( - prefaceTimeout = 10 * time.Second - firstSettingsTimeout = 2 * time.Second // should be in-flight with preface anyway - handlerChunkWriteSize = 4 << 10 - defaultMaxStreams = 250 // TODO: make this 100 as the GFE seems to? + prefaceTimeout = 10 * time.Second + + firstSettingsTimeout = 2 * time.Second // should be in-flight with preface anyway + + handlerChunkWriteSize = 4 << 10 + + defaultMaxStreams = 250 // TODO: make this 100 as the GFE seems to? + maxQueuedControlFrames = 10000 ) var ( errClientDisconnected = errors.New("client disconnected") - errClosedBody = errors.New("body closed by handler") - errHandlerComplete = errors.New("http2: request body closed due to handler exiting") - errStreamClosed = errors.New("http2: stream closed") + + errClosedBody = errors.New("body closed by handler") + + errHandlerComplete = errors.New("http2: request body closed due to handler exiting") + + errStreamClosed = errors.New("http2: stream closed") ) var responseWriterStatePool = sync.Pool{ + New: func() interface{} { + rws := &responseWriterState{} + rws.bw = bufio.NewWriterSize(chunkWriter{rws}, handlerChunkWriteSize) + return rws + }, } // Test hooks. + var ( - testHookOnConn func() + testHookOnConn func() + testHookGetServerConn func(*serverConn) - testHookOnPanicMu *sync.Mutex // nil except in tests - testHookOnPanic func(sc *serverConn, panicVal interface{}) (rePanic bool) + + testHookOnPanicMu *sync.Mutex // nil except in tests + + testHookOnPanic func(sc *serverConn, panicVal interface{}) (rePanic bool) ) // Server is an HTTP/2 server. + type Server struct { + // MaxHandlers limits the number of http.Handler ServeHTTP goroutines + // which may run at a time over all connections. + // Negative or zero no limit. + // TODO: implement + MaxHandlers int // MaxConcurrentStreams optionally specifies the number of + // concurrent streams that each client may have open at a + // time. This is unrelated to the number of http.Handler goroutines + // which may be active globally, which is MaxHandlers. + // If zero, MaxConcurrentStreams defaults to at least 100, per + // the HTTP/2 spec's recommendations. + MaxConcurrentStreams uint32 // MaxDecoderHeaderTableSize optionally specifies the http2 + // SETTINGS_HEADER_TABLE_SIZE to send in the initial settings frame. It + // informs the remote endpoint of the maximum size of the header compression + // table used to decode header blocks, in octets. If zero, the default value + // of 4096 is used. + MaxDecoderHeaderTableSize uint32 // MaxEncoderHeaderTableSize optionally specifies an upper limit for the + // header compression table used for encoding request headers. Received + // SETTINGS_HEADER_TABLE_SIZE settings are capped at this limit. If zero, + // the default value of 4096 is used. + MaxEncoderHeaderTableSize uint32 // MaxReadFrameSize optionally specifies the largest frame + // this server is willing to read. A valid value is between + // 16k and 16M, inclusive. If zero or otherwise invalid, a + // default value is used. + MaxReadFrameSize uint32 // PermitProhibitedCipherSuites, if true, permits the use of + // cipher suites prohibited by the HTTP/2 spec. + PermitProhibitedCipherSuites bool // IdleTimeout specifies how long until idle clients should be + // closed with a GOAWAY frame. PING frames are not considered + // activity for the purposes of IdleTimeout. + // If zero or negative, there is no timeout. + IdleTimeout time.Duration // MaxUploadBufferPerConnection is the size of the initial flow + // control window for each connections. The HTTP/2 spec does not + // allow this to be smaller than 65535 or larger than 2^32-1. + // If the value is outside this range, a default value will be + // used instead. + MaxUploadBufferPerConnection int32 // MaxUploadBufferPerStream is the size of the initial flow control + // window for each stream. The HTTP/2 spec does not allow this to + // be larger than 2^32-1. If the value is zero or larger than the + // maximum, a default value will be used instead. + MaxUploadBufferPerStream int32 // NewWriteScheduler constructs a write scheduler for a connection. + // If nil, a default scheduler is chosen. + NewWriteScheduler func() WriteScheduler // CountError, if non-nil, is called on HTTP/2 server errors. + // It's intended to increment a metric for monitoring, such + // as an expvar or Prometheus metric. + // The errType consists of only ASCII word characters. + CountError func(errType string) // Internal state. This is a pointer (rather than embedded directly) + // so that we don't embed a Mutex in this struct, which will make the + // struct non-copyable, which might break some callers. + state *serverInternalState } func (s *Server) initialConnRecvWindowSize() int32 { + if s.MaxUploadBufferPerConnection >= initialWindowSize { + return s.MaxUploadBufferPerConnection + } + return 1 << 20 + } func (s *Server) initialStreamRecvWindowSize() int32 { + if s.MaxUploadBufferPerStream > 0 { + return s.MaxUploadBufferPerStream + } + return 1 << 20 + } func (s *Server) maxReadFrameSize() uint32 { + if v := s.MaxReadFrameSize; v >= minMaxFrameSize && v <= maxFrameSize { + return v + } + return defaultMaxReadFrameSize + } func (s *Server) maxConcurrentStreams() uint32 { + if v := s.MaxConcurrentStreams; v > 0 { + return v + } + return defaultMaxStreams + } func (s *Server) maxDecoderHeaderTableSize() uint32 { + if v := s.MaxDecoderHeaderTableSize; v > 0 { + return v + } + return initialHeaderTableSize + } func (s *Server) maxEncoderHeaderTableSize() uint32 { + if v := s.MaxEncoderHeaderTableSize; v > 0 { + return v + } + return initialHeaderTableSize + } // maxQueuedControlFrames is the maximum number of control frames like + // SETTINGS, PING and RST_STREAM that will be queued for writing before + // the connection is closed to prevent memory exhaustion attacks. + func (s *Server) maxQueuedControlFrames() int { + // TODO: if anybody asks, add a Server field, and remember to define the + // behavior of negative values. + return maxQueuedControlFrames + } type serverInternalState struct { - mu sync.Mutex + mu sync.Mutex + activeConns map[*serverConn]struct{} } func (s *serverInternalState) registerConn(sc *serverConn) { + if s == nil { + return // if the Server was used without calling ConfigureServer + } + s.mu.Lock() + s.activeConns[sc] = struct{}{} + s.mu.Unlock() + } func (s *serverInternalState) unregisterConn(sc *serverConn) { + if s == nil { + return // if the Server was used without calling ConfigureServer + } + s.mu.Lock() + delete(s.activeConns, sc) + s.mu.Unlock() + } func (s *serverInternalState) startGracefulShutdown() { + if s == nil { + return // if the Server was used without calling ConfigureServer + } + s.mu.Lock() + for sc := range s.activeConns { + sc.startGracefulShutdown() + } + s.mu.Unlock() + } // ConfigureServer adds HTTP/2 support to a net/http Server. + // + // The configuration conf may be nil. + // + // ConfigureServer must be called before s begins serving. + func ConfigureServer(s *http.Server, conf *Server) error { + if s == nil { + panic("nil *http.Server") + } + if conf == nil { + conf = new(Server) + } + conf.state = &serverInternalState{activeConns: make(map[*serverConn]struct{})} + if h1, h2 := s, conf; h2.IdleTimeout == 0 { + if h1.IdleTimeout != 0 { + h2.IdleTimeout = h1.IdleTimeout + } else { + h2.IdleTimeout = h1.ReadTimeout + } + } + s.RegisterOnShutdown(conf.state.startGracefulShutdown) if s.TLSConfig == nil { + s.TLSConfig = new(tls.Config) + } else if s.TLSConfig.CipherSuites != nil && s.TLSConfig.MinVersion < tls.VersionTLS13 { + // If they already provided a TLS 1.0–1.2 CipherSuite list, return an + // error if it is missing ECDHE_RSA_WITH_AES_128_GCM_SHA256 or + // ECDHE_ECDSA_WITH_AES_128_GCM_SHA256. + haveRequired := false + for _, cs := range s.TLSConfig.CipherSuites { + switch cs { + case tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, + // Alternative MTI cipher to not discourage ECDSA-only servers. + // See http://golang.org/cl/30721 for further information. + tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: + haveRequired = true + } + } + if !haveRequired { + return fmt.Errorf("http2: TLSConfig.CipherSuites is missing an HTTP/2-required AES_128_GCM_SHA256 cipher (need at least one of TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 or TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)") + } + } // Note: not setting MinVersion to tls.VersionTLS12, + // as we don't want to interfere with HTTP/1.1 traffic + // on the user's server. We enforce TLS 1.2 later once + // we accept a connection. Ideally this should be done + // during next-proto selection, but using TLS <1.2 with + // HTTP/2 is still the client's bug. s.TLSConfig.PreferServerCipherSuites = true if !strSliceContains(s.TLSConfig.NextProtos, NextProtoTLS) { + s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, NextProtoTLS) + } + if !strSliceContains(s.TLSConfig.NextProtos, "http/1.1") { + s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, "http/1.1") + } if s.TLSNextProto == nil { + s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){} + } + protoHandler := func(hs *http.Server, c *tls.Conn, h http.Handler) { + if testHookOnConn != nil { + testHookOnConn() + } + // The TLSNextProto interface predates contexts, so + // the net/http package passes down its per-connection + // base context via an exported but unadvertised + // method on the Handler. This is for internal + // net/http<=>http2 use only. + var ctx context.Context + type baseContexter interface { BaseContext() context.Context } + if bc, ok := h.(baseContexter); ok { + ctx = bc.BaseContext() + } + conf.ServeConn(c, &ServeConnOpts{ - Context: ctx, - Handler: h, + + Context: ctx, + + Handler: h, + BaseConfig: hs, }) + } + s.TLSNextProto[NextProtoTLS] = protoHandler + return nil + } // ServeConnOpts are options for the Server.ServeConn method. + type ServeConnOpts struct { + // Context is the base context to use. + // If nil, context.Background is used. + Context context.Context // BaseConfig optionally sets the base configuration + // for values. If nil, defaults are used. + BaseConfig *http.Server // Handler specifies which handler to use for processing + // requests. If nil, BaseConfig.Handler is used. If BaseConfig + // or BaseConfig.Handler is nil, http.DefaultServeMux is used. + Handler http.Handler // UpgradeRequest is an initial request received on a connection + // undergoing an h2c upgrade. The request body must have been + // completely read from the connection before calling ServeConn, + // and the 101 Switching Protocols response written. + UpgradeRequest *http.Request // Settings is the decoded contents of the HTTP2-Settings header + // in an h2c upgrade request. + Settings []byte // SawClientPreface is set if the HTTP/2 connection preface + // has already been read from the connection. + SawClientPreface bool } func (o *ServeConnOpts) context() context.Context { + if o != nil && o.Context != nil { + return o.Context + } + return context.Background() + } func (o *ServeConnOpts) baseConfig() *http.Server { + if o != nil && o.BaseConfig != nil { + return o.BaseConfig + } + return new(http.Server) + } func (o *ServeConnOpts) handler() http.Handler { + if o != nil { + if o.Handler != nil { + return o.Handler + } + if o.BaseConfig != nil && o.BaseConfig.Handler != nil { + return o.BaseConfig.Handler + } + } + return http.DefaultServeMux + } // ServeConn serves HTTP/2 requests on the provided connection and + // blocks until the connection is no longer readable. + // + // ServeConn starts speaking HTTP/2 assuming that c has not had any + // reads or writes. It writes its initial settings frame and expects + // to be able to read the preface and settings frame from the + // client. If c has a ConnectionState method like a *tls.Conn, the + // ConnectionState is used to verify the TLS ciphersuite and to set + // the Request.TLS field in Handlers. + // + // ServeConn does not support h2c by itself. Any h2c support must be + // implemented in terms of providing a suitably-behaving net.Conn. + // + // The opts parameter is optional. If nil, default values are used. + func (s *Server) ServeConn(c net.Conn, opts *ServeConnOpts) { + baseCtx, cancel := serverConnBaseContext(c, opts) + defer cancel() sc := &serverConn{ - srv: s, - hs: opts.baseConfig(), - conn: c, - baseCtx: baseCtx, - remoteAddrStr: c.RemoteAddr().String(), - bw: newBufferedWriter(c), - handler: opts.handler(), - streams: make(map[uint32]*stream), - readFrameCh: make(chan readFrameResult), - wantWriteFrameCh: make(chan FrameWriteRequest, 8), - serveMsgCh: make(chan interface{}, 8), - wroteFrameCh: make(chan frameWriteResult, 1), // buffered; one send in writeFrameAsync - bodyReadCh: make(chan bodyReadMsg), // buffering doesn't matter either way - doneServing: make(chan struct{}), - clientMaxStreams: math.MaxUint32, // Section 6.5.2: "Initially, there is no limit to this value" - advMaxStreams: s.maxConcurrentStreams(), + + srv: s, + + hs: opts.baseConfig(), + + conn: c, + + baseCtx: baseCtx, + + remoteAddrStr: c.RemoteAddr().String(), + + bw: newBufferedWriter(c), + + handler: opts.handler(), + + streams: make(map[uint32]*stream), + + readFrameCh: make(chan readFrameResult), + + wantWriteFrameCh: make(chan FrameWriteRequest, 8), + + serveMsgCh: make(chan interface{}, 8), + + wroteFrameCh: make(chan frameWriteResult, 1), // buffered; one send in writeFrameAsync + + bodyReadCh: make(chan bodyReadMsg), // buffering doesn't matter either way + + doneServing: make(chan struct{}), + + clientMaxStreams: math.MaxUint32, // Section 6.5.2: "Initially, there is no limit to this value" + + advMaxStreams: s.maxConcurrentStreams(), + initialStreamSendWindowSize: initialWindowSize, - maxFrameSize: initialMaxFrameSize, - serveG: newGoroutineLock(), - pushEnabled: true, - sawClientPreface: opts.SawClientPreface, + + maxFrameSize: initialMaxFrameSize, + + serveG: newGoroutineLock(), + + pushEnabled: true, + + sawClientPreface: opts.SawClientPreface, } s.state.registerConn(sc) + defer s.state.unregisterConn(sc) // The net/http package sets the write deadline from the + // http.Server.WriteTimeout during the TLS handshake, but then + // passes the connection off to us with the deadline already set. + // Write deadlines are set per stream in serverConn.newStream. + // Disarm the net.Conn write deadline here. + if sc.hs.WriteTimeout > 0 { + sc.conn.SetWriteDeadline(time.Time{}) + } if s.NewWriteScheduler != nil { + sc.writeSched = s.NewWriteScheduler() + } else { + sc.writeSched = newRoundRobinWriteScheduler() + } // These start at the RFC-specified defaults. If there is a higher + // configured value for inflow, that will be updated when we send a + // WINDOW_UPDATE shortly after sending SETTINGS. + sc.flow.add(initialWindowSize) + sc.inflow.init(initialWindowSize) + sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf) + sc.hpackEncoder.SetMaxDynamicTableSizeLimit(s.maxEncoderHeaderTableSize()) fr := NewFramer(sc.bw, c) + if s.CountError != nil { + fr.countError = s.CountError + } + fr.ReadMetaHeaders = hpack.NewDecoder(s.maxDecoderHeaderTableSize(), nil) + fr.MaxHeaderListSize = sc.maxHeaderListSize() + fr.SetMaxReadFrameSize(s.maxReadFrameSize()) + sc.framer = fr if tc, ok := c.(connectionStater); ok { + sc.tlsState = new(tls.ConnectionState) + *sc.tlsState = tc.ConnectionState() + // 9.2 Use of TLS Features + // An implementation of HTTP/2 over TLS MUST use TLS + // 1.2 or higher with the restrictions on feature set + // and cipher suite described in this section. Due to + // implementation limitations, it might not be + // possible to fail TLS negotiation. An endpoint MUST + // immediately terminate an HTTP/2 connection that + // does not meet the TLS requirements described in + // this section with a connection error (Section + // 5.4.1) of type INADEQUATE_SECURITY. + if sc.tlsState.Version < tls.VersionTLS12 { + sc.rejectConn(ErrCodeInadequateSecurity, "TLS version too low") + return + } if sc.tlsState.ServerName == "" { + // Client must use SNI, but we don't enforce that anymore, + // since it was causing problems when connecting to bare IP + // addresses during development. + // + // TODO: optionally enforce? Or enforce at the time we receive + // a new request, and verify the ServerName matches the :authority? + // But that precludes proxy situations, perhaps. + // + // So for now, do nothing here again. + } if !s.PermitProhibitedCipherSuites && isBadCipher(sc.tlsState.CipherSuite) { + // "Endpoints MAY choose to generate a connection error + // (Section 5.4.1) of type INADEQUATE_SECURITY if one of + // the prohibited cipher suites are negotiated." + // + // We choose that. In my opinion, the spec is weak + // here. It also says both parties must support at least + // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 so there's no + // excuses here. If we really must, we could allow an + // "AllowInsecureWeakCiphers" option on the server later. + // Let's see how it plays out first. + sc.rejectConn(ErrCodeInadequateSecurity, fmt.Sprintf("Prohibited TLS 1.2 Cipher Suite: %x", sc.tlsState.CipherSuite)) + return + } + } if opts.Settings != nil { + fr := &SettingsFrame{ + FrameHeader: FrameHeader{valid: true}, - p: opts.Settings, + + p: opts.Settings, } + if err := fr.ForeachSetting(sc.processSetting); err != nil { + sc.rejectConn(ErrCodeProtocol, "invalid settings") + return + } + opts.Settings = nil + } if hook := testHookGetServerConn; hook != nil { + hook(sc) + } if opts.UpgradeRequest != nil { + sc.upgradeRequest(opts.UpgradeRequest) + opts.UpgradeRequest = nil + } sc.serve() + } func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx context.Context, cancel func()) { + ctx, cancel = context.WithCancel(opts.context()) + ctx = context.WithValue(ctx, http.LocalAddrContextKey, c.LocalAddr()) + if hs := opts.baseConfig(); hs != nil { + ctx = context.WithValue(ctx, http.ServerContextKey, hs) + } + return + } func (sc *serverConn) rejectConn(err ErrCode, debug string) { + sc.vlogf("http2: server rejecting conn: %v, %s", err, debug) + // ignoring errors. hanging up anyway. + sc.framer.WriteGoAway(0, err, []byte(debug)) + sc.bw.Flush() + sc.conn.Close() + } type serverConn struct { + // Immutable: - srv *Server - hs *http.Server - conn net.Conn - bw *bufferedWriter // writing to conn - handler http.Handler - baseCtx context.Context - framer *Framer - doneServing chan struct{} // closed when serverConn.serve ends - readFrameCh chan readFrameResult // written by serverConn.readFrames + + srv *Server + + hs *http.Server + + conn net.Conn + + bw *bufferedWriter // writing to conn + + handler http.Handler + + baseCtx context.Context + + framer *Framer + + doneServing chan struct{} // closed when serverConn.serve ends + + readFrameCh chan readFrameResult // written by serverConn.readFrames + wantWriteFrameCh chan FrameWriteRequest // from handlers -> serve - wroteFrameCh chan frameWriteResult // from writeFrameAsync -> serve, tickles more frame writes - bodyReadCh chan bodyReadMsg // from handlers -> serve - serveMsgCh chan interface{} // misc messages & code to send to / run on the serve loop - flow outflow // conn-wide (not stream-specific) outbound flow control - inflow inflow // conn-wide inbound flow control - tlsState *tls.ConnectionState // shared by all handlers, like net/http - remoteAddrStr string - writeSched WriteScheduler + + wroteFrameCh chan frameWriteResult // from writeFrameAsync -> serve, tickles more frame writes + + bodyReadCh chan bodyReadMsg // from handlers -> serve + + serveMsgCh chan interface{} // misc messages & code to send to / run on the serve loop + + flow outflow // conn-wide (not stream-specific) outbound flow control + + inflow inflow // conn-wide inbound flow control + + tlsState *tls.ConnectionState // shared by all handlers, like net/http + + remoteAddrStr string + + writeSched WriteScheduler // Everything following is owned by the serve loop; use serveG.check(): - serveG goroutineLock // used to verify funcs are on serve() - pushEnabled bool - sawClientPreface bool // preface has already been read, used in h2c upgrade - sawFirstSettings bool // got the initial SETTINGS frame after the preface - needToSendSettingsAck bool - unackedSettings int // how many SETTINGS have we sent without ACKs? - queuedControlFrames int // control frames in the writeSched queue - clientMaxStreams uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit) - advMaxStreams uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client - curClientStreams uint32 // number of open streams initiated by the client - curPushedStreams uint32 // number of open streams initiated by server push - curHandlers uint32 // number of running handler goroutines - maxClientStreamID uint32 // max ever seen from client (odd), or 0 if there have been no client requests - maxPushPromiseID uint32 // ID of the last push promise (even), or 0 if there have been no pushes - streams map[uint32]*stream - unstartedHandlers []unstartedHandler + + serveG goroutineLock // used to verify funcs are on serve() + + pushEnabled bool + + sawClientPreface bool // preface has already been read, used in h2c upgrade + + sawFirstSettings bool // got the initial SETTINGS frame after the preface + + needToSendSettingsAck bool + + unackedSettings int // how many SETTINGS have we sent without ACKs? + + queuedControlFrames int // control frames in the writeSched queue + + clientMaxStreams uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit) + + advMaxStreams uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client + + curClientStreams uint32 // number of open streams initiated by the client + + curPushedStreams uint32 // number of open streams initiated by server push + + curHandlers uint32 // number of running handler goroutines + + maxClientStreamID uint32 // max ever seen from client (odd), or 0 if there have been no client requests + + maxPushPromiseID uint32 // ID of the last push promise (even), or 0 if there have been no pushes + + streams map[uint32]*stream + + unstartedHandlers []unstartedHandler + initialStreamSendWindowSize int32 - maxFrameSize int32 - peerMaxHeaderListSize uint32 // zero means unknown (default) - canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case - canonHeaderKeysSize int // canonHeader keys size in bytes - writingFrame bool // started writing a frame (on serve goroutine or separate) - writingFrameAsync bool // started a frame on its own goroutine but haven't heard back on wroteFrameCh - needsFrameFlush bool // last frame write wasn't a flush - inGoAway bool // we've started to or sent GOAWAY - inFrameScheduleLoop bool // whether we're in the scheduleFrameWrite loop - needToSendGoAway bool // we need to schedule a GOAWAY frame write - goAwayCode ErrCode - shutdownTimer *time.Timer // nil until used - idleTimer *time.Timer // nil if unused + + maxFrameSize int32 + + peerMaxHeaderListSize uint32 // zero means unknown (default) + + canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case + + canonHeaderKeysSize int // canonHeader keys size in bytes + + writingFrame bool // started writing a frame (on serve goroutine or separate) + + writingFrameAsync bool // started a frame on its own goroutine but haven't heard back on wroteFrameCh + + needsFrameFlush bool // last frame write wasn't a flush + + inGoAway bool // we've started to or sent GOAWAY + + inFrameScheduleLoop bool // whether we're in the scheduleFrameWrite loop + + needToSendGoAway bool // we need to schedule a GOAWAY frame write + + goAwayCode ErrCode + + shutdownTimer *time.Timer // nil until used + + idleTimer *time.Timer // nil if unused // Owned by the writeFrameAsync goroutine: + headerWriteBuf bytes.Buffer - hpackEncoder *hpack.Encoder + + hpackEncoder *hpack.Encoder // Used by startGracefulShutdown. + shutdownOnce sync.Once } func (sc *serverConn) maxHeaderListSize() uint32 { + n := sc.hs.MaxHeaderBytes + if n <= 0 { + n = http.DefaultMaxHeaderBytes + } + // http2's count is in a slightly different unit and includes 32 bytes per pair. + // So, take the net/http.Server value and pad it up a bit, assuming 10 headers. + const perFieldOverhead = 32 // per http2 spec - const typicalHeaders = 10 // conservative + + const typicalHeaders = 10 // conservative + return uint32(n + typicalHeaders*perFieldOverhead) + } func (sc *serverConn) curOpenStreams() uint32 { + sc.serveG.check() + return sc.curClientStreams + sc.curPushedStreams + } // stream represents a stream. This is the minimal metadata needed by + // the serve goroutine. Most of the actual stream state is owned by + // the http.Handler's goroutine in the responseWriter. Because the + // responseWriter's responseWriterState is recycled at the end of a + // handler, this struct intentionally has no pointer to the + // *responseWriter{,State} itself, as the Handler ending nils out the + // responseWriter's state field. + type stream struct { + // immutable: - sc *serverConn - id uint32 - body *pipe // non-nil if expecting DATA frames - cw closeWaiter // closed wait stream transitions to closed state - ctx context.Context + + sc *serverConn + + id uint32 + + body *pipe // non-nil if expecting DATA frames + + cw closeWaiter // closed wait stream transitions to closed state + + ctx context.Context + cancelCtx func() // owned by serverConn's serve loop: - bodyBytes int64 // body bytes seen so far - declBodyBytes int64 // or -1 if undeclared - flow outflow // limits writing from Handler to client - inflow inflow // what the client is allowed to POST/etc to us - state streamState - resetQueued bool // RST_STREAM queued for write; set by sc.resetStream - gotTrailerHeader bool // HEADER frame for trailers was seen - wroteHeaders bool // whether we wrote headers (not status 100) - readDeadline *time.Timer // nil if unused - writeDeadline *time.Timer // nil if unused - closeErr error // set before cw is closed - trailer http.Header // accumulated trailers + bodyBytes int64 // body bytes seen so far + + declBodyBytes int64 // or -1 if undeclared + + flow outflow // limits writing from Handler to client + + inflow inflow // what the client is allowed to POST/etc to us + + state streamState + + resetQueued bool // RST_STREAM queued for write; set by sc.resetStream + + gotTrailerHeader bool // HEADER frame for trailers was seen + + wroteHeaders bool // whether we wrote headers (not status 100) + + readDeadline *time.Timer // nil if unused + + writeDeadline *time.Timer // nil if unused + + closeErr error // set before cw is closed + + trailer http.Header // accumulated trailers + reqTrailer http.Header // handler's Request.Trailer + } -func (sc *serverConn) Framer() *Framer { return sc.framer } +func (sc *serverConn) Framer() *Framer { return sc.framer } + func (sc *serverConn) CloseConn() error { return sc.conn.Close() } -func (sc *serverConn) Flush() error { return sc.bw.Flush() } + +func (sc *serverConn) Flush() error { return sc.bw.Flush() } + func (sc *serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) { + return sc.hpackEncoder, &sc.headerWriteBuf + } func (sc *serverConn) state(streamID uint32) (streamState, *stream) { + sc.serveG.check() + // http://tools.ietf.org/html/rfc7540#section-5.1 + if st, ok := sc.streams[streamID]; ok { + return st.state, st + } + // "The first use of a new stream identifier implicitly closes all + // streams in the "idle" state that might have been initiated by + // that peer with a lower-valued stream identifier. For example, if + // a client sends a HEADERS frame on stream 7 without ever sending a + // frame on stream 5, then stream 5 transitions to the "closed" + // state when the first frame for stream 7 is sent or received." + if streamID%2 == 1 { + if streamID <= sc.maxClientStreamID { + return stateClosed, nil + } + } else { + if streamID <= sc.maxPushPromiseID { + return stateClosed, nil + } + } + return stateIdle, nil + } // setConnState calls the net/http ConnState hook for this connection, if configured. + // Note that the net/http package does StateNew and StateClosed for us. + // There is currently no plan for StateHijacked or hijacking HTTP/2 connections. + func (sc *serverConn) setConnState(state http.ConnState) { + if sc.hs.ConnState != nil { + sc.hs.ConnState(sc.conn, state) + } + } func (sc *serverConn) vlogf(format string, args ...interface{}) { + if VerboseLogs { + sc.logf(format, args...) + } + } func (sc *serverConn) logf(format string, args ...interface{}) { + if lg := sc.hs.ErrorLog; lg != nil { + lg.Printf(format, args...) + } else { + log.Printf(format, args...) + } + } // errno returns v's underlying uintptr, else 0. + // + // TODO: remove this helper function once http2 can use build + // tags. See comment in isClosedConnError. + func errno(v error) uintptr { + if rv := reflect.ValueOf(v); rv.Kind() == reflect.Uintptr { + return uintptr(rv.Uint()) + } + return 0 + } // isClosedConnError reports whether err is an error from use of a closed + // network connection. + func isClosedConnError(err error) bool { + if err == nil { + return false + } if errors.Is(err, net.ErrClosed) { + return true + } // TODO(bradfitz): x/tools/cmd/bundle doesn't really support + // build tags, so I can't make an http2_windows.go file with + // Windows-specific stuff. Fix that and move this, once we + // have a way to bundle this into std's net/http somehow. + if runtime.GOOS == "windows" { + if oe, ok := err.(*net.OpError); ok && oe.Op == "read" { + if se, ok := oe.Err.(*os.SyscallError); ok && se.Syscall == "wsarecv" { + const WSAECONNABORTED = 10053 + const WSAECONNRESET = 10054 + if n := errno(se.Err); n == WSAECONNRESET || n == WSAECONNABORTED { + return true + } + } + } + } + return false + } func (sc *serverConn) condlogf(err error, format string, args ...interface{}) { + if err == nil { + return + } + if err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) || err == errPrefaceTimeout { + // Boring, expected errors. + sc.vlogf(format, args...) + } else { + sc.logf(format, args...) + } + } // maxCachedCanonicalHeadersKeysSize is an arbitrarily-chosen limit on the size + // of the entries in the canonHeader cache. + // This should be larger than the size of unique, uncommon header keys likely to + // be sent by the peer, while not so high as to permit unreasonable memory usage + // if the peer sends an unbounded number of unique header keys. + const maxCachedCanonicalHeadersKeysSize = 2048 func (sc *serverConn) canonicalHeader(v string) string { + sc.serveG.check() + buildCommonHeaderMapsOnce() + cv, ok := commonCanonHeader[v] + if ok { + return cv + } + cv, ok = sc.canonHeader[v] + if ok { + return cv + } + if sc.canonHeader == nil { + sc.canonHeader = make(map[string]string) + } + cv = http.CanonicalHeaderKey(v) + size := 100 + len(v)*2 // 100 bytes of map overhead + key + value + if sc.canonHeaderKeysSize+size <= maxCachedCanonicalHeadersKeysSize { + sc.canonHeader[v] = cv + sc.canonHeaderKeysSize += size + } + return cv + } type readFrameResult struct { - f Frame // valid until readMore is called + f Frame // valid until readMore is called + err error // readMore should be called once the consumer no longer needs or + // retains f. After readMore, f is invalid and more frames can be + // read. + readMore func() } // readFrames is the loop that reads incoming frames. + // It takes care to only read one frame at a time, blocking until the + // consumer is done with the frame. + // It's run on its own goroutine. + func (sc *serverConn) readFrames() { + gate := make(gate) + gateDone := gate.Done + for { + f, err := sc.framer.ReadFrame() + select { + case sc.readFrameCh <- readFrameResult{f, err, gateDone}: + case <-sc.doneServing: + return + } + select { + case <-gate: + case <-sc.doneServing: + return + } + if terminalReadFrameError(err) { + return + } + } + } // frameWriteResult is the message passed from writeFrameAsync to the serve goroutine. + type frameWriteResult struct { - _ incomparable - wr FrameWriteRequest // what was written (or attempted) - err error // result of the writeFrame call + _ incomparable + + wr FrameWriteRequest // what was written (or attempted) + + err error // result of the writeFrame call + } // writeFrameAsync runs in its own goroutine and writes a single frame + // and then reports when it's done. + // At most one goroutine can be running writeFrameAsync at a time per + // serverConn. + func (sc *serverConn) writeFrameAsync(wr FrameWriteRequest, wd *writeData) { + var err error + if wd == nil { + err = wr.write.writeFrame(sc) + } else { + err = sc.framer.endWrite() + } + sc.wroteFrameCh <- frameWriteResult{wr: wr, err: err} + } func (sc *serverConn) closeAllStreamsOnConnClose() { + sc.serveG.check() + for _, st := range sc.streams { + sc.closeStream(st, errClientDisconnected) + } + } func (sc *serverConn) stopShutdownTimer() { + sc.serveG.check() + if t := sc.shutdownTimer; t != nil { + t.Stop() + } + } func (sc *serverConn) notePanic() { + // Note: this is for serverConn.serve panicking, not http.Handler code. + if testHookOnPanicMu != nil { + testHookOnPanicMu.Lock() + defer testHookOnPanicMu.Unlock() + } + if testHookOnPanic != nil { + if e := recover(); e != nil { + if testHookOnPanic(sc, e) { + panic(e) + } + } + } + } func (sc *serverConn) serve() { + sc.serveG.check() + defer sc.notePanic() + defer sc.conn.Close() + defer sc.closeAllStreamsOnConnClose() + defer sc.stopShutdownTimer() + defer close(sc.doneServing) // unblocks handlers trying to send if VerboseLogs { + sc.vlogf("http2: server connection from %v on %p", sc.conn.RemoteAddr(), sc.hs) + } sc.writeFrame(FrameWriteRequest{ + write: writeSettings{ + {SettingMaxFrameSize, sc.srv.maxReadFrameSize()}, + {SettingMaxConcurrentStreams, sc.advMaxStreams}, + {SettingMaxHeaderListSize, sc.maxHeaderListSize()}, + {SettingHeaderTableSize, sc.srv.maxDecoderHeaderTableSize()}, + {SettingInitialWindowSize, uint32(sc.srv.initialStreamRecvWindowSize())}, }, }) + sc.unackedSettings++ // Each connection starts with initialWindowSize inflow tokens. + // If a higher value is configured, we add more tokens. + if diff := sc.srv.initialConnRecvWindowSize() - initialWindowSize; diff > 0 { + sc.sendWindowUpdate(nil, int(diff)) + } if err := sc.readPreface(); err != nil { + sc.condlogf(err, "http2: server: error reading preface from client %v: %v", sc.conn.RemoteAddr(), err) + return + } + // Now that we've got the preface, get us out of the + // "StateNew" state. We can't go directly to idle, though. + // Active means we read some data and anticipate a request. We'll + // do another Active when we get a HEADERS frame. + sc.setConnState(http.StateActive) + sc.setConnState(http.StateIdle) if sc.srv.IdleTimeout > 0 { + sc.idleTimer = time.AfterFunc(sc.srv.IdleTimeout, sc.onIdleTimer) + defer sc.idleTimer.Stop() + } go sc.readFrames() // closed by defer sc.conn.Close above settingsTimer := time.AfterFunc(firstSettingsTimeout, sc.onSettingsTimer) + defer settingsTimer.Stop() loopNum := 0 + for { + loopNum++ + select { + case wr := <-sc.wantWriteFrameCh: + if se, ok := wr.write.(StreamError); ok { + sc.resetStream(se) + break + } + sc.writeFrame(wr) + case res := <-sc.wroteFrameCh: + sc.wroteFrame(res) + case res := <-sc.readFrameCh: + // Process any written frames before reading new frames from the client since a + // written frame could have triggered a new stream to be started. + if sc.writingFrameAsync { + select { + case wroteRes := <-sc.wroteFrameCh: + sc.wroteFrame(wroteRes) + default: + } + } + if !sc.processFrameFromReader(res) { + return + } + res.readMore() + if settingsTimer != nil { + settingsTimer.Stop() + settingsTimer = nil + } + case m := <-sc.bodyReadCh: + sc.noteBodyRead(m.st, m.n) + case msg := <-sc.serveMsgCh: + switch v := msg.(type) { + case func(int): + v(loopNum) // for testing + case *serverMessage: + switch v { + case settingsTimerMsg: + sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr()) + return + case idleTimerMsg: + sc.vlogf("connection is idle") + sc.goAway(ErrCodeNo) + case shutdownTimerMsg: + sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr()) + return + case gracefulShutdownMsg: + sc.startGracefulShutdownInternal() + case handlerDoneMsg: + sc.handlerDone() + default: + panic("unknown timer") + } + case *startPushRequest: + sc.startPush(v) + case func(*serverConn): + v(sc) + default: + panic(fmt.Sprintf("unexpected type %T", v)) + } + } // If the peer is causing us to generate a lot of control frames, + // but not reading them from us, assume they are trying to make us + // run out of memory. + if sc.queuedControlFrames > sc.srv.maxQueuedControlFrames() { + sc.vlogf("http2: too many control frames in send queue, closing connection") + return + } // Start the shutdown timer after sending a GOAWAY. When sending GOAWAY + // with no error code (graceful shutdown), don't start the timer until + // all open streams have been completed. + sentGoAway := sc.inGoAway && !sc.needToSendGoAway && !sc.writingFrame + gracefulShutdownComplete := sc.goAwayCode == ErrCodeNo && sc.curOpenStreams() == 0 + if sentGoAway && sc.shutdownTimer == nil && (sc.goAwayCode != ErrCodeNo || gracefulShutdownComplete) { + sc.shutDownIn(goAwayTimeout) + } + } + } type serverMessage int // Message values sent to serveMsgCh. + var ( - settingsTimerMsg = new(serverMessage) - idleTimerMsg = new(serverMessage) - shutdownTimerMsg = new(serverMessage) + settingsTimerMsg = new(serverMessage) + + idleTimerMsg = new(serverMessage) + + shutdownTimerMsg = new(serverMessage) + gracefulShutdownMsg = new(serverMessage) - handlerDoneMsg = new(serverMessage) + + handlerDoneMsg = new(serverMessage) ) func (sc *serverConn) onSettingsTimer() { sc.sendServeMsg(settingsTimerMsg) } -func (sc *serverConn) onIdleTimer() { sc.sendServeMsg(idleTimerMsg) } + +func (sc *serverConn) onIdleTimer() { sc.sendServeMsg(idleTimerMsg) } + func (sc *serverConn) onShutdownTimer() { sc.sendServeMsg(shutdownTimerMsg) } func (sc *serverConn) sendServeMsg(msg interface{}) { + sc.serveG.checkNotOn() // NOT + select { + case sc.serveMsgCh <- msg: + case <-sc.doneServing: + } + } var errPrefaceTimeout = errors.New("timeout waiting for client preface") // readPreface reads the ClientPreface greeting from the peer or + // returns errPrefaceTimeout on timeout, or an error if the greeting + // is invalid. + func (sc *serverConn) readPreface() error { + if sc.sawClientPreface { + return nil + } + errc := make(chan error, 1) + go func() { + // Read the client preface + buf := make([]byte, len(ClientPreface)) + if _, err := io.ReadFull(sc.conn, buf); err != nil { + errc <- err + } else if !bytes.Equal(buf, clientPreface) { + errc <- fmt.Errorf("bogus greeting %q", buf) + } else { + errc <- nil + } + }() + timer := time.NewTimer(prefaceTimeout) // TODO: configurable on *Server? + defer timer.Stop() + select { + case <-timer.C: + return errPrefaceTimeout + case err := <-errc: + if err == nil { + if VerboseLogs { + sc.vlogf("http2: server: client %v said hello", sc.conn.RemoteAddr()) + } + } + return err + } + } var errChanPool = sync.Pool{ + New: func() interface{} { return make(chan error, 1) }, } var writeDataPool = sync.Pool{ + New: func() interface{} { return new(writeData) }, } // writeDataFromHandler writes DATA response frames from a handler on + // the given stream. + func (sc *serverConn) writeDataFromHandler(stream *stream, data []byte, endStream bool) error { + ch := errChanPool.Get().(chan error) + writeArg := writeDataPool.Get().(*writeData) + *writeArg = writeData{stream.id, data, endStream} + err := sc.writeFrameFromHandler(FrameWriteRequest{ - write: writeArg, + + write: writeArg, + stream: stream, - done: ch, + + done: ch, }) + if err != nil { + return err + } + var frameWriteDone bool // the frame write is done (successfully or not) + select { + case err = <-ch: + frameWriteDone = true + case <-sc.doneServing: + return errClientDisconnected + case <-stream.cw: + // If both ch and stream.cw were ready (as might + // happen on the final Write after an http.Handler + // ends), prefer the write result. Otherwise this + // might just be us successfully closing the stream. + // The writeFrameAsync and serve goroutines guarantee + // that the ch send will happen before the stream.cw + // close. + select { + case err = <-ch: + frameWriteDone = true + default: + return errStreamClosed + } + } + errChanPool.Put(ch) + if frameWriteDone { + writeDataPool.Put(writeArg) + } + return err + } // writeFrameFromHandler sends wr to sc.wantWriteFrameCh, but aborts + // if the connection has gone away. + // + // This must not be run from the serve goroutine itself, else it might + // deadlock writing to sc.wantWriteFrameCh (which is only mildly + // buffered and is read by serve itself). If you're on the serve + // goroutine, call writeFrame instead. + func (sc *serverConn) writeFrameFromHandler(wr FrameWriteRequest) error { + sc.serveG.checkNotOn() // NOT + select { + case sc.wantWriteFrameCh <- wr: + return nil + case <-sc.doneServing: + // Serve loop is gone. + // Client has closed their connection to the server. + return errClientDisconnected + } + } // writeFrame schedules a frame to write and sends it if there's nothing + // already being written. + // + // There is no pushback here (the serve goroutine never blocks). It's + // the http.Handlers that block, waiting for their previous frames to + // make it onto the wire + // + // If you're not on the serve goroutine, use writeFrameFromHandler instead. + func (sc *serverConn) writeFrame(wr FrameWriteRequest) { + sc.serveG.check() // If true, wr will not be written and wr.done will not be signaled. + var ignoreWrite bool // We are not allowed to write frames on closed streams. RFC 7540 Section + // 5.1.1 says: "An endpoint MUST NOT send frames other than PRIORITY on + // a closed stream." Our server never sends PRIORITY, so that exception + // does not apply. + // + // The serverConn might close an open stream while the stream's handler + // is still running. For example, the server might close a stream when it + // receives bad data from the client. If this happens, the handler might + // attempt to write a frame after the stream has been closed (since the + // handler hasn't yet been notified of the close). In this case, we simply + // ignore the frame. The handler will notice that the stream is closed when + // it waits for the frame to be written. + // + // As an exception to this rule, we allow sending RST_STREAM after close. + // This allows us to immediately reject new streams without tracking any + // state for those streams (except for the queued RST_STREAM frame). This + // may result in duplicate RST_STREAMs in some cases, but the client should + // ignore those. + if wr.StreamID() != 0 { + _, isReset := wr.write.(StreamError) + if state, _ := sc.state(wr.StreamID()); state == stateClosed && !isReset { + ignoreWrite = true + } + } // Don't send a 100-continue response if we've already sent headers. + // See golang.org/issue/14030. + switch wr.write.(type) { + case *writeResHeaders: + wr.stream.wroteHeaders = true + case write100ContinueHeadersFrame: + if wr.stream.wroteHeaders { + // We do not need to notify wr.done because this frame is + // never written with wr.done != nil. + if wr.done != nil { + panic("wr.done != nil for write100ContinueHeadersFrame") + } + ignoreWrite = true + } + } if !ignoreWrite { + if wr.isControl() { + sc.queuedControlFrames++ + // For extra safety, detect wraparounds, which should not happen, + // and pull the plug. + if sc.queuedControlFrames < 0 { + sc.conn.Close() + } + } + sc.writeSched.Push(wr) + } + sc.scheduleFrameWrite() + } // startFrameWrite starts a goroutine to write wr (in a separate + // goroutine since that might block on the network), and updates the + // serve goroutine's state about the world, updated from info in wr. + func (sc *serverConn) startFrameWrite(wr FrameWriteRequest) { + sc.serveG.check() + if sc.writingFrame { + panic("internal error: can only be writing one frame at a time") + } st := wr.stream + if st != nil { + switch st.state { + case stateHalfClosedLocal: + switch wr.write.(type) { + case StreamError, handlerPanicRST, writeWindowUpdate: + // RFC 7540 Section 5.1 allows sending RST_STREAM, PRIORITY, and WINDOW_UPDATE + // in this state. (We never send PRIORITY from the server, so that is not checked.) + default: + panic(fmt.Sprintf("internal error: attempt to send frame on a half-closed-local stream: %v", wr)) + } + case stateClosed: + panic(fmt.Sprintf("internal error: attempt to send frame on a closed stream: %v", wr)) + } + } + if wpp, ok := wr.write.(*writePushPromise); ok { + var err error + wpp.promisedID, err = wpp.allocatePromisedID() + if err != nil { + sc.writingFrameAsync = false + wr.replyToWriter(err) + return + } + } sc.writingFrame = true + sc.needsFrameFlush = true + if wr.write.staysWithinBuffer(sc.bw.Available()) { + sc.writingFrameAsync = false + err := wr.write.writeFrame(sc) + sc.wroteFrame(frameWriteResult{wr: wr, err: err}) + } else if wd, ok := wr.write.(*writeData); ok { + // Encode the frame in the serve goroutine, to ensure we don't have + // any lingering asynchronous references to data passed to Write. + // See https://go.dev/issue/58446. + sc.framer.startWriteDataPadded(wd.streamID, wd.endStream, wd.p, nil) + sc.writingFrameAsync = true + go sc.writeFrameAsync(wr, wd) + } else { + sc.writingFrameAsync = true + go sc.writeFrameAsync(wr, nil) + } + } // errHandlerPanicked is the error given to any callers blocked in a read from + // Request.Body when the main goroutine panics. Since most handlers read in the + // main ServeHTTP goroutine, this will show up rarely. + var errHandlerPanicked = errors.New("http2: handler panicked") // wroteFrame is called on the serve goroutine with the result of + // whatever happened on writeFrameAsync. + func (sc *serverConn) wroteFrame(res frameWriteResult) { + sc.serveG.check() + if !sc.writingFrame { + panic("internal error: expected to be already writing a frame") + } + sc.writingFrame = false + sc.writingFrameAsync = false wr := res.wr if writeEndsStream(wr.write) { + st := wr.stream + if st == nil { + panic("internal error: expecting non-nil stream") + } + switch st.state { + case stateOpen: + // Here we would go to stateHalfClosedLocal in + // theory, but since our handler is done and + // the net/http package provides no mechanism + // for closing a ResponseWriter while still + // reading data (see possible TODO at top of + // this file), we go into closed state here + // anyway, after telling the peer we're + // hanging up on them. We'll transition to + // stateClosed after the RST_STREAM frame is + // written. + st.state = stateHalfClosedLocal + // Section 8.1: a server MAY request that the client abort + // transmission of a request without error by sending a + // RST_STREAM with an error code of NO_ERROR after sending + // a complete response. + sc.resetStream(streamError(st.id, ErrCodeNo)) + case stateHalfClosedRemote: + sc.closeStream(st, errHandlerComplete) + } + } else { + switch v := wr.write.(type) { + case StreamError: + // st may be unknown if the RST_STREAM was generated to reject bad input. + if st, ok := sc.streams[v.StreamID]; ok { + sc.closeStream(st, v) + } + case handlerPanicRST: + sc.closeStream(wr.stream, errHandlerPanicked) + } + } // Reply (if requested) to unblock the ServeHTTP goroutine. + wr.replyToWriter(res.err) sc.scheduleFrameWrite() + } // scheduleFrameWrite tickles the frame writing scheduler. + // + // If a frame is already being written, nothing happens. This will be called again + // when the frame is done being written. + // + // If a frame isn't being written and we need to send one, the best frame + // to send is selected by writeSched. + // + // If a frame isn't being written and there's nothing else to send, we + // flush the write buffer. + func (sc *serverConn) scheduleFrameWrite() { + sc.serveG.check() + if sc.writingFrame || sc.inFrameScheduleLoop { + return + } + sc.inFrameScheduleLoop = true + for !sc.writingFrameAsync { + if sc.needToSendGoAway { + sc.needToSendGoAway = false + sc.startFrameWrite(FrameWriteRequest{ + write: &writeGoAway{ + maxStreamID: sc.maxClientStreamID, - code: sc.goAwayCode, + + code: sc.goAwayCode, }, }) + continue + } + if sc.needToSendSettingsAck { + sc.needToSendSettingsAck = false + sc.startFrameWrite(FrameWriteRequest{write: writeSettingsAck{}}) + continue + } + if !sc.inGoAway || sc.goAwayCode == ErrCodeNo { + if wr, ok := sc.writeSched.Pop(); ok { + if wr.isControl() { + sc.queuedControlFrames-- + } + sc.startFrameWrite(wr) + continue + } + } + if sc.needsFrameFlush { + sc.startFrameWrite(FrameWriteRequest{write: flushFrameWriter{}}) + sc.needsFrameFlush = false // after startFrameWrite, since it sets this true + continue + } + break + } + sc.inFrameScheduleLoop = false + } // startGracefulShutdown gracefully shuts down a connection. This + // sends GOAWAY with ErrCodeNo to tell the client we're gracefully + // shutting down. The connection isn't closed until all current + // streams are done. + // + // startGracefulShutdown returns immediately; it does not wait until + // the connection has shut down. + func (sc *serverConn) startGracefulShutdown() { + sc.serveG.checkNotOn() // NOT + sc.shutdownOnce.Do(func() { sc.sendServeMsg(gracefulShutdownMsg) }) + } // After sending GOAWAY with an error code (non-graceful shutdown), the + // connection will close after goAwayTimeout. + // + // If we close the connection immediately after sending GOAWAY, there may + // be unsent data in our kernel receive buffer, which will cause the kernel + // to send a TCP RST on close() instead of a FIN. This RST will abort the + // connection immediately, whether or not the client had received the GOAWAY. + // + // Ideally we should delay for at least 1 RTT + epsilon so the client has + // a chance to read the GOAWAY and stop sending messages. Measuring RTT + // is hard, so we approximate with 1 second. See golang.org/issue/18701. + // + // This is a var so it can be shorter in tests, where all requests uses the + // loopback interface making the expected RTT very small. + // + // TODO: configurable? + var goAwayTimeout = 1 * time.Second func (sc *serverConn) startGracefulShutdownInternal() { + sc.goAway(ErrCodeNo) + } func (sc *serverConn) goAway(code ErrCode) { + sc.serveG.check() + if sc.inGoAway { + if sc.goAwayCode == ErrCodeNo { + sc.goAwayCode = code + } + return + } + sc.inGoAway = true + sc.needToSendGoAway = true + sc.goAwayCode = code + sc.scheduleFrameWrite() + } func (sc *serverConn) shutDownIn(d time.Duration) { + sc.serveG.check() + sc.shutdownTimer = time.AfterFunc(d, sc.onShutdownTimer) + } func (sc *serverConn) resetStream(se StreamError) { + sc.serveG.check() + sc.writeFrame(FrameWriteRequest{write: se}) + if st, ok := sc.streams[se.StreamID]; ok { + st.resetQueued = true + } + } // processFrameFromReader processes the serve loop's read from readFrameCh from the + // frame-reading goroutine. + // processFrameFromReader returns whether the connection should be kept open. + func (sc *serverConn) processFrameFromReader(res readFrameResult) bool { + sc.serveG.check() + err := res.err + if err != nil { + if err == ErrFrameTooLarge { + sc.goAway(ErrCodeFrameSize) + return true // goAway will close the loop + } + clientGone := err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) + if clientGone { + // TODO: could we also get into this state if + // the peer does a half close + // (e.g. CloseWrite) because they're done + // sending frames but they're still wanting + // our open replies? Investigate. + // TODO: add CloseWrite to crypto/tls.Conn first + // so we have a way to test this? I suppose + // just for testing we could have a non-TLS mode. + return false + } + } else { + f := res.f + if VerboseLogs { + sc.vlogf("http2: server read frame %v", summarizeFrame(f)) + } + err = sc.processFrame(f) + if err == nil { + return true + } + } switch ev := err.(type) { + case StreamError: + sc.resetStream(ev) + return true + case goAwayFlowError: + sc.goAway(ErrCodeFlowControl) + return true + case ConnectionError: + if res.f != nil { + if id := res.f.Header().StreamID; id > sc.maxClientStreamID { + sc.maxClientStreamID = id + } + } + sc.logf("http2: server connection error from %v: %v", sc.conn.RemoteAddr(), ev) + sc.goAway(ErrCode(ev)) + return true // goAway will handle shutdown + default: + if res.err != nil { + sc.vlogf("http2: server closing client connection; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err) + } else { + sc.logf("http2: server closing client connection: %v", err) + } + return false + } + } func (sc *serverConn) processFrame(f Frame) error { + sc.serveG.check() // First frame received must be SETTINGS. + if !sc.sawFirstSettings { + if _, ok := f.(*SettingsFrame); !ok { + return sc.countError("first_settings", ConnectionError(ErrCodeProtocol)) + } + sc.sawFirstSettings = true + } // Discard frames for streams initiated after the identified last + // stream sent in a GOAWAY, or all frames after sending an error. + // We still need to return connection-level flow control for DATA frames. + // RFC 9113 Section 6.8. + if sc.inGoAway && (sc.goAwayCode != ErrCodeNo || f.Header().StreamID > sc.maxClientStreamID) { if f, ok := f.(*DataFrame); ok { + if !sc.inflow.take(f.Length) { + return sc.countError("data_flow", streamError(f.Header().StreamID, ErrCodeFlowControl)) + } + sc.sendWindowUpdate(nil, int(f.Length)) // conn-level + } + return nil + } switch f := f.(type) { + case *SettingsFrame: + return sc.processSettings(f) + case *MetaHeadersFrame: + return sc.processHeaders(f) + case *WindowUpdateFrame: + return sc.processWindowUpdate(f) + case *PingFrame: + return sc.processPing(f) + case *DataFrame: + return sc.processData(f) + case *RSTStreamFrame: + return sc.processResetStream(f) + case *PriorityFrame: + return sc.processPriority(f) + case *GoAwayFrame: + return sc.processGoAway(f) + case *PushPromiseFrame: + // A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE + // frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR. + return sc.countError("push_promise", ConnectionError(ErrCodeProtocol)) + default: + sc.vlogf("http2: server ignoring frame: %v", f.Header()) + return nil + } + } func (sc *serverConn) processPing(f *PingFrame) error { + sc.serveG.check() + if f.IsAck() { + // 6.7 PING: " An endpoint MUST NOT respond to PING frames + // containing this flag." + return nil + } + if f.StreamID != 0 { + // "PING frames are not associated with any individual + // stream. If a PING frame is received with a stream + // identifier field value other than 0x0, the recipient MUST + // respond with a connection error (Section 5.4.1) of type + // PROTOCOL_ERROR." + return sc.countError("ping_on_stream", ConnectionError(ErrCodeProtocol)) + } + sc.writeFrame(FrameWriteRequest{write: writePingAck{f}}) + return nil + } func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error { + sc.serveG.check() + switch { + case f.StreamID != 0: // stream-level flow control + state, st := sc.state(f.StreamID) + if state == stateIdle { + // Section 5.1: "Receiving any frame other than HEADERS + // or PRIORITY on a stream in this state MUST be + // treated as a connection error (Section 5.4.1) of + // type PROTOCOL_ERROR." + return sc.countError("stream_idle", ConnectionError(ErrCodeProtocol)) + } + if st == nil { + // "WINDOW_UPDATE can be sent by a peer that has sent a + // frame bearing the END_STREAM flag. This means that a + // receiver could receive a WINDOW_UPDATE frame on a "half + // closed (remote)" or "closed" stream. A receiver MUST + // NOT treat this as an error, see Section 5.1." + return nil + } + if !st.flow.add(int32(f.Increment)) { + return sc.countError("bad_flow", streamError(f.StreamID, ErrCodeFlowControl)) + } + default: // connection-level flow control + if !sc.flow.add(int32(f.Increment)) { + return goAwayFlowError{} + } + } + sc.scheduleFrameWrite() + return nil + } func (sc *serverConn) processResetStream(f *RSTStreamFrame) error { + sc.serveG.check() state, st := sc.state(f.StreamID) + if state == stateIdle { + // 6.4 "RST_STREAM frames MUST NOT be sent for a + // stream in the "idle" state. If a RST_STREAM frame + // identifying an idle stream is received, the + // recipient MUST treat this as a connection error + // (Section 5.4.1) of type PROTOCOL_ERROR. + return sc.countError("reset_idle_stream", ConnectionError(ErrCodeProtocol)) + } + if st != nil { + st.cancelCtx() + sc.closeStream(st, streamError(f.StreamID, f.ErrCode)) + } + return nil + } func (sc *serverConn) closeStream(st *stream, err error) { + sc.serveG.check() + if st.state == stateIdle || st.state == stateClosed { + panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state)) + } + st.state = stateClosed + if st.readDeadline != nil { + st.readDeadline.Stop() + } + if st.writeDeadline != nil { + st.writeDeadline.Stop() + } + if st.isPushed() { + sc.curPushedStreams-- + } else { + sc.curClientStreams-- + } + delete(sc.streams, st.id) + if len(sc.streams) == 0 { + sc.setConnState(http.StateIdle) + if sc.srv.IdleTimeout > 0 { + sc.idleTimer.Reset(sc.srv.IdleTimeout) + } + if h1ServerKeepAlivesDisabled(sc.hs) { + sc.startGracefulShutdownInternal() + } + } + if p := st.body; p != nil { + // Return any buffered unread bytes worth of conn-level flow control. + // See golang.org/issue/16481 + sc.sendWindowUpdate(nil, p.Len()) p.CloseWithError(err) + } + if e, ok := err.(StreamError); ok { + if e.Cause != nil { + err = e.Cause + } else { + err = errStreamClosed + } + } + st.closeErr = err + st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc + sc.writeSched.CloseStream(st.id) + } func (sc *serverConn) processSettings(f *SettingsFrame) error { + sc.serveG.check() + if f.IsAck() { + sc.unackedSettings-- + if sc.unackedSettings < 0 { + // Why is the peer ACKing settings we never sent? + // The spec doesn't mention this case, but + // hang up on them anyway. + return sc.countError("ack_mystery", ConnectionError(ErrCodeProtocol)) + } + return nil + } + if f.NumSettings() > 100 || f.HasDuplicates() { + // This isn't actually in the spec, but hang up on + // suspiciously large settings frames or those with + // duplicate entries. + return sc.countError("settings_big_or_dups", ConnectionError(ErrCodeProtocol)) + } + if err := f.ForeachSetting(sc.processSetting); err != nil { + return err + } + // TODO: judging by RFC 7540, Section 6.5.3 each SETTINGS frame should be + // acknowledged individually, even if multiple are received before the ACK. + sc.needToSendSettingsAck = true + sc.scheduleFrameWrite() + return nil + } func (sc *serverConn) processSetting(s Setting) error { + sc.serveG.check() + if err := s.Valid(); err != nil { + return err + } + if VerboseLogs { + sc.vlogf("http2: server processing setting %v", s) + } + switch s.ID { + case SettingHeaderTableSize: + sc.hpackEncoder.SetMaxDynamicTableSize(s.Val) + case SettingEnablePush: + sc.pushEnabled = s.Val != 0 + case SettingMaxConcurrentStreams: + sc.clientMaxStreams = s.Val + case SettingInitialWindowSize: + return sc.processSettingInitialWindowSize(s.Val) + case SettingMaxFrameSize: + sc.maxFrameSize = int32(s.Val) // the maximum valid s.Val is < 2^31 + case SettingMaxHeaderListSize: + sc.peerMaxHeaderListSize = s.Val + default: + // Unknown setting: "An endpoint that receives a SETTINGS + // frame with any unknown or unsupported identifier MUST + // ignore that setting." + if VerboseLogs { + sc.vlogf("http2: server ignoring unknown setting %v", s) + } + } + return nil + } func (sc *serverConn) processSettingInitialWindowSize(val uint32) error { + sc.serveG.check() + // Note: val already validated to be within range by + // processSetting's Valid call. // "A SETTINGS frame can alter the initial flow control window + // size for all current streams. When the value of + // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST + // adjust the size of all stream flow control windows that it + // maintains by the difference between the new value and the + // old value." + old := sc.initialStreamSendWindowSize + sc.initialStreamSendWindowSize = int32(val) + growth := int32(val) - old // may be negative + for _, st := range sc.streams { + if !st.flow.add(growth) { + // 6.9.2 Initial Flow Control Window Size + // "An endpoint MUST treat a change to + // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow + // control window to exceed the maximum size as a + // connection error (Section 5.4.1) of type + // FLOW_CONTROL_ERROR." + return sc.countError("setting_win_size", ConnectionError(ErrCodeFlowControl)) + } + } + return nil + } func (sc *serverConn) processData(f *DataFrame) error { + sc.serveG.check() + id := f.Header().StreamID data := f.Data() + state, st := sc.state(id) + if id == 0 || state == stateIdle { + // Section 6.1: "DATA frames MUST be associated with a + // stream. If a DATA frame is received whose stream + // identifier field is 0x0, the recipient MUST respond + // with a connection error (Section 5.4.1) of type + // PROTOCOL_ERROR." + // + // Section 5.1: "Receiving any frame other than HEADERS + // or PRIORITY on a stream in this state MUST be + // treated as a connection error (Section 5.4.1) of + // type PROTOCOL_ERROR." + return sc.countError("data_on_idle", ConnectionError(ErrCodeProtocol)) + } // "If a DATA frame is received whose stream is not in "open" + // or "half closed (local)" state, the recipient MUST respond + // with a stream error (Section 5.4.2) of type STREAM_CLOSED." + if st == nil || state != stateOpen || st.gotTrailerHeader || st.resetQueued { + // This includes sending a RST_STREAM if the stream is + // in stateHalfClosedLocal (which currently means that + // the http.Handler returned, so it's done reading & + // done writing). Try to stop the client from sending + // more DATA. // But still enforce their connection-level flow control, + // and return any flow control bytes since we're not going + // to consume them. + if !sc.inflow.take(f.Length) { + return sc.countError("data_flow", streamError(id, ErrCodeFlowControl)) + } + sc.sendWindowUpdate(nil, int(f.Length)) // conn-level if st != nil && st.resetQueued { + // Already have a stream error in flight. Don't send another. + return nil + } + return sc.countError("closed", streamError(id, ErrCodeStreamClosed)) + } + if st.body == nil { + panic("internal error: should have a body in this state") + } // Sender sending more than they'd declared? + if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes { + if !sc.inflow.take(f.Length) { + return sc.countError("data_flow", streamError(id, ErrCodeFlowControl)) + } + sc.sendWindowUpdate(nil, int(f.Length)) // conn-level st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes)) + // RFC 7540, sec 8.1.2.6: A request or response is also malformed if the + // value of a content-length header field does not equal the sum of the + // DATA frame payload lengths that form the body. + return sc.countError("send_too_much", streamError(id, ErrCodeProtocol)) + } + if f.Length > 0 { + // Check whether the client has flow control quota. + if !takeInflows(&sc.inflow, &st.inflow, f.Length) { + return sc.countError("flow_on_data_length", streamError(id, ErrCodeFlowControl)) + } if len(data) > 0 { + st.bodyBytes += int64(len(data)) + wrote, err := st.body.Write(data) + if err != nil { + // The handler has closed the request body. + // Return the connection-level flow control for the discarded data, + // but not the stream-level flow control. + sc.sendWindowUpdate(nil, int(f.Length)-wrote) + return nil + } + if wrote != len(data) { + panic("internal error: bad Writer") + } + } // Return any padded flow control now, since we won't + // refund it later on body reads. + // Call sendWindowUpdate even if there is no padding, + // to return buffered flow control credit if the sent + // window has shrunk. + pad := int32(f.Length) - int32(len(data)) + sc.sendWindowUpdate32(nil, pad) + sc.sendWindowUpdate32(st, pad) + } + if f.StreamEnded() { + st.endStream() + } + return nil + } func (sc *serverConn) processGoAway(f *GoAwayFrame) error { + sc.serveG.check() + if f.ErrCode != ErrCodeNo { + sc.logf("http2: received GOAWAY %+v, starting graceful shutdown", f) + } else { + sc.vlogf("http2: received GOAWAY %+v, starting graceful shutdown", f) + } + sc.startGracefulShutdownInternal() + // http://tools.ietf.org/html/rfc7540#section-6.8 + // We should not create any new streams, which means we should disable push. + sc.pushEnabled = false + return nil + } // isPushed reports whether the stream is server-initiated. + func (st *stream) isPushed() bool { + return st.id%2 == 0 + } // endStream closes a Request.Body's pipe. It is called when a DATA + // frame says a request body is over (or after trailers). + func (st *stream) endStream() { + sc := st.sc + sc.serveG.check() if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes { + st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes", + st.declBodyBytes, st.bodyBytes)) + } else { + st.body.closeWithErrorAndCode(io.EOF, st.copyTrailersToHandlerRequest) + st.body.CloseWithError(io.EOF) + } + st.state = stateHalfClosedRemote + } // copyTrailersToHandlerRequest is run in the Handler's goroutine in + // its Request.Body.Read just before it gets io.EOF. + func (st *stream) copyTrailersToHandlerRequest() { + for k, vv := range st.trailer { + if _, ok := st.reqTrailer[k]; ok { + // Only copy it over it was pre-declared. + st.reqTrailer[k] = vv + } + } + } // onReadTimeout is run on its own goroutine (from time.AfterFunc) + // when the stream's ReadTimeout has fired. + func (st *stream) onReadTimeout() { + if st.body != nil { + // Wrap the ErrDeadlineExceeded to avoid callers depending on us + // returning the bare error. + st.body.CloseWithError(fmt.Errorf("%w", os.ErrDeadlineExceeded)) + } + } // onWriteTimeout is run on its own goroutine (from time.AfterFunc) + // when the stream's WriteTimeout has fired. + func (st *stream) onWriteTimeout() { + st.sc.writeFrameFromHandler(FrameWriteRequest{write: StreamError{ + StreamID: st.id, - Code: ErrCodeInternal, - Cause: os.ErrDeadlineExceeded, + + Code: ErrCodeInternal, + + Cause: os.ErrDeadlineExceeded, }}) + } func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error { + sc.serveG.check() + id := f.StreamID + // http://tools.ietf.org/html/rfc7540#section-5.1.1 + // Streams initiated by a client MUST use odd-numbered stream + // identifiers. [...] An endpoint that receives an unexpected + // stream identifier MUST respond with a connection error + // (Section 5.4.1) of type PROTOCOL_ERROR. + if id%2 != 1 { + return sc.countError("headers_even", ConnectionError(ErrCodeProtocol)) + } + // A HEADERS frame can be used to create a new stream or + // send a trailer for an open one. If we already have a stream + // open, let it process its own HEADERS frame (trailers at this + // point, if it's valid). + if st := sc.streams[f.StreamID]; st != nil { + if st.resetQueued { + // We're sending RST_STREAM to close the stream, so don't bother + // processing this frame. + return nil + } + // RFC 7540, sec 5.1: If an endpoint receives additional frames, other than + // WINDOW_UPDATE, PRIORITY, or RST_STREAM, for a stream that is in + // this state, it MUST respond with a stream error (Section 5.4.2) of + // type STREAM_CLOSED. + if st.state == stateHalfClosedRemote { + return sc.countError("headers_half_closed", streamError(id, ErrCodeStreamClosed)) + } + return st.processTrailerHeaders(f) + } // [...] The identifier of a newly established stream MUST be + // numerically greater than all streams that the initiating + // endpoint has opened or reserved. [...] An endpoint that + // receives an unexpected stream identifier MUST respond with + // a connection error (Section 5.4.1) of type PROTOCOL_ERROR. + if id <= sc.maxClientStreamID { + return sc.countError("stream_went_down", ConnectionError(ErrCodeProtocol)) + } + sc.maxClientStreamID = id if sc.idleTimer != nil { + sc.idleTimer.Stop() + } // http://tools.ietf.org/html/rfc7540#section-5.1.2 + // [...] Endpoints MUST NOT exceed the limit set by their peer. An + // endpoint that receives a HEADERS frame that causes their + // advertised concurrent stream limit to be exceeded MUST treat + // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR + // or REFUSED_STREAM. + if sc.curClientStreams+1 > sc.advMaxStreams { + if sc.unackedSettings == 0 { + // They should know better. + return sc.countError("over_max_streams", streamError(id, ErrCodeProtocol)) + } + // Assume it's a network race, where they just haven't + // received our last SETTINGS update. But actually + // this can't happen yet, because we don't yet provide + // a way for users to adjust server parameters at + // runtime. + return sc.countError("over_max_streams_race", streamError(id, ErrCodeRefusedStream)) + } initialState := stateOpen + if f.StreamEnded() { + initialState = stateHalfClosedRemote + } + st := sc.newStream(id, 0, initialState) if f.HasPriority() { + if err := sc.checkPriority(f.StreamID, f.Priority); err != nil { + return err + } + sc.writeSched.AdjustStream(st.id, f.Priority) + } rw, req, err := sc.newWriterAndRequest(st, f) + if err != nil { + return err + } + st.reqTrailer = req.Trailer + if st.reqTrailer != nil { + st.trailer = make(http.Header) + } + st.body = req.Body.(*requestBody).pipe // may be nil + st.declBodyBytes = req.ContentLength handler := sc.handler.ServeHTTP + if f.Truncated { + // Their header list was too long. Send a 431 error. + handler = handleHeaderListTooLong + } else if err := checkValidHTTP2RequestHeaders(req.Header); err != nil { + handler = new400Handler(err) + } // The net/http package sets the read deadline from the + // http.Server.ReadTimeout during the TLS handshake, but then + // passes the connection off to us with the deadline already + // set. Disarm it here after the request headers are read, + // similar to how the http1 server works. Here it's + // technically more like the http1 Server's ReadHeaderTimeout + // (in Go 1.8), though. That's a more sane option anyway. + if sc.hs.ReadTimeout > 0 { + sc.conn.SetReadDeadline(time.Time{}) + st.readDeadline = time.AfterFunc(sc.hs.ReadTimeout, st.onReadTimeout) + } return sc.scheduleHandler(id, rw, req, handler) + } func (sc *serverConn) upgradeRequest(req *http.Request) { + sc.serveG.check() + id := uint32(1) + sc.maxClientStreamID = id + st := sc.newStream(id, 0, stateHalfClosedRemote) + st.reqTrailer = req.Trailer + if st.reqTrailer != nil { + st.trailer = make(http.Header) + } + rw := sc.newResponseWriter(st, req) // Disable any read deadline set by the net/http package + // prior to the upgrade. + if sc.hs.ReadTimeout > 0 { + sc.conn.SetReadDeadline(time.Time{}) + } // This is the first request on the connection, + // so start the handler directly rather than going + // through scheduleHandler. + sc.curHandlers++ + go sc.runHandler(rw, req, sc.handler.ServeHTTP) + } func (st *stream) processTrailerHeaders(f *MetaHeadersFrame) error { + sc := st.sc + sc.serveG.check() + if st.gotTrailerHeader { + return sc.countError("dup_trailers", ConnectionError(ErrCodeProtocol)) + } + st.gotTrailerHeader = true + if !f.StreamEnded() { + return sc.countError("trailers_not_ended", streamError(st.id, ErrCodeProtocol)) + } if len(f.PseudoFields()) > 0 { + return sc.countError("trailers_pseudo", streamError(st.id, ErrCodeProtocol)) + } + if st.trailer != nil { + for _, hf := range f.RegularFields() { + key := sc.canonicalHeader(hf.Name) + if !httpguts.ValidTrailerHeader(key) { + // TODO: send more details to the peer somehow. But http2 has + // no way to send debug data at a stream level. Discuss with + // HTTP folk. + return sc.countError("trailers_bogus", streamError(st.id, ErrCodeProtocol)) + } + st.trailer[key] = append(st.trailer[key], hf.Value) + } + } + st.endStream() + return nil + } func (sc *serverConn) checkPriority(streamID uint32, p PriorityParam) error { + if streamID == p.StreamDep { + // Section 5.3.1: "A stream cannot depend on itself. An endpoint MUST treat + // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR." + // Section 5.3.3 says that a stream can depend on one of its dependencies, + // so it's only self-dependencies that are forbidden. + return sc.countError("priority", streamError(streamID, ErrCodeProtocol)) + } + return nil + } func (sc *serverConn) processPriority(f *PriorityFrame) error { + if err := sc.checkPriority(f.StreamID, f.PriorityParam); err != nil { + return err + } + sc.writeSched.AdjustStream(f.StreamID, f.PriorityParam) + return nil + } func (sc *serverConn) newStream(id, pusherID uint32, state streamState) *stream { + sc.serveG.check() + if id == 0 { + panic("internal error: cannot create stream with id 0") + } ctx, cancelCtx := context.WithCancel(sc.baseCtx) + st := &stream{ - sc: sc, - id: id, - state: state, - ctx: ctx, + + sc: sc, + + id: id, + + state: state, + + ctx: ctx, + cancelCtx: cancelCtx, } + st.cw.Init() + st.flow.conn = &sc.flow // link to conn-level counter + st.flow.add(sc.initialStreamSendWindowSize) + st.inflow.init(sc.srv.initialStreamRecvWindowSize()) + if sc.hs.WriteTimeout > 0 { + st.writeDeadline = time.AfterFunc(sc.hs.WriteTimeout, st.onWriteTimeout) + } sc.streams[id] = st + sc.writeSched.OpenStream(st.id, OpenStreamOptions{PusherID: pusherID}) + if st.isPushed() { + sc.curPushedStreams++ + } else { + sc.curClientStreams++ + } + if sc.curOpenStreams() == 1 { + sc.setConnState(http.StateActive) + } return st + } func (sc *serverConn) newWriterAndRequest(st *stream, f *MetaHeadersFrame) (*responseWriter, *http.Request, error) { + sc.serveG.check() rp := requestParam{ - method: f.PseudoValue("method"), - scheme: f.PseudoValue("scheme"), + + method: f.PseudoValue("method"), + + scheme: f.PseudoValue("scheme"), + authority: f.PseudoValue("authority"), - path: f.PseudoValue("path"), + + path: f.PseudoValue("path"), } isConnect := rp.method == "CONNECT" + if isConnect { + if rp.path != "" || rp.scheme != "" || rp.authority == "" { + return nil, nil, sc.countError("bad_connect", streamError(f.StreamID, ErrCodeProtocol)) + } + } else if rp.method == "" || rp.path == "" || (rp.scheme != "https" && rp.scheme != "http") { + // See 8.1.2.6 Malformed Requests and Responses: + // + // Malformed requests or responses that are detected + // MUST be treated as a stream error (Section 5.4.2) + // of type PROTOCOL_ERROR." + // + // 8.1.2.3 Request Pseudo-Header Fields + // "All HTTP/2 requests MUST include exactly one valid + // value for the :method, :scheme, and :path + // pseudo-header fields" + return nil, nil, sc.countError("bad_path_method", streamError(f.StreamID, ErrCodeProtocol)) + } rp.header = make(http.Header) + for _, hf := range f.RegularFields() { + rp.header.Add(sc.canonicalHeader(hf.Name), hf.Value) + } + if rp.authority == "" { + rp.authority = rp.header.Get("Host") + } rw, req, err := sc.newWriterAndRequestNoBody(st, rp) + if err != nil { + return nil, nil, err + } + bodyOpen := !f.StreamEnded() + if bodyOpen { + if vv, ok := rp.header["Content-Length"]; ok { + if cl, err := strconv.ParseUint(vv[0], 10, 63); err == nil { + req.ContentLength = int64(cl) + } else { + req.ContentLength = 0 + } + } else { + req.ContentLength = -1 + } + req.Body.(*requestBody).pipe = &pipe{ + b: &dataBuffer{expected: req.ContentLength}, } + } + return rw, req, nil + } type requestParam struct { - method string + method string + scheme, authority, path string - header http.Header + + header http.Header } func (sc *serverConn) newWriterAndRequestNoBody(st *stream, rp requestParam) (*responseWriter, *http.Request, error) { + sc.serveG.check() var tlsState *tls.ConnectionState // nil if not scheme https + if rp.scheme == "https" { + tlsState = sc.tlsState + } needsContinue := httpguts.HeaderValuesContainsToken(rp.header["Expect"], "100-continue") + if needsContinue { + rp.header.Del("Expect") + } + // Merge Cookie headers into one "; "-delimited value. + if cookies := rp.header["Cookie"]; len(cookies) > 1 { + rp.header.Set("Cookie", strings.Join(cookies, "; ")) + } // Setup Trailers + var trailer http.Header + for _, v := range rp.header["Trailer"] { + for _, key := range strings.Split(v, ",") { + key = http.CanonicalHeaderKey(textproto.TrimString(key)) + switch key { + case "Transfer-Encoding", "Trailer", "Content-Length": + // Bogus. (copy of http1 rules) + // Ignore. + default: + if trailer == nil { + trailer = make(http.Header) + } + trailer[key] = nil + } + } + } + delete(rp.header, "Trailer") var url_ *url.URL + var requestURI string + if rp.method == "CONNECT" { + url_ = &url.URL{Host: rp.authority} + requestURI = rp.authority // mimic HTTP/1 server behavior + } else { + var err error + url_, err = url.ParseRequestURI(rp.path) + if err != nil { + return nil, nil, sc.countError("bad_path", streamError(st.id, ErrCodeProtocol)) + } + requestURI = rp.path + } body := &requestBody{ - conn: sc, - stream: st, + + conn: sc, + + stream: st, + needsContinue: needsContinue, } + req := &http.Request{ - Method: rp.method, - URL: url_, + + Method: rp.method, + + URL: url_, + RemoteAddr: sc.remoteAddrStr, - Header: rp.header, + + Header: rp.header, + RequestURI: requestURI, - Proto: "HTTP/2.0", + + Proto: "HTTP/2.0", + ProtoMajor: 2, + ProtoMinor: 0, - TLS: tlsState, - Host: rp.authority, - Body: body, - Trailer: trailer, + + TLS: tlsState, + + Host: rp.authority, + + Body: body, + + Trailer: trailer, } + req = req.WithContext(st.ctx) rw := sc.newResponseWriter(st, req) + return rw, req, nil + } func (sc *serverConn) newResponseWriter(st *stream, req *http.Request) *responseWriter { + rws := responseWriterStatePool.Get().(*responseWriterState) + bwSave := rws.bw + *rws = responseWriterState{} // zero all the fields + rws.conn = sc + rws.bw = bwSave + rws.bw.Reset(chunkWriter{rws}) + rws.stream = st + rws.req = req + return &responseWriter{rws: rws} + } type unstartedHandler struct { streamID uint32 - rw *responseWriter - req *http.Request - handler func(http.ResponseWriter, *http.Request) + + rw *responseWriter + + req *http.Request + + handler func(http.ResponseWriter, *http.Request) } // scheduleHandler starts a handler goroutine, + // or schedules one to start as soon as an existing handler finishes. + func (sc *serverConn) scheduleHandler(streamID uint32, rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) error { + sc.serveG.check() + maxHandlers := sc.advMaxStreams + if sc.curHandlers < maxHandlers { + sc.curHandlers++ + go sc.runHandler(rw, req, handler) + return nil + } + if len(sc.unstartedHandlers) > int(4*sc.advMaxStreams) { + return sc.countError("too_many_early_resets", ConnectionError(ErrCodeEnhanceYourCalm)) + } + sc.unstartedHandlers = append(sc.unstartedHandlers, unstartedHandler{ + streamID: streamID, - rw: rw, - req: req, - handler: handler, + + rw: rw, + + req: req, + + handler: handler, }) + return nil + } func (sc *serverConn) handlerDone() { + sc.serveG.check() + sc.curHandlers-- + i := 0 + maxHandlers := sc.advMaxStreams + for ; i < len(sc.unstartedHandlers); i++ { + u := sc.unstartedHandlers[i] + if sc.streams[u.streamID] == nil { + // This stream was reset before its goroutine had a chance to start. + continue + } + if sc.curHandlers >= maxHandlers { + break + } + sc.curHandlers++ + go sc.runHandler(u.rw, u.req, u.handler) + sc.unstartedHandlers[i] = unstartedHandler{} // don't retain references + } + sc.unstartedHandlers = sc.unstartedHandlers[i:] + if len(sc.unstartedHandlers) == 0 { + sc.unstartedHandlers = nil + } + } // Run on its own goroutine. + func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) { + defer sc.sendServeMsg(handlerDoneMsg) + didPanic := true + defer func() { + rw.rws.stream.cancelCtx() + if req.MultipartForm != nil { + req.MultipartForm.RemoveAll() + } + if didPanic { + e := recover() + sc.writeFrameFromHandler(FrameWriteRequest{ - write: handlerPanicRST{rw.rws.stream.id}, + + write: handlerPanicRST{rw.rws.stream.id}, + stream: rw.rws.stream, }) + // Same as net/http: + if e != nil && e != http.ErrAbortHandler { + const size = 64 << 10 + buf := make([]byte, size) + buf = buf[:runtime.Stack(buf, false)] + sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf) + } + return + } + rw.handlerDone() + }() + handler(rw, req) + didPanic = false + } func handleHeaderListTooLong(w http.ResponseWriter, r *http.Request) { + // 10.5.1 Limits on Header Block Size: + // .. "A server that receives a larger header block than it is + // willing to handle can send an HTTP 431 (Request Header Fields Too + // Large) status code" + const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+ + w.WriteHeader(statusRequestHeaderFieldsTooLarge) + io.WriteString(w, "

HTTP Error 431

Request Header Field(s) Too Large

") + } // called from handler goroutines. + // h may be nil. + func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) error { + sc.serveG.checkNotOn() // NOT on + var errc chan error + if headerData.h != nil { + // If there's a header map (which we don't own), so we have to block on + // waiting for this frame to be written, so an http.Flush mid-handler + // writes out the correct value of keys, before a handler later potentially + // mutates it. + errc = errChanPool.Get().(chan error) + } + if err := sc.writeFrameFromHandler(FrameWriteRequest{ - write: headerData, + + write: headerData, + stream: st, - done: errc, + + done: errc, }); err != nil { + return err + } + if errc != nil { + select { + case err := <-errc: + errChanPool.Put(errc) + return err + case <-sc.doneServing: + return errClientDisconnected + case <-st.cw: + return errStreamClosed + } + } + return nil + } // called from handler goroutines. + func (sc *serverConn) write100ContinueHeaders(st *stream) { + sc.writeFrameFromHandler(FrameWriteRequest{ - write: write100ContinueHeadersFrame{st.id}, + + write: write100ContinueHeadersFrame{st.id}, + stream: st, }) + } // A bodyReadMsg tells the server loop that the http.Handler read n + // bytes of the DATA from the client on the given stream. + type bodyReadMsg struct { st *stream - n int + + n int } // called from handler goroutines. + // Notes that the handler for the given stream ID read n bytes of its body + // and schedules flow control tokens to be sent. + func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int, err error) { + sc.serveG.checkNotOn() // NOT on + if n > 0 { + select { + case sc.bodyReadCh <- bodyReadMsg{st, n}: + case <-sc.doneServing: + } + } + } func (sc *serverConn) noteBodyRead(st *stream, n int) { + sc.serveG.check() + sc.sendWindowUpdate(nil, n) // conn-level + if st.state != stateHalfClosedRemote && st.state != stateClosed { + // Don't send this WINDOW_UPDATE if the stream is closed + // remotely. + sc.sendWindowUpdate(st, n) + } + } // st may be nil for conn-level + func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) { + sc.sendWindowUpdate(st, int(n)) + } // st may be nil for conn-level + func (sc *serverConn) sendWindowUpdate(st *stream, n int) { + sc.serveG.check() + var streamID uint32 + var send int32 + if st == nil { + send = sc.inflow.add(n) + } else { + streamID = st.id + send = st.inflow.add(n) + } + if send == 0 { + return + } + sc.writeFrame(FrameWriteRequest{ - write: writeWindowUpdate{streamID: streamID, n: uint32(send)}, + + write: writeWindowUpdate{streamID: streamID, n: uint32(send)}, + stream: st, }) + } // requestBody is the Handler's Request.Body type. + // Read and Close may be called concurrently. + type requestBody struct { - _ incomparable - stream *stream - conn *serverConn - closeOnce sync.Once // for use by Close only - sawEOF bool // for use by Read only - pipe *pipe // non-nil if we have an HTTP entity message body - needsContinue bool // need to send a 100-continue + _ incomparable + + stream *stream + + conn *serverConn + + closeOnce sync.Once // for use by Close only + + sawEOF bool // for use by Read only + + pipe *pipe // non-nil if we have an HTTP entity message body + + needsContinue bool // need to send a 100-continue + } func (b *requestBody) Close() error { + b.closeOnce.Do(func() { + if b.pipe != nil { + b.pipe.BreakWithError(errClosedBody) + } + }) + return nil + } func (b *requestBody) Read(p []byte) (n int, err error) { + if b.needsContinue { + b.needsContinue = false + b.conn.write100ContinueHeaders(b.stream) + } + if b.pipe == nil || b.sawEOF { + return 0, io.EOF + } + n, err = b.pipe.Read(p) + if err == io.EOF { + b.sawEOF = true + } + if b.conn == nil && inTests { + return + } + b.conn.noteBodyReadFromHandler(b.stream, n, err) + return + } // responseWriter is the http.ResponseWriter implementation. It's + // intentionally small (1 pointer wide) to minimize garbage. The + // responseWriterState pointer inside is zeroed at the end of a + // request (in handlerDone) and calls on the responseWriter thereafter + // simply crash (caller's mistake), but the much larger responseWriterState + // and buffers are reused between multiple requests. + type responseWriter struct { rws *responseWriterState } // Optional http.ResponseWriter interfaces implemented. + var ( _ http.CloseNotifier = (*responseWriter)(nil) - _ http.Flusher = (*responseWriter)(nil) - _ stringWriter = (*responseWriter)(nil) + + _ http.Flusher = (*responseWriter)(nil) + + _ stringWriter = (*responseWriter)(nil) ) type responseWriterState struct { + // immutable within a request: + stream *stream - req *http.Request - conn *serverConn + + req *http.Request + + conn *serverConn // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc + bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState} // mutated by http.Handler goroutine: + handlerHeader http.Header // nil until called - snapHeader http.Header // snapshot of handlerHeader at WriteHeader time - trailers []string // set in writeChunk - status int // status code passed to WriteHeader - wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet. - sentHeader bool // have we sent the header frame? - handlerDone bool // handler has finished + + snapHeader http.Header // snapshot of handlerHeader at WriteHeader time + + trailers []string // set in writeChunk + + status int // status code passed to WriteHeader + + wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet. + + sentHeader bool // have we sent the header frame? + + handlerDone bool // handler has finished sentContentLen int64 // non-zero if handler set a Content-Length header - wroteBytes int64 + + wroteBytes int64 closeNotifierMu sync.Mutex // guards closeNotifierCh - closeNotifierCh chan bool // nil until first used + + closeNotifierCh chan bool // nil until first used + } type chunkWriter struct{ rws *responseWriterState } func (cw chunkWriter) Write(p []byte) (n int, err error) { + n, err = cw.rws.writeChunk(p) + if err == errStreamClosed { + // If writing failed because the stream has been closed, + // return the reason it was closed. + err = cw.rws.stream.closeErr + } + return n, err + } func (rws *responseWriterState) hasTrailers() bool { return len(rws.trailers) > 0 } func (rws *responseWriterState) hasNonemptyTrailers() bool { + for _, trailer := range rws.trailers { + if _, ok := rws.handlerHeader[trailer]; ok { + return true + } + } + return false + } // declareTrailer is called for each Trailer header when the + // response header is written. It notes that a header will need to be + // written in the trailers at the end of the response. + func (rws *responseWriterState) declareTrailer(k string) { + k = http.CanonicalHeaderKey(k) + if !httpguts.ValidTrailerHeader(k) { + // Forbidden by RFC 7230, section 4.1.2. + rws.conn.logf("ignoring invalid trailer %q", k) + return + } + if !strSliceContains(rws.trailers, k) { + rws.trailers = append(rws.trailers, k) + } + } // writeChunk writes chunks from the bufio.Writer. But because + // bufio.Writer may bypass its chunking, sometimes p may be + // arbitrarily large. + // + // writeChunk is also responsible (on the first chunk) for sending the + // HEADER response. + func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) { + if !rws.wroteHeader { + rws.writeHeader(200) + } if rws.handlerDone { + rws.promoteUndeclaredTrailers() + } isHeadResp := rws.req.Method == "HEAD" + if !rws.sentHeader { + rws.sentHeader = true + var ctype, clen string + if clen = rws.snapHeader.Get("Content-Length"); clen != "" { + rws.snapHeader.Del("Content-Length") + if cl, err := strconv.ParseUint(clen, 10, 63); err == nil { + rws.sentContentLen = int64(cl) + } else { + clen = "" + } + } + _, hasContentLength := rws.snapHeader["Content-Length"] + if !hasContentLength && clen == "" && rws.handlerDone && bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) { + clen = strconv.Itoa(len(p)) + } + _, hasContentType := rws.snapHeader["Content-Type"] + // If the Content-Encoding is non-blank, we shouldn't + // sniff the body. See Issue golang.org/issue/31753. + ce := rws.snapHeader.Get("Content-Encoding") + hasCE := len(ce) > 0 + if !hasCE && !hasContentType && bodyAllowedForStatus(rws.status) && len(p) > 0 { + ctype = http.DetectContentType(p) + } + var date string + if _, ok := rws.snapHeader["Date"]; !ok { + // TODO(bradfitz): be faster here, like net/http? measure. + date = time.Now().UTC().Format(http.TimeFormat) + } for _, v := range rws.snapHeader["Trailer"] { + foreachHeaderElement(v, rws.declareTrailer) + } // "Connection" headers aren't allowed in HTTP/2 (RFC 7540, 8.1.2.2), + // but respect "Connection" == "close" to mean sending a GOAWAY and tearing + // down the TCP connection when idle, like we do for HTTP/1. + // TODO: remove more Connection-specific header fields here, in addition + // to "Connection". + if _, ok := rws.snapHeader["Connection"]; ok { + v := rws.snapHeader.Get("Connection") + delete(rws.snapHeader, "Connection") + if v == "close" { + rws.conn.startGracefulShutdown() + } + } endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp + err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{ - streamID: rws.stream.id, - httpResCode: rws.status, - h: rws.snapHeader, - endStream: endStream, - contentType: ctype, + + streamID: rws.stream.id, + + httpResCode: rws.status, + + h: rws.snapHeader, + + endStream: endStream, + + contentType: ctype, + contentLength: clen, - date: date, + + date: date, }) + if err != nil { + return 0, err + } + if endStream { + return 0, nil + } + } + if isHeadResp { + return len(p), nil + } + if len(p) == 0 && !rws.handlerDone { + return 0, nil + } // only send trailers if they have actually been defined by the + // server handler. + hasNonemptyTrailers := rws.hasNonemptyTrailers() + endStream := rws.handlerDone && !hasNonemptyTrailers + if len(p) > 0 || endStream { + // only send a 0 byte DATA frame if we're ending the stream. + if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil { + return 0, err + } + } if rws.handlerDone && hasNonemptyTrailers { + err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{ - streamID: rws.stream.id, - h: rws.handlerHeader, - trailers: rws.trailers, + + streamID: rws.stream.id, + + h: rws.handlerHeader, + + trailers: rws.trailers, + endStream: true, }) + return len(p), err + } + return len(p), nil + } // TrailerPrefix is a magic prefix for ResponseWriter.Header map keys + // that, if present, signals that the map entry is actually for + // the response trailers, and not the response headers. The prefix + // is stripped after the ServeHTTP call finishes and the values are + // sent in the trailers. + // + // This mechanism is intended only for trailers that are not known + // prior to the headers being written. If the set of trailers is fixed + // or known before the header is written, the normal Go trailers mechanism + // is preferred: + // + // https://golang.org/pkg/net/http/#ResponseWriter + // https://golang.org/pkg/net/http/#example_ResponseWriter_trailers + const TrailerPrefix = "Trailer:" // promoteUndeclaredTrailers permits http.Handlers to set trailers + // after the header has already been flushed. Because the Go + // ResponseWriter interface has no way to set Trailers (only the + // Header), and because we didn't want to expand the ResponseWriter + // interface, and because nobody used trailers, and because RFC 7230 + // says you SHOULD (but not must) predeclare any trailers in the + // header, the official ResponseWriter rules said trailers in Go must + // be predeclared, and then we reuse the same ResponseWriter.Header() + // map to mean both Headers and Trailers. When it's time to write the + // Trailers, we pick out the fields of Headers that were declared as + // trailers. That worked for a while, until we found the first major + // user of Trailers in the wild: gRPC (using them only over http2), + // and gRPC libraries permit setting trailers mid-stream without + // predeclaring them. So: change of plans. We still permit the old + // way, but we also permit this hack: if a Header() key begins with + // "Trailer:", the suffix of that key is a Trailer. Because ':' is an + // invalid token byte anyway, there is no ambiguity. (And it's already + // filtered out) It's mildly hacky, but not terrible. + // + // This method runs after the Handler is done and promotes any Header + // fields to be trailers. + func (rws *responseWriterState) promoteUndeclaredTrailers() { + for k, vv := range rws.handlerHeader { + if !strings.HasPrefix(k, TrailerPrefix) { + continue + } + trailerKey := strings.TrimPrefix(k, TrailerPrefix) + rws.declareTrailer(trailerKey) + rws.handlerHeader[http.CanonicalHeaderKey(trailerKey)] = vv + } if len(rws.trailers) > 1 { + sorter := sorterPool.Get().(*sorter) + sorter.SortStrings(rws.trailers) + sorterPool.Put(sorter) + } + } func (w *responseWriter) SetReadDeadline(deadline time.Time) error { + st := w.rws.stream + if !deadline.IsZero() && deadline.Before(time.Now()) { + // If we're setting a deadline in the past, reset the stream immediately + // so writes after SetWriteDeadline returns will fail. + st.onReadTimeout() + return nil + } + w.rws.conn.sendServeMsg(func(sc *serverConn) { + if st.readDeadline != nil { + if !st.readDeadline.Stop() { + // Deadline already exceeded, or stream has been closed. + return + } + } + if deadline.IsZero() { + st.readDeadline = nil + } else if st.readDeadline == nil { + st.readDeadline = time.AfterFunc(deadline.Sub(time.Now()), st.onReadTimeout) + } else { + st.readDeadline.Reset(deadline.Sub(time.Now())) + } + }) + return nil + } func (w *responseWriter) SetWriteDeadline(deadline time.Time) error { + st := w.rws.stream + if !deadline.IsZero() && deadline.Before(time.Now()) { + // If we're setting a deadline in the past, reset the stream immediately + // so writes after SetWriteDeadline returns will fail. + st.onWriteTimeout() + return nil + } + w.rws.conn.sendServeMsg(func(sc *serverConn) { + if st.writeDeadline != nil { + if !st.writeDeadline.Stop() { + // Deadline already exceeded, or stream has been closed. + return + } + } + if deadline.IsZero() { + st.writeDeadline = nil + } else if st.writeDeadline == nil { + st.writeDeadline = time.AfterFunc(deadline.Sub(time.Now()), st.onWriteTimeout) + } else { + st.writeDeadline.Reset(deadline.Sub(time.Now())) + } + }) + return nil + } func (w *responseWriter) Flush() { + w.FlushError() + } func (w *responseWriter) FlushError() error { + rws := w.rws + if rws == nil { + panic("Header called after Handler finished") + } + var err error + if rws.bw.Buffered() > 0 { + err = rws.bw.Flush() + } else { + // The bufio.Writer won't call chunkWriter.Write + // (writeChunk with zero bytes), so we have to do it + // ourselves to force the HTTP response header and/or + // final DATA frame (with END_STREAM) to be sent. + _, err = chunkWriter{rws}.Write(nil) + if err == nil { + select { + case <-rws.stream.cw: + err = rws.stream.closeErr + default: + } + } + } + return err + } func (w *responseWriter) CloseNotify() <-chan bool { + rws := w.rws + if rws == nil { + panic("CloseNotify called after Handler finished") + } + rws.closeNotifierMu.Lock() + ch := rws.closeNotifierCh + if ch == nil { + ch = make(chan bool, 1) + rws.closeNotifierCh = ch + cw := rws.stream.cw + go func() { + cw.Wait() // wait for close + ch <- true + }() + } + rws.closeNotifierMu.Unlock() + return ch + } func (w *responseWriter) Header() http.Header { + rws := w.rws + if rws == nil { + panic("Header called after Handler finished") + } + if rws.handlerHeader == nil { + rws.handlerHeader = make(http.Header) + } + return rws.handlerHeader + } // checkWriteHeaderCode is a copy of net/http's checkWriteHeaderCode. + func checkWriteHeaderCode(code int) { + // Issue 22880: require valid WriteHeader status codes. + // For now we only enforce that it's three digits. + // In the future we might block things over 599 (600 and above aren't defined + // at http://httpwg.org/specs/rfc7231.html#status.codes). + // But for now any three digits. + // + // We used to send "HTTP/1.1 000 0" on the wire in responses but there's + // no equivalent bogus thing we can realistically send in HTTP/2, + // so we'll consistently panic instead and help people find their bugs + // early. (We can't return an error from WriteHeader even if we wanted to.) + if code < 100 || code > 999 { + panic(fmt.Sprintf("invalid WriteHeader code %v", code)) + } + } func (w *responseWriter) WriteHeader(code int) { + rws := w.rws + if rws == nil { + panic("WriteHeader called after Handler finished") + } + rws.writeHeader(code) + } func (rws *responseWriterState) writeHeader(code int) { + if rws.wroteHeader { + return + } checkWriteHeaderCode(code) // Handle informational headers + if code >= 100 && code <= 199 { + // Per RFC 8297 we must not clear the current header map + h := rws.handlerHeader _, cl := h["Content-Length"] + _, te := h["Transfer-Encoding"] + if cl || te { + h = h.Clone() + h.Del("Content-Length") + h.Del("Transfer-Encoding") + } rws.conn.writeHeaders(rws.stream, &writeResHeaders{ - streamID: rws.stream.id, + + streamID: rws.stream.id, + httpResCode: code, - h: h, - endStream: rws.handlerDone && !rws.hasTrailers(), + + h: h, + + endStream: rws.handlerDone && !rws.hasTrailers(), }) return + } rws.wroteHeader = true + rws.status = code + if len(rws.handlerHeader) > 0 { + rws.snapHeader = cloneHeader(rws.handlerHeader) + } + } func cloneHeader(h http.Header) http.Header { + h2 := make(http.Header, len(h)) + for k, vv := range h { + vv2 := make([]string, len(vv)) + copy(vv2, vv) + h2[k] = vv2 + } + return h2 + } // The Life Of A Write is like this: + // + // * Handler calls w.Write or w.WriteString -> + // * -> rws.bw (*bufio.Writer) -> + // * (Handler might call Flush) + // * -> chunkWriter{rws} + // * -> responseWriterState.writeChunk(p []byte) + // * -> responseWriterState.writeChunk (most of the magic; see comment there) + func (w *responseWriter) Write(p []byte) (n int, err error) { + return w.write(len(p), p, "") + } func (w *responseWriter) WriteString(s string) (n int, err error) { + return w.write(len(s), nil, s) + } // either dataB or dataS is non-zero. + func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) { + rws := w.rws + if rws == nil { + panic("Write called after Handler finished") + } + if !rws.wroteHeader { + w.WriteHeader(200) + } + if !bodyAllowedForStatus(rws.status) { + return 0, http.ErrBodyNotAllowed + } + rws.wroteBytes += int64(len(dataB)) + int64(len(dataS)) // only one can be set + if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen { + // TODO: send a RST_STREAM + return 0, errors.New("http2: handler wrote more than declared Content-Length") + } if dataB != nil { + return rws.bw.Write(dataB) + } else { + return rws.bw.WriteString(dataS) + } + } func (w *responseWriter) handlerDone() { + rws := w.rws + rws.handlerDone = true + w.Flush() + w.rws = nil + responseWriterStatePool.Put(rws) + } // Push errors. + var ( - ErrRecursivePush = errors.New("http2: recursive push not allowed") + ErrRecursivePush = errors.New("http2: recursive push not allowed") + ErrPushLimitReached = errors.New("http2: push would exceed peer's SETTINGS_MAX_CONCURRENT_STREAMS") ) var _ http.Pusher = (*responseWriter)(nil) func (w *responseWriter) Push(target string, opts *http.PushOptions) error { + st := w.rws.stream + sc := st.sc + sc.serveG.checkNotOn() // No recursive pushes: "PUSH_PROMISE frames MUST only be sent on a peer-initiated stream." + // http://tools.ietf.org/html/rfc7540#section-6.6 + if st.isPushed() { + return ErrRecursivePush + } if opts == nil { + opts = new(http.PushOptions) + } // Default options. + if opts.Method == "" { + opts.Method = "GET" + } + if opts.Header == nil { + opts.Header = http.Header{} + } + wantScheme := "http" + if w.rws.req.TLS != nil { + wantScheme = "https" + } // Validate the request. + u, err := url.Parse(target) + if err != nil { + return err + } + if u.Scheme == "" { + if !strings.HasPrefix(target, "/") { + return fmt.Errorf("target must be an absolute URL or an absolute path: %q", target) + } + u.Scheme = wantScheme + u.Host = w.rws.req.Host + } else { + if u.Scheme != wantScheme { + return fmt.Errorf("cannot push URL with scheme %q from request with scheme %q", u.Scheme, wantScheme) + } + if u.Host == "" { + return errors.New("URL must have a host") + } + } + for k := range opts.Header { + if strings.HasPrefix(k, ":") { + return fmt.Errorf("promised request headers cannot include pseudo header %q", k) + } + // These headers are meaningful only if the request has a body, + // but PUSH_PROMISE requests cannot have a body. + // http://tools.ietf.org/html/rfc7540#section-8.2 + // Also disallow Host, since the promised URL must be absolute. + if asciiEqualFold(k, "content-length") || + asciiEqualFold(k, "content-encoding") || + asciiEqualFold(k, "trailer") || + asciiEqualFold(k, "te") || + asciiEqualFold(k, "expect") || + asciiEqualFold(k, "host") { + return fmt.Errorf("promised request headers cannot include %q", k) + } + } + if err := checkValidHTTP2RequestHeaders(opts.Header); err != nil { + return err + } // The RFC effectively limits promised requests to GET and HEAD: + // "Promised requests MUST be cacheable [GET, HEAD, or POST], and MUST be safe [GET or HEAD]" + // http://tools.ietf.org/html/rfc7540#section-8.2 + if opts.Method != "GET" && opts.Method != "HEAD" { + return fmt.Errorf("method %q must be GET or HEAD", opts.Method) + } msg := &startPushRequest{ + parent: st, + method: opts.Method, - url: u, + + url: u, + header: cloneHeader(opts.Header), - done: errChanPool.Get().(chan error), + + done: errChanPool.Get().(chan error), } select { + case <-sc.doneServing: + return errClientDisconnected + case <-st.cw: + return errStreamClosed + case sc.serveMsgCh <- msg: + } select { + case <-sc.doneServing: + return errClientDisconnected + case <-st.cw: + return errStreamClosed + case err := <-msg.done: + errChanPool.Put(msg.done) + return err + } + } type startPushRequest struct { parent *stream + method string - url *url.URL + + url *url.URL + header http.Header - done chan error + + done chan error } func (sc *serverConn) startPush(msg *startPushRequest) { + sc.serveG.check() // http://tools.ietf.org/html/rfc7540#section-6.6. + // PUSH_PROMISE frames MUST only be sent on a peer-initiated stream that + // is in either the "open" or "half-closed (remote)" state. + if msg.parent.state != stateOpen && msg.parent.state != stateHalfClosedRemote { + // responseWriter.Push checks that the stream is peer-initiated. + msg.done <- errStreamClosed + return + } // http://tools.ietf.org/html/rfc7540#section-6.6. + if !sc.pushEnabled { + msg.done <- http.ErrNotSupported + return + } // PUSH_PROMISE frames must be sent in increasing order by stream ID, so + // we allocate an ID for the promised stream lazily, when the PUSH_PROMISE + // is written. Once the ID is allocated, we start the request handler. + allocatePromisedID := func() (uint32, error) { + sc.serveG.check() // Check this again, just in case. Technically, we might have received + // an updated SETTINGS by the time we got around to writing this frame. + if !sc.pushEnabled { + return 0, http.ErrNotSupported + } + // http://tools.ietf.org/html/rfc7540#section-6.5.2. + if sc.curPushedStreams+1 > sc.clientMaxStreams { + return 0, ErrPushLimitReached + } // http://tools.ietf.org/html/rfc7540#section-5.1.1. + // Streams initiated by the server MUST use even-numbered identifiers. + // A server that is unable to establish a new stream identifier can send a GOAWAY + // frame so that the client is forced to open a new connection for new streams. + if sc.maxPushPromiseID+2 >= 1<<31 { + sc.startGracefulShutdownInternal() + return 0, ErrPushLimitReached + } + sc.maxPushPromiseID += 2 + promisedID := sc.maxPushPromiseID // http://tools.ietf.org/html/rfc7540#section-8.2. + // Strictly speaking, the new stream should start in "reserved (local)", then + // transition to "half closed (remote)" after sending the initial HEADERS, but + // we start in "half closed (remote)" for simplicity. + // See further comments at the definition of stateHalfClosedRemote. + promised := sc.newStream(promisedID, msg.parent.id, stateHalfClosedRemote) + rw, req, err := sc.newWriterAndRequestNoBody(promised, requestParam{ - method: msg.method, - scheme: msg.url.Scheme, + + method: msg.method, + + scheme: msg.url.Scheme, + authority: msg.url.Host, - path: msg.url.RequestURI(), - header: cloneHeader(msg.header), // clone since handler runs concurrently with writing the PUSH_PROMISE + + path: msg.url.RequestURI(), + + header: cloneHeader(msg.header), // clone since handler runs concurrently with writing the PUSH_PROMISE + }) + if err != nil { + // Should not happen, since we've already validated msg.url. + panic(fmt.Sprintf("newWriterAndRequestNoBody(%+v): %v", msg.url, err)) + } sc.curHandlers++ + go sc.runHandler(rw, req, sc.handler.ServeHTTP) + return promisedID, nil + } sc.writeFrame(FrameWriteRequest{ + write: &writePushPromise{ - streamID: msg.parent.id, - method: msg.method, - url: msg.url, - h: msg.header, + + streamID: msg.parent.id, + + method: msg.method, + + url: msg.url, + + h: msg.header, + allocatePromisedID: allocatePromisedID, }, + stream: msg.parent, - done: msg.done, + + done: msg.done, }) + } // foreachHeaderElement splits v according to the "#rule" construction + // in RFC 7230 section 7 and calls fn for each non-empty element. + func foreachHeaderElement(v string, fn func(string)) { + v = textproto.TrimString(v) + if v == "" { + return + } + if !strings.Contains(v, ",") { + fn(v) + return + } + for _, f := range strings.Split(v, ",") { + if f = textproto.TrimString(f); f != "" { + fn(f) + } + } + } // From http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.2 + var connHeaders = []string{ + "Connection", + "Keep-Alive", + "Proxy-Connection", + "Transfer-Encoding", + "Upgrade", } // checkValidHTTP2RequestHeaders checks whether h is a valid HTTP/2 request, + // per RFC 7540 Section 8.1.2.2. + // The returned error is reported to users. + func checkValidHTTP2RequestHeaders(h http.Header) error { + for _, k := range connHeaders { + if _, ok := h[k]; ok { + return fmt.Errorf("request header %q is not valid in HTTP/2", k) + } + } + te := h["Te"] + if len(te) > 0 && (len(te) > 1 || (te[0] != "trailers" && te[0] != "")) { + return errors.New(`request header "TE" may only be "trailers" in HTTP/2`) + } + return nil + } func new400Handler(err error) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + http.Error(w, err.Error(), http.StatusBadRequest) + } + } // h1ServerKeepAlivesDisabled reports whether hs has its keep-alives + // disabled. See comments on h1ServerShutdownChan above for why + // the code is written this way. + func h1ServerKeepAlivesDisabled(hs *http.Server) bool { + var x interface{} = hs + type I interface { doKeepAlives() bool } + if hs, ok := x.(I); ok { + return !hs.doKeepAlives() + } + return false + } func (sc *serverConn) countError(name string, err error) error { + if sc == nil || sc.srv == nil { + return err + } + f := sc.srv.CountError + if f == nil { + return err + } + var typ string + var code ErrCode + switch e := err.(type) { + case ConnectionError: + typ = "conn" + code = ErrCode(e) + case StreamError: + typ = "stream" + code = ErrCode(e.Code) + default: + return err + } + codeStr := errCodeName[code] + if codeStr == "" { + codeStr = strconv.Itoa(int(code)) + } + f(fmt.Sprintf("%s_%s_%s", typ, codeStr, name)) + return err + } diff --git a/vendor/golang.org/x/net/http2/testsync.go b/vendor/golang.org/x/net/http2/testsync.go index 61075bd..845b928 100644 --- a/vendor/golang.org/x/net/http2/testsync.go +++ b/vendor/golang.org/x/net/http2/testsync.go @@ -1,6 +1,9 @@ // Copyright 2024 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. + package http2 import ( @@ -10,322 +13,571 @@ import ( ) // testSyncHooks coordinates goroutines in tests. + // + // For example, a call to ClientConn.RoundTrip involves several goroutines, including: + // - the goroutine running RoundTrip; + // - the clientStream.doRequest goroutine, which writes the request; and + // - the clientStream.readLoop goroutine, which reads the response. + // + // Using testSyncHooks, a test can start a RoundTrip and identify when all these goroutines + // are blocked waiting for some condition such as reading the Request.Body or waiting for + // flow control to become available. + // + // The testSyncHooks also manage timers and synthetic time in tests. + // This permits us to, for example, start a request and cause it to time out waiting for + // response headers without resorting to time.Sleep calls. + type testSyncHooks struct { + // active/inactive act as a mutex and condition variable. + // + // - neither chan contains a value: testSyncHooks is locked. + // - active contains a value: unlocked, and at least one goroutine is not blocked + // - inactive contains a value: unlocked, and all goroutines are blocked - active chan struct{} + + active chan struct{} + inactive chan struct{} // goroutine counts - total int // total goroutines - condwait map[*sync.Cond]int // blocked in sync.Cond.Wait - blocked []*testBlockedGoroutine // otherwise blocked + + total int // total goroutines + + condwait map[*sync.Cond]int // blocked in sync.Cond.Wait + + blocked []*testBlockedGoroutine // otherwise blocked // fake time - now time.Time + + now time.Time + timers []*fakeTimer // Transport testing: Report various events. + newclientconn func(*ClientConn) - newstream func(*clientStream) + + newstream func(*clientStream) } // testBlockedGoroutine is a blocked goroutine. + type testBlockedGoroutine struct { - f func() bool // blocked until f returns true + f func() bool // blocked until f returns true + ch chan struct{} // closed when unblocked + } func newTestSyncHooks() *testSyncHooks { + h := &testSyncHooks{ - active: make(chan struct{}, 1), + + active: make(chan struct{}, 1), + inactive: make(chan struct{}, 1), + condwait: map[*sync.Cond]int{}, } + h.inactive <- struct{}{} + h.now = time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC) + return h + } // lock acquires the testSyncHooks mutex. + func (h *testSyncHooks) lock() { + select { + case <-h.active: + case <-h.inactive: + } + } // waitInactive waits for all goroutines to become inactive. + func (h *testSyncHooks) waitInactive() { + for { + <-h.inactive + if !h.unlock() { + break + } + } + } // unlock releases the testSyncHooks mutex. + // It reports whether any goroutines are active. + func (h *testSyncHooks) unlock() (active bool) { + // Look for a blocked goroutine which can be unblocked. + blocked := h.blocked[:0] + unblocked := false + for _, b := range h.blocked { + if !unblocked && b.f() { + unblocked = true + close(b.ch) + } else { + blocked = append(blocked, b) + } + } + h.blocked = blocked // Count goroutines blocked on condition variables. + condwait := 0 + for _, count := range h.condwait { + condwait += count + } if h.total > condwait+len(blocked) { + h.active <- struct{}{} + return true + } else { + h.inactive <- struct{}{} + return false + } + } // goRun starts a new goroutine. + func (h *testSyncHooks) goRun(f func()) { + h.lock() + h.total++ + h.unlock() + go func() { + defer func() { + h.lock() + h.total-- + h.unlock() + }() + f() + }() + } // blockUntil indicates that a goroutine is blocked waiting for some condition to become true. + // It waits until f returns true before proceeding. + // + // Example usage: + // + // h.blockUntil(func() bool { + // // Is the context done yet? + // select { + // case <-ctx.Done(): + // default: + // return false + // } + // return true + // }) + // // Wait for the context to become done. + // <-ctx.Done() + // + // The function f passed to blockUntil must be non-blocking and idempotent. + func (h *testSyncHooks) blockUntil(f func() bool) { + if f() { + return + } + ch := make(chan struct{}) + h.lock() + h.blocked = append(h.blocked, &testBlockedGoroutine{ - f: f, + + f: f, + ch: ch, }) + h.unlock() + <-ch + } // broadcast is sync.Cond.Broadcast. + func (h *testSyncHooks) condBroadcast(cond *sync.Cond) { + h.lock() + delete(h.condwait, cond) + h.unlock() + cond.Broadcast() + } // broadcast is sync.Cond.Wait. + func (h *testSyncHooks) condWait(cond *sync.Cond) { + h.lock() + h.condwait[cond]++ + h.unlock() + } // newTimer creates a new fake timer. + func (h *testSyncHooks) newTimer(d time.Duration) timer { + h.lock() + defer h.unlock() + t := &fakeTimer{ + hooks: h, - when: h.now.Add(d), - c: make(chan time.Time), + + when: h.now.Add(d), + + c: make(chan time.Time), } + h.timers = append(h.timers, t) + return t + } // afterFunc creates a new fake AfterFunc timer. + func (h *testSyncHooks) afterFunc(d time.Duration, f func()) timer { + h.lock() + defer h.unlock() + t := &fakeTimer{ + hooks: h, - when: h.now.Add(d), - f: f, + + when: h.now.Add(d), + + f: f, } + h.timers = append(h.timers, t) + return t + } func (h *testSyncHooks) contextWithTimeout(ctx context.Context, d time.Duration) (context.Context, context.CancelFunc) { + ctx, cancel := context.WithCancel(ctx) + t := h.afterFunc(d, cancel) + return ctx, func() { + t.Stop() + cancel() + } + } func (h *testSyncHooks) timeUntilEvent() time.Duration { + h.lock() + defer h.unlock() + var next time.Time + for _, t := range h.timers { + if next.IsZero() || t.when.Before(next) { + next = t.when + } + } + if d := next.Sub(h.now); d > 0 { + return d + } + return 0 + } // advance advances time and causes synthetic timers to fire. + func (h *testSyncHooks) advance(d time.Duration) { + h.lock() + defer h.unlock() + h.now = h.now.Add(d) + timers := h.timers[:0] + for _, t := range h.timers { + t := t // remove after go.mod depends on go1.22 + t.mu.Lock() + switch { + case t.when.After(h.now): + timers = append(timers, t) + case t.when.IsZero(): + // stopped timer + default: + t.when = time.Time{} + if t.c != nil { + close(t.c) + } + if t.f != nil { + h.total++ + go func() { + defer func() { + h.lock() + h.total-- + h.unlock() + }() + t.f() + }() + } + } + t.mu.Unlock() + } + h.timers = timers + } // A timer wraps a time.Timer, or a synthetic equivalent in tests. + // Unlike time.Timer, timer is single-use: The timer channel is closed when the timer expires. + type timer interface { C() <-chan time.Time + Stop() bool + Reset(d time.Duration) bool } // timeTimer implements timer using real time. + type timeTimer struct { t *time.Timer + c chan time.Time } // newTimeTimer creates a new timer using real time. + func newTimeTimer(d time.Duration) timer { + ch := make(chan time.Time) + t := time.AfterFunc(d, func() { + close(ch) + }) + return &timeTimer{t, ch} + } // newTimeAfterFunc creates an AfterFunc timer using real time. + func newTimeAfterFunc(d time.Duration, f func()) timer { + return &timeTimer{ + t: time.AfterFunc(d, f), } + } -func (t timeTimer) C() <-chan time.Time { return t.c } -func (t timeTimer) Stop() bool { return t.t.Stop() } +func (t timeTimer) C() <-chan time.Time { return t.c } + +func (t timeTimer) Stop() bool { return t.t.Stop() } + func (t timeTimer) Reset(d time.Duration) bool { return t.t.Reset(d) } // fakeTimer implements timer using fake time. + type fakeTimer struct { hooks *testSyncHooks - mu sync.Mutex - when time.Time // when the timer will fire - c chan time.Time // closed when the timer fires; mutually exclusive with f - f func() // called when the timer fires; mutually exclusive with c + mu sync.Mutex + + when time.Time // when the timer will fire + + c chan time.Time // closed when the timer fires; mutually exclusive with f + + f func() // called when the timer fires; mutually exclusive with c + } func (t *fakeTimer) C() <-chan time.Time { return t.c } func (t *fakeTimer) Stop() bool { + t.mu.Lock() + defer t.mu.Unlock() + stopped := t.when.IsZero() + t.when = time.Time{} + return stopped + } func (t *fakeTimer) Reset(d time.Duration) bool { + if t.c != nil || t.f == nil { + panic("fakeTimer only supports Reset on AfterFunc timers") + } + t.mu.Lock() + defer t.mu.Unlock() + t.hooks.lock() + defer t.hooks.unlock() + active := !t.when.IsZero() + t.when = t.hooks.now.Add(d) + if !active { + t.hooks.timers = append(t.hooks.timers, t) + } + return active + } diff --git a/vendor/golang.org/x/net/http2/transport.go b/vendor/golang.org/x/net/http2/transport.go index 2fa4949..1b779bb 100644 --- a/vendor/golang.org/x/net/http2/transport.go +++ b/vendor/golang.org/x/net/http2/transport.go @@ -1,5 +1,7 @@ // Copyright 2015 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Transport code. @@ -39,3259 +41,5873 @@ import ( ) const ( + // transportDefaultConnFlow is how many connection-level flow control + // tokens we give the server at start-up, past the default 64k. + transportDefaultConnFlow = 1 << 30 // transportDefaultStreamFlow is how many stream-level flow + // control tokens we announce to the peer, and how many bytes + // we buffer per stream. + transportDefaultStreamFlow = 4 << 20 defaultUserAgent = "Go-http-client/2.0" // initialMaxConcurrentStreams is a connections maxConcurrentStreams until + // it's received servers initial SETTINGS frame, which corresponds with the + // spec's minimum recommended value. + initialMaxConcurrentStreams = 100 // defaultMaxConcurrentStreams is a connections default maxConcurrentStreams + // if the server doesn't include one in its initial SETTINGS frame. + defaultMaxConcurrentStreams = 1000 ) // Transport is an HTTP/2 Transport. + // + // A Transport internally caches connections to servers. It is safe + // for concurrent use by multiple goroutines. + type Transport struct { + // DialTLSContext specifies an optional dial function with context for + // creating TLS connections for requests. + // + // If DialTLSContext and DialTLS is nil, tls.Dial is used. + // + // If the returned net.Conn has a ConnectionState method like tls.Conn, + // it will be used to set http.Response.TLS. + DialTLSContext func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error) // DialTLS specifies an optional dial function for creating + // TLS connections for requests. + // + // If DialTLSContext and DialTLS is nil, tls.Dial is used. + // + // Deprecated: Use DialTLSContext instead, which allows the transport + // to cancel dials as soon as they are no longer needed. + // If both are set, DialTLSContext takes priority. + DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error) // TLSClientConfig specifies the TLS configuration to use with + // tls.Client. If nil, the default configuration is used. + TLSClientConfig *tls.Config // ConnPool optionally specifies an alternate connection pool to use. + // If nil, the default is used. + ConnPool ClientConnPool // DisableCompression, if true, prevents the Transport from + // requesting compression with an "Accept-Encoding: gzip" + // request header when the Request contains no existing + // Accept-Encoding value. If the Transport requests gzip on + // its own and gets a gzipped response, it's transparently + // decoded in the Response.Body. However, if the user + // explicitly requested gzip it is not automatically + // uncompressed. + DisableCompression bool // AllowHTTP, if true, permits HTTP/2 requests using the insecure, + // plain-text "http" scheme. Note that this does not enable h2c support. + AllowHTTP bool // MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to + // send in the initial settings frame. It is how many bytes + // of response headers are allowed. Unlike the http2 spec, zero here + // means to use a default limit (currently 10MB). If you actually + // want to advertise an unlimited value to the peer, Transport + // interprets the highest possible value here (0xffffffff or 1<<32-1) + // to mean no limit. + MaxHeaderListSize uint32 // MaxReadFrameSize is the http2 SETTINGS_MAX_FRAME_SIZE to send in the + // initial settings frame. It is the size in bytes of the largest frame + // payload that the sender is willing to receive. If 0, no setting is + // sent, and the value is provided by the peer, which should be 16384 + // according to the spec: + // https://datatracker.ietf.org/doc/html/rfc7540#section-6.5.2. + // Values are bounded in the range 16k to 16M. + MaxReadFrameSize uint32 // MaxDecoderHeaderTableSize optionally specifies the http2 + // SETTINGS_HEADER_TABLE_SIZE to send in the initial settings frame. It + // informs the remote endpoint of the maximum size of the header compression + // table used to decode header blocks, in octets. If zero, the default value + // of 4096 is used. + MaxDecoderHeaderTableSize uint32 // MaxEncoderHeaderTableSize optionally specifies an upper limit for the + // header compression table used for encoding request headers. Received + // SETTINGS_HEADER_TABLE_SIZE settings are capped at this limit. If zero, + // the default value of 4096 is used. + MaxEncoderHeaderTableSize uint32 // StrictMaxConcurrentStreams controls whether the server's + // SETTINGS_MAX_CONCURRENT_STREAMS should be respected + // globally. If false, new TCP connections are created to the + // server as needed to keep each under the per-connection + // SETTINGS_MAX_CONCURRENT_STREAMS limit. If true, the + // server's SETTINGS_MAX_CONCURRENT_STREAMS is interpreted as + // a global limit and callers of RoundTrip block when needed, + // waiting for their turn. + StrictMaxConcurrentStreams bool // IdleConnTimeout is the maximum amount of time an idle + // (keep-alive) connection will remain idle before closing + // itself. + // Zero means no limit. + IdleConnTimeout time.Duration // ReadIdleTimeout is the timeout after which a health check using ping + // frame will be carried out if no frame is received on the connection. + // Note that a ping response will is considered a received frame, so if + // there is no other traffic on the connection, the health check will + // be performed every ReadIdleTimeout interval. + // If zero, no health check is performed. + ReadIdleTimeout time.Duration // PingTimeout is the timeout after which the connection will be closed + // if a response to Ping is not received. + // Defaults to 15s. + PingTimeout time.Duration // WriteByteTimeout is the timeout after which the connection will be + // closed no data can be written to it. The timeout begins when data is + // available to write, and is extended whenever any bytes are written. + WriteByteTimeout time.Duration // CountError, if non-nil, is called on HTTP/2 transport errors. + // It's intended to increment a metric for monitoring, such + // as an expvar or Prometheus metric. + // The errType consists of only ASCII word characters. + CountError func(errType string) // t1, if non-nil, is the standard library Transport using + // this transport. Its settings are used (but not its + // RoundTrip method, etc). + t1 *http.Transport - connPoolOnce sync.Once + connPoolOnce sync.Once + connPoolOrDef ClientConnPool // non-nil version of ConnPool syncHooks *testSyncHooks } func (t *Transport) maxHeaderListSize() uint32 { + if t.MaxHeaderListSize == 0 { + return 10 << 20 + } + if t.MaxHeaderListSize == 0xffffffff { + return 0 + } + return t.MaxHeaderListSize + } func (t *Transport) maxFrameReadSize() uint32 { + if t.MaxReadFrameSize == 0 { + return 0 // use the default provided by the peer + } + if t.MaxReadFrameSize < minMaxFrameSize { + return minMaxFrameSize + } + if t.MaxReadFrameSize > maxFrameSize { + return maxFrameSize + } + return t.MaxReadFrameSize + } func (t *Transport) disableCompression() bool { + return t.DisableCompression || (t.t1 != nil && t.t1.DisableCompression) + } func (t *Transport) pingTimeout() time.Duration { + if t.PingTimeout == 0 { + return 15 * time.Second + } + return t.PingTimeout } // ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2. + // It returns an error if t1 has already been HTTP/2-enabled. + // + // Use ConfigureTransports instead to configure the HTTP/2 Transport. + func ConfigureTransport(t1 *http.Transport) error { + _, err := ConfigureTransports(t1) + return err + } // ConfigureTransports configures a net/http HTTP/1 Transport to use HTTP/2. + // It returns a new HTTP/2 Transport for further configuration. + // It returns an error if t1 has already been HTTP/2-enabled. + func ConfigureTransports(t1 *http.Transport) (*Transport, error) { + return configureTransports(t1) + } func configureTransports(t1 *http.Transport) (*Transport, error) { + connPool := new(clientConnPool) + t2 := &Transport{ + ConnPool: noDialClientConnPool{connPool}, - t1: t1, + + t1: t1, } + connPool.t = t2 + if err := registerHTTPSProtocol(t1, noDialH2RoundTripper{t2}); err != nil { + return nil, err + } + if t1.TLSClientConfig == nil { + t1.TLSClientConfig = new(tls.Config) + } + if !strSliceContains(t1.TLSClientConfig.NextProtos, "h2") { + t1.TLSClientConfig.NextProtos = append([]string{"h2"}, t1.TLSClientConfig.NextProtos...) + } + if !strSliceContains(t1.TLSClientConfig.NextProtos, "http/1.1") { + t1.TLSClientConfig.NextProtos = append(t1.TLSClientConfig.NextProtos, "http/1.1") + } + upgradeFn := func(authority string, c *tls.Conn) http.RoundTripper { + addr := authorityAddr("https", authority) + if used, err := connPool.addConnIfNeeded(addr, t2, c); err != nil { + go c.Close() + return erringRoundTripper{err} + } else if !used { + // Turns out we don't need this c. + // For example, two goroutines made requests to the same host + // at the same time, both kicking off TCP dials. (since protocol + // was unknown) + go c.Close() + } + return t2 + } + if m := t1.TLSNextProto; len(m) == 0 { + t1.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{ + "h2": upgradeFn, } + } else { + m["h2"] = upgradeFn + } + return t2, nil + } func (t *Transport) connPool() ClientConnPool { + t.connPoolOnce.Do(t.initConnPool) + return t.connPoolOrDef + } func (t *Transport) initConnPool() { + if t.ConnPool != nil { + t.connPoolOrDef = t.ConnPool + } else { + t.connPoolOrDef = &clientConnPool{t: t} + } + } // ClientConn is the state of a single HTTP/2 client connection to an + // HTTP/2 server. + type ClientConn struct { - t *Transport - tconn net.Conn // usually *tls.Conn, except specialized impls - tlsState *tls.ConnectionState // nil only for specialized impls - reused uint32 // whether conn is being reused; atomic - singleUse bool // whether being used for a single http.Request - getConnCalled bool // used by clientConnPool + t *Transport + + tconn net.Conn // usually *tls.Conn, except specialized impls + + tlsState *tls.ConnectionState // nil only for specialized impls + + reused uint32 // whether conn is being reused; atomic + + singleUse bool // whether being used for a single http.Request + + getConnCalled bool // used by clientConnPool // readLoop goroutine fields: + readerDone chan struct{} // closed on error - readerErr error // set before readerDone is closed + + readerErr error // set before readerDone is closed idleTimeout time.Duration // or 0 for never - idleTimer timer - mu sync.Mutex // guards following - cond *sync.Cond // hold mu; broadcast on flow/closed changes - flow outflow // our conn-level flow control quota (cs.outflow is per stream) - inflow inflow // peer's conn-level flow control - doNotReuse bool // whether conn is marked to not be reused for any future requests - closing bool - closed bool - seenSettings bool // true if we've seen a settings frame, false otherwise - wantSettingsAck bool // we sent a SETTINGS frame and haven't heard back - goAway *GoAwayFrame // if non-nil, the GoAwayFrame we received - goAwayDebug string // goAway frame's debug data, retained as a string - streams map[uint32]*clientStream // client-initiated - streamsReserved int // incr by ReserveNewRequest; decr on RoundTrip - nextStreamID uint32 - pendingRequests int // requests blocked and waiting to be sent because len(streams) == maxConcurrentStreams - pings map[[8]byte]chan struct{} // in flight ping data to notification channel - br *bufio.Reader - lastActive time.Time - lastIdle time.Time // time last idle + idleTimer timer + + mu sync.Mutex // guards following + + cond *sync.Cond // hold mu; broadcast on flow/closed changes + + flow outflow // our conn-level flow control quota (cs.outflow is per stream) + + inflow inflow // peer's conn-level flow control + + doNotReuse bool // whether conn is marked to not be reused for any future requests + + closing bool + + closed bool + + seenSettings bool // true if we've seen a settings frame, false otherwise + + wantSettingsAck bool // we sent a SETTINGS frame and haven't heard back + + goAway *GoAwayFrame // if non-nil, the GoAwayFrame we received + + goAwayDebug string // goAway frame's debug data, retained as a string + + streams map[uint32]*clientStream // client-initiated + + streamsReserved int // incr by ReserveNewRequest; decr on RoundTrip + + nextStreamID uint32 + + pendingRequests int // requests blocked and waiting to be sent because len(streams) == maxConcurrentStreams + + pings map[[8]byte]chan struct{} // in flight ping data to notification channel + + br *bufio.Reader + + lastActive time.Time + + lastIdle time.Time // time last idle + // Settings from peer: (also guarded by wmu) - maxFrameSize uint32 - maxConcurrentStreams uint32 - peerMaxHeaderListSize uint64 + + maxFrameSize uint32 + + maxConcurrentStreams uint32 + + peerMaxHeaderListSize uint64 + peerMaxHeaderTableSize uint32 - initialWindowSize uint32 + + initialWindowSize uint32 // reqHeaderMu is a 1-element semaphore channel controlling access to sending new requests. + // Write to reqHeaderMu to lock it, read from it to unlock. + // Lock reqmu BEFORE mu or wmu. + reqHeaderMu chan struct{} // wmu is held while writing. + // Acquire BEFORE mu when holding both, to avoid blocking mu on network writes. + // Only acquire both at the same time when changing peer settings. - wmu sync.Mutex - bw *bufio.Writer - fr *Framer - werr error // first write error that has occurred + + wmu sync.Mutex + + bw *bufio.Writer + + fr *Framer + + werr error // first write error that has occurred + hbuf bytes.Buffer // HPACK encoder writes into this + henc *hpack.Encoder syncHooks *testSyncHooks // can be nil + } // Hook points used for testing. + // Outside of tests, cc.syncHooks is nil and these all have minimal implementations. + // Inside tests, see the testSyncHooks function docs. // goRun starts a new goroutine. + func (cc *ClientConn) goRun(f func()) { + if cc.syncHooks != nil { + cc.syncHooks.goRun(f) + return + } + go f() + } // condBroadcast is cc.cond.Broadcast. + func (cc *ClientConn) condBroadcast() { + if cc.syncHooks != nil { + cc.syncHooks.condBroadcast(cc.cond) + } + cc.cond.Broadcast() + } // condWait is cc.cond.Wait. + func (cc *ClientConn) condWait() { + if cc.syncHooks != nil { + cc.syncHooks.condWait(cc.cond) + } + cc.cond.Wait() + } // newTimer creates a new time.Timer, or a synthetic timer in tests. + func (cc *ClientConn) newTimer(d time.Duration) timer { + if cc.syncHooks != nil { + return cc.syncHooks.newTimer(d) + } + return newTimeTimer(d) + } // afterFunc creates a new time.AfterFunc timer, or a synthetic timer in tests. + func (cc *ClientConn) afterFunc(d time.Duration, f func()) timer { + if cc.syncHooks != nil { + return cc.syncHooks.afterFunc(d, f) + } + return newTimeAfterFunc(d, f) + } func (cc *ClientConn) contextWithTimeout(ctx context.Context, d time.Duration) (context.Context, context.CancelFunc) { + if cc.syncHooks != nil { + return cc.syncHooks.contextWithTimeout(ctx, d) + } + return context.WithTimeout(ctx, d) + } // clientStream is the state for a single HTTP/2 stream. One of these + // is created for each Transport.RoundTrip call. + type clientStream struct { cc *ClientConn // Fields of Request that we may access even after the response body is closed. - ctx context.Context + + ctx context.Context + reqCancel <-chan struct{} - trace *httptrace.ClientTrace // or nil - ID uint32 - bufPipe pipe // buffered pipe with the flow-controlled response payload + trace *httptrace.ClientTrace // or nil + + ID uint32 + + bufPipe pipe // buffered pipe with the flow-controlled response payload + requestedGzip bool - isHead bool + + isHead bool abortOnce sync.Once - abort chan struct{} // closed to signal stream should end immediately - abortErr error // set if abort is closed + + abort chan struct{} // closed to signal stream should end immediately + + abortErr error // set if abort is closed peerClosed chan struct{} // closed when the peer sends an END_STREAM flag - donec chan struct{} // closed after the stream is in the closed state - on100 chan struct{} // buffered; written to if a 100 is received - respHeaderRecv chan struct{} // closed when headers are received - res *http.Response // set if respHeaderRecv is closed + donec chan struct{} // closed after the stream is in the closed state - flow outflow // guarded by cc.mu - inflow inflow // guarded by cc.mu - bytesRemain int64 // -1 means unknown; owned by transportResponseBody.Read - readErr error // sticky read error; owned by transportResponseBody.Read + on100 chan struct{} // buffered; written to if a 100 is received - reqBody io.ReadCloser - reqBodyContentLength int64 // -1 means unknown - reqBodyClosed chan struct{} // guarded by cc.mu; non-nil on Close, closed when done + respHeaderRecv chan struct{} // closed when headers are received + + res *http.Response // set if respHeaderRecv is closed + + flow outflow // guarded by cc.mu + + inflow inflow // guarded by cc.mu + + bytesRemain int64 // -1 means unknown; owned by transportResponseBody.Read + + readErr error // sticky read error; owned by transportResponseBody.Read + + reqBody io.ReadCloser + + reqBodyContentLength int64 // -1 means unknown + + reqBodyClosed chan struct{} // guarded by cc.mu; non-nil on Close, closed when done // owned by writeRequest: + sentEndStream bool // sent an END_STREAM flag to the peer - sentHeaders bool + + sentHeaders bool // owned by clientConnReadLoop: - firstByte bool // got the first response byte - pastHeaders bool // got first MetaHeadersFrame (actual headers) - pastTrailers bool // got optional second MetaHeadersFrame (trailers) - num1xx uint8 // number of 1xx responses seen - readClosed bool // peer sent an END_STREAM flag - readAborted bool // read loop reset the stream - trailer http.Header // accumulated trailers + firstByte bool // got the first response byte + + pastHeaders bool // got first MetaHeadersFrame (actual headers) + + pastTrailers bool // got optional second MetaHeadersFrame (trailers) + + num1xx uint8 // number of 1xx responses seen + + readClosed bool // peer sent an END_STREAM flag + + readAborted bool // read loop reset the stream + + trailer http.Header // accumulated trailers + resTrailer *http.Header // client's Response.Trailer + } var got1xxFuncForTests func(int, textproto.MIMEHeader) error // get1xxTraceFunc returns the value of request's httptrace.ClientTrace.Got1xxResponse func, + // if any. It returns nil if not set or if the Go version is too old. + func (cs *clientStream) get1xxTraceFunc() func(int, textproto.MIMEHeader) error { + if fn := got1xxFuncForTests; fn != nil { + return fn + } + return traceGot1xxResponseFunc(cs.trace) + } func (cs *clientStream) abortStream(err error) { + cs.cc.mu.Lock() + defer cs.cc.mu.Unlock() + cs.abortStreamLocked(err) + } func (cs *clientStream) abortStreamLocked(err error) { + cs.abortOnce.Do(func() { + cs.abortErr = err + close(cs.abort) + }) + if cs.reqBody != nil { + cs.closeReqBodyLocked() + } + // TODO(dneil): Clean up tests where cs.cc.cond is nil. + if cs.cc.cond != nil { + // Wake up writeRequestBody if it is waiting on flow control. + cs.cc.condBroadcast() + } + } func (cs *clientStream) abortRequestBodyWrite() { + cc := cs.cc + cc.mu.Lock() + defer cc.mu.Unlock() + if cs.reqBody != nil && cs.reqBodyClosed == nil { + cs.closeReqBodyLocked() + cc.condBroadcast() + } + } func (cs *clientStream) closeReqBodyLocked() { + if cs.reqBodyClosed != nil { + return + } + cs.reqBodyClosed = make(chan struct{}) + reqBodyClosed := cs.reqBodyClosed + cs.cc.goRun(func() { + cs.reqBody.Close() + close(reqBodyClosed) + }) + } type stickyErrWriter struct { - conn net.Conn + conn net.Conn + timeout time.Duration - err *error + + err *error } func (sew stickyErrWriter) Write(p []byte) (n int, err error) { + if *sew.err != nil { + return 0, *sew.err + } + for { + if sew.timeout != 0 { + sew.conn.SetWriteDeadline(time.Now().Add(sew.timeout)) + } + nn, err := sew.conn.Write(p[n:]) + n += nn + if n < len(p) && nn > 0 && errors.Is(err, os.ErrDeadlineExceeded) { + // Keep extending the deadline so long as we're making progress. + continue + } + if sew.timeout != 0 { + sew.conn.SetWriteDeadline(time.Time{}) + } + *sew.err = err + return n, err + } + } // noCachedConnError is the concrete type of ErrNoCachedConn, which + // needs to be detected by net/http regardless of whether it's its + // bundled version (in h2_bundle.go with a rewritten type name) or + // from a user's x/net/http2. As such, as it has a unique method name + // (IsHTTP2NoCachedConnError) that net/http sniffs for via func + // isNoCachedConnError. + type noCachedConnError struct{} func (noCachedConnError) IsHTTP2NoCachedConnError() {} -func (noCachedConnError) Error() string { return "http2: no cached connection was available" } + +func (noCachedConnError) Error() string { return "http2: no cached connection was available" } // isNoCachedConnError reports whether err is of type noCachedConnError + // or its equivalent renamed type in net/http2's h2_bundle.go. Both types + // may coexist in the same running program. + func isNoCachedConnError(err error) bool { + _, ok := err.(interface{ IsHTTP2NoCachedConnError() }) + return ok + } var ErrNoCachedConn error = noCachedConnError{} // RoundTripOpt are options for the Transport.RoundTripOpt method. + type RoundTripOpt struct { + // OnlyCachedConn controls whether RoundTripOpt may + // create a new TCP connection. If set true and + // no cached connection is available, RoundTripOpt + // will return ErrNoCachedConn. + OnlyCachedConn bool } func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { + return t.RoundTripOpt(req, RoundTripOpt{}) + } // authorityAddr returns a given authority (a host/IP, or host:port / ip:port) + // and returns a host:port. The port 443 is added if needed. + func authorityAddr(scheme string, authority string) (addr string) { + host, port, err := net.SplitHostPort(authority) + if err != nil { // authority didn't have a port + host = authority + port = "" + } + if port == "" { // authority's port was empty + port = "443" + if scheme == "http" { + port = "80" + } + } + if a, err := idna.ToASCII(host); err == nil { + host = a + } + // IPv6 address literal, without a port: + if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") { + return host + ":" + port + } + return net.JoinHostPort(host, port) + } // RoundTripOpt is like RoundTrip, but takes options. + func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) { + if !(req.URL.Scheme == "https" || (req.URL.Scheme == "http" && t.AllowHTTP)) { + return nil, errors.New("http2: unsupported scheme") + } addr := authorityAddr(req.URL.Scheme, req.URL.Host) + for retry := 0; ; retry++ { + cc, err := t.connPool().GetClientConn(req, addr) + if err != nil { + t.vlogf("http2: Transport failed to get client conn for %s: %v", addr, err) + return nil, err + } + reused := !atomic.CompareAndSwapUint32(&cc.reused, 0, 1) + traceGotConn(req, cc, reused) + res, err := cc.RoundTrip(req) + if err != nil && retry <= 6 { + roundTripErr := err + if req, err = shouldRetryRequest(req, err); err == nil { + // After the first retry, do exponential backoff with 10% jitter. + if retry == 0 { + t.vlogf("RoundTrip retrying after failure: %v", roundTripErr) + continue + } + backoff := float64(uint(1) << (uint(retry) - 1)) + backoff += backoff * (0.1 * mathrand.Float64()) + d := time.Second * time.Duration(backoff) + var tm timer + if t.syncHooks != nil { + tm = t.syncHooks.newTimer(d) + t.syncHooks.blockUntil(func() bool { + select { + case <-tm.C(): + case <-req.Context().Done(): + default: + return false + } + return true + }) + } else { + tm = newTimeTimer(d) + } + select { + case <-tm.C(): + t.vlogf("RoundTrip retrying after failure: %v", roundTripErr) + continue + case <-req.Context().Done(): + tm.Stop() + err = req.Context().Err() + } + } + } + if err != nil { + t.vlogf("RoundTrip failure: %v", err) + return nil, err + } + return res, nil + } + } // CloseIdleConnections closes any connections which were previously + // connected from previous requests but are now sitting idle. + // It does not interrupt any connections currently in use. + func (t *Transport) CloseIdleConnections() { + if cp, ok := t.connPool().(clientConnPoolIdleCloser); ok { + cp.closeIdleConnections() + } + } var ( - errClientConnClosed = errors.New("http2: client conn is closed") - errClientConnUnusable = errors.New("http2: client conn not usable") + errClientConnClosed = errors.New("http2: client conn is closed") + + errClientConnUnusable = errors.New("http2: client conn not usable") + errClientConnGotGoAway = errors.New("http2: Transport received Server's graceful shutdown GOAWAY") ) // shouldRetryRequest is called by RoundTrip when a request fails to get + // response headers. It is always called with a non-nil error. + // It returns either a request to retry (either the same request, or a + // modified clone), or an error if the request can't be replayed. + func shouldRetryRequest(req *http.Request, err error) (*http.Request, error) { + if !canRetryError(err) { + return nil, err + } + // If the Body is nil (or http.NoBody), it's safe to reuse + // this request and its Body. + if req.Body == nil || req.Body == http.NoBody { + return req, nil + } // If the request body can be reset back to its original + // state via the optional req.GetBody, do that. + if req.GetBody != nil { + body, err := req.GetBody() + if err != nil { + return nil, err + } + newReq := *req + newReq.Body = body + return &newReq, nil + } // The Request.Body can't reset back to the beginning, but we + // don't seem to have started to read from it yet, so reuse + // the request directly. + if err == errClientConnUnusable { + return req, nil + } return nil, fmt.Errorf("http2: Transport: cannot retry err [%v] after Request.Body was written; define Request.GetBody to avoid this error", err) + } func canRetryError(err error) bool { + if err == errClientConnUnusable || err == errClientConnGotGoAway { + return true + } + if se, ok := err.(StreamError); ok { + if se.Code == ErrCodeProtocol && se.Cause == errFromPeer { + // See golang/go#47635, golang/go#42777 + return true + } + return se.Code == ErrCodeRefusedStream + } + return false + } func (t *Transport) dialClientConn(ctx context.Context, addr string, singleUse bool) (*ClientConn, error) { + if t.syncHooks != nil { + return t.newClientConn(nil, singleUse, t.syncHooks) + } + host, _, err := net.SplitHostPort(addr) + if err != nil { + return nil, err + } + tconn, err := t.dialTLS(ctx, "tcp", addr, t.newTLSConfig(host)) + if err != nil { + return nil, err + } + return t.newClientConn(tconn, singleUse, nil) + } func (t *Transport) newTLSConfig(host string) *tls.Config { + cfg := new(tls.Config) + if t.TLSClientConfig != nil { + *cfg = *t.TLSClientConfig.Clone() + } + if !strSliceContains(cfg.NextProtos, NextProtoTLS) { + cfg.NextProtos = append([]string{NextProtoTLS}, cfg.NextProtos...) + } + if cfg.ServerName == "" { + cfg.ServerName = host + } + return cfg + } func (t *Transport) dialTLS(ctx context.Context, network, addr string, tlsCfg *tls.Config) (net.Conn, error) { + if t.DialTLSContext != nil { + return t.DialTLSContext(ctx, network, addr, tlsCfg) + } else if t.DialTLS != nil { + return t.DialTLS(network, addr, tlsCfg) + } tlsCn, err := t.dialTLSWithContext(ctx, network, addr, tlsCfg) + if err != nil { + return nil, err + } + state := tlsCn.ConnectionState() + if p := state.NegotiatedProtocol; p != NextProtoTLS { + return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, NextProtoTLS) + } + if !state.NegotiatedProtocolIsMutual { + return nil, errors.New("http2: could not negotiate protocol mutually") + } + return tlsCn, nil + } // disableKeepAlives reports whether connections should be closed as + // soon as possible after handling the first request. + func (t *Transport) disableKeepAlives() bool { + return t.t1 != nil && t.t1.DisableKeepAlives + } func (t *Transport) expectContinueTimeout() time.Duration { + if t.t1 == nil { + return 0 + } + return t.t1.ExpectContinueTimeout + } func (t *Transport) maxDecoderHeaderTableSize() uint32 { + if v := t.MaxDecoderHeaderTableSize; v > 0 { + return v + } + return initialHeaderTableSize + } func (t *Transport) maxEncoderHeaderTableSize() uint32 { + if v := t.MaxEncoderHeaderTableSize; v > 0 { + return v + } + return initialHeaderTableSize + } func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) { + return t.newClientConn(c, t.disableKeepAlives(), nil) + } func (t *Transport) newClientConn(c net.Conn, singleUse bool, hooks *testSyncHooks) (*ClientConn, error) { + cc := &ClientConn{ - t: t, - tconn: c, - readerDone: make(chan struct{}), - nextStreamID: 1, - maxFrameSize: 16 << 10, // spec default - initialWindowSize: 65535, // spec default - maxConcurrentStreams: initialMaxConcurrentStreams, // "infinite", per spec. Use a smaller value until we have received server settings. - peerMaxHeaderListSize: 0xffffffffffffffff, // "infinite", per spec. Use 2^64-1 instead. - streams: make(map[uint32]*clientStream), - singleUse: singleUse, - wantSettingsAck: true, - pings: make(map[[8]byte]chan struct{}), - reqHeaderMu: make(chan struct{}, 1), - syncHooks: hooks, + + t: t, + + tconn: c, + + readerDone: make(chan struct{}), + + nextStreamID: 1, + + maxFrameSize: 16 << 10, // spec default + + initialWindowSize: 65535, // spec default + + maxConcurrentStreams: initialMaxConcurrentStreams, // "infinite", per spec. Use a smaller value until we have received server settings. + + peerMaxHeaderListSize: 0xffffffffffffffff, // "infinite", per spec. Use 2^64-1 instead. + + streams: make(map[uint32]*clientStream), + + singleUse: singleUse, + + wantSettingsAck: true, + + pings: make(map[[8]byte]chan struct{}), + + reqHeaderMu: make(chan struct{}, 1), + + syncHooks: hooks, } + if hooks != nil { + hooks.newclientconn(cc) + c = cc.tconn + } + if d := t.idleConnTimeout(); d != 0 { + cc.idleTimeout = d + cc.idleTimer = cc.afterFunc(d, cc.onIdleTimeout) + } + if VerboseLogs { + t.vlogf("http2: Transport creating client conn %p to %v", cc, c.RemoteAddr()) + } cc.cond = sync.NewCond(&cc.mu) + cc.flow.add(int32(initialWindowSize)) // TODO: adjust this writer size to account for frame size + + // MTU + crypto/tls record padding. + cc.bw = bufio.NewWriter(stickyErrWriter{ - conn: c, + + conn: c, + timeout: t.WriteByteTimeout, - err: &cc.werr, + + err: &cc.werr, }) + cc.br = bufio.NewReader(c) + cc.fr = NewFramer(cc.bw, cc.br) + if t.maxFrameReadSize() != 0 { + cc.fr.SetMaxReadFrameSize(t.maxFrameReadSize()) + } + if t.CountError != nil { + cc.fr.countError = t.CountError + } + maxHeaderTableSize := t.maxDecoderHeaderTableSize() + cc.fr.ReadMetaHeaders = hpack.NewDecoder(maxHeaderTableSize, nil) + cc.fr.MaxHeaderListSize = t.maxHeaderListSize() cc.henc = hpack.NewEncoder(&cc.hbuf) + cc.henc.SetMaxDynamicTableSizeLimit(t.maxEncoderHeaderTableSize()) + cc.peerMaxHeaderTableSize = initialHeaderTableSize if t.AllowHTTP { + cc.nextStreamID = 3 + } if cs, ok := c.(connectionStater); ok { + state := cs.ConnectionState() + cc.tlsState = &state + } initialSettings := []Setting{ + {ID: SettingEnablePush, Val: 0}, + {ID: SettingInitialWindowSize, Val: transportDefaultStreamFlow}, } + if max := t.maxFrameReadSize(); max != 0 { + initialSettings = append(initialSettings, Setting{ID: SettingMaxFrameSize, Val: max}) + } + if max := t.maxHeaderListSize(); max != 0 { + initialSettings = append(initialSettings, Setting{ID: SettingMaxHeaderListSize, Val: max}) + } + if maxHeaderTableSize != initialHeaderTableSize { + initialSettings = append(initialSettings, Setting{ID: SettingHeaderTableSize, Val: maxHeaderTableSize}) + } cc.bw.Write(clientPreface) + cc.fr.WriteSettings(initialSettings...) + cc.fr.WriteWindowUpdate(0, transportDefaultConnFlow) + cc.inflow.init(transportDefaultConnFlow + initialWindowSize) + cc.bw.Flush() + if cc.werr != nil { + cc.Close() + return nil, cc.werr + } cc.goRun(cc.readLoop) + return cc, nil + } func (cc *ClientConn) healthCheck() { + pingTimeout := cc.t.pingTimeout() + // We don't need to periodically ping in the health check, because the readLoop of ClientConn will + // trigger the healthCheck again if there is no frame received. + ctx, cancel := cc.contextWithTimeout(context.Background(), pingTimeout) + defer cancel() + cc.vlogf("http2: Transport sending health check") + err := cc.Ping(ctx) + if err != nil { + cc.vlogf("http2: Transport health check failure: %v", err) + cc.closeForLostPing() + } else { + cc.vlogf("http2: Transport health check success") + } + } // SetDoNotReuse marks cc as not reusable for future HTTP requests. + func (cc *ClientConn) SetDoNotReuse() { + cc.mu.Lock() + defer cc.mu.Unlock() + cc.doNotReuse = true + } func (cc *ClientConn) setGoAway(f *GoAwayFrame) { + cc.mu.Lock() + defer cc.mu.Unlock() old := cc.goAway + cc.goAway = f // Merge the previous and current GoAway error frames. + if cc.goAwayDebug == "" { + cc.goAwayDebug = string(f.DebugData()) + } + if old != nil && old.ErrCode != ErrCodeNo { + cc.goAway.ErrCode = old.ErrCode + } + last := f.LastStreamID + for streamID, cs := range cc.streams { + if streamID <= last { + // The server's GOAWAY indicates that it received this stream. + // It will either finish processing it, or close the connection + // without doing so. Either way, leave the stream alone for now. + continue + } + if streamID == 1 && cc.goAway.ErrCode != ErrCodeNo { + // Don't retry the first stream on a connection if we get a non-NO error. + // If the server is sending an error on a new connection, + // retrying the request on a new one probably isn't going to work. + cs.abortStreamLocked(fmt.Errorf("http2: Transport received GOAWAY from server ErrCode:%v", cc.goAway.ErrCode)) + } else { + // Aborting the stream with errClentConnGotGoAway indicates that + // the request should be retried on a new connection. + cs.abortStreamLocked(errClientConnGotGoAway) + } + } + } // CanTakeNewRequest reports whether the connection can take a new request, + // meaning it has not been closed or received or sent a GOAWAY. + // + // If the caller is going to immediately make a new request on this + // connection, use ReserveNewRequest instead. + func (cc *ClientConn) CanTakeNewRequest() bool { + cc.mu.Lock() + defer cc.mu.Unlock() + return cc.canTakeNewRequestLocked() + } // ReserveNewRequest is like CanTakeNewRequest but also reserves a + // concurrent stream in cc. The reservation is decremented on the + // next call to RoundTrip. + func (cc *ClientConn) ReserveNewRequest() bool { + cc.mu.Lock() + defer cc.mu.Unlock() + if st := cc.idleStateLocked(); !st.canTakeNewRequest { + return false + } + cc.streamsReserved++ + return true + } // ClientConnState describes the state of a ClientConn. + type ClientConnState struct { + // Closed is whether the connection is closed. + Closed bool // Closing is whether the connection is in the process of + // closing. It may be closing due to shutdown, being a + // single-use connection, being marked as DoNotReuse, or + // having received a GOAWAY frame. + Closing bool // StreamsActive is how many streams are active. + StreamsActive int // StreamsReserved is how many streams have been reserved via + // ClientConn.ReserveNewRequest. + StreamsReserved int // StreamsPending is how many requests have been sent in excess + // of the peer's advertised MaxConcurrentStreams setting and + // are waiting for other streams to complete. + StreamsPending int // MaxConcurrentStreams is how many concurrent streams the + // peer advertised as acceptable. Zero means no SETTINGS + // frame has been received yet. + MaxConcurrentStreams uint32 // LastIdle, if non-zero, is when the connection last + // transitioned to idle state. + LastIdle time.Time } // State returns a snapshot of cc's state. + func (cc *ClientConn) State() ClientConnState { + cc.wmu.Lock() + maxConcurrent := cc.maxConcurrentStreams + if !cc.seenSettings { + maxConcurrent = 0 + } + cc.wmu.Unlock() cc.mu.Lock() + defer cc.mu.Unlock() + return ClientConnState{ - Closed: cc.closed, - Closing: cc.closing || cc.singleUse || cc.doNotReuse || cc.goAway != nil, - StreamsActive: len(cc.streams), - StreamsReserved: cc.streamsReserved, - StreamsPending: cc.pendingRequests, - LastIdle: cc.lastIdle, + + Closed: cc.closed, + + Closing: cc.closing || cc.singleUse || cc.doNotReuse || cc.goAway != nil, + + StreamsActive: len(cc.streams), + + StreamsReserved: cc.streamsReserved, + + StreamsPending: cc.pendingRequests, + + LastIdle: cc.lastIdle, + MaxConcurrentStreams: maxConcurrent, } + } // clientConnIdleState describes the suitability of a client + // connection to initiate a new RoundTrip request. + type clientConnIdleState struct { canTakeNewRequest bool } func (cc *ClientConn) idleState() clientConnIdleState { + cc.mu.Lock() + defer cc.mu.Unlock() + return cc.idleStateLocked() + } func (cc *ClientConn) idleStateLocked() (st clientConnIdleState) { + if cc.singleUse && cc.nextStreamID > 1 { + return + } + var maxConcurrentOkay bool + if cc.t.StrictMaxConcurrentStreams { + // We'll tell the caller we can take a new request to + // prevent the caller from dialing a new TCP + // connection, but then we'll block later before + // writing it. + maxConcurrentOkay = true + } else { + maxConcurrentOkay = int64(len(cc.streams)+cc.streamsReserved+1) <= int64(cc.maxConcurrentStreams) + } st.canTakeNewRequest = cc.goAway == nil && !cc.closed && !cc.closing && maxConcurrentOkay && + !cc.doNotReuse && + int64(cc.nextStreamID)+2*int64(cc.pendingRequests) < math.MaxInt32 && + !cc.tooIdleLocked() + return + } func (cc *ClientConn) canTakeNewRequestLocked() bool { + st := cc.idleStateLocked() + return st.canTakeNewRequest + } // tooIdleLocked reports whether this connection has been been sitting idle + // for too much wall time. + func (cc *ClientConn) tooIdleLocked() bool { + // The Round(0) strips the monontonic clock reading so the + // times are compared based on their wall time. We don't want + // to reuse a connection that's been sitting idle during + // VM/laptop suspend if monotonic time was also frozen. + return cc.idleTimeout != 0 && !cc.lastIdle.IsZero() && time.Since(cc.lastIdle.Round(0)) > cc.idleTimeout + } // onIdleTimeout is called from a time.AfterFunc goroutine. It will + // only be called when we're idle, but because we're coming from a new + // goroutine, there could be a new request coming in at the same time, + // so this simply calls the synchronized closeIfIdle to shut down this + // connection. The timer could just call closeIfIdle, but this is more + // clear. + func (cc *ClientConn) onIdleTimeout() { + cc.closeIfIdle() + } func (cc *ClientConn) closeConn() { + t := time.AfterFunc(250*time.Millisecond, cc.forceCloseConn) + defer t.Stop() + cc.tconn.Close() + } // A tls.Conn.Close can hang for a long time if the peer is unresponsive. + // Try to shut it down more aggressively. + func (cc *ClientConn) forceCloseConn() { + tc, ok := cc.tconn.(*tls.Conn) + if !ok { + return + } + if nc := tc.NetConn(); nc != nil { + nc.Close() + } + } func (cc *ClientConn) closeIfIdle() { + cc.mu.Lock() + if len(cc.streams) > 0 || cc.streamsReserved > 0 { + cc.mu.Unlock() + return + } + cc.closed = true + nextID := cc.nextStreamID + // TODO: do clients send GOAWAY too? maybe? Just Close: + cc.mu.Unlock() if VerboseLogs { + cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, nextID-2) + } + cc.closeConn() + } func (cc *ClientConn) isDoNotReuseAndIdle() bool { + cc.mu.Lock() + defer cc.mu.Unlock() + return cc.doNotReuse && len(cc.streams) == 0 + } var shutdownEnterWaitStateHook = func() {} // Shutdown gracefully closes the client connection, waiting for running streams to complete. + func (cc *ClientConn) Shutdown(ctx context.Context) error { + if err := cc.sendGoAway(); err != nil { + return err + } + // Wait for all in-flight streams to complete or connection to close + done := make(chan struct{}) + cancelled := false // guarded by cc.mu + cc.goRun(func() { + cc.mu.Lock() + defer cc.mu.Unlock() + for { + if len(cc.streams) == 0 || cc.closed { + cc.closed = true + close(done) + break + } + if cancelled { + break + } + cc.condWait() + } + }) + shutdownEnterWaitStateHook() + select { + case <-done: + cc.closeConn() + return nil + case <-ctx.Done(): + cc.mu.Lock() + // Free the goroutine above + cancelled = true + cc.condBroadcast() + cc.mu.Unlock() + return ctx.Err() + } + } func (cc *ClientConn) sendGoAway() error { + cc.mu.Lock() + closing := cc.closing + cc.closing = true + maxStreamID := cc.nextStreamID + cc.mu.Unlock() + if closing { + // GOAWAY sent already + return nil + } cc.wmu.Lock() + defer cc.wmu.Unlock() + // Send a graceful shutdown frame to server + if err := cc.fr.WriteGoAway(maxStreamID, ErrCodeNo, nil); err != nil { + return err + } + if err := cc.bw.Flush(); err != nil { + return err + } + // Prevent new requests + return nil + } // closes the client connection immediately. In-flight requests are interrupted. + // err is sent to streams. + func (cc *ClientConn) closeForError(err error) { + cc.mu.Lock() + cc.closed = true + for _, cs := range cc.streams { + cs.abortStreamLocked(err) + } + cc.condBroadcast() + cc.mu.Unlock() + cc.closeConn() + } // Close closes the client connection immediately. + // + // In-flight requests are interrupted. For a graceful shutdown, use Shutdown instead. + func (cc *ClientConn) Close() error { + err := errors.New("http2: client connection force closed via ClientConn.Close") + cc.closeForError(err) + return nil + } // closes the client connection immediately. In-flight requests are interrupted. + func (cc *ClientConn) closeForLostPing() { + err := errors.New("http2: client connection lost") + if f := cc.t.CountError; f != nil { + f("conn_close_lost_ping") + } + cc.closeForError(err) + } // errRequestCanceled is a copy of net/http's errRequestCanceled because it's not + // exported. At least they'll be DeepEqual for h1-vs-h2 comparisons tests. + var errRequestCanceled = errors.New("net/http: request canceled") func commaSeparatedTrailers(req *http.Request) (string, error) { + keys := make([]string, 0, len(req.Trailer)) + for k := range req.Trailer { + k = canonicalHeader(k) + switch k { + case "Transfer-Encoding", "Trailer", "Content-Length": + return "", fmt.Errorf("invalid Trailer key %q", k) + } + keys = append(keys, k) + } + if len(keys) > 0 { + sort.Strings(keys) + return strings.Join(keys, ","), nil + } + return "", nil + } func (cc *ClientConn) responseHeaderTimeout() time.Duration { + if cc.t.t1 != nil { + return cc.t.t1.ResponseHeaderTimeout + } + // No way to do this (yet?) with just an http2.Transport. Probably + // no need. Request.Cancel this is the new way. We only need to support + // this for compatibility with the old http.Transport fields when + // we're doing transparent http2. + return 0 + } // checkConnHeaders checks whether req has any invalid connection-level headers. + // per RFC 7540 section 8.1.2.2: Connection-Specific Header Fields. + // Certain headers are special-cased as okay but not transmitted later. + func checkConnHeaders(req *http.Request) error { + if v := req.Header.Get("Upgrade"); v != "" { + return fmt.Errorf("http2: invalid Upgrade request header: %q", req.Header["Upgrade"]) + } + if vv := req.Header["Transfer-Encoding"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "chunked") { + return fmt.Errorf("http2: invalid Transfer-Encoding request header: %q", vv) + } + if vv := req.Header["Connection"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && !asciiEqualFold(vv[0], "close") && !asciiEqualFold(vv[0], "keep-alive")) { + return fmt.Errorf("http2: invalid Connection request header: %q", vv) + } + return nil + } // actualContentLength returns a sanitized version of + // req.ContentLength, where 0 actually means zero (not unknown) and -1 + // means unknown. + func actualContentLength(req *http.Request) int64 { + if req.Body == nil || req.Body == http.NoBody { + return 0 + } + if req.ContentLength != 0 { + return req.ContentLength + } + return -1 + } func (cc *ClientConn) decrStreamReservations() { + cc.mu.Lock() + defer cc.mu.Unlock() + cc.decrStreamReservationsLocked() + } func (cc *ClientConn) decrStreamReservationsLocked() { + if cc.streamsReserved > 0 { + cc.streamsReserved-- + } + } func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) { + return cc.roundTrip(req, nil) + } func (cc *ClientConn) roundTrip(req *http.Request, streamf func(*clientStream)) (*http.Response, error) { + ctx := req.Context() + cs := &clientStream{ - cc: cc, - ctx: ctx, - reqCancel: req.Cancel, - isHead: req.Method == "HEAD", - reqBody: req.Body, + + cc: cc, + + ctx: ctx, + + reqCancel: req.Cancel, + + isHead: req.Method == "HEAD", + + reqBody: req.Body, + reqBodyContentLength: actualContentLength(req), - trace: httptrace.ContextClientTrace(ctx), - peerClosed: make(chan struct{}), - abort: make(chan struct{}), - respHeaderRecv: make(chan struct{}), - donec: make(chan struct{}), + + trace: httptrace.ContextClientTrace(ctx), + + peerClosed: make(chan struct{}), + + abort: make(chan struct{}), + + respHeaderRecv: make(chan struct{}), + + donec: make(chan struct{}), } + cc.goRun(func() { + cs.doRequest(req) + }) waitDone := func() error { + if cc.syncHooks != nil { + cc.syncHooks.blockUntil(func() bool { + select { + case <-cs.donec: + case <-ctx.Done(): + case <-cs.reqCancel: + default: + return false + } + return true + }) + } + select { + case <-cs.donec: + return nil + case <-ctx.Done(): + return ctx.Err() + case <-cs.reqCancel: + return errRequestCanceled + } + } handleResponseHeaders := func() (*http.Response, error) { + res := cs.res + if res.StatusCode > 299 { + // On error or status code 3xx, 4xx, 5xx, etc abort any + // ongoing write, assuming that the server doesn't care + // about our request body. If the server replied with 1xx or + // 2xx, however, then assume the server DOES potentially + // want our body (e.g. full-duplex streaming: + // golang.org/issue/13444). If it turns out the server + // doesn't, they'll RST_STREAM us soon enough. This is a + // heuristic to avoid adding knobs to Transport. Hopefully + // we can keep it. + cs.abortRequestBodyWrite() + } + res.Request = req + res.TLS = cc.tlsState + if res.Body == noBody && actualContentLength(req) == 0 { + // If there isn't a request or response body still being + // written, then wait for the stream to be closed before + // RoundTrip returns. + if err := waitDone(); err != nil { + return nil, err + } + } + return res, nil + } cancelRequest := func(cs *clientStream, err error) error { + cs.cc.mu.Lock() + bodyClosed := cs.reqBodyClosed + cs.cc.mu.Unlock() + // Wait for the request body to be closed. + // + // If nothing closed the body before now, abortStreamLocked + // will have started a goroutine to close it. + // + // Closing the body before returning avoids a race condition + // with net/http checking its readTrackingBody to see if the + // body was read from or closed. See golang/go#60041. + // + // The body is closed in a separate goroutine without the + // connection mutex held, but dropping the mutex before waiting + // will keep us from holding it indefinitely if the body + // close is slow for some reason. + if bodyClosed != nil { + <-bodyClosed + } + return err + } if streamf != nil { + streamf(cs) + } for { + if cc.syncHooks != nil { + cc.syncHooks.blockUntil(func() bool { + select { + case <-cs.respHeaderRecv: + case <-cs.abort: + case <-ctx.Done(): + case <-cs.reqCancel: + default: + return false + } + return true + }) + } + select { + case <-cs.respHeaderRecv: + return handleResponseHeaders() + case <-cs.abort: + select { + case <-cs.respHeaderRecv: + // If both cs.respHeaderRecv and cs.abort are signaling, + // pick respHeaderRecv. The server probably wrote the + // response and immediately reset the stream. + // golang.org/issue/49645 + return handleResponseHeaders() + default: + waitDone() + return nil, cs.abortErr + } + case <-ctx.Done(): + err := ctx.Err() + cs.abortStream(err) + return nil, cancelRequest(cs, err) + case <-cs.reqCancel: + cs.abortStream(errRequestCanceled) + return nil, cancelRequest(cs, errRequestCanceled) + } + } + } // doRequest runs for the duration of the request lifetime. + // + // It sends the request and performs post-request cleanup (closing Request.Body, etc.). + func (cs *clientStream) doRequest(req *http.Request) { + err := cs.writeRequest(req) + cs.cleanupWriteRequest(err) + } // writeRequest sends a request. + // + // It returns nil after the request is written, the response read, + // and the request stream is half-closed by the peer. + // + // It returns non-nil if the request ends otherwise. + // If the returned error is StreamError, the error Code may be used in resetting the stream. + func (cs *clientStream) writeRequest(req *http.Request) (err error) { + cc := cs.cc + ctx := cs.ctx if err := checkConnHeaders(req); err != nil { + return err + } // Acquire the new-request lock by writing to reqHeaderMu. + // This lock guards the critical section covering allocating a new stream ID + // (requires mu) and creating the stream (requires wmu). + if cc.reqHeaderMu == nil { + panic("RoundTrip on uninitialized ClientConn") // for tests + } + var newStreamHook func(*clientStream) + if cc.syncHooks != nil { + newStreamHook = cc.syncHooks.newstream + cc.syncHooks.blockUntil(func() bool { + select { + case cc.reqHeaderMu <- struct{}{}: + <-cc.reqHeaderMu + case <-cs.reqCancel: + case <-ctx.Done(): + default: + return false + } + return true + }) + } + select { + case cc.reqHeaderMu <- struct{}{}: + case <-cs.reqCancel: + return errRequestCanceled + case <-ctx.Done(): + return ctx.Err() + } cc.mu.Lock() + if cc.idleTimer != nil { + cc.idleTimer.Stop() + } + cc.decrStreamReservationsLocked() + if err := cc.awaitOpenSlotForStreamLocked(cs); err != nil { + cc.mu.Unlock() + <-cc.reqHeaderMu + return err + } + cc.addStreamLocked(cs) // assigns stream ID + if isConnectionCloseRequest(req) { + cc.doNotReuse = true + } + cc.mu.Unlock() if newStreamHook != nil { + newStreamHook(cs) + } // TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere? + if !cc.t.disableCompression() && + req.Header.Get("Accept-Encoding") == "" && + req.Header.Get("Range") == "" && + !cs.isHead { + // Request gzip only, not deflate. Deflate is ambiguous and + // not as universally supported anyway. + // See: https://zlib.net/zlib_faq.html#faq39 + // + // Note that we don't request this for HEAD requests, + // due to a bug in nginx: + // http://trac.nginx.org/nginx/ticket/358 + // https://golang.org/issue/5522 + // + // We don't request gzip if the request is for a range, since + // auto-decoding a portion of a gzipped document will just fail + // anyway. See https://golang.org/issue/8923 + cs.requestedGzip = true + } continueTimeout := cc.t.expectContinueTimeout() + if continueTimeout != 0 { + if !httpguts.HeaderValuesContainsToken(req.Header["Expect"], "100-continue") { + continueTimeout = 0 + } else { + cs.on100 = make(chan struct{}, 1) + } + } // Past this point (where we send request headers), it is possible for + // RoundTrip to return successfully. Since the RoundTrip contract permits + // the caller to "mutate or reuse" the Request after closing the Response's Body, + // we must take care when referencing the Request from here on. + err = cs.encodeAndWriteHeaders(req) + <-cc.reqHeaderMu + if err != nil { + return err + } hasBody := cs.reqBodyContentLength != 0 + if !hasBody { + cs.sentEndStream = true + } else { + if continueTimeout != 0 { + traceWait100Continue(cs.trace) + timer := time.NewTimer(continueTimeout) + select { + case <-timer.C: + err = nil + case <-cs.on100: + err = nil + case <-cs.abort: + err = cs.abortErr + case <-ctx.Done(): + err = ctx.Err() + case <-cs.reqCancel: + err = errRequestCanceled + } + timer.Stop() + if err != nil { + traceWroteRequest(cs.trace, err) + return err + } + } if err = cs.writeRequestBody(req); err != nil { + if err != errStopReqBodyWrite { + traceWroteRequest(cs.trace, err) + return err + } + } else { + cs.sentEndStream = true + } + } traceWroteRequest(cs.trace, err) var respHeaderTimer <-chan time.Time + var respHeaderRecv chan struct{} + if d := cc.responseHeaderTimeout(); d != 0 { + timer := cc.newTimer(d) + defer timer.Stop() + respHeaderTimer = timer.C() + respHeaderRecv = cs.respHeaderRecv + } + // Wait until the peer half-closes its end of the stream, + // or until the request is aborted (via context, error, or otherwise), + // whichever comes first. + for { + if cc.syncHooks != nil { + cc.syncHooks.blockUntil(func() bool { + select { + case <-cs.peerClosed: + case <-respHeaderTimer: + case <-respHeaderRecv: + case <-cs.abort: + case <-ctx.Done(): + case <-cs.reqCancel: + default: + return false + } + return true + }) + } + select { + case <-cs.peerClosed: + return nil + case <-respHeaderTimer: + return errTimeout + case <-respHeaderRecv: + respHeaderRecv = nil + respHeaderTimer = nil // keep waiting for END_STREAM + case <-cs.abort: + return cs.abortErr + case <-ctx.Done(): + return ctx.Err() + case <-cs.reqCancel: + return errRequestCanceled + } + } + } func (cs *clientStream) encodeAndWriteHeaders(req *http.Request) error { + cc := cs.cc + ctx := cs.ctx cc.wmu.Lock() + defer cc.wmu.Unlock() // If the request was canceled while waiting for cc.mu, just quit. + select { + case <-cs.abort: + return cs.abortErr + case <-ctx.Done(): + return ctx.Err() + case <-cs.reqCancel: + return errRequestCanceled + default: + } // Encode headers. + // + // we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,} (DATA is + // sent by writeRequestBody below, along with any Trailers, + // again in form HEADERS{1}, CONTINUATION{0,}) + trailers, err := commaSeparatedTrailers(req) + if err != nil { + return err + } + hasTrailers := trailers != "" + contentLen := actualContentLength(req) + hasBody := contentLen != 0 + hdrs, err := cc.encodeHeaders(req, cs.requestedGzip, trailers, contentLen) + if err != nil { + return err + } // Write the request. + endStream := !hasBody && !hasTrailers + cs.sentHeaders = true + err = cc.writeHeaders(cs.ID, endStream, int(cc.maxFrameSize), hdrs) + traceWroteHeaders(cs.trace) + return err + } // cleanupWriteRequest performs post-request tasks. + // + // If err (the result of writeRequest) is non-nil and the stream is not closed, + // cleanupWriteRequest will send a reset to the peer. + func (cs *clientStream) cleanupWriteRequest(err error) { + cc := cs.cc if cs.ID == 0 { + // We were canceled before creating the stream, so return our reservation. + cc.decrStreamReservations() + } // TODO: write h12Compare test showing whether + // Request.Body is closed by the Transport, + // and in multiple cases: server replies <=299 and >299 + // while still writing request body + cc.mu.Lock() + mustCloseBody := false + if cs.reqBody != nil && cs.reqBodyClosed == nil { + mustCloseBody = true + cs.reqBodyClosed = make(chan struct{}) + } + bodyClosed := cs.reqBodyClosed + cc.mu.Unlock() + if mustCloseBody { + cs.reqBody.Close() + close(bodyClosed) + } + if bodyClosed != nil { + <-bodyClosed + } if err != nil && cs.sentEndStream { + // If the connection is closed immediately after the response is read, + // we may be aborted before finishing up here. If the stream was closed + // cleanly on both sides, there is no error. + select { + case <-cs.peerClosed: + err = nil + default: + } + } + if err != nil { + cs.abortStream(err) // possibly redundant, but harmless + if cs.sentHeaders { + if se, ok := err.(StreamError); ok { + if se.Cause != errFromPeer { + cc.writeStreamReset(cs.ID, se.Code, err) + } + } else { + cc.writeStreamReset(cs.ID, ErrCodeCancel, err) + } + } + cs.bufPipe.CloseWithError(err) // no-op if already closed + } else { + if cs.sentHeaders && !cs.sentEndStream { + cc.writeStreamReset(cs.ID, ErrCodeNo, nil) + } + cs.bufPipe.CloseWithError(errRequestCanceled) + } + if cs.ID != 0 { + cc.forgetStreamID(cs.ID) + } cc.wmu.Lock() + werr := cc.werr + cc.wmu.Unlock() + if werr != nil { + cc.Close() + } close(cs.donec) + } // awaitOpenSlotForStreamLocked waits until len(streams) < maxConcurrentStreams. + // Must hold cc.mu. + func (cc *ClientConn) awaitOpenSlotForStreamLocked(cs *clientStream) error { + for { + cc.lastActive = time.Now() + if cc.closed || !cc.canTakeNewRequestLocked() { + return errClientConnUnusable + } + cc.lastIdle = time.Time{} + if int64(len(cc.streams)) < int64(cc.maxConcurrentStreams) { + return nil + } + cc.pendingRequests++ + cc.condWait() + cc.pendingRequests-- + select { + case <-cs.abort: + return cs.abortErr + default: + } + } + } // requires cc.wmu be held + func (cc *ClientConn) writeHeaders(streamID uint32, endStream bool, maxFrameSize int, hdrs []byte) error { + first := true // first frame written (HEADERS is first, then CONTINUATION) + for len(hdrs) > 0 && cc.werr == nil { + chunk := hdrs + if len(chunk) > maxFrameSize { + chunk = chunk[:maxFrameSize] + } + hdrs = hdrs[len(chunk):] + endHeaders := len(hdrs) == 0 + if first { + cc.fr.WriteHeaders(HeadersFrameParam{ - StreamID: streamID, + + StreamID: streamID, + BlockFragment: chunk, - EndStream: endStream, - EndHeaders: endHeaders, + + EndStream: endStream, + + EndHeaders: endHeaders, }) + first = false + } else { + cc.fr.WriteContinuation(streamID, endHeaders, chunk) + } + } + cc.bw.Flush() + return cc.werr + } // internal error values; they don't escape to callers + var ( + // abort request body write; don't send cancel + errStopReqBodyWrite = errors.New("http2: aborting request body write") // abort request body write, but send stream reset of cancel. + errStopReqBodyWriteAndCancel = errors.New("http2: canceling request") errReqBodyTooLong = errors.New("http2: request body larger than specified content length") ) // frameScratchBufferLen returns the length of a buffer to use for + // outgoing request bodies to read/write to/from. + // + // It returns max(1, min(peer's advertised max frame size, + // Request.ContentLength+1, 512KB)). + func (cs *clientStream) frameScratchBufferLen(maxFrameSize int) int { + const max = 512 << 10 + n := int64(maxFrameSize) + if n > max { + n = max + } + if cl := cs.reqBodyContentLength; cl != -1 && cl+1 < n { + // Add an extra byte past the declared content-length to + // give the caller's Request.Body io.Reader a chance to + // give us more bytes than they declared, so we can catch it + // early. + n = cl + 1 + } + if n < 1 { + return 1 + } + return int(n) // doesn't truncate; max is 512K + } // Seven bufPools manage different frame sizes. This helps to avoid scenarios where long-running + // streaming requests using small frame sizes occupy large buffers initially allocated for prior + // requests needing big buffers. The size ranges are as follows: + // {0 KB, 16 KB], {16 KB, 32 KB], {32 KB, 64 KB], {64 KB, 128 KB], {128 KB, 256 KB], + // {256 KB, 512 KB], {512 KB, infinity} + // In practice, the maximum scratch buffer size should not exceed 512 KB due to + // frameScratchBufferLen(maxFrameSize), thus the "infinity pool" should never be used. + // It exists mainly as a safety measure, for potential future increases in max buffer size. + var bufPools [7]sync.Pool // of *[]byte + func bufPoolIndex(size int) int { + if size <= 16384 { + return 0 + } + size -= 1 + bits := bits.Len(uint(size)) + index := bits - 14 + if index >= len(bufPools) { + return len(bufPools) - 1 + } + return index + } func (cs *clientStream) writeRequestBody(req *http.Request) (err error) { + cc := cs.cc + body := cs.reqBody + sentEnd := false // whether we sent the final DATA frame w/ END_STREAM hasTrailers := req.Trailer != nil + remainLen := cs.reqBodyContentLength + hasContentLen := remainLen != -1 cc.mu.Lock() + maxFrameSize := int(cc.maxFrameSize) + cc.mu.Unlock() // Scratch buffer for reading into & writing from. + scratchLen := cs.frameScratchBufferLen(maxFrameSize) + var buf []byte + index := bufPoolIndex(scratchLen) + if bp, ok := bufPools[index].Get().(*[]byte); ok && len(*bp) >= scratchLen { + defer bufPools[index].Put(bp) + buf = *bp + } else { + buf = make([]byte, scratchLen) + defer bufPools[index].Put(&buf) + } var sawEOF bool + for !sawEOF { + n, err := body.Read(buf) + if hasContentLen { + remainLen -= int64(n) + if remainLen == 0 && err == nil { + // The request body's Content-Length was predeclared and + // we just finished reading it all, but the underlying io.Reader + // returned the final chunk with a nil error (which is one of + // the two valid things a Reader can do at EOF). Because we'd prefer + // to send the END_STREAM bit early, double-check that we're actually + // at EOF. Subsequent reads should return (0, EOF) at this point. + // If either value is different, we return an error in one of two ways below. + var scratch [1]byte + var n1 int + n1, err = body.Read(scratch[:]) + remainLen -= int64(n1) + } + if remainLen < 0 { + err = errReqBodyTooLong + return err + } + } + if err != nil { + cc.mu.Lock() + bodyClosed := cs.reqBodyClosed != nil + cc.mu.Unlock() + switch { + case bodyClosed: + return errStopReqBodyWrite + case err == io.EOF: + sawEOF = true + err = nil + default: + return err + } + } remain := buf[:n] + for len(remain) > 0 && err == nil { + var allowed int32 + allowed, err = cs.awaitFlowControl(len(remain)) + if err != nil { + return err + } + cc.wmu.Lock() + data := remain[:allowed] + remain = remain[allowed:] + sentEnd = sawEOF && len(remain) == 0 && !hasTrailers + err = cc.fr.WriteData(cs.ID, sentEnd, data) + if err == nil { + // TODO(bradfitz): this flush is for latency, not bandwidth. + // Most requests won't need this. Make this opt-in or + // opt-out? Use some heuristic on the body type? Nagel-like + // timers? Based on 'n'? Only last chunk of this for loop, + // unless flow control tokens are low? For now, always. + // If we change this, see comment below. + err = cc.bw.Flush() + } + cc.wmu.Unlock() + } + if err != nil { + return err + } + } if sentEnd { + // Already sent END_STREAM (which implies we have no + // trailers) and flushed, because currently all + // WriteData frames above get a flush. So we're done. + return nil + } // Since the RoundTrip contract permits the caller to "mutate or reuse" + // a request after the Response's Body is closed, verify that this hasn't + // happened before accessing the trailers. + cc.mu.Lock() + trailer := req.Trailer + err = cs.abortErr + cc.mu.Unlock() + if err != nil { + return err + } cc.wmu.Lock() + defer cc.wmu.Unlock() + var trls []byte + if len(trailer) > 0 { + trls, err = cc.encodeTrailers(trailer) + if err != nil { + return err + } + } // Two ways to send END_STREAM: either with trailers, or + // with an empty DATA frame. + if len(trls) > 0 { + err = cc.writeHeaders(cs.ID, true, maxFrameSize, trls) + } else { + err = cc.fr.WriteData(cs.ID, true, nil) + } + if ferr := cc.bw.Flush(); ferr != nil && err == nil { + err = ferr + } + return err + } // awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow + // control tokens from the server. + // It returns either the non-zero number of tokens taken or an error + // if the stream is dead. + func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) { + cc := cs.cc + ctx := cs.ctx + cc.mu.Lock() + defer cc.mu.Unlock() + for { + if cc.closed { + return 0, errClientConnClosed + } + if cs.reqBodyClosed != nil { + return 0, errStopReqBodyWrite + } + select { + case <-cs.abort: + return 0, cs.abortErr + case <-ctx.Done(): + return 0, ctx.Err() + case <-cs.reqCancel: + return 0, errRequestCanceled + default: + } + if a := cs.flow.available(); a > 0 { + take := a + if int(take) > maxBytes { take = int32(maxBytes) // can't truncate int; take is int32 + } + if take > int32(cc.maxFrameSize) { + take = int32(cc.maxFrameSize) + } + cs.flow.take(take) + return take, nil + } + cc.condWait() + } + } func validateHeaders(hdrs http.Header) string { + for k, vv := range hdrs { + if !httpguts.ValidHeaderFieldName(k) { + return fmt.Sprintf("name %q", k) + } + for _, v := range vv { + if !httpguts.ValidHeaderFieldValue(v) { + // Don't include the value in the error, + // because it may be sensitive. + return fmt.Sprintf("value for header %q", k) + } + } + } + return "" + } var errNilRequestURL = errors.New("http2: Request.URI is nil") // requires cc.wmu be held. + func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) { + cc.hbuf.Reset() + if req.URL == nil { + return nil, errNilRequestURL + } host := req.Host + if host == "" { + host = req.URL.Host + } + host, err := httpguts.PunycodeHostPort(host) + if err != nil { + return nil, err + } + if !httpguts.ValidHostHeader(host) { + return nil, errors.New("http2: invalid Host header") + } var path string + if req.Method != "CONNECT" { + path = req.URL.RequestURI() + if !validPseudoPath(path) { + orig := path + path = strings.TrimPrefix(path, req.URL.Scheme+"://"+host) + if !validPseudoPath(path) { + if req.URL.Opaque != "" { + return nil, fmt.Errorf("invalid request :path %q from URL.Opaque = %q", orig, req.URL.Opaque) + } else { + return nil, fmt.Errorf("invalid request :path %q", orig) + } + } + } + } // Check for any invalid headers+trailers and return an error before we + // potentially pollute our hpack state. (We want to be able to + // continue to reuse the hpack encoder for future requests) + if err := validateHeaders(req.Header); err != "" { + return nil, fmt.Errorf("invalid HTTP header %s", err) + } + if err := validateHeaders(req.Trailer); err != "" { + return nil, fmt.Errorf("invalid HTTP trailer %s", err) + } enumerateHeaders := func(f func(name, value string)) { + // 8.1.2.3 Request Pseudo-Header Fields + // The :path pseudo-header field includes the path and query parts of the + // target URI (the path-absolute production and optionally a '?' character + // followed by the query production, see Sections 3.3 and 3.4 of + // [RFC3986]). + f(":authority", host) + m := req.Method + if m == "" { + m = http.MethodGet + } + f(":method", m) + if req.Method != "CONNECT" { + f(":path", path) + f(":scheme", req.URL.Scheme) + } + if trailers != "" { + f("trailer", trailers) + } var didUA bool + for k, vv := range req.Header { + if asciiEqualFold(k, "host") || asciiEqualFold(k, "content-length") { + // Host is :authority, already sent. + // Content-Length is automatic, set below. + continue + } else if asciiEqualFold(k, "connection") || + asciiEqualFold(k, "proxy-connection") || + asciiEqualFold(k, "transfer-encoding") || + asciiEqualFold(k, "upgrade") || + asciiEqualFold(k, "keep-alive") { + // Per 8.1.2.2 Connection-Specific Header + // Fields, don't send connection-specific + // fields. We have already checked if any + // are error-worthy so just ignore the rest. + continue + } else if asciiEqualFold(k, "user-agent") { + // Match Go's http1 behavior: at most one + // User-Agent. If set to nil or empty string, + // then omit it. Otherwise if not mentioned, + // include the default (below). + didUA = true + if len(vv) < 1 { + continue + } + vv = vv[:1] + if vv[0] == "" { + continue + } + } else if asciiEqualFold(k, "cookie") { + // Per 8.1.2.5 To allow for better compression efficiency, the + // Cookie header field MAY be split into separate header fields, + // each with one or more cookie-pairs. + for _, v := range vv { + for { + p := strings.IndexByte(v, ';') + if p < 0 { + break + } + f("cookie", v[:p]) + p++ + // strip space after semicolon if any. + for p+1 <= len(v) && v[p] == ' ' { + p++ + } + v = v[p:] + } + if len(v) > 0 { + f("cookie", v) + } + } + continue + } for _, v := range vv { + f(k, v) + } + } + if shouldSendReqContentLength(req.Method, contentLength) { + f("content-length", strconv.FormatInt(contentLength, 10)) + } + if addGzipHeader { + f("accept-encoding", "gzip") + } + if !didUA { + f("user-agent", defaultUserAgent) + } + } // Do a first pass over the headers counting bytes to ensure + // we don't exceed cc.peerMaxHeaderListSize. This is done as a + // separate pass before encoding the headers to prevent + // modifying the hpack state. + hlSize := uint64(0) + enumerateHeaders(func(name, value string) { + hf := hpack.HeaderField{Name: name, Value: value} + hlSize += uint64(hf.Size()) + }) if hlSize > cc.peerMaxHeaderListSize { + return nil, errRequestHeaderListSize + } trace := httptrace.ContextClientTrace(req.Context()) + traceHeaders := traceHasWroteHeaderField(trace) // Header list size is ok. Write the headers. + enumerateHeaders(func(name, value string) { + name, ascii := lowerHeader(name) + if !ascii { + // Skip writing invalid headers. Per RFC 7540, Section 8.1.2, header + // field names have to be ASCII characters (just as in HTTP/1.x). + return + } + cc.writeHeader(name, value) + if traceHeaders { + traceWroteHeaderField(trace, name, value) + } + }) return cc.hbuf.Bytes(), nil + } // shouldSendReqContentLength reports whether the http2.Transport should send + // a "content-length" request header. This logic is basically a copy of the net/http + // transferWriter.shouldSendContentLength. + // The contentLength is the corrected contentLength (so 0 means actually 0, not unknown). + // -1 means unknown. + func shouldSendReqContentLength(method string, contentLength int64) bool { + if contentLength > 0 { + return true + } + if contentLength < 0 { + return false + } + // For zero bodies, whether we send a content-length depends on the method. + // It also kinda doesn't matter for http2 either way, with END_STREAM. + switch method { + case "POST", "PUT", "PATCH": + return true + default: + return false + } + } // requires cc.wmu be held. + func (cc *ClientConn) encodeTrailers(trailer http.Header) ([]byte, error) { + cc.hbuf.Reset() hlSize := uint64(0) + for k, vv := range trailer { + for _, v := range vv { + hf := hpack.HeaderField{Name: k, Value: v} + hlSize += uint64(hf.Size()) + } + } + if hlSize > cc.peerMaxHeaderListSize { + return nil, errRequestHeaderListSize + } for k, vv := range trailer { + lowKey, ascii := lowerHeader(k) + if !ascii { + // Skip writing invalid headers. Per RFC 7540, Section 8.1.2, header + // field names have to be ASCII characters (just as in HTTP/1.x). + continue + } + // Transfer-Encoding, etc.. have already been filtered at the + // start of RoundTrip + for _, v := range vv { + cc.writeHeader(lowKey, v) + } + } + return cc.hbuf.Bytes(), nil + } func (cc *ClientConn) writeHeader(name, value string) { + if VerboseLogs { + log.Printf("http2: Transport encoding header %q = %q", name, value) + } + cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value}) + } type resAndError struct { - _ incomparable + _ incomparable + res *http.Response + err error } // requires cc.mu be held. + func (cc *ClientConn) addStreamLocked(cs *clientStream) { + cs.flow.add(int32(cc.initialWindowSize)) + cs.flow.setConnFlow(&cc.flow) + cs.inflow.init(transportDefaultStreamFlow) + cs.ID = cc.nextStreamID + cc.nextStreamID += 2 + cc.streams[cs.ID] = cs + if cs.ID == 0 { + panic("assigned stream ID 0") + } + } func (cc *ClientConn) forgetStreamID(id uint32) { + cc.mu.Lock() + slen := len(cc.streams) + delete(cc.streams, id) + if len(cc.streams) != slen-1 { + panic("forgetting unknown stream id") + } + cc.lastActive = time.Now() + if len(cc.streams) == 0 && cc.idleTimer != nil { + cc.idleTimer.Reset(cc.idleTimeout) + cc.lastIdle = time.Now() + } + // Wake up writeRequestBody via clientStream.awaitFlowControl and + // wake up RoundTrip if there is a pending request. + cc.condBroadcast() closeOnIdle := cc.singleUse || cc.doNotReuse || cc.t.disableKeepAlives() || cc.goAway != nil + if closeOnIdle && cc.streamsReserved == 0 && len(cc.streams) == 0 { + if VerboseLogs { + cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, cc.nextStreamID-2) + } + cc.closed = true + defer cc.closeConn() + } cc.mu.Unlock() + } // clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop. + type clientConnReadLoop struct { - _ incomparable + _ incomparable + cc *ClientConn } // readLoop runs in its own goroutine and reads and dispatches frames. + func (cc *ClientConn) readLoop() { + rl := &clientConnReadLoop{cc: cc} + defer rl.cleanup() + cc.readerErr = rl.run() + if ce, ok := cc.readerErr.(ConnectionError); ok { + cc.wmu.Lock() + cc.fr.WriteGoAway(0, ErrCode(ce), nil) + cc.wmu.Unlock() + } + } // GoAwayError is returned by the Transport when the server closes the + // TCP connection after sending a GOAWAY frame. + type GoAwayError struct { LastStreamID uint32 - ErrCode ErrCode - DebugData string + + ErrCode ErrCode + + DebugData string } func (e GoAwayError) Error() string { + return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q", + e.LastStreamID, e.ErrCode, e.DebugData) + } func isEOFOrNetReadError(err error) bool { + if err == io.EOF { + return true + } + ne, ok := err.(*net.OpError) + return ok && ne.Op == "read" + } func (rl *clientConnReadLoop) cleanup() { + cc := rl.cc + cc.t.connPool().MarkDead(cc) + defer cc.closeConn() + defer close(cc.readerDone) if cc.idleTimer != nil { + cc.idleTimer.Stop() + } // Close any response bodies if the server closes prematurely. + // TODO: also do this if we've written the headers but not + // gotten a response yet. + err := cc.readerErr + cc.mu.Lock() + if cc.goAway != nil && isEOFOrNetReadError(err) { + err = GoAwayError{ + LastStreamID: cc.goAway.LastStreamID, - ErrCode: cc.goAway.ErrCode, - DebugData: cc.goAwayDebug, + + ErrCode: cc.goAway.ErrCode, + + DebugData: cc.goAwayDebug, } + } else if err == io.EOF { + err = io.ErrUnexpectedEOF + } + cc.closed = true for _, cs := range cc.streams { + select { + case <-cs.peerClosed: + // The server closed the stream before closing the conn, + // so no need to interrupt it. + default: + cs.abortStreamLocked(err) + } + } + cc.condBroadcast() + cc.mu.Unlock() + } // countReadFrameError calls Transport.CountError with a string + // representing err. + func (cc *ClientConn) countReadFrameError(err error) { + f := cc.t.CountError + if f == nil || err == nil { + return + } + if ce, ok := err.(ConnectionError); ok { + errCode := ErrCode(ce) + f(fmt.Sprintf("read_frame_conn_error_%s", errCode.stringToken())) + return + } + if errors.Is(err, io.EOF) { + f("read_frame_eof") + return + } + if errors.Is(err, io.ErrUnexpectedEOF) { + f("read_frame_unexpected_eof") + return + } + if errors.Is(err, ErrFrameTooLarge) { + f("read_frame_too_large") + return + } + f("read_frame_other") + } func (rl *clientConnReadLoop) run() error { + cc := rl.cc + gotSettings := false + readIdleTimeout := cc.t.ReadIdleTimeout + var t timer + if readIdleTimeout != 0 { + t = cc.afterFunc(readIdleTimeout, cc.healthCheck) + } + for { + f, err := cc.fr.ReadFrame() + if t != nil { + t.Reset(readIdleTimeout) + } + if err != nil { + cc.vlogf("http2: Transport readFrame error on conn %p: (%T) %v", cc, err, err) + } + if se, ok := err.(StreamError); ok { + if cs := rl.streamByID(se.StreamID); cs != nil { + if se.Cause == nil { + se.Cause = cc.fr.errDetail + } + rl.endStreamError(cs, se) + } + continue + } else if err != nil { + cc.countReadFrameError(err) + return err + } + if VerboseLogs { + cc.vlogf("http2: Transport received %s", summarizeFrame(f)) + } + if !gotSettings { + if _, ok := f.(*SettingsFrame); !ok { + cc.logf("protocol error: received %T before a SETTINGS frame", f) + return ConnectionError(ErrCodeProtocol) + } + gotSettings = true + } switch f := f.(type) { + case *MetaHeadersFrame: + err = rl.processHeaders(f) + case *DataFrame: + err = rl.processData(f) + case *GoAwayFrame: + err = rl.processGoAway(f) + case *RSTStreamFrame: + err = rl.processResetStream(f) + case *SettingsFrame: + err = rl.processSettings(f) + case *PushPromiseFrame: + err = rl.processPushPromise(f) + case *WindowUpdateFrame: + err = rl.processWindowUpdate(f) + case *PingFrame: + err = rl.processPing(f) + default: + cc.logf("Transport: unhandled response frame type %T", f) + } + if err != nil { + if VerboseLogs { + cc.vlogf("http2: Transport conn %p received error from processing frame %v: %v", cc, summarizeFrame(f), err) + } + return err + } + } + } func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error { + cs := rl.streamByID(f.StreamID) + if cs == nil { + // We'd get here if we canceled a request while the + // server had its response still in flight. So if this + // was just something we canceled, ignore it. + return nil + } + if cs.readClosed { + rl.endStreamError(cs, StreamError{ + StreamID: f.StreamID, - Code: ErrCodeProtocol, - Cause: errors.New("protocol error: headers after END_STREAM"), + + Code: ErrCodeProtocol, + + Cause: errors.New("protocol error: headers after END_STREAM"), }) + return nil + } + if !cs.firstByte { + if cs.trace != nil { + // TODO(bradfitz): move first response byte earlier, + // when we first read the 9 byte header, not waiting + // until all the HEADERS+CONTINUATION frames have been + // merged. This works for now. + traceFirstResponseByte(cs.trace) + } + cs.firstByte = true + } + if !cs.pastHeaders { + cs.pastHeaders = true + } else { + return rl.processTrailers(cs, f) + } res, err := rl.handleResponse(cs, f) + if err != nil { + if _, ok := err.(ConnectionError); ok { + return err + } + // Any other error type is a stream error. + rl.endStreamError(cs, StreamError{ + StreamID: f.StreamID, - Code: ErrCodeProtocol, - Cause: err, + + Code: ErrCodeProtocol, + + Cause: err, }) + return nil // return nil from process* funcs to keep conn alive + } + if res == nil { + // (nil, nil) special case. See handleResponse docs. + return nil + } + cs.resTrailer = &res.Trailer + cs.res = res + close(cs.respHeaderRecv) + if f.StreamEnded() { + rl.endStream(cs) + } + return nil + } // may return error types nil, or ConnectionError. Any other error value + // is a StreamError of type ErrCodeProtocol. The returned error in that case + // is the detail. + // + // As a special case, handleResponse may return (nil, nil) to skip the + // frame (currently only used for 1xx responses). + func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFrame) (*http.Response, error) { + if f.Truncated { + return nil, errResponseHeaderListSize + } status := f.PseudoValue("status") + if status == "" { + return nil, errors.New("malformed response from server: missing status pseudo header") + } + statusCode, err := strconv.Atoi(status) + if err != nil { + return nil, errors.New("malformed response from server: malformed non-numeric status pseudo header") + } regularFields := f.RegularFields() + strs := make([]string, len(regularFields)) + header := make(http.Header, len(regularFields)) + res := &http.Response{ - Proto: "HTTP/2.0", + + Proto: "HTTP/2.0", + ProtoMajor: 2, - Header: header, + + Header: header, + StatusCode: statusCode, - Status: status + " " + http.StatusText(statusCode), + + Status: status + " " + http.StatusText(statusCode), } + for _, hf := range regularFields { + key := canonicalHeader(hf.Name) + if key == "Trailer" { + t := res.Trailer + if t == nil { + t = make(http.Header) + res.Trailer = t + } + foreachHeaderElement(hf.Value, func(v string) { + t[canonicalHeader(v)] = nil + }) + } else { + vv := header[key] + if vv == nil && len(strs) > 0 { + // More than likely this will be a single-element key. + // Most headers aren't multi-valued. + // Set the capacity on strs[0] to 1, so any future append + // won't extend the slice into the other strings. + vv, strs = strs[:1:1], strs[1:] + vv[0] = hf.Value + header[key] = vv + } else { + header[key] = append(vv, hf.Value) + } + } + } if statusCode >= 100 && statusCode <= 199 { + if f.StreamEnded() { + return nil, errors.New("1xx informational response with END_STREAM flag") + } + cs.num1xx++ + const max1xxResponses = 5 // arbitrary bound on number of informational responses, same as net/http + if cs.num1xx > max1xxResponses { + return nil, errors.New("http2: too many 1xx informational responses") + } + if fn := cs.get1xxTraceFunc(); fn != nil { + if err := fn(statusCode, textproto.MIMEHeader(header)); err != nil { + return nil, err + } + } + if statusCode == 100 { + traceGot100Continue(cs.trace) + select { + case cs.on100 <- struct{}{}: + default: + } + } + cs.pastHeaders = false // do it all again + return nil, nil + } res.ContentLength = -1 + if clens := res.Header["Content-Length"]; len(clens) == 1 { + if cl, err := strconv.ParseUint(clens[0], 10, 63); err == nil { + res.ContentLength = int64(cl) + } else { + // TODO: care? unlike http/1, it won't mess up our framing, so it's + // more safe smuggling-wise to ignore. + } + } else if len(clens) > 1 { + // TODO: care? unlike http/1, it won't mess up our framing, so it's + // more safe smuggling-wise to ignore. + } else if f.StreamEnded() && !cs.isHead { + res.ContentLength = 0 + } if cs.isHead { + res.Body = noBody + return res, nil + } if f.StreamEnded() { + if res.ContentLength > 0 { + res.Body = missingBody{} + } else { + res.Body = noBody + } + return res, nil + } cs.bufPipe.setBuffer(&dataBuffer{expected: res.ContentLength}) + cs.bytesRemain = res.ContentLength + res.Body = transportResponseBody{cs} if cs.requestedGzip && asciiEqualFold(res.Header.Get("Content-Encoding"), "gzip") { + res.Header.Del("Content-Encoding") + res.Header.Del("Content-Length") + res.ContentLength = -1 + res.Body = &gzipReader{body: res.Body} + res.Uncompressed = true + } + return res, nil + } func (rl *clientConnReadLoop) processTrailers(cs *clientStream, f *MetaHeadersFrame) error { + if cs.pastTrailers { + // Too many HEADERS frames for this stream. + return ConnectionError(ErrCodeProtocol) + } + cs.pastTrailers = true + if !f.StreamEnded() { + // We expect that any headers for trailers also + // has END_STREAM. + return ConnectionError(ErrCodeProtocol) + } + if len(f.PseudoFields()) > 0 { + // No pseudo header fields are defined for trailers. + // TODO: ConnectionError might be overly harsh? Check. + return ConnectionError(ErrCodeProtocol) + } trailer := make(http.Header) + for _, hf := range f.RegularFields() { + key := canonicalHeader(hf.Name) + trailer[key] = append(trailer[key], hf.Value) + } + cs.trailer = trailer rl.endStream(cs) + return nil + } // transportResponseBody is the concrete type of Transport.RoundTrip's + // Response.Body. It is an io.ReadCloser. + type transportResponseBody struct { cs *clientStream } func (b transportResponseBody) Read(p []byte) (n int, err error) { + cs := b.cs + cc := cs.cc if cs.readErr != nil { + return 0, cs.readErr + } + n, err = b.cs.bufPipe.Read(p) + if cs.bytesRemain != -1 { + if int64(n) > cs.bytesRemain { + n = int(cs.bytesRemain) + if err == nil { + err = errors.New("net/http: server replied with more than declared Content-Length; truncated") + cs.abortStream(err) + } + cs.readErr = err + return int(cs.bytesRemain), err + } + cs.bytesRemain -= int64(n) + if err == io.EOF && cs.bytesRemain > 0 { + err = io.ErrUnexpectedEOF + cs.readErr = err + return n, err + } + } + if n == 0 { + // No flow control tokens to send back. + return + } cc.mu.Lock() + connAdd := cc.inflow.add(n) + var streamAdd int32 + if err == nil { // No need to refresh if the stream is over or failed. + streamAdd = cs.inflow.add(n) + } + cc.mu.Unlock() if connAdd != 0 || streamAdd != 0 { + cc.wmu.Lock() + defer cc.wmu.Unlock() + if connAdd != 0 { + cc.fr.WriteWindowUpdate(0, mustUint31(connAdd)) + } + if streamAdd != 0 { + cc.fr.WriteWindowUpdate(cs.ID, mustUint31(streamAdd)) + } + cc.bw.Flush() + } + return + } var errClosedResponseBody = errors.New("http2: response body closed") func (b transportResponseBody) Close() error { + cs := b.cs + cc := cs.cc cs.bufPipe.BreakWithError(errClosedResponseBody) + cs.abortStream(errClosedResponseBody) unread := cs.bufPipe.Len() + if unread > 0 { + cc.mu.Lock() + // Return connection-level flow control. + connAdd := cc.inflow.add(unread) + cc.mu.Unlock() // TODO(dneil): Acquiring this mutex can block indefinitely. + // Move flow control return to a goroutine? + cc.wmu.Lock() + // Return connection-level flow control. + if connAdd > 0 { + cc.fr.WriteWindowUpdate(0, uint32(connAdd)) + } + cc.bw.Flush() + cc.wmu.Unlock() + } select { + case <-cs.donec: + case <-cs.ctx.Done(): + // See golang/go#49366: The net/http package can cancel the + // request context after the response body is fully read. + // Don't treat this as an error. + return nil + case <-cs.reqCancel: + return errRequestCanceled + } + return nil + } func (rl *clientConnReadLoop) processData(f *DataFrame) error { + cc := rl.cc + cs := rl.streamByID(f.StreamID) + data := f.Data() + if cs == nil { + cc.mu.Lock() + neverSent := cc.nextStreamID + cc.mu.Unlock() + if f.StreamID >= neverSent { + // We never asked for this. + cc.logf("http2: Transport received unsolicited DATA frame; closing connection") + return ConnectionError(ErrCodeProtocol) + } + // We probably did ask for this, but canceled. Just ignore it. + // TODO: be stricter here? only silently ignore things which + // we canceled, but not things which were closed normally + // by the peer? Tough without accumulating too much state. // But at least return their flow control: + if f.Length > 0 { + cc.mu.Lock() + ok := cc.inflow.take(f.Length) + connAdd := cc.inflow.add(int(f.Length)) + cc.mu.Unlock() + if !ok { + return ConnectionError(ErrCodeFlowControl) + } + if connAdd > 0 { + cc.wmu.Lock() + cc.fr.WriteWindowUpdate(0, uint32(connAdd)) + cc.bw.Flush() + cc.wmu.Unlock() + } + } + return nil + } + if cs.readClosed { + cc.logf("protocol error: received DATA after END_STREAM") + rl.endStreamError(cs, StreamError{ + StreamID: f.StreamID, - Code: ErrCodeProtocol, + + Code: ErrCodeProtocol, }) + return nil + } + if !cs.pastHeaders { + cc.logf("protocol error: received DATA before a HEADERS frame") + rl.endStreamError(cs, StreamError{ + StreamID: f.StreamID, - Code: ErrCodeProtocol, + + Code: ErrCodeProtocol, }) + return nil + } + if f.Length > 0 { + if cs.isHead && len(data) > 0 { + cc.logf("protocol error: received DATA on a HEAD request") + rl.endStreamError(cs, StreamError{ + StreamID: f.StreamID, - Code: ErrCodeProtocol, + + Code: ErrCodeProtocol, }) + return nil + } + // Check connection-level flow control. + cc.mu.Lock() + if !takeInflows(&cc.inflow, &cs.inflow, f.Length) { + cc.mu.Unlock() + return ConnectionError(ErrCodeFlowControl) + } + // Return any padded flow control now, since we won't + // refund it later on body reads. + var refund int + if pad := int(f.Length) - len(data); pad > 0 { + refund += pad + } didReset := false + var err error + if len(data) > 0 { + if _, err = cs.bufPipe.Write(data); err != nil { + // Return len(data) now if the stream is already closed, + // since data will never be read. + didReset = true + refund += len(data) + } + } sendConn := cc.inflow.add(refund) + var sendStream int32 + if !didReset { + sendStream = cs.inflow.add(refund) + } + cc.mu.Unlock() if sendConn > 0 || sendStream > 0 { + cc.wmu.Lock() + if sendConn > 0 { + cc.fr.WriteWindowUpdate(0, uint32(sendConn)) + } + if sendStream > 0 { + cc.fr.WriteWindowUpdate(cs.ID, uint32(sendStream)) + } + cc.bw.Flush() + cc.wmu.Unlock() + } if err != nil { + rl.endStreamError(cs, err) + return nil + } + } if f.StreamEnded() { + rl.endStream(cs) + } + return nil + } func (rl *clientConnReadLoop) endStream(cs *clientStream) { + // TODO: check that any declared content-length matches, like + // server.go's (*stream).endStream method. + if !cs.readClosed { + cs.readClosed = true + // Close cs.bufPipe and cs.peerClosed with cc.mu held to avoid a + // race condition: The caller can read io.EOF from Response.Body + // and close the body before we close cs.peerClosed, causing + // cleanupWriteRequest to send a RST_STREAM. + rl.cc.mu.Lock() + defer rl.cc.mu.Unlock() + cs.bufPipe.closeWithErrorAndCode(io.EOF, cs.copyTrailers) + close(cs.peerClosed) + } + } func (rl *clientConnReadLoop) endStreamError(cs *clientStream, err error) { + cs.readAborted = true + cs.abortStream(err) + } func (rl *clientConnReadLoop) streamByID(id uint32) *clientStream { + rl.cc.mu.Lock() + defer rl.cc.mu.Unlock() + cs := rl.cc.streams[id] + if cs != nil && !cs.readAborted { + return cs + } + return nil + } func (cs *clientStream) copyTrailers() { + for k, vv := range cs.trailer { + t := cs.resTrailer + if *t == nil { + *t = make(http.Header) + } + (*t)[k] = vv + } + } func (rl *clientConnReadLoop) processGoAway(f *GoAwayFrame) error { + cc := rl.cc + cc.t.connPool().MarkDead(cc) + if f.ErrCode != 0 { + // TODO: deal with GOAWAY more. particularly the error code + cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode) + if fn := cc.t.CountError; fn != nil { + fn("recv_goaway_" + f.ErrCode.stringToken()) + } + } + cc.setGoAway(f) + return nil + } func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error { + cc := rl.cc + // Locking both mu and wmu here allows frame encoding to read settings with only wmu held. + // Acquiring wmu when f.IsAck() is unnecessary, but convenient and mostly harmless. + cc.wmu.Lock() + defer cc.wmu.Unlock() if err := rl.processSettingsNoWrite(f); err != nil { + return err + } + if !f.IsAck() { + cc.fr.WriteSettingsAck() + cc.bw.Flush() + } + return nil + } func (rl *clientConnReadLoop) processSettingsNoWrite(f *SettingsFrame) error { + cc := rl.cc + cc.mu.Lock() + defer cc.mu.Unlock() if f.IsAck() { + if cc.wantSettingsAck { + cc.wantSettingsAck = false + return nil + } + return ConnectionError(ErrCodeProtocol) + } var seenMaxConcurrentStreams bool + err := f.ForeachSetting(func(s Setting) error { + switch s.ID { + case SettingMaxFrameSize: + cc.maxFrameSize = s.Val + case SettingMaxConcurrentStreams: + cc.maxConcurrentStreams = s.Val + seenMaxConcurrentStreams = true + case SettingMaxHeaderListSize: + cc.peerMaxHeaderListSize = uint64(s.Val) + case SettingInitialWindowSize: + // Values above the maximum flow-control + // window size of 2^31-1 MUST be treated as a + // connection error (Section 5.4.1) of type + // FLOW_CONTROL_ERROR. + if s.Val > math.MaxInt32 { + return ConnectionError(ErrCodeFlowControl) + } // Adjust flow control of currently-open + // frames by the difference of the old initial + // window size and this one. + delta := int32(s.Val) - int32(cc.initialWindowSize) + for _, cs := range cc.streams { + cs.flow.add(delta) + } + cc.condBroadcast() cc.initialWindowSize = s.Val + case SettingHeaderTableSize: + cc.henc.SetMaxDynamicTableSize(s.Val) + cc.peerMaxHeaderTableSize = s.Val + default: + cc.vlogf("Unhandled Setting: %v", s) + } + return nil + }) + if err != nil { + return err + } if !cc.seenSettings { + if !seenMaxConcurrentStreams { + // This was the servers initial SETTINGS frame and it + // didn't contain a MAX_CONCURRENT_STREAMS field so + // increase the number of concurrent streams this + // connection can establish to our default. + cc.maxConcurrentStreams = defaultMaxConcurrentStreams + } + cc.seenSettings = true + } return nil + } func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error { + cc := rl.cc + cs := rl.streamByID(f.StreamID) + if f.StreamID != 0 && cs == nil { + return nil + } cc.mu.Lock() + defer cc.mu.Unlock() fl := &cc.flow + if cs != nil { + fl = &cs.flow + } + if !fl.add(int32(f.Increment)) { + // For stream, the sender sends RST_STREAM with an error code of FLOW_CONTROL_ERROR + if cs != nil { + rl.endStreamError(cs, StreamError{ + StreamID: f.StreamID, - Code: ErrCodeFlowControl, + + Code: ErrCodeFlowControl, }) + return nil + } return ConnectionError(ErrCodeFlowControl) + } + cc.condBroadcast() + return nil + } func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error { + cs := rl.streamByID(f.StreamID) + if cs == nil { + // TODO: return error if server tries to RST_STREAM an idle stream + return nil + } + serr := streamError(cs.ID, f.ErrCode) + serr.Cause = errFromPeer + if f.ErrCode == ErrCodeProtocol { + rl.cc.SetDoNotReuse() + } + if fn := cs.cc.t.CountError; fn != nil { + fn("recv_rststream_" + f.ErrCode.stringToken()) + } + cs.abortStream(serr) cs.bufPipe.CloseWithError(serr) + return nil + } // Ping sends a PING frame to the server and waits for the ack. + func (cc *ClientConn) Ping(ctx context.Context) error { + c := make(chan struct{}) + // Generate a random payload + var p [8]byte + for { + if _, err := rand.Read(p[:]); err != nil { + return err + } + cc.mu.Lock() + // check for dup before insert + if _, found := cc.pings[p]; !found { + cc.pings[p] = c + cc.mu.Unlock() + break + } + cc.mu.Unlock() + } + var pingError error + errc := make(chan struct{}) + cc.goRun(func() { + cc.wmu.Lock() + defer cc.wmu.Unlock() + if pingError = cc.fr.WritePing(false, p); pingError != nil { + close(errc) + return + } + if pingError = cc.bw.Flush(); pingError != nil { + close(errc) + return + } + }) + if cc.syncHooks != nil { + cc.syncHooks.blockUntil(func() bool { + select { + case <-c: + case <-errc: + case <-ctx.Done(): + case <-cc.readerDone: + default: + return false + } + return true + }) + } + select { + case <-c: + return nil + case <-errc: + return pingError + case <-ctx.Done(): + return ctx.Err() + case <-cc.readerDone: + // connection closed + return cc.readerErr + } + } func (rl *clientConnReadLoop) processPing(f *PingFrame) error { + if f.IsAck() { + cc := rl.cc + cc.mu.Lock() + defer cc.mu.Unlock() + // If ack, notify listener if any + if c, ok := cc.pings[f.Data]; ok { + close(c) + delete(cc.pings, f.Data) + } + return nil + } + cc := rl.cc + cc.wmu.Lock() + defer cc.wmu.Unlock() + if err := cc.fr.WritePing(true, f.Data); err != nil { + return err + } + return cc.bw.Flush() + } func (rl *clientConnReadLoop) processPushPromise(f *PushPromiseFrame) error { + // We told the peer we don't want them. + // Spec says: + // "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH + // setting of the peer endpoint is set to 0. An endpoint that + // has set this setting and has received acknowledgement MUST + // treat the receipt of a PUSH_PROMISE frame as a connection + // error (Section 5.4.1) of type PROTOCOL_ERROR." + return ConnectionError(ErrCodeProtocol) + } func (cc *ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error) { + // TODO: map err to more interesting error codes, once the + // HTTP community comes up with some. But currently for + // RST_STREAM there's no equivalent to GOAWAY frame's debug + // data, and the error codes are all pretty vague ("cancel"). + cc.wmu.Lock() + cc.fr.WriteRSTStream(streamID, code) + cc.bw.Flush() + cc.wmu.Unlock() + } var ( errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit") - errRequestHeaderListSize = errors.New("http2: request header list larger than peer's advertised limit") + + errRequestHeaderListSize = errors.New("http2: request header list larger than peer's advertised limit") ) func (cc *ClientConn) logf(format string, args ...interface{}) { + cc.t.logf(format, args...) + } func (cc *ClientConn) vlogf(format string, args ...interface{}) { + cc.t.vlogf(format, args...) + } func (t *Transport) vlogf(format string, args ...interface{}) { + if VerboseLogs { + t.logf(format, args...) + } + } func (t *Transport) logf(format string, args ...interface{}) { + log.Printf(format, args...) + } var noBody io.ReadCloser = noBodyReader{} type noBodyReader struct{} -func (noBodyReader) Close() error { return nil } +func (noBodyReader) Close() error { return nil } + func (noBodyReader) Read([]byte) (int, error) { return 0, io.EOF } type missingBody struct{} -func (missingBody) Close() error { return nil } +func (missingBody) Close() error { return nil } + func (missingBody) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF } func strSliceContains(ss []string, s string) bool { + for _, v := range ss { + if v == s { + return true + } + } + return false + } type erringRoundTripper struct{ err error } -func (rt erringRoundTripper) RoundTripErr() error { return rt.err } +func (rt erringRoundTripper) RoundTripErr() error { return rt.err } + func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, rt.err } // gzipReader wraps a response body so it can lazily + // call gzip.NewReader on the first call to Read + type gzipReader struct { - _ incomparable + _ incomparable + body io.ReadCloser // underlying Response.Body - zr *gzip.Reader // lazily-initialized gzip reader - zerr error // sticky error + + zr *gzip.Reader // lazily-initialized gzip reader + + zerr error // sticky error + } func (gz *gzipReader) Read(p []byte) (n int, err error) { + if gz.zerr != nil { + return 0, gz.zerr + } + if gz.zr == nil { + gz.zr, err = gzip.NewReader(gz.body) + if err != nil { + gz.zerr = err + return 0, err + } + } + return gz.zr.Read(p) + } func (gz *gzipReader) Close() error { + if err := gz.body.Close(); err != nil { + return err + } + gz.zerr = fs.ErrClosed + return nil + } type errorReader struct{ err error } @@ -3299,134 +5915,228 @@ type errorReader struct{ err error } func (r errorReader) Read(p []byte) (int, error) { return 0, r.err } // isConnectionCloseRequest reports whether req should use its own + // connection for a single request and then close the connection. + func isConnectionCloseRequest(req *http.Request) bool { + return req.Close || httpguts.HeaderValuesContainsToken(req.Header["Connection"], "close") + } // registerHTTPSProtocol calls Transport.RegisterProtocol but + // converting panics into errors. + func registerHTTPSProtocol(t *http.Transport, rt noDialH2RoundTripper) (err error) { + defer func() { + if e := recover(); e != nil { + err = fmt.Errorf("%v", e) + } + }() + t.RegisterProtocol("https", rt) + return nil + } // noDialH2RoundTripper is a RoundTripper which only tries to complete the request + // if there's already has a cached connection to the host. + // (The field is exported so it can be accessed via reflect from net/http; tested + // by TestNoDialH2RoundTripperType) + type noDialH2RoundTripper struct{ *Transport } func (rt noDialH2RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + res, err := rt.Transport.RoundTrip(req) + if isNoCachedConnError(err) { + return nil, http.ErrSkipAltProtocol + } + return res, err + } func (t *Transport) idleConnTimeout() time.Duration { + // to keep things backwards compatible, we use non-zero values of + // IdleConnTimeout, followed by using the IdleConnTimeout on the underlying + // http1 transport, followed by 0 + if t.IdleConnTimeout != 0 { + return t.IdleConnTimeout + } if t.t1 != nil { + return t.t1.IdleConnTimeout + } return 0 + } func traceGetConn(req *http.Request, hostPort string) { + trace := httptrace.ContextClientTrace(req.Context()) + if trace == nil || trace.GetConn == nil { + return + } + trace.GetConn(hostPort) + } func traceGotConn(req *http.Request, cc *ClientConn, reused bool) { + trace := httptrace.ContextClientTrace(req.Context()) + if trace == nil || trace.GotConn == nil { + return + } + ci := httptrace.GotConnInfo{Conn: cc.tconn} + ci.Reused = reused + cc.mu.Lock() + ci.WasIdle = len(cc.streams) == 0 && reused + if ci.WasIdle && !cc.lastActive.IsZero() { + ci.IdleTime = time.Since(cc.lastActive) + } + cc.mu.Unlock() trace.GotConn(ci) + } func traceWroteHeaders(trace *httptrace.ClientTrace) { + if trace != nil && trace.WroteHeaders != nil { + trace.WroteHeaders() + } + } func traceGot100Continue(trace *httptrace.ClientTrace) { + if trace != nil && trace.Got100Continue != nil { + trace.Got100Continue() + } + } func traceWait100Continue(trace *httptrace.ClientTrace) { + if trace != nil && trace.Wait100Continue != nil { + trace.Wait100Continue() + } + } func traceWroteRequest(trace *httptrace.ClientTrace, err error) { + if trace != nil && trace.WroteRequest != nil { + trace.WroteRequest(httptrace.WroteRequestInfo{Err: err}) + } + } func traceFirstResponseByte(trace *httptrace.ClientTrace) { + if trace != nil && trace.GotFirstResponseByte != nil { + trace.GotFirstResponseByte() + } + } func traceHasWroteHeaderField(trace *httptrace.ClientTrace) bool { + return trace != nil && trace.WroteHeaderField != nil + } func traceWroteHeaderField(trace *httptrace.ClientTrace, k, v string) { + if trace != nil && trace.WroteHeaderField != nil { + trace.WroteHeaderField(k, []string{v}) + } + } func traceGot1xxResponseFunc(trace *httptrace.ClientTrace) func(int, textproto.MIMEHeader) error { + if trace != nil { + return trace.Got1xxResponse + } + return nil + } // dialTLSWithContext uses tls.Dialer, added in Go 1.15, to open a TLS + // connection. + func (t *Transport) dialTLSWithContext(ctx context.Context, network, addr string, cfg *tls.Config) (*tls.Conn, error) { + dialer := &tls.Dialer{ + Config: cfg, } + cn, err := dialer.DialContext(ctx, network, addr) + if err != nil { + return nil, err + } + tlsCn := cn.(*tls.Conn) // DialContext comment promises this will always succeed + return tlsCn, nil + } diff --git a/vendor/golang.org/x/net/http2/write.go b/vendor/golang.org/x/net/http2/write.go index 33f6139..23eb723 100644 --- a/vendor/golang.org/x/net/http2/write.go +++ b/vendor/golang.org/x/net/http2/write.go @@ -1,5 +1,7 @@ // Copyright 2014 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package http2 @@ -16,56 +18,93 @@ import ( ) // writeFramer is implemented by any type that is used to write frames. + type writeFramer interface { writeFrame(writeContext) error // staysWithinBuffer reports whether this writer promises that + // it will only write less than or equal to size bytes, and it + // won't Flush the write context. + staysWithinBuffer(size int) bool } // writeContext is the interface needed by the various frame writer + // types below. All the writeFrame methods below are scheduled via the + // frame writing scheduler (see writeScheduler in writesched.go). + // + // This interface is implemented by *serverConn. + // + // TODO: decide whether to a) use this in the client code (which didn't + // end up using this yet, because it has a simpler design, not + // currently implementing priorities), or b) delete this and + // make the server code a bit more concrete. + type writeContext interface { Framer() *Framer + Flush() error + CloseConn() error + // HeaderEncoder returns an HPACK encoder that writes to the + // returned buffer. + HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) } // writeEndsStream reports whether w writes a frame that will transition + // the stream to a half-closed local state. This returns false for RST_STREAM, + // which closes the entire stream (not just the local half). + func writeEndsStream(w writeFramer) bool { + switch v := w.(type) { + case *writeData: + return v.endStream + case *writeResHeaders: + return v.endStream + case nil: + // This can only happen if the caller reuses w after it's + // been intentionally nil'ed out to prevent use. Keep this + // here to catch future refactoring breaking it. + panic("writeEndsStream called on nil writeFramer") + } + return false + } type flushFrameWriter struct{} func (flushFrameWriter) writeFrame(ctx writeContext) error { + return ctx.Flush() + } func (flushFrameWriter) staysWithinBuffer(max int) bool { return false } @@ -73,60 +112,83 @@ func (flushFrameWriter) staysWithinBuffer(max int) bool { return false } type writeSettings []Setting func (s writeSettings) staysWithinBuffer(max int) bool { + const settingSize = 6 // uint16 + uint32 + return frameHeaderLen+settingSize*len(s) <= max } func (s writeSettings) writeFrame(ctx writeContext) error { + return ctx.Framer().WriteSettings([]Setting(s)...) + } type writeGoAway struct { maxStreamID uint32 - code ErrCode + + code ErrCode } func (p *writeGoAway) writeFrame(ctx writeContext) error { + err := ctx.Framer().WriteGoAway(p.maxStreamID, p.code, nil) + ctx.Flush() // ignore error: we're hanging up on them anyway + return err + } func (*writeGoAway) staysWithinBuffer(max int) bool { return false } // flushes type writeData struct { - streamID uint32 - p []byte + streamID uint32 + + p []byte + endStream bool } func (w *writeData) String() string { + return fmt.Sprintf("writeData(stream=%d, p=%d, endStream=%v)", w.streamID, len(w.p), w.endStream) + } func (w *writeData) writeFrame(ctx writeContext) error { + return ctx.Framer().WriteData(w.streamID, w.endStream, w.p) + } func (w *writeData) staysWithinBuffer(max int) bool { + return frameHeaderLen+len(w.p) <= max + } // handlerPanicRST is the message sent from handler goroutines when + // the handler panics. + type handlerPanicRST struct { StreamID uint32 } func (hp handlerPanicRST) writeFrame(ctx writeContext) error { + return ctx.Framer().WriteRSTStream(hp.StreamID, ErrCodeInternal) + } func (hp handlerPanicRST) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max } func (se StreamError) writeFrame(ctx writeContext) error { + return ctx.Framer().WriteRSTStream(se.StreamID, se.Code) + } func (se StreamError) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max } @@ -134,7 +196,9 @@ func (se StreamError) staysWithinBuffer(max int) bool { return frameHeaderLen+4 type writePingAck struct{ pf *PingFrame } func (w writePingAck) writeFrame(ctx writeContext) error { + return ctx.Framer().WritePing(true, w.pf.Data) + } func (w writePingAck) staysWithinBuffer(max int) bool { return frameHeaderLen+len(w.pf.Data) <= max } @@ -142,158 +206,261 @@ func (w writePingAck) staysWithinBuffer(max int) bool { return frameHeaderLen+le type writeSettingsAck struct{} func (writeSettingsAck) writeFrame(ctx writeContext) error { + return ctx.Framer().WriteSettingsAck() + } func (writeSettingsAck) staysWithinBuffer(max int) bool { return frameHeaderLen <= max } // splitHeaderBlock splits headerBlock into fragments so that each fragment fits + // in a single frame, then calls fn for each fragment. firstFrag/lastFrag are true + // for the first/last fragment, respectively. + func splitHeaderBlock(ctx writeContext, headerBlock []byte, fn func(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error) error { + // For now we're lazy and just pick the minimum MAX_FRAME_SIZE + // that all peers must support (16KB). Later we could care + // more and send larger frames if the peer advertised it, but + // there's little point. Most headers are small anyway (so we + // generally won't have CONTINUATION frames), and extra frames + // only waste 9 bytes anyway. + const maxFrameSize = 16384 first := true + for len(headerBlock) > 0 { + frag := headerBlock + if len(frag) > maxFrameSize { + frag = frag[:maxFrameSize] + } + headerBlock = headerBlock[len(frag):] + if err := fn(ctx, frag, first, len(headerBlock) == 0); err != nil { + return err + } + first = false + } + return nil + } // writeResHeaders is a request to write a HEADERS and 0+ CONTINUATION frames -// for HTTP response headers or trailers from a server handler. -type writeResHeaders struct { - streamID uint32 - httpResCode int // 0 means no ":status" line - h http.Header // may be nil - trailers []string // if non-nil, which keys of h to write. nil means all. - endStream bool - date string - contentType string +// for HTTP response headers or trailers from a server handler. + +type writeResHeaders struct { + streamID uint32 + + httpResCode int // 0 means no ":status" line + + h http.Header // may be nil + + trailers []string // if non-nil, which keys of h to write. nil means all. + + endStream bool + + date string + + contentType string + contentLength string } func encKV(enc *hpack.Encoder, k, v string) { + if VerboseLogs { + log.Printf("http2: server encoding header %q = %q", k, v) + } + enc.WriteField(hpack.HeaderField{Name: k, Value: v}) + } func (w *writeResHeaders) staysWithinBuffer(max int) bool { + // TODO: this is a common one. It'd be nice to return true + // here and get into the fast path if we could be clever and + // calculate the size fast enough, or at least a conservative + // upper bound that usually fires. (Maybe if w.h and + // w.trailers are nil, so we don't need to enumerate it.) + // Otherwise I'm afraid that just calculating the length to + // answer this question would be slower than the ~2µs benefit. + return false + } func (w *writeResHeaders) writeFrame(ctx writeContext) error { + enc, buf := ctx.HeaderEncoder() + buf.Reset() if w.httpResCode != 0 { + encKV(enc, ":status", httpCodeString(w.httpResCode)) + } encodeHeaders(enc, w.h, w.trailers) if w.contentType != "" { + encKV(enc, "content-type", w.contentType) + } + if w.contentLength != "" { + encKV(enc, "content-length", w.contentLength) + } + if w.date != "" { + encKV(enc, "date", w.date) + } headerBlock := buf.Bytes() + if len(headerBlock) == 0 && w.trailers == nil { + panic("unexpected empty hpack") + } return splitHeaderBlock(ctx, headerBlock, w.writeHeaderBlock) + } func (w *writeResHeaders) writeHeaderBlock(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error { + if firstFrag { + return ctx.Framer().WriteHeaders(HeadersFrameParam{ - StreamID: w.streamID, + + StreamID: w.streamID, + BlockFragment: frag, - EndStream: w.endStream, - EndHeaders: lastFrag, + + EndStream: w.endStream, + + EndHeaders: lastFrag, }) + } else { + return ctx.Framer().WriteContinuation(w.streamID, lastFrag, frag) + } + } // writePushPromise is a request to write a PUSH_PROMISE and 0+ CONTINUATION frames. + type writePushPromise struct { - streamID uint32 // pusher stream - method string // for :method - url *url.URL // for :scheme, :authority, :path - h http.Header + streamID uint32 // pusher stream + + method string // for :method + + url *url.URL // for :scheme, :authority, :path + + h http.Header // Creates an ID for a pushed stream. This runs on serveG just before + // the frame is written. The returned ID is copied to promisedID. + allocatePromisedID func() (uint32, error) - promisedID uint32 + + promisedID uint32 } func (w *writePushPromise) staysWithinBuffer(max int) bool { + // TODO: see writeResHeaders.staysWithinBuffer + return false + } func (w *writePushPromise) writeFrame(ctx writeContext) error { + enc, buf := ctx.HeaderEncoder() + buf.Reset() encKV(enc, ":method", w.method) + encKV(enc, ":scheme", w.url.Scheme) + encKV(enc, ":authority", w.url.Host) + encKV(enc, ":path", w.url.RequestURI()) + encodeHeaders(enc, w.h, nil) headerBlock := buf.Bytes() + if len(headerBlock) == 0 { + panic("unexpected empty hpack") + } return splitHeaderBlock(ctx, headerBlock, w.writeHeaderBlock) + } func (w *writePushPromise) writeHeaderBlock(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error { + if firstFrag { + return ctx.Framer().WritePushPromise(PushPromiseParam{ - StreamID: w.streamID, - PromiseID: w.promisedID, + + StreamID: w.streamID, + + PromiseID: w.promisedID, + BlockFragment: frag, - EndHeaders: lastFrag, + + EndHeaders: lastFrag, }) + } else { + return ctx.Framer().WriteContinuation(w.streamID, lastFrag, frag) + } + } type write100ContinueHeadersFrame struct { @@ -301,70 +468,124 @@ type write100ContinueHeadersFrame struct { } func (w write100ContinueHeadersFrame) writeFrame(ctx writeContext) error { + enc, buf := ctx.HeaderEncoder() + buf.Reset() + encKV(enc, ":status", "100") + return ctx.Framer().WriteHeaders(HeadersFrameParam{ - StreamID: w.streamID, + + StreamID: w.streamID, + BlockFragment: buf.Bytes(), - EndStream: false, - EndHeaders: true, + + EndStream: false, + + EndHeaders: true, }) + } func (w write100ContinueHeadersFrame) staysWithinBuffer(max int) bool { + // Sloppy but conservative: + return 9+2*(len(":status")+len("100")) <= max + } type writeWindowUpdate struct { streamID uint32 // or 0 for conn-level - n uint32 + + n uint32 } func (wu writeWindowUpdate) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max } func (wu writeWindowUpdate) writeFrame(ctx writeContext) error { + return ctx.Framer().WriteWindowUpdate(wu.streamID, wu.n) + } // encodeHeaders encodes an http.Header. If keys is not nil, then (k, h[k]) + // is encoded only if k is in keys. + func encodeHeaders(enc *hpack.Encoder, h http.Header, keys []string) { + if keys == nil { + sorter := sorterPool.Get().(*sorter) + // Using defer here, since the returned keys from the + // sorter.Keys method is only valid until the sorter + // is returned: + defer sorterPool.Put(sorter) + keys = sorter.Keys(h) + } + for _, k := range keys { + vv := h[k] + k, ascii := lowerHeader(k) + if !ascii { + // Skip writing invalid headers. Per RFC 7540, Section 8.1.2, header + // field names have to be ASCII characters (just as in HTTP/1.x). + continue + } + if !validWireHeaderFieldName(k) { + // Skip it as backup paranoia. Per + // golang.org/issue/14048, these should + // already be rejected at a higher level. + continue + } + isTE := k == "transfer-encoding" + for _, v := range vv { + if !httpguts.ValidHeaderFieldValue(v) { + // TODO: return an error? golang.org/issue/14048 + // For now just omit it. + continue + } + // TODO: more of "8.1.2.2 Connection-Specific Header Fields" + if isTE && v != "trailers" { + continue + } + encKV(enc, k, v) + } + } + } diff --git a/vendor/golang.org/x/net/http2/writesched_priority.go b/vendor/golang.org/x/net/http2/writesched_priority.go index 0a242c6..7aaa110 100644 --- a/vendor/golang.org/x/net/http2/writesched_priority.go +++ b/vendor/golang.org/x/net/http2/writesched_priority.go @@ -1,5 +1,7 @@ // Copyright 2016 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package http2 @@ -11,441 +13,790 @@ import ( ) // RFC 7540, Section 5.3.5: the default weight is 16. + const priorityDefaultWeight = 15 // 16 = 15 + 1 // PriorityWriteSchedulerConfig configures a priorityWriteScheduler. + type PriorityWriteSchedulerConfig struct { + // MaxClosedNodesInTree controls the maximum number of closed streams to + // retain in the priority tree. Setting this to zero saves a small amount + // of memory at the cost of performance. + // + // See RFC 7540, Section 5.3.4: + // "It is possible for a stream to become closed while prioritization + // information ... is in transit. ... This potentially creates suboptimal + // prioritization, since the stream could be given a priority that is + // different from what is intended. To avoid these problems, an endpoint + // SHOULD retain stream prioritization state for a period after streams + // become closed. The longer state is retained, the lower the chance that + // streams are assigned incorrect or default priority values." + MaxClosedNodesInTree int // MaxIdleNodesInTree controls the maximum number of idle streams to + // retain in the priority tree. Setting this to zero saves a small amount + // of memory at the cost of performance. + // + // See RFC 7540, Section 5.3.4: + // Similarly, streams that are in the "idle" state can be assigned + // priority or become a parent of other streams. This allows for the + // creation of a grouping node in the dependency tree, which enables + // more flexible expressions of priority. Idle streams begin with a + // default priority (Section 5.3.5). + MaxIdleNodesInTree int // ThrottleOutOfOrderWrites enables write throttling to help ensure that + // data is delivered in priority order. This works around a race where + // stream B depends on stream A and both streams are about to call Write + // to queue DATA frames. If B wins the race, a naive scheduler would eagerly + // write as much data from B as possible, but this is suboptimal because A + // is a higher-priority stream. With throttling enabled, we write a small + // amount of data from B to minimize the amount of bandwidth that B can + // steal from A. + ThrottleOutOfOrderWrites bool } // NewPriorityWriteScheduler constructs a WriteScheduler that schedules + // frames by following HTTP/2 priorities as described in RFC 7540 Section 5.3. + // If cfg is nil, default options are used. + func NewPriorityWriteScheduler(cfg *PriorityWriteSchedulerConfig) WriteScheduler { + if cfg == nil { + // For justification of these defaults, see: + // https://docs.google.com/document/d/1oLhNg1skaWD4_DtaoCxdSRN5erEXrH-KnLrMwEpOtFY + cfg = &PriorityWriteSchedulerConfig{ - MaxClosedNodesInTree: 10, - MaxIdleNodesInTree: 10, + + MaxClosedNodesInTree: 10, + + MaxIdleNodesInTree: 10, + ThrottleOutOfOrderWrites: false, } + } ws := &priorityWriteScheduler{ - nodes: make(map[uint32]*priorityNode), + + nodes: make(map[uint32]*priorityNode), + maxClosedNodesInTree: cfg.MaxClosedNodesInTree, - maxIdleNodesInTree: cfg.MaxIdleNodesInTree, - enableWriteThrottle: cfg.ThrottleOutOfOrderWrites, + + maxIdleNodesInTree: cfg.MaxIdleNodesInTree, + + enableWriteThrottle: cfg.ThrottleOutOfOrderWrites, } + ws.nodes[0] = &ws.root + if cfg.ThrottleOutOfOrderWrites { + ws.writeThrottleLimit = 1024 + } else { + ws.writeThrottleLimit = math.MaxInt32 + } + return ws + } type priorityNodeState int const ( priorityNodeOpen priorityNodeState = iota + priorityNodeClosed + priorityNodeIdle ) // priorityNode is a node in an HTTP/2 priority tree. + // Each node is associated with a single stream ID. + // See RFC 7540, Section 5.3. + type priorityNode struct { - q writeQueue // queue of pending frames to write - id uint32 // id of the stream, or 0 for the root of the tree - weight uint8 // the actual weight is weight+1, so the value is in [1,256] - state priorityNodeState // open | closed | idle - bytes int64 // number of bytes written by this node, or 0 if closed - subtreeBytes int64 // sum(node.bytes) of all nodes in this subtree + q writeQueue // queue of pending frames to write + + id uint32 // id of the stream, or 0 for the root of the tree + + weight uint8 // the actual weight is weight+1, so the value is in [1,256] + + state priorityNodeState // open | closed | idle + + bytes int64 // number of bytes written by this node, or 0 if closed + + subtreeBytes int64 // sum(node.bytes) of all nodes in this subtree // These links form the priority tree. - parent *priorityNode - kids *priorityNode // start of the kids list + + parent *priorityNode + + kids *priorityNode // start of the kids list + prev, next *priorityNode // doubly-linked list of siblings + } func (n *priorityNode) setParent(parent *priorityNode) { + if n == parent { + panic("setParent to self") + } + if n.parent == parent { + return + } + // Unlink from current parent. + if parent := n.parent; parent != nil { + if n.prev == nil { + parent.kids = n.next + } else { + n.prev.next = n.next + } + if n.next != nil { + n.next.prev = n.prev + } + } + // Link to new parent. + // If parent=nil, remove n from the tree. + // Always insert at the head of parent.kids (this is assumed by walkReadyInOrder). + n.parent = parent + if parent == nil { + n.next = nil + n.prev = nil + } else { + n.next = parent.kids + n.prev = nil + if n.next != nil { + n.next.prev = n + } + parent.kids = n + } + } func (n *priorityNode) addBytes(b int64) { + n.bytes += b + for ; n != nil; n = n.parent { + n.subtreeBytes += b + } + } // walkReadyInOrder iterates over the tree in priority order, calling f for each node + // with a non-empty write queue. When f returns true, this function returns true and the + // walk halts. tmp is used as scratch space for sorting. + // + // f(n, openParent) takes two arguments: the node to visit, n, and a bool that is true + // if any ancestor p of n is still open (ignoring the root node). + func (n *priorityNode) walkReadyInOrder(openParent bool, tmp *[]*priorityNode, f func(*priorityNode, bool) bool) bool { + if !n.q.empty() && f(n, openParent) { + return true + } + if n.kids == nil { + return false + } // Don't consider the root "open" when updating openParent since + // we can't send data frames on the root stream (only control frames). + if n.id != 0 { + openParent = openParent || (n.state == priorityNodeOpen) + } // Common case: only one kid or all kids have the same weight. + // Some clients don't use weights; other clients (like web browsers) + // use mostly-linear priority trees. + w := n.kids.weight + needSort := false + for k := n.kids.next; k != nil; k = k.next { + if k.weight != w { + needSort = true + break + } + } + if !needSort { + for k := n.kids; k != nil; k = k.next { + if k.walkReadyInOrder(openParent, tmp, f) { + return true + } + } + return false + } // Uncommon case: sort the child nodes. We remove the kids from the parent, + // then re-insert after sorting so we can reuse tmp for future sort calls. + *tmp = (*tmp)[:0] + for n.kids != nil { + *tmp = append(*tmp, n.kids) + n.kids.setParent(nil) + } + sort.Sort(sortPriorityNodeSiblings(*tmp)) + for i := len(*tmp) - 1; i >= 0; i-- { + (*tmp)[i].setParent(n) // setParent inserts at the head of n.kids + } + for k := n.kids; k != nil; k = k.next { + if k.walkReadyInOrder(openParent, tmp, f) { + return true + } + } + return false + } type sortPriorityNodeSiblings []*priorityNode -func (z sortPriorityNodeSiblings) Len() int { return len(z) } +func (z sortPriorityNodeSiblings) Len() int { return len(z) } + func (z sortPriorityNodeSiblings) Swap(i, k int) { z[i], z[k] = z[k], z[i] } + func (z sortPriorityNodeSiblings) Less(i, k int) bool { + // Prefer the subtree that has sent fewer bytes relative to its weight. + // See sections 5.3.2 and 5.3.4. + wi, bi := float64(z[i].weight+1), float64(z[i].subtreeBytes) + wk, bk := float64(z[k].weight+1), float64(z[k].subtreeBytes) + if bi == 0 && bk == 0 { + return wi >= wk + } + if bk == 0 { + return false + } + return bi/bk <= wi/wk + } type priorityWriteScheduler struct { + // root is the root of the priority tree, where root.id = 0. + // The root queues control frames that are not associated with any stream. + root priorityNode // nodes maps stream ids to priority tree nodes. + nodes map[uint32]*priorityNode // maxID is the maximum stream id in nodes. + maxID uint32 // lists of nodes that have been closed or are idle, but are kept in + // the tree for improved prioritization. When the lengths exceed either + // maxClosedNodesInTree or maxIdleNodesInTree, old nodes are discarded. + closedNodes, idleNodes []*priorityNode // From the config. + maxClosedNodesInTree int - maxIdleNodesInTree int - writeThrottleLimit int32 - enableWriteThrottle bool + + maxIdleNodesInTree int + + writeThrottleLimit int32 + + enableWriteThrottle bool // tmp is scratch space for priorityNode.walkReadyInOrder to reduce allocations. + tmp []*priorityNode // pool of empty queues for reuse. + queuePool writeQueuePool } func (ws *priorityWriteScheduler) OpenStream(streamID uint32, options OpenStreamOptions) { + // The stream may be currently idle but cannot be opened or closed. + if curr := ws.nodes[streamID]; curr != nil { + if curr.state != priorityNodeIdle { + panic(fmt.Sprintf("stream %d already opened", streamID)) + } + curr.state = priorityNodeOpen + return + } // RFC 7540, Section 5.3.5: + // "All streams are initially assigned a non-exclusive dependency on stream 0x0. + // Pushed streams initially depend on their associated stream. In both cases, + // streams are assigned a default weight of 16." + parent := ws.nodes[options.PusherID] + if parent == nil { + parent = &ws.root + } + n := &priorityNode{ - q: *ws.queuePool.get(), - id: streamID, + + q: *ws.queuePool.get(), + + id: streamID, + weight: priorityDefaultWeight, - state: priorityNodeOpen, + + state: priorityNodeOpen, } + n.setParent(parent) + ws.nodes[streamID] = n + if streamID > ws.maxID { + ws.maxID = streamID + } + } func (ws *priorityWriteScheduler) CloseStream(streamID uint32) { + if streamID == 0 { + panic("violation of WriteScheduler interface: cannot close stream 0") + } + if ws.nodes[streamID] == nil { + panic(fmt.Sprintf("violation of WriteScheduler interface: unknown stream %d", streamID)) + } + if ws.nodes[streamID].state != priorityNodeOpen { + panic(fmt.Sprintf("violation of WriteScheduler interface: stream %d already closed", streamID)) + } n := ws.nodes[streamID] + n.state = priorityNodeClosed + n.addBytes(-n.bytes) q := n.q + ws.queuePool.put(&q) + n.q.s = nil + if ws.maxClosedNodesInTree > 0 { + ws.addClosedOrIdleNode(&ws.closedNodes, ws.maxClosedNodesInTree, n) + } else { + ws.removeNode(n) + } + } func (ws *priorityWriteScheduler) AdjustStream(streamID uint32, priority PriorityParam) { + if streamID == 0 { + panic("adjustPriority on root") + } // If streamID does not exist, there are two cases: + // - A closed stream that has been removed (this will have ID <= maxID) + // - An idle stream that is being used for "grouping" (this will have ID > maxID) + n := ws.nodes[streamID] + if n == nil { + if streamID <= ws.maxID || ws.maxIdleNodesInTree == 0 { + return + } + ws.maxID = streamID + n = &priorityNode{ - q: *ws.queuePool.get(), - id: streamID, + + q: *ws.queuePool.get(), + + id: streamID, + weight: priorityDefaultWeight, - state: priorityNodeIdle, + + state: priorityNodeIdle, } + n.setParent(&ws.root) + ws.nodes[streamID] = n + ws.addClosedOrIdleNode(&ws.idleNodes, ws.maxIdleNodesInTree, n) + } // Section 5.3.1: A dependency on a stream that is not currently in the tree + // results in that stream being given a default priority (Section 5.3.5). + parent := ws.nodes[priority.StreamDep] + if parent == nil { + n.setParent(&ws.root) + n.weight = priorityDefaultWeight + return + } // Ignore if the client tries to make a node its own parent. + if n == parent { + return + } // Section 5.3.3: + // "If a stream is made dependent on one of its own dependencies, the + // formerly dependent stream is first moved to be dependent on the + // reprioritized stream's previous parent. The moved dependency retains + // its weight." + // + // That is: if parent depends on n, move parent to depend on n.parent. + for x := parent.parent; x != nil; x = x.parent { + if x == n { + parent.setParent(n.parent) + break + } + } // Section 5.3.3: The exclusive flag causes the stream to become the sole + // dependency of its parent stream, causing other dependencies to become + // dependent on the exclusive stream. + if priority.Exclusive { + k := parent.kids + for k != nil { + next := k.next + if k != n { + k.setParent(n) + } + k = next + } + } n.setParent(parent) + n.weight = priority.Weight + } func (ws *priorityWriteScheduler) Push(wr FrameWriteRequest) { + var n *priorityNode + if wr.isControl() { + n = &ws.root + } else { + id := wr.StreamID() + n = ws.nodes[id] + if n == nil { + // id is an idle or closed stream. wr should not be a HEADERS or + // DATA frame. In other case, we push wr onto the root, rather + // than creating a new priorityNode. + if wr.DataSize() > 0 { + panic("add DATA on non-open stream") + } + n = &ws.root + } + } + n.q.push(wr) + } func (ws *priorityWriteScheduler) Pop() (wr FrameWriteRequest, ok bool) { + ws.root.walkReadyInOrder(false, &ws.tmp, func(n *priorityNode, openParent bool) bool { + limit := int32(math.MaxInt32) + if openParent { + limit = ws.writeThrottleLimit + } + wr, ok = n.q.consume(limit) + if !ok { + return false + } + n.addBytes(int64(wr.DataSize())) + // If B depends on A and B continuously has data available but A + // does not, gradually increase the throttling limit to allow B to + // steal more and more bandwidth from A. + if openParent { + ws.writeThrottleLimit += 1024 + if ws.writeThrottleLimit < 0 { + ws.writeThrottleLimit = math.MaxInt32 + } + } else if ws.enableWriteThrottle { + ws.writeThrottleLimit = 1024 + } + return true + }) + return wr, ok + } func (ws *priorityWriteScheduler) addClosedOrIdleNode(list *[]*priorityNode, maxSize int, n *priorityNode) { + if maxSize == 0 { + return + } + if len(*list) == maxSize { + // Remove the oldest node, then shift left. + ws.removeNode((*list)[0]) + x := (*list)[1:] + copy(*list, x) + *list = (*list)[:len(x)] + } + *list = append(*list, n) + } func (ws *priorityWriteScheduler) removeNode(n *priorityNode) { + for k := n.kids; k != nil; k = k.next { + k.setParent(n.parent) + } + n.setParent(nil) + delete(ws.nodes, n.id) + } diff --git a/vendor/golang.org/x/net/http2/writesched_roundrobin.go b/vendor/golang.org/x/net/http2/writesched_roundrobin.go index 54fe863..7f5fc1c 100644 --- a/vendor/golang.org/x/net/http2/writesched_roundrobin.go +++ b/vendor/golang.org/x/net/http2/writesched_roundrobin.go @@ -1,5 +1,7 @@ // Copyright 2023 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package http2 @@ -10,110 +12,197 @@ import ( ) type roundRobinWriteScheduler struct { + // control contains control frames (SETTINGS, PING, etc.). + control writeQueue // streams maps stream ID to a queue. + streams map[uint32]*writeQueue // stream queues are stored in a circular linked list. + // head is the next stream to write, or nil if there are no streams open. + head *writeQueue // pool of empty queues for reuse. + queuePool writeQueuePool } // newRoundRobinWriteScheduler constructs a new write scheduler. + // The round robin scheduler priorizes control frames + // like SETTINGS and PING over DATA frames. + // When there are no control frames to send, it performs a round-robin + // selection from the ready streams. + func newRoundRobinWriteScheduler() WriteScheduler { + ws := &roundRobinWriteScheduler{ + streams: make(map[uint32]*writeQueue), } + return ws + } func (ws *roundRobinWriteScheduler) OpenStream(streamID uint32, options OpenStreamOptions) { + if ws.streams[streamID] != nil { + panic(fmt.Errorf("stream %d already opened", streamID)) + } + q := ws.queuePool.get() + ws.streams[streamID] = q + if ws.head == nil { + ws.head = q + q.next = q + q.prev = q + } else { + // Queues are stored in a ring. + // Insert the new stream before ws.head, putting it at the end of the list. + q.prev = ws.head.prev + q.next = ws.head + q.prev.next = q + q.next.prev = q + } + } func (ws *roundRobinWriteScheduler) CloseStream(streamID uint32) { + q := ws.streams[streamID] + if q == nil { + return + } + if q.next == q { + // This was the only open stream. + ws.head = nil + } else { + q.prev.next = q.next + q.next.prev = q.prev + if ws.head == q { + ws.head = q.next + } + } + delete(ws.streams, streamID) + ws.queuePool.put(q) + } func (ws *roundRobinWriteScheduler) AdjustStream(streamID uint32, priority PriorityParam) {} func (ws *roundRobinWriteScheduler) Push(wr FrameWriteRequest) { + if wr.isControl() { + ws.control.push(wr) + return + } + q := ws.streams[wr.StreamID()] + if q == nil { + // This is a closed stream. + // wr should not be a HEADERS or DATA frame. + // We push the request onto the control queue. + if wr.DataSize() > 0 { + panic("add DATA on non-open stream") + } + ws.control.push(wr) + return + } + q.push(wr) + } func (ws *roundRobinWriteScheduler) Pop() (FrameWriteRequest, bool) { + // Control and RST_STREAM frames first. + if !ws.control.empty() { + return ws.control.shift(), true + } + if ws.head == nil { + return FrameWriteRequest{}, false + } + q := ws.head + for { + if wr, ok := q.consume(math.MaxInt32); ok { + ws.head = q.next + return wr, true + } + q = q.next + if q == ws.head { + break + } + } + return FrameWriteRequest{}, false + } diff --git a/vendor/golang.org/x/net/idna/idna10.0.0.go b/vendor/golang.org/x/net/idna/idna10.0.0.go index 7b37178..dcdc906 100644 --- a/vendor/golang.org/x/net/idna/idna10.0.0.go +++ b/vendor/golang.org/x/net/idna/idna10.0.0.go @@ -1,20 +1,31 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. // Copyright 2016 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build go1.10 // Package idna implements IDNA2008 using the compatibility processing + // defined by UTS (Unicode Technical Standard) #46, which defines a standard to + // deal with the transition from IDNA2003. + // + // IDNA2008 (Internationalized Domain Names for Applications), is defined in RFC + // 5890, RFC 5891, RFC 5892, RFC 5893 and RFC 5894. + // UTS #46 is defined in https://www.unicode.org/reports/tr46. + // See https://unicode.org/cldr/utility/idna.jsp for a visualization of the + // differences between these two standards. + package idna // import "golang.org/x/net/idna" import ( @@ -28,742 +39,1348 @@ import ( ) // NOTE: Unlike common practice in Go APIs, the functions will return a + // sanitized domain name in case of errors. Browsers sometimes use a partially + // evaluated string as lookup. + // TODO: the current error handling is, in my opinion, the least opinionated. + // Other strategies are also viable, though: + // Option 1) Return an empty string in case of error, but allow the user to + // specify explicitly which errors to ignore. + // Option 2) Return the partially evaluated string if it is itself a valid + // string, otherwise return the empty string in case of error. + // Option 3) Option 1 and 2. + // Option 4) Always return an empty string for now and implement Option 1 as + // needed, and document that the return string may not be empty in case of + // error in the future. + // I think Option 1 is best, but it is quite opinionated. // ToASCII is a wrapper for Punycode.ToASCII. + func ToASCII(s string) (string, error) { + return Punycode.process(s, true) + } // ToUnicode is a wrapper for Punycode.ToUnicode. + func ToUnicode(s string) (string, error) { + return Punycode.process(s, false) + } // An Option configures a Profile at creation time. + type Option func(*options) // Transitional sets a Profile to use the Transitional mapping as defined in UTS + // #46. This will cause, for example, "ß" to be mapped to "ss". Using the + // transitional mapping provides a compromise between IDNA2003 and IDNA2008 + // compatibility. It is used by some browsers when resolving domain names. This + // option is only meaningful if combined with MapForLookup. + func Transitional(transitional bool) Option { + return func(o *options) { o.transitional = transitional } + } // VerifyDNSLength sets whether a Profile should fail if any of the IDN parts + // are longer than allowed by the RFC. + // + // This option corresponds to the VerifyDnsLength flag in UTS #46. + func VerifyDNSLength(verify bool) Option { + return func(o *options) { o.verifyDNSLength = verify } + } // RemoveLeadingDots removes leading label separators. Leading runes that map to + // dots, such as U+3002 IDEOGRAPHIC FULL STOP, are removed as well. + func RemoveLeadingDots(remove bool) Option { + return func(o *options) { o.removeLeadingDots = remove } + } // ValidateLabels sets whether to check the mandatory label validation criteria + // as defined in Section 5.4 of RFC 5891. This includes testing for correct use + // of hyphens ('-'), normalization, validity of runes, and the context rules. + // In particular, ValidateLabels also sets the CheckHyphens and CheckJoiners flags + // in UTS #46. + func ValidateLabels(enable bool) Option { + return func(o *options) { + // Don't override existing mappings, but set one that at least checks + // normalization if it is not set. + if o.mapping == nil && enable { + o.mapping = normalize + } + o.trie = trie + o.checkJoiners = enable + o.checkHyphens = enable + if enable { + o.fromPuny = validateFromPunycode + } else { + o.fromPuny = nil + } + } + } // CheckHyphens sets whether to check for correct use of hyphens ('-') in + // labels. Most web browsers do not have this option set, since labels such as + // "r3---sn-apo3qvuoxuxbt-j5pe" are in common use. + // + // This option corresponds to the CheckHyphens flag in UTS #46. + func CheckHyphens(enable bool) Option { + return func(o *options) { o.checkHyphens = enable } + } // CheckJoiners sets whether to check the ContextJ rules as defined in Appendix + // A of RFC 5892, concerning the use of joiner runes. + // + // This option corresponds to the CheckJoiners flag in UTS #46. + func CheckJoiners(enable bool) Option { + return func(o *options) { + o.trie = trie + o.checkJoiners = enable + } + } // StrictDomainName limits the set of permissible ASCII characters to those + // allowed in domain names as defined in RFC 1034 (A-Z, a-z, 0-9 and the + // hyphen). This is set by default for MapForLookup and ValidateForRegistration, + // but is only useful if ValidateLabels is set. + // + // This option is useful, for instance, for browsers that allow characters + // outside this range, for example a '_' (U+005F LOW LINE). See + // http://www.rfc-editor.org/std/std3.txt for more details. + // + // This option corresponds to the UseSTD3ASCIIRules flag in UTS #46. + func StrictDomainName(use bool) Option { + return func(o *options) { o.useSTD3Rules = use } + } // NOTE: the following options pull in tables. The tables should not be linked + // in as long as the options are not used. // BidiRule enables the Bidi rule as defined in RFC 5893. Any application + // that relies on proper validation of labels should include this rule. + // + // This option corresponds to the CheckBidi flag in UTS #46. + func BidiRule() Option { + return func(o *options) { o.bidirule = bidirule.ValidString } + } // ValidateForRegistration sets validation options to verify that a given IDN is + // properly formatted for registration as defined by Section 4 of RFC 5891. + func ValidateForRegistration() Option { + return func(o *options) { + o.mapping = validateRegistration + StrictDomainName(true)(o) + ValidateLabels(true)(o) + VerifyDNSLength(true)(o) + BidiRule()(o) + } + } // MapForLookup sets validation and mapping options such that a given IDN is + // transformed for domain name lookup according to the requirements set out in + // Section 5 of RFC 5891. The mappings follow the recommendations of RFC 5894, + // RFC 5895 and UTS 46. It does not add the Bidi Rule. Use the BidiRule option + // to add this check. + // + // The mappings include normalization and mapping case, width and other + // compatibility mappings. + func MapForLookup() Option { + return func(o *options) { + o.mapping = validateAndMap + StrictDomainName(true)(o) + ValidateLabels(true)(o) + } + } type options struct { - transitional bool - useSTD3Rules bool - checkHyphens bool - checkJoiners bool - verifyDNSLength bool + transitional bool + + useSTD3Rules bool + + checkHyphens bool + + checkJoiners bool + + verifyDNSLength bool + removeLeadingDots bool trie *idnaTrie // fromPuny calls validation rules when converting A-labels to U-labels. + fromPuny func(p *Profile, s string) error // mapping implements a validation and mapping step as defined in RFC 5895 + // or UTS 46, tailored to, for example, domain registration or lookup. + mapping func(p *Profile, s string) (mapped string, isBidi bool, err error) // bidirule, if specified, checks whether s conforms to the Bidi Rule + // defined in RFC 5893. + bidirule func(s string) bool } // A Profile defines the configuration of an IDNA mapper. + type Profile struct { options } func apply(o *options, opts []Option) { + for _, f := range opts { + f(o) + } + } // New creates a new Profile. + // + // With no options, the returned Profile is the most permissive and equals the + // Punycode Profile. Options can be passed to further restrict the Profile. The + // MapForLookup and ValidateForRegistration options set a collection of options, + // for lookup and registration purposes respectively, which can be tailored by + // adding more fine-grained options, where later options override earlier + // options. + func New(o ...Option) *Profile { + p := &Profile{} + apply(&p.options, o) + return p + } // ToASCII converts a domain or domain label to its ASCII form. For example, + // ToASCII("bücher.example.com") is "xn--bcher-kva.example.com", and + // ToASCII("golang") is "golang". If an error is encountered it will return + // an error and a (partially) processed result. + func (p *Profile) ToASCII(s string) (string, error) { + return p.process(s, true) + } // ToUnicode converts a domain or domain label to its Unicode form. For example, + // ToUnicode("xn--bcher-kva.example.com") is "bücher.example.com", and + // ToUnicode("golang") is "golang". If an error is encountered it will return + // an error and a (partially) processed result. + func (p *Profile) ToUnicode(s string) (string, error) { + pp := *p + pp.transitional = false + return pp.process(s, false) + } // String reports a string with a description of the profile for debugging + // purposes. The string format may change with different versions. + func (p *Profile) String() string { + s := "" + if p.transitional { + s = "Transitional" + } else { + s = "NonTransitional" + } + if p.useSTD3Rules { + s += ":UseSTD3Rules" + } + if p.checkHyphens { + s += ":CheckHyphens" + } + if p.checkJoiners { + s += ":CheckJoiners" + } + if p.verifyDNSLength { + s += ":VerifyDNSLength" + } + return s + } var ( + // Punycode is a Profile that does raw punycode processing with a minimum + // of validation. + Punycode *Profile = punycode // Lookup is the recommended profile for looking up domain names, according + // to Section 5 of RFC 5891. The exact configuration of this profile may + // change over time. + Lookup *Profile = lookup // Display is the recommended profile for displaying domain names. + // The configuration of this profile may change over time. + Display *Profile = display // Registration is the recommended profile for checking whether a given + // IDN is valid for registration, according to Section 4 of RFC 5891. + Registration *Profile = registration punycode = &Profile{} - lookup = &Profile{options{ + + lookup = &Profile{options{ + transitional: transitionalLookup, + useSTD3Rules: true, + checkHyphens: true, + checkJoiners: true, - trie: trie, - fromPuny: validateFromPunycode, - mapping: validateAndMap, - bidirule: bidirule.ValidString, + + trie: trie, + + fromPuny: validateFromPunycode, + + mapping: validateAndMap, + + bidirule: bidirule.ValidString, }} + display = &Profile{options{ + useSTD3Rules: true, + checkHyphens: true, + checkJoiners: true, - trie: trie, - fromPuny: validateFromPunycode, - mapping: validateAndMap, - bidirule: bidirule.ValidString, + + trie: trie, + + fromPuny: validateFromPunycode, + + mapping: validateAndMap, + + bidirule: bidirule.ValidString, }} + registration = &Profile{options{ - useSTD3Rules: true, + + useSTD3Rules: true, + verifyDNSLength: true, - checkHyphens: true, - checkJoiners: true, - trie: trie, - fromPuny: validateFromPunycode, - mapping: validateRegistration, - bidirule: bidirule.ValidString, + + checkHyphens: true, + + checkJoiners: true, + + trie: trie, + + fromPuny: validateFromPunycode, + + mapping: validateRegistration, + + bidirule: bidirule.ValidString, }} // TODO: profiles + // Register: recommended for approving domain names: don't do any mappings + // but rather reject on invalid input. Bundle or block deviation characters. + ) type labelError struct{ label, code_ string } func (e labelError) code() string { return e.code_ } + func (e labelError) Error() string { + return fmt.Sprintf("idna: invalid label %q", e.label) + } type runeError rune func (e runeError) code() string { return "P1" } + func (e runeError) Error() string { + return fmt.Sprintf("idna: disallowed rune %U", e) + } // process implements the algorithm described in section 4 of UTS #46, + // see https://www.unicode.org/reports/tr46. + func (p *Profile) process(s string, toASCII bool) (string, error) { + var err error + var isBidi bool + if p.mapping != nil { + s, isBidi, err = p.mapping(p, s) + } + // Remove leading empty labels. + if p.removeLeadingDots { + for ; len(s) > 0 && s[0] == '.'; s = s[1:] { + } + } + // TODO: allow for a quick check of the tables data. + // It seems like we should only create this error on ToASCII, but the + // UTS 46 conformance tests suggests we should always check this. + if err == nil && p.verifyDNSLength && s == "" { + err = &labelError{s, "A4"} + } + labels := labelIter{orig: s} + for ; !labels.done(); labels.next() { + label := labels.label() + if label == "" { + // Empty labels are not okay. The label iterator skips the last + // label if it is empty. + if err == nil && p.verifyDNSLength { + err = &labelError{s, "A4"} + } + continue + } + if strings.HasPrefix(label, acePrefix) { + u, err2 := decode(label[len(acePrefix):]) + if err2 != nil { + if err == nil { + err = err2 + } + // Spec says keep the old label. + continue + } + isBidi = isBidi || bidirule.DirectionString(u) != bidi.LeftToRight + labels.set(u) + if err == nil && p.fromPuny != nil { + err = p.fromPuny(p, u) + } + if err == nil { + // This should be called on NonTransitional, according to the + // spec, but that currently does not have any effect. Use the + // original profile to preserve options. + err = p.validateLabel(u) + } + } else if err == nil { + err = p.validateLabel(label) + } + } + if isBidi && p.bidirule != nil && err == nil { + for labels.reset(); !labels.done(); labels.next() { + if !p.bidirule(labels.label()) { + err = &labelError{s, "B"} + break + } + } + } + if toASCII { + for labels.reset(); !labels.done(); labels.next() { + label := labels.label() + if !ascii(label) { + a, err2 := encode(acePrefix, label) + if err == nil { + err = err2 + } + label = a + labels.set(a) + } + n := len(label) + if p.verifyDNSLength && err == nil && (n == 0 || n > 63) { + err = &labelError{label, "A4"} + } + } + } + s = labels.result() + if toASCII && p.verifyDNSLength && err == nil { + // Compute the length of the domain name minus the root label and its dot. + n := len(s) + if n > 0 && s[n-1] == '.' { + n-- + } + if len(s) < 1 || n > 253 { + err = &labelError{s, "A4"} + } + } + return s, err + } func normalize(p *Profile, s string) (mapped string, isBidi bool, err error) { + // TODO: consider first doing a quick check to see if any of these checks + // need to be done. This will make it slower in the general case, but + // faster in the common case. + mapped = norm.NFC.String(s) + isBidi = bidirule.DirectionString(mapped) == bidi.RightToLeft + return mapped, isBidi, nil + } func validateRegistration(p *Profile, s string) (idem string, bidi bool, err error) { + // TODO: filter need for normalization in loop below. + if !norm.NFC.IsNormalString(s) { + return s, false, &labelError{s, "V1"} + } + for i := 0; i < len(s); { + v, sz := trie.lookupString(s[i:]) + if sz == 0 { + return s, bidi, runeError(utf8.RuneError) + } + bidi = bidi || info(v).isBidi(s[i:]) + // Copy bytes not copied so far. + switch p.simplify(info(v).category()) { + // TODO: handle the NV8 defined in the Unicode idna data set to allow + // for strict conformance to IDNA2008. + case valid, deviation: + case disallowed, mapped, unknown, ignored: + r, _ := utf8.DecodeRuneInString(s[i:]) + return s, bidi, runeError(r) + } + i += sz + } + return s, bidi, nil + } func (c info) isBidi(s string) bool { + if !c.isMapped() { + return c&attributesMask == rtl + } + // TODO: also store bidi info for mapped data. This is possible, but a bit + // cumbersome and not for the common case. + p, _ := bidi.LookupString(s) + switch p.Class() { + case bidi.R, bidi.AL, bidi.AN: + return true + } + return false + } func validateAndMap(p *Profile, s string) (vm string, bidi bool, err error) { + var ( b []byte + k int ) + // combinedInfoBits contains the or-ed bits of all runes. We use this + // to derive the mayNeedNorm bit later. This may trigger normalization + // overeagerly, but it will not do so in the common case. The end result + // is another 10% saving on BenchmarkProfile for the common case. + var combinedInfoBits info + for i := 0; i < len(s); { + v, sz := trie.lookupString(s[i:]) + if sz == 0 { + b = append(b, s[k:i]...) + b = append(b, "\ufffd"...) + k = len(s) + if err == nil { + err = runeError(utf8.RuneError) + } + break + } + combinedInfoBits |= info(v) + bidi = bidi || info(v).isBidi(s[i:]) + start := i + i += sz + // Copy bytes not copied so far. + switch p.simplify(info(v).category()) { + case valid: + continue + case disallowed: + if err == nil { + r, _ := utf8.DecodeRuneInString(s[start:]) + err = runeError(r) + } + continue + case mapped, deviation: + b = append(b, s[k:start]...) + b = info(v).appendMapping(b, s[start:i]) + case ignored: + b = append(b, s[k:start]...) + // drop the rune + case unknown: + b = append(b, s[k:start]...) + b = append(b, "\ufffd"...) + } + k = i + } + if k == 0 { + // No changes so far. + if combinedInfoBits&mayNeedNorm != 0 { + s = norm.NFC.String(s) + } + } else { + b = append(b, s[k:]...) + if norm.NFC.QuickSpan(b) != len(b) { + b = norm.NFC.Bytes(b) + } + // TODO: the punycode converters require strings as input. + s = string(b) + } + return s, bidi, err + } // A labelIter allows iterating over domain name labels. + type labelIter struct { - orig string - slice []string + orig string + + slice []string + curStart int - curEnd int - i int + + curEnd int + + i int } func (l *labelIter) reset() { + l.curStart = 0 + l.curEnd = 0 + l.i = 0 + } func (l *labelIter) done() bool { + return l.curStart >= len(l.orig) + } func (l *labelIter) result() string { + if l.slice != nil { + return strings.Join(l.slice, ".") + } + return l.orig + } func (l *labelIter) label() string { + if l.slice != nil { + return l.slice[l.i] + } + p := strings.IndexByte(l.orig[l.curStart:], '.') + l.curEnd = l.curStart + p + if p == -1 { + l.curEnd = len(l.orig) + } + return l.orig[l.curStart:l.curEnd] + } // next sets the value to the next label. It skips the last label if it is empty. + func (l *labelIter) next() { + l.i++ + if l.slice != nil { + if l.i >= len(l.slice) || l.i == len(l.slice)-1 && l.slice[l.i] == "" { + l.curStart = len(l.orig) + } + } else { + l.curStart = l.curEnd + 1 + if l.curStart == len(l.orig)-1 && l.orig[l.curStart] == '.' { + l.curStart = len(l.orig) + } + } + } func (l *labelIter) set(s string) { + if l.slice == nil { + l.slice = strings.Split(l.orig, ".") + } + l.slice[l.i] = s + } // acePrefix is the ASCII Compatible Encoding prefix. + const acePrefix = "xn--" func (p *Profile) simplify(cat category) category { + switch cat { + case disallowedSTD3Mapped: + if p.useSTD3Rules { + cat = disallowed + } else { + cat = mapped + } + case disallowedSTD3Valid: + if p.useSTD3Rules { + cat = disallowed + } else { + cat = valid + } + case deviation: + if !p.transitional { + cat = valid + } + case validNV8, validXV8: + // TODO: handle V2008 + cat = valid + } + return cat + } func validateFromPunycode(p *Profile, s string) error { + if !norm.NFC.IsNormalString(s) { + return &labelError{s, "V1"} + } + // TODO: detect whether string may have to be normalized in the following + // loop. + for i := 0; i < len(s); { + v, sz := trie.lookupString(s[i:]) + if sz == 0 { + return runeError(utf8.RuneError) + } + if c := p.simplify(info(v).category()); c != valid && c != deviation { + return &labelError{s, "V6"} + } + i += sz + } + return nil + } const ( zwnj = "\u200c" - zwj = "\u200d" + + zwj = "\u200d" ) type joinState int8 const ( stateStart joinState = iota + stateVirama + stateBefore + stateBeforeVirama + stateAfter + stateFAIL ) var joinStates = [][numJoinTypes]joinState{ + stateStart: { - joiningL: stateBefore, - joiningD: stateBefore, - joinZWNJ: stateFAIL, - joinZWJ: stateFAIL, + + joiningL: stateBefore, + + joiningD: stateBefore, + + joinZWNJ: stateFAIL, + + joinZWJ: stateFAIL, + joinVirama: stateVirama, }, + stateVirama: { + joiningL: stateBefore, + joiningD: stateBefore, }, + stateBefore: { - joiningL: stateBefore, - joiningD: stateBefore, - joiningT: stateBefore, - joinZWNJ: stateAfter, - joinZWJ: stateFAIL, + + joiningL: stateBefore, + + joiningD: stateBefore, + + joiningT: stateBefore, + + joinZWNJ: stateAfter, + + joinZWJ: stateFAIL, + joinVirama: stateBeforeVirama, }, + stateBeforeVirama: { + joiningL: stateBefore, + joiningD: stateBefore, + joiningT: stateBefore, }, + stateAfter: { - joiningL: stateFAIL, - joiningD: stateBefore, - joiningT: stateAfter, - joiningR: stateStart, - joinZWNJ: stateFAIL, - joinZWJ: stateFAIL, + + joiningL: stateFAIL, + + joiningD: stateBefore, + + joiningT: stateAfter, + + joiningR: stateStart, + + joinZWNJ: stateFAIL, + + joinZWJ: stateFAIL, + joinVirama: stateAfter, // no-op as we can't accept joiners here + }, + stateFAIL: { - 0: stateFAIL, - joiningL: stateFAIL, - joiningD: stateFAIL, - joiningT: stateFAIL, - joiningR: stateFAIL, - joinZWNJ: stateFAIL, - joinZWJ: stateFAIL, + + 0: stateFAIL, + + joiningL: stateFAIL, + + joiningD: stateFAIL, + + joiningT: stateFAIL, + + joiningR: stateFAIL, + + joinZWNJ: stateFAIL, + + joinZWJ: stateFAIL, + joinVirama: stateFAIL, }, } // validateLabel validates the criteria from Section 4.1. Item 1, 4, and 6 are + // already implicitly satisfied by the overall implementation. + func (p *Profile) validateLabel(s string) (err error) { + if s == "" { + if p.verifyDNSLength { + return &labelError{s, "A4"} + } + return nil + } + if p.checkHyphens { + if len(s) > 4 && s[2] == '-' && s[3] == '-' { + return &labelError{s, "V2"} + } + if s[0] == '-' || s[len(s)-1] == '-' { + return &labelError{s, "V3"} + } + } + if !p.checkJoiners { + return nil + } + trie := p.trie // p.checkJoiners is only set if trie is set. + // TODO: merge the use of this in the trie. + v, sz := trie.lookupString(s) + x := info(v) + if x.isModifier() { + return &labelError{s, "V5"} + } + // Quickly return in the absence of zero-width (non) joiners. + if strings.Index(s, zwj) == -1 && strings.Index(s, zwnj) == -1 { + return nil + } + st := stateStart + for i := 0; ; { + jt := x.joinType() + if s[i:i+sz] == zwj { + jt = joinZWJ + } else if s[i:i+sz] == zwnj { + jt = joinZWNJ + } + st = joinStates[st][jt] + if x.isViramaModifier() { + st = joinStates[st][joinVirama] + } + if i += sz; i == len(s) { + break + } + v, sz = trie.lookupString(s[i:]) + x = info(v) + } + if st == stateFAIL || st == stateAfter { + return &labelError{s, "C"} + } + return nil + } func ascii(s string) bool { + for i := 0; i < len(s); i++ { + if s[i] >= utf8.RuneSelf { + return false + } + } + return true + } diff --git a/vendor/golang.org/x/net/idna/idna9.0.0.go b/vendor/golang.org/x/net/idna/idna9.0.0.go index cc6a892..7983336 100644 --- a/vendor/golang.org/x/net/idna/idna9.0.0.go +++ b/vendor/golang.org/x/net/idna/idna9.0.0.go @@ -1,20 +1,31 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. // Copyright 2016 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build !go1.10 // Package idna implements IDNA2008 using the compatibility processing + // defined by UTS (Unicode Technical Standard) #46, which defines a standard to + // deal with the transition from IDNA2003. + // + // IDNA2008 (Internationalized Domain Names for Applications), is defined in RFC + // 5890, RFC 5891, RFC 5892, RFC 5893 and RFC 5894. + // UTS #46 is defined in https://www.unicode.org/reports/tr46. + // See https://unicode.org/cldr/utility/idna.jsp for a visualization of the + // differences between these two standards. + package idna // import "golang.org/x/net/idna" import ( @@ -27,691 +38,1248 @@ import ( ) // NOTE: Unlike common practice in Go APIs, the functions will return a + // sanitized domain name in case of errors. Browsers sometimes use a partially + // evaluated string as lookup. + // TODO: the current error handling is, in my opinion, the least opinionated. + // Other strategies are also viable, though: + // Option 1) Return an empty string in case of error, but allow the user to + // specify explicitly which errors to ignore. + // Option 2) Return the partially evaluated string if it is itself a valid + // string, otherwise return the empty string in case of error. + // Option 3) Option 1 and 2. + // Option 4) Always return an empty string for now and implement Option 1 as + // needed, and document that the return string may not be empty in case of + // error in the future. + // I think Option 1 is best, but it is quite opinionated. // ToASCII is a wrapper for Punycode.ToASCII. + func ToASCII(s string) (string, error) { + return Punycode.process(s, true) + } // ToUnicode is a wrapper for Punycode.ToUnicode. + func ToUnicode(s string) (string, error) { + return Punycode.process(s, false) + } // An Option configures a Profile at creation time. + type Option func(*options) // Transitional sets a Profile to use the Transitional mapping as defined in UTS + // #46. This will cause, for example, "ß" to be mapped to "ss". Using the + // transitional mapping provides a compromise between IDNA2003 and IDNA2008 + // compatibility. It is used by some browsers when resolving domain names. This + // option is only meaningful if combined with MapForLookup. + func Transitional(transitional bool) Option { + return func(o *options) { o.transitional = transitional } + } // VerifyDNSLength sets whether a Profile should fail if any of the IDN parts + // are longer than allowed by the RFC. + // + // This option corresponds to the VerifyDnsLength flag in UTS #46. + func VerifyDNSLength(verify bool) Option { + return func(o *options) { o.verifyDNSLength = verify } + } // RemoveLeadingDots removes leading label separators. Leading runes that map to + // dots, such as U+3002 IDEOGRAPHIC FULL STOP, are removed as well. + func RemoveLeadingDots(remove bool) Option { + return func(o *options) { o.removeLeadingDots = remove } + } // ValidateLabels sets whether to check the mandatory label validation criteria + // as defined in Section 5.4 of RFC 5891. This includes testing for correct use + // of hyphens ('-'), normalization, validity of runes, and the context rules. + // In particular, ValidateLabels also sets the CheckHyphens and CheckJoiners flags + // in UTS #46. + func ValidateLabels(enable bool) Option { + return func(o *options) { + // Don't override existing mappings, but set one that at least checks + // normalization if it is not set. + if o.mapping == nil && enable { + o.mapping = normalize + } + o.trie = trie + o.checkJoiners = enable + o.checkHyphens = enable + if enable { + o.fromPuny = validateFromPunycode + } else { + o.fromPuny = nil + } + } + } // CheckHyphens sets whether to check for correct use of hyphens ('-') in + // labels. Most web browsers do not have this option set, since labels such as + // "r3---sn-apo3qvuoxuxbt-j5pe" are in common use. + // + // This option corresponds to the CheckHyphens flag in UTS #46. + func CheckHyphens(enable bool) Option { + return func(o *options) { o.checkHyphens = enable } + } // CheckJoiners sets whether to check the ContextJ rules as defined in Appendix + // A of RFC 5892, concerning the use of joiner runes. + // + // This option corresponds to the CheckJoiners flag in UTS #46. + func CheckJoiners(enable bool) Option { + return func(o *options) { + o.trie = trie + o.checkJoiners = enable + } + } // StrictDomainName limits the set of permissible ASCII characters to those + // allowed in domain names as defined in RFC 1034 (A-Z, a-z, 0-9 and the + // hyphen). This is set by default for MapForLookup and ValidateForRegistration, + // but is only useful if ValidateLabels is set. + // + // This option is useful, for instance, for browsers that allow characters + // outside this range, for example a '_' (U+005F LOW LINE). See + // http://www.rfc-editor.org/std/std3.txt for more details. + // + // This option corresponds to the UseSTD3ASCIIRules flag in UTS #46. + func StrictDomainName(use bool) Option { + return func(o *options) { o.useSTD3Rules = use } + } // NOTE: the following options pull in tables. The tables should not be linked + // in as long as the options are not used. // BidiRule enables the Bidi rule as defined in RFC 5893. Any application + // that relies on proper validation of labels should include this rule. + // + // This option corresponds to the CheckBidi flag in UTS #46. + func BidiRule() Option { + return func(o *options) { o.bidirule = bidirule.ValidString } + } // ValidateForRegistration sets validation options to verify that a given IDN is + // properly formatted for registration as defined by Section 4 of RFC 5891. + func ValidateForRegistration() Option { + return func(o *options) { + o.mapping = validateRegistration + StrictDomainName(true)(o) + ValidateLabels(true)(o) + VerifyDNSLength(true)(o) + BidiRule()(o) + } + } // MapForLookup sets validation and mapping options such that a given IDN is + // transformed for domain name lookup according to the requirements set out in + // Section 5 of RFC 5891. The mappings follow the recommendations of RFC 5894, + // RFC 5895 and UTS 46. It does not add the Bidi Rule. Use the BidiRule option + // to add this check. + // + // The mappings include normalization and mapping case, width and other + // compatibility mappings. + func MapForLookup() Option { + return func(o *options) { + o.mapping = validateAndMap + StrictDomainName(true)(o) + ValidateLabels(true)(o) + RemoveLeadingDots(true)(o) + } + } type options struct { - transitional bool - useSTD3Rules bool - checkHyphens bool - checkJoiners bool - verifyDNSLength bool + transitional bool + + useSTD3Rules bool + + checkHyphens bool + + checkJoiners bool + + verifyDNSLength bool + removeLeadingDots bool trie *idnaTrie // fromPuny calls validation rules when converting A-labels to U-labels. + fromPuny func(p *Profile, s string) error // mapping implements a validation and mapping step as defined in RFC 5895 + // or UTS 46, tailored to, for example, domain registration or lookup. + mapping func(p *Profile, s string) (string, error) // bidirule, if specified, checks whether s conforms to the Bidi Rule + // defined in RFC 5893. + bidirule func(s string) bool } // A Profile defines the configuration of a IDNA mapper. + type Profile struct { options } func apply(o *options, opts []Option) { + for _, f := range opts { + f(o) + } + } // New creates a new Profile. + // + // With no options, the returned Profile is the most permissive and equals the + // Punycode Profile. Options can be passed to further restrict the Profile. The + // MapForLookup and ValidateForRegistration options set a collection of options, + // for lookup and registration purposes respectively, which can be tailored by + // adding more fine-grained options, where later options override earlier + // options. + func New(o ...Option) *Profile { + p := &Profile{} + apply(&p.options, o) + return p + } // ToASCII converts a domain or domain label to its ASCII form. For example, + // ToASCII("bücher.example.com") is "xn--bcher-kva.example.com", and + // ToASCII("golang") is "golang". If an error is encountered it will return + // an error and a (partially) processed result. + func (p *Profile) ToASCII(s string) (string, error) { + return p.process(s, true) + } // ToUnicode converts a domain or domain label to its Unicode form. For example, + // ToUnicode("xn--bcher-kva.example.com") is "bücher.example.com", and + // ToUnicode("golang") is "golang". If an error is encountered it will return + // an error and a (partially) processed result. + func (p *Profile) ToUnicode(s string) (string, error) { + pp := *p + pp.transitional = false + return pp.process(s, false) + } // String reports a string with a description of the profile for debugging + // purposes. The string format may change with different versions. + func (p *Profile) String() string { + s := "" + if p.transitional { + s = "Transitional" + } else { + s = "NonTransitional" + } + if p.useSTD3Rules { + s += ":UseSTD3Rules" + } + if p.checkHyphens { + s += ":CheckHyphens" + } + if p.checkJoiners { + s += ":CheckJoiners" + } + if p.verifyDNSLength { + s += ":VerifyDNSLength" + } + return s + } var ( + // Punycode is a Profile that does raw punycode processing with a minimum + // of validation. + Punycode *Profile = punycode // Lookup is the recommended profile for looking up domain names, according + // to Section 5 of RFC 5891. The exact configuration of this profile may + // change over time. + Lookup *Profile = lookup // Display is the recommended profile for displaying domain names. + // The configuration of this profile may change over time. + Display *Profile = display // Registration is the recommended profile for checking whether a given + // IDN is valid for registration, according to Section 4 of RFC 5891. + Registration *Profile = registration punycode = &Profile{} - lookup = &Profile{options{ - transitional: true, + + lookup = &Profile{options{ + + transitional: true, + removeLeadingDots: true, - useSTD3Rules: true, - checkHyphens: true, - checkJoiners: true, - trie: trie, - fromPuny: validateFromPunycode, - mapping: validateAndMap, - bidirule: bidirule.ValidString, + + useSTD3Rules: true, + + checkHyphens: true, + + checkJoiners: true, + + trie: trie, + + fromPuny: validateFromPunycode, + + mapping: validateAndMap, + + bidirule: bidirule.ValidString, }} + display = &Profile{options{ - useSTD3Rules: true, + + useSTD3Rules: true, + removeLeadingDots: true, - checkHyphens: true, - checkJoiners: true, - trie: trie, - fromPuny: validateFromPunycode, - mapping: validateAndMap, - bidirule: bidirule.ValidString, + + checkHyphens: true, + + checkJoiners: true, + + trie: trie, + + fromPuny: validateFromPunycode, + + mapping: validateAndMap, + + bidirule: bidirule.ValidString, }} + registration = &Profile{options{ - useSTD3Rules: true, + + useSTD3Rules: true, + verifyDNSLength: true, - checkHyphens: true, - checkJoiners: true, - trie: trie, - fromPuny: validateFromPunycode, - mapping: validateRegistration, - bidirule: bidirule.ValidString, + + checkHyphens: true, + + checkJoiners: true, + + trie: trie, + + fromPuny: validateFromPunycode, + + mapping: validateRegistration, + + bidirule: bidirule.ValidString, }} // TODO: profiles + // Register: recommended for approving domain names: don't do any mappings + // but rather reject on invalid input. Bundle or block deviation characters. + ) type labelError struct{ label, code_ string } func (e labelError) code() string { return e.code_ } + func (e labelError) Error() string { + return fmt.Sprintf("idna: invalid label %q", e.label) + } type runeError rune func (e runeError) code() string { return "P1" } + func (e runeError) Error() string { + return fmt.Sprintf("idna: disallowed rune %U", e) + } // process implements the algorithm described in section 4 of UTS #46, + // see https://www.unicode.org/reports/tr46. + func (p *Profile) process(s string, toASCII bool) (string, error) { + var err error + if p.mapping != nil { + s, err = p.mapping(p, s) + } + // Remove leading empty labels. + if p.removeLeadingDots { + for ; len(s) > 0 && s[0] == '.'; s = s[1:] { + } + } + // It seems like we should only create this error on ToASCII, but the + // UTS 46 conformance tests suggests we should always check this. + if err == nil && p.verifyDNSLength && s == "" { + err = &labelError{s, "A4"} + } + labels := labelIter{orig: s} + for ; !labels.done(); labels.next() { + label := labels.label() + if label == "" { + // Empty labels are not okay. The label iterator skips the last + // label if it is empty. + if err == nil && p.verifyDNSLength { + err = &labelError{s, "A4"} + } + continue + } + if strings.HasPrefix(label, acePrefix) { + u, err2 := decode(label[len(acePrefix):]) + if err2 != nil { + if err == nil { + err = err2 + } + // Spec says keep the old label. + continue + } + labels.set(u) + if err == nil && p.fromPuny != nil { + err = p.fromPuny(p, u) + } + if err == nil { + // This should be called on NonTransitional, according to the + // spec, but that currently does not have any effect. Use the + // original profile to preserve options. + err = p.validateLabel(u) + } + } else if err == nil { + err = p.validateLabel(label) + } + } + if toASCII { + for labels.reset(); !labels.done(); labels.next() { + label := labels.label() + if !ascii(label) { + a, err2 := encode(acePrefix, label) + if err == nil { + err = err2 + } + label = a + labels.set(a) + } + n := len(label) + if p.verifyDNSLength && err == nil && (n == 0 || n > 63) { + err = &labelError{label, "A4"} + } + } + } + s = labels.result() + if toASCII && p.verifyDNSLength && err == nil { + // Compute the length of the domain name minus the root label and its dot. + n := len(s) + if n > 0 && s[n-1] == '.' { + n-- + } + if len(s) < 1 || n > 253 { + err = &labelError{s, "A4"} + } + } + return s, err + } func normalize(p *Profile, s string) (string, error) { + return norm.NFC.String(s), nil + } func validateRegistration(p *Profile, s string) (string, error) { + if !norm.NFC.IsNormalString(s) { + return s, &labelError{s, "V1"} + } + for i := 0; i < len(s); { + v, sz := trie.lookupString(s[i:]) + // Copy bytes not copied so far. + switch p.simplify(info(v).category()) { + // TODO: handle the NV8 defined in the Unicode idna data set to allow + // for strict conformance to IDNA2008. + case valid, deviation: + case disallowed, mapped, unknown, ignored: + r, _ := utf8.DecodeRuneInString(s[i:]) + return s, runeError(r) + } + i += sz + } + return s, nil + } func validateAndMap(p *Profile, s string) (string, error) { + var ( err error - b []byte - k int + + b []byte + + k int ) + for i := 0; i < len(s); { + v, sz := trie.lookupString(s[i:]) + start := i + i += sz + // Copy bytes not copied so far. + switch p.simplify(info(v).category()) { + case valid: + continue + case disallowed: + if err == nil { + r, _ := utf8.DecodeRuneInString(s[start:]) + err = runeError(r) + } + continue + case mapped, deviation: + b = append(b, s[k:start]...) + b = info(v).appendMapping(b, s[start:i]) + case ignored: + b = append(b, s[k:start]...) + // drop the rune + case unknown: + b = append(b, s[k:start]...) + b = append(b, "\ufffd"...) + } + k = i + } + if k == 0 { + // No changes so far. + s = norm.NFC.String(s) + } else { + b = append(b, s[k:]...) + if norm.NFC.QuickSpan(b) != len(b) { + b = norm.NFC.Bytes(b) + } + // TODO: the punycode converters require strings as input. + s = string(b) + } + return s, err + } // A labelIter allows iterating over domain name labels. + type labelIter struct { - orig string - slice []string + orig string + + slice []string + curStart int - curEnd int - i int + + curEnd int + + i int } func (l *labelIter) reset() { + l.curStart = 0 + l.curEnd = 0 + l.i = 0 + } func (l *labelIter) done() bool { + return l.curStart >= len(l.orig) + } func (l *labelIter) result() string { + if l.slice != nil { + return strings.Join(l.slice, ".") + } + return l.orig + } func (l *labelIter) label() string { + if l.slice != nil { + return l.slice[l.i] + } + p := strings.IndexByte(l.orig[l.curStart:], '.') + l.curEnd = l.curStart + p + if p == -1 { + l.curEnd = len(l.orig) + } + return l.orig[l.curStart:l.curEnd] + } // next sets the value to the next label. It skips the last label if it is empty. + func (l *labelIter) next() { + l.i++ + if l.slice != nil { + if l.i >= len(l.slice) || l.i == len(l.slice)-1 && l.slice[l.i] == "" { + l.curStart = len(l.orig) + } + } else { + l.curStart = l.curEnd + 1 + if l.curStart == len(l.orig)-1 && l.orig[l.curStart] == '.' { + l.curStart = len(l.orig) + } + } + } func (l *labelIter) set(s string) { + if l.slice == nil { + l.slice = strings.Split(l.orig, ".") + } + l.slice[l.i] = s + } // acePrefix is the ASCII Compatible Encoding prefix. + const acePrefix = "xn--" func (p *Profile) simplify(cat category) category { + switch cat { + case disallowedSTD3Mapped: + if p.useSTD3Rules { + cat = disallowed + } else { + cat = mapped + } + case disallowedSTD3Valid: + if p.useSTD3Rules { + cat = disallowed + } else { + cat = valid + } + case deviation: + if !p.transitional { + cat = valid + } + case validNV8, validXV8: + // TODO: handle V2008 + cat = valid + } + return cat + } func validateFromPunycode(p *Profile, s string) error { + if !norm.NFC.IsNormalString(s) { + return &labelError{s, "V1"} + } + for i := 0; i < len(s); { + v, sz := trie.lookupString(s[i:]) + if c := p.simplify(info(v).category()); c != valid && c != deviation { + return &labelError{s, "V6"} + } + i += sz + } + return nil + } const ( zwnj = "\u200c" - zwj = "\u200d" + + zwj = "\u200d" ) type joinState int8 const ( stateStart joinState = iota + stateVirama + stateBefore + stateBeforeVirama + stateAfter + stateFAIL ) var joinStates = [][numJoinTypes]joinState{ + stateStart: { - joiningL: stateBefore, - joiningD: stateBefore, - joinZWNJ: stateFAIL, - joinZWJ: stateFAIL, + + joiningL: stateBefore, + + joiningD: stateBefore, + + joinZWNJ: stateFAIL, + + joinZWJ: stateFAIL, + joinVirama: stateVirama, }, + stateVirama: { + joiningL: stateBefore, + joiningD: stateBefore, }, + stateBefore: { - joiningL: stateBefore, - joiningD: stateBefore, - joiningT: stateBefore, - joinZWNJ: stateAfter, - joinZWJ: stateFAIL, + + joiningL: stateBefore, + + joiningD: stateBefore, + + joiningT: stateBefore, + + joinZWNJ: stateAfter, + + joinZWJ: stateFAIL, + joinVirama: stateBeforeVirama, }, + stateBeforeVirama: { + joiningL: stateBefore, + joiningD: stateBefore, + joiningT: stateBefore, }, + stateAfter: { - joiningL: stateFAIL, - joiningD: stateBefore, - joiningT: stateAfter, - joiningR: stateStart, - joinZWNJ: stateFAIL, - joinZWJ: stateFAIL, + + joiningL: stateFAIL, + + joiningD: stateBefore, + + joiningT: stateAfter, + + joiningR: stateStart, + + joinZWNJ: stateFAIL, + + joinZWJ: stateFAIL, + joinVirama: stateAfter, // no-op as we can't accept joiners here + }, + stateFAIL: { - 0: stateFAIL, - joiningL: stateFAIL, - joiningD: stateFAIL, - joiningT: stateFAIL, - joiningR: stateFAIL, - joinZWNJ: stateFAIL, - joinZWJ: stateFAIL, + + 0: stateFAIL, + + joiningL: stateFAIL, + + joiningD: stateFAIL, + + joiningT: stateFAIL, + + joiningR: stateFAIL, + + joinZWNJ: stateFAIL, + + joinZWJ: stateFAIL, + joinVirama: stateFAIL, }, } // validateLabel validates the criteria from Section 4.1. Item 1, 4, and 6 are + // already implicitly satisfied by the overall implementation. + func (p *Profile) validateLabel(s string) error { + if s == "" { + if p.verifyDNSLength { + return &labelError{s, "A4"} + } + return nil + } + if p.bidirule != nil && !p.bidirule(s) { + return &labelError{s, "B"} + } + if p.checkHyphens { + if len(s) > 4 && s[2] == '-' && s[3] == '-' { + return &labelError{s, "V2"} + } + if s[0] == '-' || s[len(s)-1] == '-' { + return &labelError{s, "V3"} + } + } + if !p.checkJoiners { + return nil + } + trie := p.trie // p.checkJoiners is only set if trie is set. + // TODO: merge the use of this in the trie. + v, sz := trie.lookupString(s) + x := info(v) + if x.isModifier() { + return &labelError{s, "V5"} + } + // Quickly return in the absence of zero-width (non) joiners. + if strings.Index(s, zwj) == -1 && strings.Index(s, zwnj) == -1 { + return nil + } + st := stateStart + for i := 0; ; { + jt := x.joinType() + if s[i:i+sz] == zwj { + jt = joinZWJ + } else if s[i:i+sz] == zwnj { + jt = joinZWNJ + } + st = joinStates[st][jt] + if x.isViramaModifier() { + st = joinStates[st][joinVirama] + } + if i += sz; i == len(s) { + break + } + v, sz = trie.lookupString(s[i:]) + x = info(v) + } + if st == stateFAIL || st == stateAfter { + return &labelError{s, "C"} + } + return nil + } func ascii(s string) bool { + for i := 0; i < len(s); i++ { + if s[i] >= utf8.RuneSelf { + return false + } + } + return true + } diff --git a/vendor/golang.org/x/net/idna/punycode.go b/vendor/golang.org/x/net/idna/punycode.go index e8e3ac1..36f9296 100644 --- a/vendor/golang.org/x/net/idna/punycode.go +++ b/vendor/golang.org/x/net/idna/punycode.go @@ -1,7 +1,9 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. // Copyright 2016 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package idna @@ -15,203 +17,387 @@ import ( ) // These parameter values are specified in section 5. + // + // All computation is done with int32s, so that overflow behavior is identical + // regardless of whether int is 32-bit or 64-bit. + const ( - base int32 = 36 - damp int32 = 700 + base int32 = 36 + + damp int32 = 700 + initialBias int32 = 72 - initialN int32 = 128 - skew int32 = 38 - tmax int32 = 26 - tmin int32 = 1 + + initialN int32 = 128 + + skew int32 = 38 + + tmax int32 = 26 + + tmin int32 = 1 ) func punyError(s string) error { return &labelError{s, "A3"} } // decode decodes a string as specified in section 6.2. + func decode(encoded string) (string, error) { + if encoded == "" { + return "", nil + } + pos := 1 + strings.LastIndex(encoded, "-") + if pos == 1 { + return "", punyError(encoded) + } + if pos == len(encoded) { + return encoded[:len(encoded)-1], nil + } + output := make([]rune, 0, len(encoded)) + if pos != 0 { + for _, r := range encoded[:pos-1] { + output = append(output, r) + } + } + i, n, bias := int32(0), initialN, initialBias + overflow := false + for pos < len(encoded) { + oldI, w := i, int32(1) + for k := base; ; k += base { + if pos == len(encoded) { + return "", punyError(encoded) + } + digit, ok := decodeDigit(encoded[pos]) + if !ok { + return "", punyError(encoded) + } + pos++ + i, overflow = madd(i, digit, w) + if overflow { + return "", punyError(encoded) + } + t := k - bias + if k <= bias { + t = tmin + } else if k >= bias+tmax { + t = tmax + } + if digit < t { + break + } + w, overflow = madd(0, w, base-t) + if overflow { + return "", punyError(encoded) + } + } + if len(output) >= 1024 { + return "", punyError(encoded) + } + x := int32(len(output) + 1) + bias = adapt(i-oldI, x, oldI == 0) + n += i / x + i %= x + if n < 0 || n > utf8.MaxRune { + return "", punyError(encoded) + } + output = append(output, 0) + copy(output[i+1:], output[i:]) + output[i] = n + i++ + } + return string(output), nil + } // encode encodes a string as specified in section 6.3 and prepends prefix to + // the result. + // + // The "while h < length(input)" line in the specification becomes "for + // remaining != 0" in the Go code, because len(s) in Go is in bytes, not runes. + func encode(prefix, s string) (string, error) { + output := make([]byte, len(prefix), len(prefix)+1+2*len(s)) + copy(output, prefix) + delta, n, bias := int32(0), initialN, initialBias + b, remaining := int32(0), int32(0) + for _, r := range s { + if r < 0x80 { + b++ + output = append(output, byte(r)) + } else { + remaining++ + } + } + h := b + if b > 0 { + output = append(output, '-') + } + overflow := false + for remaining != 0 { + m := int32(0x7fffffff) + for _, r := range s { + if m > r && r >= n { + m = r + } + } + delta, overflow = madd(delta, m-n, h+1) + if overflow { + return "", punyError(s) + } + n = m + for _, r := range s { + if r < n { + delta++ + if delta < 0 { + return "", punyError(s) + } + continue + } + if r > n { + continue + } + q := delta + for k := base; ; k += base { + t := k - bias + if k <= bias { + t = tmin + } else if k >= bias+tmax { + t = tmax + } + if q < t { + break + } + output = append(output, encodeDigit(t+(q-t)%(base-t))) + q = (q - t) / (base - t) + } + output = append(output, encodeDigit(q)) + bias = adapt(delta, h+1, h == b) + delta = 0 + h++ + remaining-- + } + delta++ + n++ + } + return string(output), nil + } // madd computes a + (b * c), detecting overflow. + func madd(a, b, c int32) (next int32, overflow bool) { + p := int64(b) * int64(c) + if p > math.MaxInt32-int64(a) { + return 0, true + } + return a + int32(p), false + } func decodeDigit(x byte) (digit int32, ok bool) { + switch { + case '0' <= x && x <= '9': + return int32(x - ('0' - 26)), true + case 'A' <= x && x <= 'Z': + return int32(x - 'A'), true + case 'a' <= x && x <= 'z': + return int32(x - 'a'), true + } + return 0, false + } func encodeDigit(digit int32) byte { + switch { + case 0 <= digit && digit < 26: + return byte(digit + 'a') + case 26 <= digit && digit < 36: + return byte(digit + ('0' - 26)) + } + panic("idna: internal error in punycode encoding") + } // adapt is the bias adaptation function specified in section 6.1. + func adapt(delta, numPoints int32, firstTime bool) int32 { + if firstTime { + delta /= damp + } else { + delta /= 2 + } + delta += delta / numPoints + k := int32(0) + for delta > ((base-tmin)*tmax)/2 { + delta /= base - tmin + k += base + } + return k + (base-tmin+1)*delta/(delta+skew) + } diff --git a/vendor/golang.org/x/sys/unix/affinity_linux.go b/vendor/golang.org/x/sys/unix/affinity_linux.go index 6e5c81a..4a50cc4 100644 --- a/vendor/golang.org/x/sys/unix/affinity_linux.go +++ b/vendor/golang.org/x/sys/unix/affinity_linux.go @@ -1,5 +1,7 @@ // Copyright 2018 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // CPU affinity functions @@ -14,73 +16,123 @@ import ( const cpuSetSize = _CPU_SETSIZE / _NCPUBITS // CPUSet represents a CPU affinity mask. + type CPUSet [cpuSetSize]cpuMask func schedAffinity(trap uintptr, pid int, set *CPUSet) error { + _, _, e := RawSyscall(trap, uintptr(pid), uintptr(unsafe.Sizeof(*set)), uintptr(unsafe.Pointer(set))) + if e != 0 { + return errnoErr(e) + } + return nil + } // SchedGetaffinity gets the CPU affinity mask of the thread specified by pid. + // If pid is 0 the calling thread is used. + func SchedGetaffinity(pid int, set *CPUSet) error { + return schedAffinity(SYS_SCHED_GETAFFINITY, pid, set) + } // SchedSetaffinity sets the CPU affinity mask of the thread specified by pid. + // If pid is 0 the calling thread is used. + func SchedSetaffinity(pid int, set *CPUSet) error { + return schedAffinity(SYS_SCHED_SETAFFINITY, pid, set) + } // Zero clears the set s, so that it contains no CPUs. + func (s *CPUSet) Zero() { + for i := range s { + s[i] = 0 + } + } func cpuBitsIndex(cpu int) int { + return cpu / _NCPUBITS + } func cpuBitsMask(cpu int) cpuMask { + return cpuMask(1 << (uint(cpu) % _NCPUBITS)) + } // Set adds cpu to the set s. + func (s *CPUSet) Set(cpu int) { + i := cpuBitsIndex(cpu) + if i < len(s) { + s[i] |= cpuBitsMask(cpu) + } + } // Clear removes cpu from the set s. + func (s *CPUSet) Clear(cpu int) { + i := cpuBitsIndex(cpu) + if i < len(s) { + s[i] &^= cpuBitsMask(cpu) + } + } // IsSet reports whether cpu is in the set s. + func (s *CPUSet) IsSet(cpu int) bool { + i := cpuBitsIndex(cpu) + if i < len(s) { + return s[i]&cpuBitsMask(cpu) != 0 + } + return false + } // Count returns the number of CPUs in the set s. + func (s *CPUSet) Count() int { + c := 0 + for _, b := range s { + c += bits.OnesCount64(uint64(b)) + } + return c + } diff --git a/vendor/golang.org/x/sys/unix/bpxsvc_zos.go b/vendor/golang.org/x/sys/unix/bpxsvc_zos.go index 39d647d..3187d46 100644 --- a/vendor/golang.org/x/sys/unix/bpxsvc_zos.go +++ b/vendor/golang.org/x/sys/unix/bpxsvc_zos.go @@ -1,5 +1,7 @@ // Copyright 2024 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build zos @@ -13,645 +15,1219 @@ import ( ) //go:noescape + func bpxcall(plist []unsafe.Pointer, bpx_offset int64) //go:noescape + func A2e([]byte) //go:noescape + func E2a([]byte) const ( - BPX4STA = 192 // stat - BPX4FST = 104 // fstat - BPX4LST = 132 // lstat - BPX4OPN = 156 // open - BPX4CLO = 72 // close - BPX4CHR = 500 // chattr - BPX4FCR = 504 // fchattr + BPX4STA = 192 // stat + + BPX4FST = 104 // fstat + + BPX4LST = 132 // lstat + + BPX4OPN = 156 // open + + BPX4CLO = 72 // close + + BPX4CHR = 500 // chattr + + BPX4FCR = 504 // fchattr + BPX4LCR = 1180 // lchattr - BPX4CTW = 492 // cond_timed_wait + + BPX4CTW = 492 // cond_timed_wait + BPX4GTH = 1056 // __getthent - BPX4PTQ = 412 // pthread_quiesc - BPX4PTR = 320 // ptrace + + BPX4PTQ = 412 // pthread_quiesc + + BPX4PTR = 320 // ptrace + ) const ( + //options + //byte1 + BPX_OPNFHIGH = 0x80 + //byte2 + BPX_OPNFEXEC = 0x80 + //byte3 + BPX_O_NOLARGEFILE = 0x08 - BPX_O_LARGEFILE = 0x04 - BPX_O_ASYNCSIG = 0x02 - BPX_O_SYNC = 0x01 + + BPX_O_LARGEFILE = 0x04 + + BPX_O_ASYNCSIG = 0x02 + + BPX_O_SYNC = 0x01 + //byte4 - BPX_O_CREXCL = 0xc0 - BPX_O_CREAT = 0x80 - BPX_O_EXCL = 0x40 - BPX_O_NOCTTY = 0x20 - BPX_O_TRUNC = 0x10 - BPX_O_APPEND = 0x08 + + BPX_O_CREXCL = 0xc0 + + BPX_O_CREAT = 0x80 + + BPX_O_EXCL = 0x40 + + BPX_O_NOCTTY = 0x20 + + BPX_O_TRUNC = 0x10 + + BPX_O_APPEND = 0x08 + BPX_O_NONBLOCK = 0x04 - BPX_FNDELAY = 0x04 - BPX_O_RDWR = 0x03 - BPX_O_RDONLY = 0x02 - BPX_O_WRONLY = 0x01 - BPX_O_ACCMODE = 0x03 - BPX_O_GETFL = 0x0f + + BPX_FNDELAY = 0x04 + + BPX_O_RDWR = 0x03 + + BPX_O_RDONLY = 0x02 + + BPX_O_WRONLY = 0x01 + + BPX_O_ACCMODE = 0x03 + + BPX_O_GETFL = 0x0f //mode - // byte1 (file type) - BPX_FT_DIR = 1 - BPX_FT_CHARSPEC = 2 - BPX_FT_REGFILE = 3 - BPX_FT_FIFO = 4 - BPX_FT_SYMLINK = 5 - BPX_FT_SOCKET = 6 - //byte3 - BPX_S_ISUID = 0x08 - BPX_S_ISGID = 0x04 - BPX_S_ISVTX = 0x02 - BPX_S_IRWXU1 = 0x01 - BPX_S_IRUSR = 0x01 - //byte4 - BPX_S_IRWXU2 = 0xc0 - BPX_S_IWUSR = 0x80 - BPX_S_IXUSR = 0x40 - BPX_S_IRWXG = 0x38 - BPX_S_IRGRP = 0x20 - BPX_S_IWGRP = 0x10 - BPX_S_IXGRP = 0x08 - BPX_S_IRWXOX = 0x07 - BPX_S_IROTH = 0x04 - BPX_S_IWOTH = 0x02 - BPX_S_IXOTH = 0x01 - CW_INTRPT = 1 + // byte1 (file type) + + BPX_FT_DIR = 1 + + BPX_FT_CHARSPEC = 2 + + BPX_FT_REGFILE = 3 + + BPX_FT_FIFO = 4 + + BPX_FT_SYMLINK = 5 + + BPX_FT_SOCKET = 6 + + //byte3 + + BPX_S_ISUID = 0x08 + + BPX_S_ISGID = 0x04 + + BPX_S_ISVTX = 0x02 + + BPX_S_IRWXU1 = 0x01 + + BPX_S_IRUSR = 0x01 + + //byte4 + + BPX_S_IRWXU2 = 0xc0 + + BPX_S_IWUSR = 0x80 + + BPX_S_IXUSR = 0x40 + + BPX_S_IRWXG = 0x38 + + BPX_S_IRGRP = 0x20 + + BPX_S_IWGRP = 0x10 + + BPX_S_IXGRP = 0x08 + + BPX_S_IRWXOX = 0x07 + + BPX_S_IROTH = 0x04 + + BPX_S_IWOTH = 0x02 + + BPX_S_IXOTH = 0x01 + + CW_INTRPT = 1 + CW_CONDVAR = 32 + CW_TIMEOUT = 64 - PGTHA_NEXT = 2 - PGTHA_CURRENT = 1 - PGTHA_FIRST = 0 - PGTHA_LAST = 3 - PGTHA_PROCESS = 0x80 - PGTHA_CONTTY = 0x40 - PGTHA_PATH = 0x20 - PGTHA_COMMAND = 0x10 - PGTHA_FILEDATA = 0x08 - PGTHA_THREAD = 0x04 - PGTHA_PTAG = 0x02 + PGTHA_NEXT = 2 + + PGTHA_CURRENT = 1 + + PGTHA_FIRST = 0 + + PGTHA_LAST = 3 + + PGTHA_PROCESS = 0x80 + + PGTHA_CONTTY = 0x40 + + PGTHA_PATH = 0x20 + + PGTHA_COMMAND = 0x10 + + PGTHA_FILEDATA = 0x08 + + PGTHA_THREAD = 0x04 + + PGTHA_PTAG = 0x02 + PGTHA_COMMANDLONG = 0x01 - PGTHA_THREADFAST = 0x80 - PGTHA_FILEPATH = 0x40 - PGTHA_THDSIGMASK = 0x20 + + PGTHA_THREADFAST = 0x80 + + PGTHA_FILEPATH = 0x40 + + PGTHA_THDSIGMASK = 0x20 + // thread quiece mode - QUIESCE_TERM int32 = 1 - QUIESCE_FORCE int32 = 2 - QUIESCE_QUERY int32 = 3 - QUIESCE_FREEZE int32 = 4 - QUIESCE_UNFREEZE int32 = 5 + + QUIESCE_TERM int32 = 1 + + QUIESCE_FORCE int32 = 2 + + QUIESCE_QUERY int32 = 3 + + QUIESCE_FREEZE int32 = 4 + + QUIESCE_UNFREEZE int32 = 5 + FREEZE_THIS_THREAD int32 = 6 - FREEZE_EXIT int32 = 8 - QUIESCE_SRB int32 = 9 + + FREEZE_EXIT int32 = 8 + + QUIESCE_SRB int32 = 9 ) type Pgtha struct { - Pid uint32 // 0 - Tid0 uint32 // 4 - Tid1 uint32 - Accesspid byte // C - Accesstid byte // D - Accessasid uint16 // E - Loginname [8]byte // 10 - Flag1 byte // 18 - Flag1b2 byte // 19 + Pid uint32 // 0 + + Tid0 uint32 // 4 + + Tid1 uint32 + + Accesspid byte // C + + Accesstid byte // D + + Accessasid uint16 // E + + Loginname [8]byte // 10 + + Flag1 byte // 18 + + Flag1b2 byte // 19 + } type Bpxystat_t struct { // DSECT BPXYSTAT - St_id [4]uint8 // 0 - St_length uint16 // 0x4 - St_version uint16 // 0x6 - St_mode uint32 // 0x8 - St_ino uint32 // 0xc - St_dev uint32 // 0x10 - St_nlink uint32 // 0x14 - St_uid uint32 // 0x18 - St_gid uint32 // 0x1c - St_size uint64 // 0x20 - St_atime uint32 // 0x28 - St_mtime uint32 // 0x2c - St_ctime uint32 // 0x30 - St_rdev uint32 // 0x34 - St_auditoraudit uint32 // 0x38 - St_useraudit uint32 // 0x3c - St_blksize uint32 // 0x40 - St_createtime uint32 // 0x44 - St_auditid [4]uint32 // 0x48 - St_res01 uint32 // 0x58 - Ft_ccsid uint16 // 0x5c - Ft_flags uint16 // 0x5e - St_res01a [2]uint32 // 0x60 - St_res02 uint32 // 0x68 - St_blocks uint32 // 0x6c - St_opaque [3]uint8 // 0x70 - St_visible uint8 // 0x73 - St_reftime uint32 // 0x74 - St_fid uint64 // 0x78 - St_filefmt uint8 // 0x80 - St_fspflag2 uint8 // 0x81 - St_res03 [2]uint8 // 0x82 - St_ctimemsec uint32 // 0x84 - St_seclabel [8]uint8 // 0x88 - St_res04 [4]uint8 // 0x90 + + St_id [4]uint8 // 0 + + St_length uint16 // 0x4 + + St_version uint16 // 0x6 + + St_mode uint32 // 0x8 + + St_ino uint32 // 0xc + + St_dev uint32 // 0x10 + + St_nlink uint32 // 0x14 + + St_uid uint32 // 0x18 + + St_gid uint32 // 0x1c + + St_size uint64 // 0x20 + + St_atime uint32 // 0x28 + + St_mtime uint32 // 0x2c + + St_ctime uint32 // 0x30 + + St_rdev uint32 // 0x34 + + St_auditoraudit uint32 // 0x38 + + St_useraudit uint32 // 0x3c + + St_blksize uint32 // 0x40 + + St_createtime uint32 // 0x44 + + St_auditid [4]uint32 // 0x48 + + St_res01 uint32 // 0x58 + + Ft_ccsid uint16 // 0x5c + + Ft_flags uint16 // 0x5e + + St_res01a [2]uint32 // 0x60 + + St_res02 uint32 // 0x68 + + St_blocks uint32 // 0x6c + + St_opaque [3]uint8 // 0x70 + + St_visible uint8 // 0x73 + + St_reftime uint32 // 0x74 + + St_fid uint64 // 0x78 + + St_filefmt uint8 // 0x80 + + St_fspflag2 uint8 // 0x81 + + St_res03 [2]uint8 // 0x82 + + St_ctimemsec uint32 // 0x84 + + St_seclabel [8]uint8 // 0x88 + + St_res04 [4]uint8 // 0x90 + // end of version 1 - _ uint32 // 0x94 - St_atime64 uint64 // 0x98 - St_mtime64 uint64 // 0xa0 - St_ctime64 uint64 // 0xa8 - St_createtime64 uint64 // 0xb0 - St_reftime64 uint64 // 0xb8 - _ uint64 // 0xc0 - St_res05 [16]uint8 // 0xc8 + + _ uint32 // 0x94 + + St_atime64 uint64 // 0x98 + + St_mtime64 uint64 // 0xa0 + + St_ctime64 uint64 // 0xa8 + + St_createtime64 uint64 // 0xb0 + + St_reftime64 uint64 // 0xb8 + + _ uint64 // 0xc0 + + St_res05 [16]uint8 // 0xc8 + // end of version 2 + } type BpxFilestatus struct { Oflag1 byte + Oflag2 byte + Oflag3 byte + Oflag4 byte } type BpxMode struct { Ftype byte + Mode1 byte + Mode2 byte + Mode3 byte } // Thr attribute structure for extended attributes + type Bpxyatt_t struct { // DSECT BPXYATT - Att_id [4]uint8 - Att_version uint16 - Att_res01 [2]uint8 - Att_setflags1 uint8 - Att_setflags2 uint8 - Att_setflags3 uint8 - Att_setflags4 uint8 - Att_mode uint32 - Att_uid uint32 - Att_gid uint32 - Att_opaquemask [3]uint8 + + Att_id [4]uint8 + + Att_version uint16 + + Att_res01 [2]uint8 + + Att_setflags1 uint8 + + Att_setflags2 uint8 + + Att_setflags3 uint8 + + Att_setflags4 uint8 + + Att_mode uint32 + + Att_uid uint32 + + Att_gid uint32 + + Att_opaquemask [3]uint8 + Att_visblmaskres uint8 - Att_opaque [3]uint8 - Att_visibleres uint8 - Att_size_h uint32 - Att_size_l uint32 - Att_atime uint32 - Att_mtime uint32 + + Att_opaque [3]uint8 + + Att_visibleres uint8 + + Att_size_h uint32 + + Att_size_l uint32 + + Att_atime uint32 + + Att_mtime uint32 + Att_auditoraudit uint32 - Att_useraudit uint32 - Att_ctime uint32 - Att_reftime uint32 + + Att_useraudit uint32 + + Att_ctime uint32 + + Att_reftime uint32 + // end of version 1 + Att_filefmt uint8 - Att_res02 [3]uint8 + + Att_res02 [3]uint8 + Att_filetag uint32 - Att_res03 [8]uint8 + + Att_res03 [8]uint8 + // end of version 2 - Att_atime64 uint64 - Att_mtime64 uint64 - Att_ctime64 uint64 + + Att_atime64 uint64 + + Att_mtime64 uint64 + + Att_ctime64 uint64 + Att_reftime64 uint64 - Att_seclabel [8]uint8 + + Att_seclabel [8]uint8 + Att_ver3res02 [8]uint8 + // end of version 3 + } func BpxOpen(name string, options *BpxFilestatus, mode *BpxMode) (rv int32, rc int32, rn int32) { + if len(name) < 1024 { + var namebuf [1024]byte + sz := int32(copy(namebuf[:], name)) + A2e(namebuf[:sz]) + var parms [7]unsafe.Pointer + parms[0] = unsafe.Pointer(&sz) + parms[1] = unsafe.Pointer(&namebuf[0]) + parms[2] = unsafe.Pointer(options) + parms[3] = unsafe.Pointer(mode) + parms[4] = unsafe.Pointer(&rv) + parms[5] = unsafe.Pointer(&rc) + parms[6] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4OPN) + return rv, rc, rn + } + return -1, -1, -1 + } func BpxClose(fd int32) (rv int32, rc int32, rn int32) { + var parms [4]unsafe.Pointer + parms[0] = unsafe.Pointer(&fd) + parms[1] = unsafe.Pointer(&rv) + parms[2] = unsafe.Pointer(&rc) + parms[3] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4CLO) + return rv, rc, rn + } func BpxFileFStat(fd int32, st *Bpxystat_t) (rv int32, rc int32, rn int32) { + st.St_id = [4]uint8{0xe2, 0xe3, 0xc1, 0xe3} + st.St_version = 2 + stat_sz := uint32(unsafe.Sizeof(*st)) + var parms [6]unsafe.Pointer + parms[0] = unsafe.Pointer(&fd) + parms[1] = unsafe.Pointer(&stat_sz) + parms[2] = unsafe.Pointer(st) + parms[3] = unsafe.Pointer(&rv) + parms[4] = unsafe.Pointer(&rc) + parms[5] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4FST) + return rv, rc, rn + } func BpxFileStat(name string, st *Bpxystat_t) (rv int32, rc int32, rn int32) { + if len(name) < 1024 { + var namebuf [1024]byte + sz := int32(copy(namebuf[:], name)) + A2e(namebuf[:sz]) + st.St_id = [4]uint8{0xe2, 0xe3, 0xc1, 0xe3} + st.St_version = 2 + stat_sz := uint32(unsafe.Sizeof(*st)) + var parms [7]unsafe.Pointer + parms[0] = unsafe.Pointer(&sz) + parms[1] = unsafe.Pointer(&namebuf[0]) + parms[2] = unsafe.Pointer(&stat_sz) + parms[3] = unsafe.Pointer(st) + parms[4] = unsafe.Pointer(&rv) + parms[5] = unsafe.Pointer(&rc) + parms[6] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4STA) + return rv, rc, rn + } + return -1, -1, -1 + } func BpxFileLStat(name string, st *Bpxystat_t) (rv int32, rc int32, rn int32) { + if len(name) < 1024 { + var namebuf [1024]byte + sz := int32(copy(namebuf[:], name)) + A2e(namebuf[:sz]) + st.St_id = [4]uint8{0xe2, 0xe3, 0xc1, 0xe3} + st.St_version = 2 + stat_sz := uint32(unsafe.Sizeof(*st)) + var parms [7]unsafe.Pointer + parms[0] = unsafe.Pointer(&sz) + parms[1] = unsafe.Pointer(&namebuf[0]) + parms[2] = unsafe.Pointer(&stat_sz) + parms[3] = unsafe.Pointer(st) + parms[4] = unsafe.Pointer(&rv) + parms[5] = unsafe.Pointer(&rc) + parms[6] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4LST) + return rv, rc, rn + } + return -1, -1, -1 + } func BpxChattr(path string, attr *Bpxyatt_t) (rv int32, rc int32, rn int32) { + if len(path) >= 1024 { + return -1, -1, -1 + } + var namebuf [1024]byte + sz := int32(copy(namebuf[:], path)) + A2e(namebuf[:sz]) + attr_sz := uint32(unsafe.Sizeof(*attr)) + var parms [7]unsafe.Pointer + parms[0] = unsafe.Pointer(&sz) + parms[1] = unsafe.Pointer(&namebuf[0]) + parms[2] = unsafe.Pointer(&attr_sz) + parms[3] = unsafe.Pointer(attr) + parms[4] = unsafe.Pointer(&rv) + parms[5] = unsafe.Pointer(&rc) + parms[6] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4CHR) + return rv, rc, rn + } func BpxLchattr(path string, attr *Bpxyatt_t) (rv int32, rc int32, rn int32) { + if len(path) >= 1024 { + return -1, -1, -1 + } + var namebuf [1024]byte + sz := int32(copy(namebuf[:], path)) + A2e(namebuf[:sz]) + attr_sz := uint32(unsafe.Sizeof(*attr)) + var parms [7]unsafe.Pointer + parms[0] = unsafe.Pointer(&sz) + parms[1] = unsafe.Pointer(&namebuf[0]) + parms[2] = unsafe.Pointer(&attr_sz) + parms[3] = unsafe.Pointer(attr) + parms[4] = unsafe.Pointer(&rv) + parms[5] = unsafe.Pointer(&rc) + parms[6] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4LCR) + return rv, rc, rn + } func BpxFchattr(fd int32, attr *Bpxyatt_t) (rv int32, rc int32, rn int32) { + attr_sz := uint32(unsafe.Sizeof(*attr)) + var parms [6]unsafe.Pointer + parms[0] = unsafe.Pointer(&fd) + parms[1] = unsafe.Pointer(&attr_sz) + parms[2] = unsafe.Pointer(attr) + parms[3] = unsafe.Pointer(&rv) + parms[4] = unsafe.Pointer(&rc) + parms[5] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4FCR) + return rv, rc, rn + } func BpxCondTimedWait(sec uint32, nsec uint32, events uint32, secrem *uint32, nsecrem *uint32) (rv int32, rc int32, rn int32) { + var parms [8]unsafe.Pointer + parms[0] = unsafe.Pointer(&sec) + parms[1] = unsafe.Pointer(&nsec) + parms[2] = unsafe.Pointer(&events) + parms[3] = unsafe.Pointer(secrem) + parms[4] = unsafe.Pointer(nsecrem) + parms[5] = unsafe.Pointer(&rv) + parms[6] = unsafe.Pointer(&rc) + parms[7] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4CTW) + return rv, rc, rn + } + func BpxGetthent(in *Pgtha, outlen *uint32, out unsafe.Pointer) (rv int32, rc int32, rn int32) { + var parms [7]unsafe.Pointer + inlen := uint32(26) // nothing else will work. Go says Pgtha is 28-byte because of alignment, but Pgtha is "packed" and must be 26-byte + parms[0] = unsafe.Pointer(&inlen) + parms[1] = unsafe.Pointer(&in) + parms[2] = unsafe.Pointer(outlen) + parms[3] = unsafe.Pointer(&out) + parms[4] = unsafe.Pointer(&rv) + parms[5] = unsafe.Pointer(&rc) + parms[6] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4GTH) + return rv, rc, rn + } + func ZosJobname() (jobname string, err error) { + var pgtha Pgtha + pgtha.Pid = uint32(Getpid()) + pgtha.Accesspid = PGTHA_CURRENT + pgtha.Flag1 = PGTHA_PROCESS + var out [256]byte + var outlen uint32 + outlen = 256 + rv, rc, rn := BpxGetthent(&pgtha, &outlen, unsafe.Pointer(&out[0])) + if rv == 0 { + gthc := []byte{0x87, 0xa3, 0x88, 0x83} // 'gthc' in ebcdic + ix := bytes.Index(out[:], gthc) + if ix == -1 { + err = fmt.Errorf("BPX4GTH: gthc return data not found") + return + } + jn := out[ix+80 : ix+88] // we didn't declare Pgthc, but jobname is 8-byte at offset 80 + E2a(jn) + jobname = string(bytes.TrimRight(jn, " ")) } else { + err = fmt.Errorf("BPX4GTH: rc=%d errno=%d reason=code=0x%x", rv, rc, rn) + } + return + } + func Bpx4ptq(code int32, data string) (rv int32, rc int32, rn int32) { + var userdata [8]byte + var parms [5]unsafe.Pointer + copy(userdata[:], data+" ") + A2e(userdata[:]) + parms[0] = unsafe.Pointer(&code) + parms[1] = unsafe.Pointer(&userdata[0]) + parms[2] = unsafe.Pointer(&rv) + parms[3] = unsafe.Pointer(&rc) + parms[4] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4PTQ) + return rv, rc, rn + } const ( - PT_TRACE_ME = 0 // Debug this process - PT_READ_I = 1 // Read a full word - PT_READ_D = 2 // Read a full word - PT_READ_U = 3 // Read control info - PT_WRITE_I = 4 //Write a full word - PT_WRITE_D = 5 //Write a full word - PT_CONTINUE = 7 //Continue the process - PT_KILL = 8 //Terminate the process - PT_READ_GPR = 11 // Read GPR, CR, PSW - PT_READ_FPR = 12 // Read FPR - PT_READ_VR = 13 // Read VR - PT_WRITE_GPR = 14 // Write GPR, CR, PSW - PT_WRITE_FPR = 15 // Write FPR - PT_WRITE_VR = 16 // Write VR - PT_READ_BLOCK = 17 // Read storage - PT_WRITE_BLOCK = 19 // Write storage - PT_READ_GPRH = 20 // Read GPRH - PT_WRITE_GPRH = 21 // Write GPRH - PT_REGHSET = 22 // Read all GPRHs - PT_ATTACH = 30 // Attach to a process - PT_DETACH = 31 // Detach from a process - PT_REGSET = 32 // Read all GPRs - PT_REATTACH = 33 // Reattach to a process - PT_LDINFO = 34 // Read loader info - PT_MULTI = 35 // Multi process mode - PT_LD64INFO = 36 // RMODE64 Info Area - PT_BLOCKREQ = 40 // Block request - PT_THREAD_INFO = 60 // Read thread info - PT_THREAD_MODIFY = 61 - PT_THREAD_READ_FOCUS = 62 - PT_THREAD_WRITE_FOCUS = 63 - PT_THREAD_HOLD = 64 - PT_THREAD_SIGNAL = 65 - PT_EXPLAIN = 66 - PT_EVENTS = 67 + PT_TRACE_ME = 0 // Debug this process + + PT_READ_I = 1 // Read a full word + + PT_READ_D = 2 // Read a full word + + PT_READ_U = 3 // Read control info + + PT_WRITE_I = 4 //Write a full word + + PT_WRITE_D = 5 //Write a full word + + PT_CONTINUE = 7 //Continue the process + + PT_KILL = 8 //Terminate the process + + PT_READ_GPR = 11 // Read GPR, CR, PSW + + PT_READ_FPR = 12 // Read FPR + + PT_READ_VR = 13 // Read VR + + PT_WRITE_GPR = 14 // Write GPR, CR, PSW + + PT_WRITE_FPR = 15 // Write FPR + + PT_WRITE_VR = 16 // Write VR + + PT_READ_BLOCK = 17 // Read storage + + PT_WRITE_BLOCK = 19 // Write storage + + PT_READ_GPRH = 20 // Read GPRH + + PT_WRITE_GPRH = 21 // Write GPRH + + PT_REGHSET = 22 // Read all GPRHs + + PT_ATTACH = 30 // Attach to a process + + PT_DETACH = 31 // Detach from a process + + PT_REGSET = 32 // Read all GPRs + + PT_REATTACH = 33 // Reattach to a process + + PT_LDINFO = 34 // Read loader info + + PT_MULTI = 35 // Multi process mode + + PT_LD64INFO = 36 // RMODE64 Info Area + + PT_BLOCKREQ = 40 // Block request + + PT_THREAD_INFO = 60 // Read thread info + + PT_THREAD_MODIFY = 61 + + PT_THREAD_READ_FOCUS = 62 + + PT_THREAD_WRITE_FOCUS = 63 + + PT_THREAD_HOLD = 64 + + PT_THREAD_SIGNAL = 65 + + PT_EXPLAIN = 66 + + PT_EVENTS = 67 + PT_THREAD_INFO_EXTENDED = 68 - PT_REATTACH2 = 71 - PT_CAPTURE = 72 - PT_UNCAPTURE = 73 - PT_GET_THREAD_TCB = 74 - PT_GET_ALET = 75 - PT_SWAPIN = 76 - PT_EXTENDED_EVENT = 98 - PT_RECOVER = 99 // Debug a program check - PT_GPR0 = 0 // General purpose register 0 - PT_GPR1 = 1 // General purpose register 1 - PT_GPR2 = 2 // General purpose register 2 - PT_GPR3 = 3 // General purpose register 3 - PT_GPR4 = 4 // General purpose register 4 - PT_GPR5 = 5 // General purpose register 5 - PT_GPR6 = 6 // General purpose register 6 - PT_GPR7 = 7 // General purpose register 7 - PT_GPR8 = 8 // General purpose register 8 - PT_GPR9 = 9 // General purpose register 9 - PT_GPR10 = 10 // General purpose register 10 - PT_GPR11 = 11 // General purpose register 11 - PT_GPR12 = 12 // General purpose register 12 - PT_GPR13 = 13 // General purpose register 13 - PT_GPR14 = 14 // General purpose register 14 - PT_GPR15 = 15 // General purpose register 15 - PT_FPR0 = 16 // Floating point register 0 - PT_FPR1 = 17 // Floating point register 1 - PT_FPR2 = 18 // Floating point register 2 - PT_FPR3 = 19 // Floating point register 3 - PT_FPR4 = 20 // Floating point register 4 - PT_FPR5 = 21 // Floating point register 5 - PT_FPR6 = 22 // Floating point register 6 - PT_FPR7 = 23 // Floating point register 7 - PT_FPR8 = 24 // Floating point register 8 - PT_FPR9 = 25 // Floating point register 9 - PT_FPR10 = 26 // Floating point register 10 - PT_FPR11 = 27 // Floating point register 11 - PT_FPR12 = 28 // Floating point register 12 - PT_FPR13 = 29 // Floating point register 13 - PT_FPR14 = 30 // Floating point register 14 - PT_FPR15 = 31 // Floating point register 15 - PT_FPC = 32 // Floating point control register - PT_PSW = 40 // PSW - PT_PSW0 = 40 // Left half of the PSW - PT_PSW1 = 41 // Right half of the PSW - PT_CR0 = 42 // Control register 0 - PT_CR1 = 43 // Control register 1 - PT_CR2 = 44 // Control register 2 - PT_CR3 = 45 // Control register 3 - PT_CR4 = 46 // Control register 4 - PT_CR5 = 47 // Control register 5 - PT_CR6 = 48 // Control register 6 - PT_CR7 = 49 // Control register 7 - PT_CR8 = 50 // Control register 8 - PT_CR9 = 51 // Control register 9 - PT_CR10 = 52 // Control register 10 - PT_CR11 = 53 // Control register 11 - PT_CR12 = 54 // Control register 12 - PT_CR13 = 55 // Control register 13 - PT_CR14 = 56 // Control register 14 - PT_CR15 = 57 // Control register 15 - PT_GPRH0 = 58 // GP High register 0 - PT_GPRH1 = 59 // GP High register 1 - PT_GPRH2 = 60 // GP High register 2 - PT_GPRH3 = 61 // GP High register 3 - PT_GPRH4 = 62 // GP High register 4 - PT_GPRH5 = 63 // GP High register 5 - PT_GPRH6 = 64 // GP High register 6 - PT_GPRH7 = 65 // GP High register 7 - PT_GPRH8 = 66 // GP High register 8 - PT_GPRH9 = 67 // GP High register 9 - PT_GPRH10 = 68 // GP High register 10 - PT_GPRH11 = 69 // GP High register 11 - PT_GPRH12 = 70 // GP High register 12 - PT_GPRH13 = 71 // GP High register 13 - PT_GPRH14 = 72 // GP High register 14 - PT_GPRH15 = 73 // GP High register 15 - PT_VR0 = 74 // Vector register 0 - PT_VR1 = 75 // Vector register 1 - PT_VR2 = 76 // Vector register 2 - PT_VR3 = 77 // Vector register 3 - PT_VR4 = 78 // Vector register 4 - PT_VR5 = 79 // Vector register 5 - PT_VR6 = 80 // Vector register 6 - PT_VR7 = 81 // Vector register 7 - PT_VR8 = 82 // Vector register 8 - PT_VR9 = 83 // Vector register 9 - PT_VR10 = 84 // Vector register 10 - PT_VR11 = 85 // Vector register 11 - PT_VR12 = 86 // Vector register 12 - PT_VR13 = 87 // Vector register 13 - PT_VR14 = 88 // Vector register 14 - PT_VR15 = 89 // Vector register 15 - PT_VR16 = 90 // Vector register 16 - PT_VR17 = 91 // Vector register 17 - PT_VR18 = 92 // Vector register 18 - PT_VR19 = 93 // Vector register 19 - PT_VR20 = 94 // Vector register 20 - PT_VR21 = 95 // Vector register 21 - PT_VR22 = 96 // Vector register 22 - PT_VR23 = 97 // Vector register 23 - PT_VR24 = 98 // Vector register 24 - PT_VR25 = 99 // Vector register 25 - PT_VR26 = 100 // Vector register 26 - PT_VR27 = 101 // Vector register 27 - PT_VR28 = 102 // Vector register 28 - PT_VR29 = 103 // Vector register 29 - PT_VR30 = 104 // Vector register 30 - PT_VR31 = 105 // Vector register 31 - PT_PSWG = 106 // PSWG - PT_PSWG0 = 106 // Bytes 0-3 - PT_PSWG1 = 107 // Bytes 4-7 - PT_PSWG2 = 108 // Bytes 8-11 (IA high word) - PT_PSWG3 = 109 // Bytes 12-15 (IA low word) + + PT_REATTACH2 = 71 + + PT_CAPTURE = 72 + + PT_UNCAPTURE = 73 + + PT_GET_THREAD_TCB = 74 + + PT_GET_ALET = 75 + + PT_SWAPIN = 76 + + PT_EXTENDED_EVENT = 98 + + PT_RECOVER = 99 // Debug a program check + + PT_GPR0 = 0 // General purpose register 0 + + PT_GPR1 = 1 // General purpose register 1 + + PT_GPR2 = 2 // General purpose register 2 + + PT_GPR3 = 3 // General purpose register 3 + + PT_GPR4 = 4 // General purpose register 4 + + PT_GPR5 = 5 // General purpose register 5 + + PT_GPR6 = 6 // General purpose register 6 + + PT_GPR7 = 7 // General purpose register 7 + + PT_GPR8 = 8 // General purpose register 8 + + PT_GPR9 = 9 // General purpose register 9 + + PT_GPR10 = 10 // General purpose register 10 + + PT_GPR11 = 11 // General purpose register 11 + + PT_GPR12 = 12 // General purpose register 12 + + PT_GPR13 = 13 // General purpose register 13 + + PT_GPR14 = 14 // General purpose register 14 + + PT_GPR15 = 15 // General purpose register 15 + + PT_FPR0 = 16 // Floating point register 0 + + PT_FPR1 = 17 // Floating point register 1 + + PT_FPR2 = 18 // Floating point register 2 + + PT_FPR3 = 19 // Floating point register 3 + + PT_FPR4 = 20 // Floating point register 4 + + PT_FPR5 = 21 // Floating point register 5 + + PT_FPR6 = 22 // Floating point register 6 + + PT_FPR7 = 23 // Floating point register 7 + + PT_FPR8 = 24 // Floating point register 8 + + PT_FPR9 = 25 // Floating point register 9 + + PT_FPR10 = 26 // Floating point register 10 + + PT_FPR11 = 27 // Floating point register 11 + + PT_FPR12 = 28 // Floating point register 12 + + PT_FPR13 = 29 // Floating point register 13 + + PT_FPR14 = 30 // Floating point register 14 + + PT_FPR15 = 31 // Floating point register 15 + + PT_FPC = 32 // Floating point control register + + PT_PSW = 40 // PSW + + PT_PSW0 = 40 // Left half of the PSW + + PT_PSW1 = 41 // Right half of the PSW + + PT_CR0 = 42 // Control register 0 + + PT_CR1 = 43 // Control register 1 + + PT_CR2 = 44 // Control register 2 + + PT_CR3 = 45 // Control register 3 + + PT_CR4 = 46 // Control register 4 + + PT_CR5 = 47 // Control register 5 + + PT_CR6 = 48 // Control register 6 + + PT_CR7 = 49 // Control register 7 + + PT_CR8 = 50 // Control register 8 + + PT_CR9 = 51 // Control register 9 + + PT_CR10 = 52 // Control register 10 + + PT_CR11 = 53 // Control register 11 + + PT_CR12 = 54 // Control register 12 + + PT_CR13 = 55 // Control register 13 + + PT_CR14 = 56 // Control register 14 + + PT_CR15 = 57 // Control register 15 + + PT_GPRH0 = 58 // GP High register 0 + + PT_GPRH1 = 59 // GP High register 1 + + PT_GPRH2 = 60 // GP High register 2 + + PT_GPRH3 = 61 // GP High register 3 + + PT_GPRH4 = 62 // GP High register 4 + + PT_GPRH5 = 63 // GP High register 5 + + PT_GPRH6 = 64 // GP High register 6 + + PT_GPRH7 = 65 // GP High register 7 + + PT_GPRH8 = 66 // GP High register 8 + + PT_GPRH9 = 67 // GP High register 9 + + PT_GPRH10 = 68 // GP High register 10 + + PT_GPRH11 = 69 // GP High register 11 + + PT_GPRH12 = 70 // GP High register 12 + + PT_GPRH13 = 71 // GP High register 13 + + PT_GPRH14 = 72 // GP High register 14 + + PT_GPRH15 = 73 // GP High register 15 + + PT_VR0 = 74 // Vector register 0 + + PT_VR1 = 75 // Vector register 1 + + PT_VR2 = 76 // Vector register 2 + + PT_VR3 = 77 // Vector register 3 + + PT_VR4 = 78 // Vector register 4 + + PT_VR5 = 79 // Vector register 5 + + PT_VR6 = 80 // Vector register 6 + + PT_VR7 = 81 // Vector register 7 + + PT_VR8 = 82 // Vector register 8 + + PT_VR9 = 83 // Vector register 9 + + PT_VR10 = 84 // Vector register 10 + + PT_VR11 = 85 // Vector register 11 + + PT_VR12 = 86 // Vector register 12 + + PT_VR13 = 87 // Vector register 13 + + PT_VR14 = 88 // Vector register 14 + + PT_VR15 = 89 // Vector register 15 + + PT_VR16 = 90 // Vector register 16 + + PT_VR17 = 91 // Vector register 17 + + PT_VR18 = 92 // Vector register 18 + + PT_VR19 = 93 // Vector register 19 + + PT_VR20 = 94 // Vector register 20 + + PT_VR21 = 95 // Vector register 21 + + PT_VR22 = 96 // Vector register 22 + + PT_VR23 = 97 // Vector register 23 + + PT_VR24 = 98 // Vector register 24 + + PT_VR25 = 99 // Vector register 25 + + PT_VR26 = 100 // Vector register 26 + + PT_VR27 = 101 // Vector register 27 + + PT_VR28 = 102 // Vector register 28 + + PT_VR29 = 103 // Vector register 29 + + PT_VR30 = 104 // Vector register 30 + + PT_VR31 = 105 // Vector register 31 + + PT_PSWG = 106 // PSWG + + PT_PSWG0 = 106 // Bytes 0-3 + + PT_PSWG1 = 107 // Bytes 4-7 + + PT_PSWG2 = 108 // Bytes 8-11 (IA high word) + + PT_PSWG3 = 109 // Bytes 12-15 (IA low word) + ) func Bpx4ptr(request int32, pid int32, addr unsafe.Pointer, data unsafe.Pointer, buffer unsafe.Pointer) (rv int32, rc int32, rn int32) { + var parms [8]unsafe.Pointer + parms[0] = unsafe.Pointer(&request) + parms[1] = unsafe.Pointer(&pid) + parms[2] = unsafe.Pointer(&addr) + parms[3] = unsafe.Pointer(&data) + parms[4] = unsafe.Pointer(&buffer) + parms[5] = unsafe.Pointer(&rv) + parms[6] = unsafe.Pointer(&rc) + parms[7] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4PTR) + return rv, rc, rn + } func copyU8(val uint8, dest []uint8) int { + if len(dest) < 1 { + return 0 + } + dest[0] = val + return 1 + } func copyU8Arr(src, dest []uint8) int { + if len(dest) < len(src) { + return 0 + } + for i, v := range src { + dest[i] = v + } + return len(src) + } func copyU16(val uint16, dest []uint16) int { + if len(dest) < 1 { + return 0 + } + dest[0] = val + return 1 + } func copyU32(val uint32, dest []uint32) int { + if len(dest) < 1 { + return 0 + } + dest[0] = val + return 1 + } func copyU32Arr(src, dest []uint32) int { + if len(dest) < len(src) { + return 0 + } + for i, v := range src { + dest[i] = v + } + return len(src) + } func copyU64(val uint64, dest []uint64) int { + if len(dest) < 1 { + return 0 + } + dest[0] = val + return 1 + } diff --git a/vendor/golang.org/x/sys/unix/cap_freebsd.go b/vendor/golang.org/x/sys/unix/cap_freebsd.go index a086578..3583343 100644 --- a/vendor/golang.org/x/sys/unix/cap_freebsd.go +++ b/vendor/golang.org/x/sys/unix/cap_freebsd.go @@ -1,5 +1,7 @@ // Copyright 2017 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build freebsd @@ -14,182 +16,311 @@ import ( // Go implementation of C mostly found in /usr/src/sys/kern/subr_capability.c const ( + // This is the version of CapRights this package understands. See C implementation for parallels. + capRightsGoVersion = CAP_RIGHTS_VERSION_00 - capArSizeMin = CAP_RIGHTS_VERSION_00 + 2 - capArSizeMax = capRightsGoVersion + 2 + + capArSizeMin = CAP_RIGHTS_VERSION_00 + 2 + + capArSizeMax = capRightsGoVersion + 2 ) var ( bit2idx = []int{ + -1, 0, 1, -1, 2, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1, + 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, } ) func capidxbit(right uint64) int { + return int((right >> 57) & 0x1f) + } func rightToIndex(right uint64) (int, error) { + idx := capidxbit(right) + if idx < 0 || idx >= len(bit2idx) { + return -2, fmt.Errorf("index for right 0x%x out of range", right) + } + return bit2idx[idx], nil + } func caprver(right uint64) int { + return int(right >> 62) + } func capver(rights *CapRights) int { + return caprver(rights.Rights[0]) + } func caparsize(rights *CapRights) int { + return capver(rights) + 2 + } // CapRightsSet sets the permissions in setrights in rights. + func CapRightsSet(rights *CapRights, setrights []uint64) error { + // This is essentially a copy of cap_rights_vset() + if capver(rights) != CAP_RIGHTS_VERSION_00 { + return fmt.Errorf("bad rights version %d", capver(rights)) + } n := caparsize(rights) + if n < capArSizeMin || n > capArSizeMax { + return errors.New("bad rights size") + } for _, right := range setrights { + if caprver(right) != CAP_RIGHTS_VERSION_00 { + return errors.New("bad right version") + } + i, err := rightToIndex(right) + if err != nil { + return err + } + if i >= n { + return errors.New("index overflow") + } + if capidxbit(rights.Rights[i]) != capidxbit(right) { + return errors.New("index mismatch") + } + rights.Rights[i] |= right + if capidxbit(rights.Rights[i]) != capidxbit(right) { + return errors.New("index mismatch (after assign)") + } + } return nil + } // CapRightsClear clears the permissions in clearrights from rights. + func CapRightsClear(rights *CapRights, clearrights []uint64) error { + // This is essentially a copy of cap_rights_vclear() + if capver(rights) != CAP_RIGHTS_VERSION_00 { + return fmt.Errorf("bad rights version %d", capver(rights)) + } n := caparsize(rights) + if n < capArSizeMin || n > capArSizeMax { + return errors.New("bad rights size") + } for _, right := range clearrights { + if caprver(right) != CAP_RIGHTS_VERSION_00 { + return errors.New("bad right version") + } + i, err := rightToIndex(right) + if err != nil { + return err + } + if i >= n { + return errors.New("index overflow") + } + if capidxbit(rights.Rights[i]) != capidxbit(right) { + return errors.New("index mismatch") + } + rights.Rights[i] &= ^(right & 0x01FFFFFFFFFFFFFF) + if capidxbit(rights.Rights[i]) != capidxbit(right) { + return errors.New("index mismatch (after assign)") + } + } return nil + } // CapRightsIsSet checks whether all the permissions in setrights are present in rights. + func CapRightsIsSet(rights *CapRights, setrights []uint64) (bool, error) { + // This is essentially a copy of cap_rights_is_vset() + if capver(rights) != CAP_RIGHTS_VERSION_00 { + return false, fmt.Errorf("bad rights version %d", capver(rights)) + } n := caparsize(rights) + if n < capArSizeMin || n > capArSizeMax { + return false, errors.New("bad rights size") + } for _, right := range setrights { + if caprver(right) != CAP_RIGHTS_VERSION_00 { + return false, errors.New("bad right version") + } + i, err := rightToIndex(right) + if err != nil { + return false, err + } + if i >= n { + return false, errors.New("index overflow") + } + if capidxbit(rights.Rights[i]) != capidxbit(right) { + return false, errors.New("index mismatch") + } + if (rights.Rights[i] & right) != right { + return false, nil + } + } return true, nil + } func capright(idx uint64, bit uint64) uint64 { + return ((1 << (57 + idx)) | bit) + } // CapRightsInit returns a pointer to an initialised CapRights structure filled with rights. + // See man cap_rights_init(3) and rights(4). + func CapRightsInit(rights []uint64) (*CapRights, error) { + var r CapRights + r.Rights[0] = (capRightsGoVersion << 62) | capright(0, 0) + r.Rights[1] = capright(1, 0) err := CapRightsSet(&r, rights) + if err != nil { + return nil, err + } + return &r, nil + } // CapRightsLimit reduces the operations permitted on fd to at most those contained in rights. + // The capability rights on fd can never be increased by CapRightsLimit. + // See man cap_rights_limit(2) and rights(4). + func CapRightsLimit(fd uintptr, rights *CapRights) error { + return capRightsLimit(int(fd), rights) + } // CapRightsGet returns a CapRights structure containing the operations permitted on fd. + // See man cap_rights_get(3) and rights(4). + func CapRightsGet(fd uintptr) (*CapRights, error) { + r, err := CapRightsInit(nil) + if err != nil { + return nil, err + } + err = capRightsGet(capRightsGoVersion, int(fd), r) + if err != nil { + return nil, err + } + return r, nil + } diff --git a/vendor/golang.org/x/sys/unix/ioctl_zos.go b/vendor/golang.org/x/sys/unix/ioctl_zos.go index c8b2a75..b34d488 100644 --- a/vendor/golang.org/x/sys/unix/ioctl_zos.go +++ b/vendor/golang.org/x/sys/unix/ioctl_zos.go @@ -1,5 +1,7 @@ // Copyright 2020 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build zos && s390x @@ -12,60 +14,105 @@ import ( ) // ioctl itself should not be exposed directly, but additional get/set + // functions for specific types are permissible. // IoctlSetInt performs an ioctl operation which sets an integer value + // on fd, using the specified request number. + func IoctlSetInt(fd int, req int, value int) error { + return ioctl(fd, req, uintptr(value)) + } // IoctlSetWinsize performs an ioctl on fd with a *Winsize argument. + // + // To change fd's window size, the req argument should be TIOCSWINSZ. + func IoctlSetWinsize(fd int, req int, value *Winsize) error { + // TODO: if we get the chance, remove the req parameter and + // hardcode TIOCSWINSZ. + return ioctlPtr(fd, req, unsafe.Pointer(value)) + } // IoctlSetTermios performs an ioctl on fd with a *Termios. + // + // The req value is expected to be TCSETS, TCSETSW, or TCSETSF + func IoctlSetTermios(fd int, req int, value *Termios) error { + if (req != TCSETS) && (req != TCSETSW) && (req != TCSETSF) { + return ENOSYS + } + err := Tcsetattr(fd, int(req), value) + runtime.KeepAlive(value) + return err + } // IoctlGetInt performs an ioctl operation which gets an integer value + // from fd, using the specified request number. + // + // A few ioctl requests use the return value as an output parameter; + // for those, IoctlRetInt should be used instead of this function. + func IoctlGetInt(fd int, req int) (int, error) { + var value int + err := ioctlPtr(fd, req, unsafe.Pointer(&value)) + return value, err + } func IoctlGetWinsize(fd int, req int) (*Winsize, error) { + var value Winsize + err := ioctlPtr(fd, req, unsafe.Pointer(&value)) + return &value, err + } // IoctlGetTermios performs an ioctl on fd with a *Termios. + // + // The req value is expected to be TCGETS + func IoctlGetTermios(fd int, req int) (*Termios, error) { + var value Termios + if req != TCGETS { + return &value, ENOSYS + } + err := Tcgetattr(fd, &value) + return &value, err + } diff --git a/vendor/golang.org/x/sys/unix/pledge_openbsd.go b/vendor/golang.org/x/sys/unix/pledge_openbsd.go index 6a09af5..1472ba8 100644 --- a/vendor/golang.org/x/sys/unix/pledge_openbsd.go +++ b/vendor/golang.org/x/sys/unix/pledge_openbsd.go @@ -1,5 +1,7 @@ // Copyright 2016 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package unix @@ -11,101 +13,167 @@ import ( ) // Pledge implements the pledge syscall. + // + // This changes both the promises and execpromises; use PledgePromises or + // PledgeExecpromises to only change the promises or execpromises + // respectively. + // + // For more information see pledge(2). + func Pledge(promises, execpromises string) error { + if err := pledgeAvailable(); err != nil { + return err + } pptr, err := BytePtrFromString(promises) + if err != nil { + return err + } exptr, err := BytePtrFromString(execpromises) + if err != nil { + return err + } return pledge(pptr, exptr) + } // PledgePromises implements the pledge syscall. + // + // This changes the promises and leaves the execpromises untouched. + // + // For more information see pledge(2). + func PledgePromises(promises string) error { + if err := pledgeAvailable(); err != nil { + return err + } pptr, err := BytePtrFromString(promises) + if err != nil { + return err + } return pledge(pptr, nil) + } // PledgeExecpromises implements the pledge syscall. + // + // This changes the execpromises and leaves the promises untouched. + // + // For more information see pledge(2). + func PledgeExecpromises(execpromises string) error { + if err := pledgeAvailable(); err != nil { + return err + } exptr, err := BytePtrFromString(execpromises) + if err != nil { + return err + } return pledge(nil, exptr) + } // majmin returns major and minor version number for an OpenBSD system. + func majmin() (major int, minor int, err error) { + var v Utsname + err = Uname(&v) + if err != nil { + return + } major, err = strconv.Atoi(string(v.Release[0])) + if err != nil { + err = errors.New("cannot parse major version number returned by uname") + return + } minor, err = strconv.Atoi(string(v.Release[2])) + if err != nil { + err = errors.New("cannot parse minor version number returned by uname") + return + } return + } // pledgeAvailable checks for availability of the pledge(2) syscall + // based on the running OpenBSD version. + func pledgeAvailable() error { + maj, min, err := majmin() + if err != nil { + return err + } // Require OpenBSD 6.4 as a minimum. + if maj < 6 || (maj == 6 && min <= 3) { + return fmt.Errorf("cannot call Pledge on OpenBSD %d.%d", maj, min) + } return nil + } diff --git a/vendor/golang.org/x/sys/unix/race.go b/vendor/golang.org/x/sys/unix/race.go index 714d2aa..2a44569 100644 --- a/vendor/golang.org/x/sys/unix/race.go +++ b/vendor/golang.org/x/sys/unix/race.go @@ -1,5 +1,7 @@ // Copyright 2012 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build (darwin && race) || (linux && race) || (freebsd && race) @@ -14,17 +16,25 @@ import ( const raceenabled = true func raceAcquire(addr unsafe.Pointer) { + runtime.RaceAcquire(addr) + } func raceReleaseMerge(addr unsafe.Pointer) { + runtime.RaceReleaseMerge(addr) + } func raceReadRange(addr unsafe.Pointer, len int) { + runtime.RaceReadRange(addr, len) + } func raceWriteRange(addr unsafe.Pointer, len int) { + runtime.RaceWriteRange(addr, len) + } diff --git a/vendor/golang.org/x/sys/unix/syscall.go b/vendor/golang.org/x/sys/unix/syscall.go index 5ea74da..737d809 100644 --- a/vendor/golang.org/x/sys/unix/syscall.go +++ b/vendor/golang.org/x/sys/unix/syscall.go @@ -1,27 +1,47 @@ // Copyright 2009 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos // Package unix contains an interface to the low-level operating system + // primitives. OS details vary depending on the underlying system, and + // by default, godoc will display OS-specific documentation for the current + // system. If you want godoc to display OS documentation for another + // system, set $GOOS and $GOARCH to the desired system. For example, if + // you want to view documentation for freebsd/arm on linux/amd64, set $GOOS + // to freebsd and $GOARCH to arm. + // + // The primary use of this package is inside other packages that provide a more + // portable interface to the system, such as "os", "time" and "net". Use + // those packages rather than this one if you can. + // + // For details of the functions and data types in this package consult + // the manuals for the appropriate operating system. + // + // These calls return err == nil to indicate success; otherwise + // err represents an operating system error describing the failure and + // holds a value of type syscall.Errno. + package unix // import "golang.org/x/sys/unix" import ( @@ -31,56 +51,97 @@ import ( ) // ByteSliceFromString returns a NUL-terminated slice of bytes + // containing the text of s. If s contains a NUL byte at any + // location, it returns (nil, EINVAL). + func ByteSliceFromString(s string) ([]byte, error) { + if strings.IndexByte(s, 0) != -1 { + return nil, EINVAL + } + a := make([]byte, len(s)+1) + copy(a, s) + return a, nil + } // BytePtrFromString returns a pointer to a NUL-terminated array of + // bytes containing the text of s. If s contains a NUL byte at any + // location, it returns (nil, EINVAL). + func BytePtrFromString(s string) (*byte, error) { + a, err := ByteSliceFromString(s) + if err != nil { + return nil, err + } + return &a[0], nil + } // ByteSliceToString returns a string form of the text represented by the slice s, with a terminating NUL and any + // bytes after the NUL removed. + func ByteSliceToString(s []byte) string { + if i := bytes.IndexByte(s, 0); i != -1 { + s = s[:i] + } + return string(s) + } // BytePtrToString takes a pointer to a sequence of text and returns the corresponding string. + // If the pointer is nil, it returns the empty string. It assumes that the text sequence is terminated + // at a zero byte; if the zero byte is not present, the program may crash. + func BytePtrToString(p *byte) string { + if p == nil { + return "" + } + if *p == 0 { + return "" + } // Find NUL terminator. + n := 0 + for ptr := unsafe.Pointer(p); *(*byte)(ptr) != 0; n++ { + ptr = unsafe.Pointer(uintptr(ptr) + 1) + } return string(unsafe.Slice(p, n)) + } // Single-word zero for use when we need a valid pointer to 0 bytes. + var _zero uintptr diff --git a/vendor/golang.org/x/sys/unix/syscall_bsd.go b/vendor/golang.org/x/sys/unix/syscall_bsd.go index a00c3e5..00452c7 100644 --- a/vendor/golang.org/x/sys/unix/syscall_bsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_bsd.go @@ -1,13 +1,19 @@ // Copyright 2009 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build darwin || dragonfly || freebsd || netbsd || openbsd // BSD system call wrappers shared by *BSD based systems + // including OS X (Darwin) and FreeBSD. Like the other + // syscall_*.go files it is compiled as Go code but also + // used as input to mksyscall which parses the //sys + // lines and generates system call stubs. package unix @@ -21,98 +27,159 @@ import ( const ImplementsGetwd = true func Getwd() (string, error) { + var buf [PathMax]byte + _, err := Getcwd(buf[0:]) + if err != nil { + return "", err + } + n := clen(buf[:]) + if n < 1 { + return "", EINVAL + } + return string(buf[:n]), nil + } /* + * Wrapped + */ //sysnb getgroups(ngid int, gid *_Gid_t) (n int, err error) + //sysnb setgroups(ngid int, gid *_Gid_t) (err error) func Getgroups() (gids []int, err error) { + n, err := getgroups(0, nil) + if err != nil { + return nil, err + } + if n == 0 { + return nil, nil + } // Sanity check group count. Max is 16 on BSD. + if n < 0 || n > 1000 { + return nil, EINVAL + } a := make([]_Gid_t, n) + n, err = getgroups(n, &a[0]) + if err != nil { + return nil, err + } + gids = make([]int, n) + for i, v := range a[0:n] { + gids[i] = int(v) + } + return + } func Setgroups(gids []int) (err error) { + if len(gids) == 0 { + return setgroups(0, nil) + } a := make([]_Gid_t, len(gids)) + for i, v := range gids { + a[i] = _Gid_t(v) + } + return setgroups(len(a), &a[0]) + } // Wait status is 7 bits at bottom, either 0 (exited), + // 0x7F (stopped), or a signal number that caused an exit. + // The 0x80 bit is whether there was a core dump. + // An extra number (exit code, signal causing a stop) + // is in the high bits. type WaitStatus uint32 const ( - mask = 0x7F - core = 0x80 + mask = 0x7F + + core = 0x80 + shift = 8 - exited = 0 - killed = 9 + exited = 0 + + killed = 9 + stopped = 0x7F ) func (w WaitStatus) Exited() bool { return w&mask == exited } func (w WaitStatus) ExitStatus() int { + if w&mask != exited { + return -1 + } + return int(w >> shift) + } func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != 0 } func (w WaitStatus) Signal() syscall.Signal { + sig := syscall.Signal(w & mask) + if sig == stopped || sig == 0 { + return -1 + } + return sig + } func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 } @@ -124,10 +191,15 @@ func (w WaitStatus) Killed() bool { return w&mask == killed && syscall.Signal(w> func (w WaitStatus) Continued() bool { return w&mask == stopped && syscall.Signal(w>>shift) == SIGSTOP } func (w WaitStatus) StopSignal() syscall.Signal { + if !w.Stopped() { + return -1 + } + return syscall.Signal(w>>shift) & 0xFF + } func (w WaitStatus) TrapCause() int { return -1 } @@ -135,475 +207,848 @@ func (w WaitStatus) TrapCause() int { return -1 } //sys wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) { + var status _C_int + wpid, err = wait4(pid, &status, options, rusage) + if wstatus != nil { + *wstatus = WaitStatus(status) + } + return + } //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) + //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) + //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) + //sysnb socket(domain int, typ int, proto int) (fd int, err error) + //sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) + //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) + //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) + //sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) + //sys Shutdown(s int, how int) (err error) func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) { + if sa.Port < 0 || sa.Port > 0xFFFF { + return nil, 0, EINVAL + } + sa.raw.Len = SizeofSockaddrInet4 + sa.raw.Family = AF_INET + p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) + p[0] = byte(sa.Port >> 8) + p[1] = byte(sa.Port) + sa.raw.Addr = sa.Addr + return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil + } func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) { + if sa.Port < 0 || sa.Port > 0xFFFF { + return nil, 0, EINVAL + } + sa.raw.Len = SizeofSockaddrInet6 + sa.raw.Family = AF_INET6 + p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) + p[0] = byte(sa.Port >> 8) + p[1] = byte(sa.Port) + sa.raw.Scope_id = sa.ZoneId + sa.raw.Addr = sa.Addr + return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil + } func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) { + name := sa.Name + n := len(name) + if n >= len(sa.raw.Path) || n == 0 { + return nil, 0, EINVAL + } + sa.raw.Len = byte(3 + n) // 2 for Family, Len; 1 for NUL + sa.raw.Family = AF_UNIX + for i := 0; i < n; i++ { + sa.raw.Path[i] = int8(name[i]) + } + return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil + } func (sa *SockaddrDatalink) sockaddr() (unsafe.Pointer, _Socklen, error) { + if sa.Index == 0 { + return nil, 0, EINVAL + } + sa.raw.Len = sa.Len + sa.raw.Family = AF_LINK + sa.raw.Index = sa.Index + sa.raw.Type = sa.Type + sa.raw.Nlen = sa.Nlen + sa.raw.Alen = sa.Alen + sa.raw.Slen = sa.Slen + sa.raw.Data = sa.Data + return unsafe.Pointer(&sa.raw), SizeofSockaddrDatalink, nil + } func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) { + switch rsa.Addr.Family { + case AF_LINK: + pp := (*RawSockaddrDatalink)(unsafe.Pointer(rsa)) + sa := new(SockaddrDatalink) + sa.Len = pp.Len + sa.Family = pp.Family + sa.Index = pp.Index + sa.Type = pp.Type + sa.Nlen = pp.Nlen + sa.Alen = pp.Alen + sa.Slen = pp.Slen + sa.Data = pp.Data + return sa, nil case AF_UNIX: + pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa)) + if pp.Len < 2 || pp.Len > SizeofSockaddrUnix { + return nil, EINVAL + } + sa := new(SockaddrUnix) // Some BSDs include the trailing NUL in the length, whereas + // others do not. Work around this by subtracting the leading + // family and len. The path is then scanned to see if a NUL + // terminator still exists within the length. + n := int(pp.Len) - 2 // subtract leading Family, Len + for i := 0; i < n; i++ { + if pp.Path[i] == 0 { + // found early NUL; assume Len included the NUL + // or was overestimating. + n = i + break + } + } + sa.Name = string(unsafe.Slice((*byte)(unsafe.Pointer(&pp.Path[0])), n)) + return sa, nil case AF_INET: + pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa)) + sa := new(SockaddrInet4) + p := (*[2]byte)(unsafe.Pointer(&pp.Port)) + sa.Port = int(p[0])<<8 + int(p[1]) + sa.Addr = pp.Addr + return sa, nil case AF_INET6: + pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa)) + sa := new(SockaddrInet6) + p := (*[2]byte)(unsafe.Pointer(&pp.Port)) + sa.Port = int(p[0])<<8 + int(p[1]) + sa.ZoneId = pp.Scope_id + sa.Addr = pp.Addr + return sa, nil + } + return anyToSockaddrGOOS(fd, rsa) + } func Accept(fd int) (nfd int, sa Sockaddr, err error) { + var rsa RawSockaddrAny + var len _Socklen = SizeofSockaddrAny + nfd, err = accept(fd, &rsa, &len) + if err != nil { + return + } + if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && len == 0 { + // Accepted socket has no address. + // This is likely due to a bug in xnu kernels, + // where instead of ECONNABORTED error socket + // is accepted, but has no address. + Close(nfd) + return 0, nil, ECONNABORTED + } + sa, err = anyToSockaddr(fd, &rsa) + if err != nil { + Close(nfd) + nfd = 0 + } + return + } func Getsockname(fd int) (sa Sockaddr, err error) { + var rsa RawSockaddrAny + var len _Socklen = SizeofSockaddrAny + if err = getsockname(fd, &rsa, &len); err != nil { + return + } + // TODO(jsing): DragonFly has a "bug" (see issue 3349), which should be + // reported upstream. + if runtime.GOOS == "dragonfly" && rsa.Addr.Family == AF_UNSPEC && rsa.Addr.Len == 0 { + rsa.Addr.Family = AF_UNIX + rsa.Addr.Len = SizeofSockaddrUnix + } + return anyToSockaddr(fd, &rsa) + } //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) // GetsockoptString returns the string value of the socket option opt for the + // socket associated with fd at the given socket level. + func GetsockoptString(fd, level, opt int) (string, error) { + buf := make([]byte, 256) + vallen := _Socklen(len(buf)) + err := getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen) + if err != nil { + return "", err + } + return ByteSliceToString(buf[:vallen]), nil + } //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) + //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) + //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) func recvmsgRaw(fd int, iov []Iovec, oob []byte, flags int, rsa *RawSockaddrAny) (n, oobn int, recvflags int, err error) { + var msg Msghdr + msg.Name = (*byte)(unsafe.Pointer(rsa)) + msg.Namelen = uint32(SizeofSockaddrAny) + var dummy byte + if len(oob) > 0 { + // receive at least one normal byte + if emptyIovecs(iov) { + var iova [1]Iovec + iova[0].Base = &dummy + iova[0].SetLen(1) + iov = iova[:] + } + msg.Control = (*byte)(unsafe.Pointer(&oob[0])) + msg.SetControllen(len(oob)) + } + if len(iov) > 0 { + msg.Iov = &iov[0] + msg.SetIovlen(len(iov)) + } + if n, err = recvmsg(fd, &msg, flags); err != nil { + return + } + oobn = int(msg.Controllen) + recvflags = int(msg.Flags) + return + } //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) func sendmsgN(fd int, iov []Iovec, oob []byte, ptr unsafe.Pointer, salen _Socklen, flags int) (n int, err error) { + var msg Msghdr + msg.Name = (*byte)(unsafe.Pointer(ptr)) + msg.Namelen = uint32(salen) + var dummy byte + var empty bool + if len(oob) > 0 { + // send at least one normal byte + empty = emptyIovecs(iov) + if empty { + var iova [1]Iovec + iova[0].Base = &dummy + iova[0].SetLen(1) + iov = iova[:] + } + msg.Control = (*byte)(unsafe.Pointer(&oob[0])) + msg.SetControllen(len(oob)) + } + if len(iov) > 0 { + msg.Iov = &iov[0] + msg.SetIovlen(len(iov)) + } + if n, err = sendmsg(fd, &msg, flags); err != nil { + return 0, err + } + if len(oob) > 0 && empty { + n = 0 + } + return n, nil + } //sys kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) func Kevent(kq int, changes, events []Kevent_t, timeout *Timespec) (n int, err error) { + var change, event unsafe.Pointer + if len(changes) > 0 { + change = unsafe.Pointer(&changes[0]) + } + if len(events) > 0 { + event = unsafe.Pointer(&events[0]) + } + return kevent(kq, change, len(changes), event, len(events), timeout) + } // sysctlmib translates name to mib number and appends any additional args. + func sysctlmib(name string, args ...int) ([]_C_int, error) { + // Translate name to mib number. + mib, err := nametomib(name) + if err != nil { + return nil, err + } for _, a := range args { + mib = append(mib, _C_int(a)) + } return mib, nil + } func Sysctl(name string) (string, error) { + return SysctlArgs(name) + } func SysctlArgs(name string, args ...int) (string, error) { + buf, err := SysctlRaw(name, args...) + if err != nil { + return "", err + } + n := len(buf) // Throw away terminating NUL. + if n > 0 && buf[n-1] == '\x00' { + n-- + } + return string(buf[0:n]), nil + } func SysctlUint32(name string) (uint32, error) { + return SysctlUint32Args(name) + } func SysctlUint32Args(name string, args ...int) (uint32, error) { + mib, err := sysctlmib(name, args...) + if err != nil { + return 0, err + } n := uintptr(4) + buf := make([]byte, 4) + if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil { + return 0, err + } + if n != 4 { + return 0, EIO + } + return *(*uint32)(unsafe.Pointer(&buf[0])), nil + } func SysctlUint64(name string, args ...int) (uint64, error) { + mib, err := sysctlmib(name, args...) + if err != nil { + return 0, err + } n := uintptr(8) + buf := make([]byte, 8) + if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil { + return 0, err + } + if n != 8 { + return 0, EIO + } + return *(*uint64)(unsafe.Pointer(&buf[0])), nil + } func SysctlRaw(name string, args ...int) ([]byte, error) { + mib, err := sysctlmib(name, args...) + if err != nil { + return nil, err + } // Find size. + n := uintptr(0) + if err := sysctl(mib, nil, &n, nil, 0); err != nil { + return nil, err + } + if n == 0 { + return nil, nil + } // Read into buffer of that size. + buf := make([]byte, n) + if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil { + return nil, err + } // The actual call may return less than the original reported required + // size so ensure we deal with that. + return buf[:n], nil + } func SysctlClockinfo(name string) (*Clockinfo, error) { + mib, err := sysctlmib(name) + if err != nil { + return nil, err + } n := uintptr(SizeofClockinfo) + var ci Clockinfo + if err := sysctl(mib, (*byte)(unsafe.Pointer(&ci)), &n, nil, 0); err != nil { + return nil, err + } + if n != SizeofClockinfo { + return nil, EIO + } + return &ci, nil + } func SysctlTimeval(name string) (*Timeval, error) { + mib, err := sysctlmib(name) + if err != nil { + return nil, err + } var tv Timeval + n := uintptr(unsafe.Sizeof(tv)) + if err := sysctl(mib, (*byte)(unsafe.Pointer(&tv)), &n, nil, 0); err != nil { + return nil, err + } + if n != unsafe.Sizeof(tv) { + return nil, EIO + } + return &tv, nil + } //sys utimes(path string, timeval *[2]Timeval) (err error) func Utimes(path string, tv []Timeval) error { + if tv == nil { + return utimes(path, nil) + } + if len(tv) != 2 { + return EINVAL + } + return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) + } func UtimesNano(path string, ts []Timespec) error { + if ts == nil { + err := utimensat(AT_FDCWD, path, nil, 0) + if err != ENOSYS { + return err + } + return utimes(path, nil) + } + if len(ts) != 2 { + return EINVAL + } + err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0) + if err != ENOSYS { + return err + } + // Not as efficient as it could be because Timespec and + // Timeval have different types in the different OSes + tv := [2]Timeval{ + NsecToTimeval(TimespecToNsec(ts[0])), + NsecToTimeval(TimespecToNsec(ts[1])), } + return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) + } func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error { + if ts == nil { + return utimensat(dirfd, path, nil, flags) + } + if len(ts) != 2 { + return EINVAL + } + return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags) + } //sys futimes(fd int, timeval *[2]Timeval) (err error) func Futimes(fd int, tv []Timeval) error { + if tv == nil { + return futimes(fd, nil) + } + if len(tv) != 2 { + return EINVAL + } + return futimes(fd, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) + } //sys poll(fds *PollFd, nfds int, timeout int) (n int, err error) func Poll(fds []PollFd, timeout int) (n int, err error) { + if len(fds) == 0 { + return poll(nil, 0, timeout) + } + return poll(&fds[0], len(fds), timeout) + } // TODO: wrap + // Acct(name nil-string) (err error) + // Gethostuuid(uuid *byte, timeout *Timespec) (err error) + // Ptrace(req int, pid int, addr uintptr, data int) (ret uintptr, err error) //sys Madvise(b []byte, behav int) (err error) + //sys Mlock(b []byte) (err error) + //sys Mlockall(flags int) (err error) + //sys Mprotect(b []byte, prot int) (err error) + //sys Msync(b []byte, flags int) (err error) + //sys Munlock(b []byte) (err error) + //sys Munlockall() (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin.go b/vendor/golang.org/x/sys/unix/syscall_darwin.go index 59542a8..7c549a5 100644 --- a/vendor/golang.org/x/sys/unix/syscall_darwin.go +++ b/vendor/golang.org/x/sys/unix/syscall_darwin.go @@ -1,13 +1,21 @@ // Copyright 2009,2010 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Darwin system calls. + // This file is compiled as ordinary Go code, + // but it is also input to mksyscall, + // which parses the //sys lines and generates system call stubs. + // Note that sometimes we use a lowercase //sys name and wrap + // it in our own nicer implementation, either here or in + // syscall_bsd.go or syscall_unix.go. package unix @@ -19,15 +27,23 @@ import ( ) //sys closedir(dir uintptr) (err error) + //sys readdir_r(dir uintptr, entry *Dirent, result **Dirent) (res Errno) func fdopendir(fd int) (dir uintptr, err error) { + r0, _, e1 := syscall_syscallPtr(libc_fdopendir_trampoline_addr, uintptr(fd), 0, 0) + dir = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fdopendir_trampoline_addr uintptr @@ -35,337 +51,567 @@ var libc_fdopendir_trampoline_addr uintptr //go:cgo_import_dynamic libc_fdopendir fdopendir "/usr/lib/libSystem.B.dylib" func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { + // Simulate Getdirentries using fdopendir/readdir_r/closedir. + // We store the number of entries to skip in the seek + // offset of fd. See issue #31368. + // It's not the full required semantics, but should handle the case + // of calling Getdirentries or ReadDirent repeatedly. + // It won't handle assigning the results of lseek to *basep, or handle + // the directory being edited underfoot. + skip, err := Seek(fd, 0, 1 /* SEEK_CUR */) + if err != nil { + return 0, err + } // We need to duplicate the incoming file descriptor + // because the caller expects to retain control of it, but + // fdopendir expects to take control of its argument. + // Just Dup'ing the file descriptor is not enough, as the + // result shares underlying state. Use Openat to make a really + // new file descriptor referring to the same directory. + fd2, err := Openat(fd, ".", O_RDONLY, 0) + if err != nil { + return 0, err + } + d, err := fdopendir(fd2) + if err != nil { + Close(fd2) + return 0, err + } + defer closedir(d) var cnt int64 + for { + var entry Dirent + var entryp *Dirent + e := readdir_r(d, &entry, &entryp) + if e != 0 { + return n, errnoErr(e) + } + if entryp == nil { + break + } + if skip > 0 { + skip-- + cnt++ + continue + } reclen := int(entry.Reclen) + if reclen > len(buf) { + // Not enough room. Return for now. + // The counter will let us know where we should start up again. + // Note: this strategy for suspending in the middle and + // restarting is O(n^2) in the length of the directory. Oh well. + break + } // Copy entry into return buffer. + s := unsafe.Slice((*byte)(unsafe.Pointer(&entry)), reclen) + copy(buf, s) buf = buf[reclen:] + n += reclen + cnt++ + } + // Set the seek offset of the input fd to record + // how many files we've already returned. + _, err = Seek(fd, cnt, 0 /* SEEK_SET */) + if err != nil { + return n, err + } return n, nil + } // SockaddrDatalink implements the Sockaddr interface for AF_LINK type sockets. + type SockaddrDatalink struct { - Len uint8 + Len uint8 + Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [12]int8 - raw RawSockaddrDatalink + + Index uint16 + + Type uint8 + + Nlen uint8 + + Alen uint8 + + Slen uint8 + + Data [12]int8 + + raw RawSockaddrDatalink } // SockaddrCtl implements the Sockaddr interface for AF_SYSTEM type sockets. + type SockaddrCtl struct { - ID uint32 + ID uint32 + Unit uint32 - raw RawSockaddrCtl + + raw RawSockaddrCtl } func (sa *SockaddrCtl) sockaddr() (unsafe.Pointer, _Socklen, error) { + sa.raw.Sc_len = SizeofSockaddrCtl + sa.raw.Sc_family = AF_SYSTEM + sa.raw.Ss_sysaddr = AF_SYS_CONTROL + sa.raw.Sc_id = sa.ID + sa.raw.Sc_unit = sa.Unit + return unsafe.Pointer(&sa.raw), SizeofSockaddrCtl, nil + } // SockaddrVM implements the Sockaddr interface for AF_VSOCK type sockets. + // SockaddrVM provides access to Darwin VM sockets: a mechanism that enables + // bidirectional communication between a hypervisor and its guest virtual + // machines. + type SockaddrVM struct { + // CID and Port specify a context ID and port address for a VM socket. + // Guests have a unique CID, and hosts may have a well-known CID of: + // - VMADDR_CID_HYPERVISOR: refers to the hypervisor process. + // - VMADDR_CID_LOCAL: refers to local communication (loopback). + // - VMADDR_CID_HOST: refers to other processes on the host. - CID uint32 + + CID uint32 + Port uint32 - raw RawSockaddrVM + + raw RawSockaddrVM } func (sa *SockaddrVM) sockaddr() (unsafe.Pointer, _Socklen, error) { + sa.raw.Len = SizeofSockaddrVM + sa.raw.Family = AF_VSOCK + sa.raw.Port = sa.Port + sa.raw.Cid = sa.CID return unsafe.Pointer(&sa.raw), SizeofSockaddrVM, nil + } func anyToSockaddrGOOS(fd int, rsa *RawSockaddrAny) (Sockaddr, error) { + switch rsa.Addr.Family { + case AF_SYSTEM: + pp := (*RawSockaddrCtl)(unsafe.Pointer(rsa)) + if pp.Ss_sysaddr == AF_SYS_CONTROL { + sa := new(SockaddrCtl) + sa.ID = pp.Sc_id + sa.Unit = pp.Sc_unit + return sa, nil + } + case AF_VSOCK: + pp := (*RawSockaddrVM)(unsafe.Pointer(rsa)) + sa := &SockaddrVM{ - CID: pp.Cid, + + CID: pp.Cid, + Port: pp.Port, } + return sa, nil + } + return nil, EAFNOSUPPORT + } // Some external packages rely on SYS___SYSCTL being defined to implement their + // own sysctl wrappers. Provide it here, even though direct syscalls are no + // longer supported on darwin. + const SYS___SYSCTL = SYS_SYSCTL // Translate "kern.hostname" to []_C_int{0,1,2,3}. + func nametomib(name string) (mib []_C_int, err error) { + const siz = unsafe.Sizeof(mib[0]) // NOTE(rsc): It seems strange to set the buffer to have + // size CTL_MAXNAME+2 but use only CTL_MAXNAME + // as the size. I don't know why the +2 is here, but the + // kernel uses +2 for its own implementation of this function. + // I am scared that if we don't include the +2 here, the kernel + // will silently write 2 words farther than we specify + // and we'll get memory corruption. + var buf [CTL_MAXNAME + 2]_C_int + n := uintptr(CTL_MAXNAME) * siz p := (*byte)(unsafe.Pointer(&buf[0])) + bytes, err := ByteSliceFromString(name) + if err != nil { + return nil, err + } // Magic sysctl: "setting" 0.3 to a string name + // lets you read back the array of integers form. + if err = sysctl([]_C_int{0, 3}, p, &n, &bytes[0], uintptr(len(name))); err != nil { + return nil, err + } + return buf[0 : n/siz], nil + } func direntIno(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino)) + } func direntReclen(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) + } func direntNamlen(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen)) + } func PtraceAttach(pid int) (err error) { return ptrace(PT_ATTACH, pid, 0, 0) } + func PtraceDetach(pid int) (err error) { return ptrace(PT_DETACH, pid, 0, 0) } -func PtraceDenyAttach() (err error) { return ptrace(PT_DENY_ATTACH, 0, 0, 0) } + +func PtraceDenyAttach() (err error) { return ptrace(PT_DENY_ATTACH, 0, 0, 0) } //sysnb pipe(p *[2]int32) (err error) func Pipe(p []int) (err error) { + if len(p) != 2 { + return EINVAL + } + var x [2]int32 + err = pipe(&x) + if err == nil { + p[0] = int(x[0]) + p[1] = int(x[1]) + } + return + } func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { + var _p0 unsafe.Pointer + var bufsize uintptr + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + bufsize = unsafe.Sizeof(Statfs_t{}) * uintptr(len(buf)) + } + return getfsstat(_p0, bufsize, flags) + } func xattrPointer(dest []byte) *byte { + // It's only when dest is set to NULL that the OS X implementations of + // getxattr() and listxattr() return the current sizes of the named attributes. + // An empty byte array is not sufficient. To maintain the same behaviour as the + // linux implementation, we wrap around the system calls and pass in NULL when + // dest is empty. + var destp *byte + if len(dest) > 0 { + destp = &dest[0] + } + return destp + } //sys getxattr(path string, attr string, dest *byte, size int, position uint32, options int) (sz int, err error) func Getxattr(path string, attr string, dest []byte) (sz int, err error) { + return getxattr(path, attr, xattrPointer(dest), len(dest), 0, 0) + } func Lgetxattr(link string, attr string, dest []byte) (sz int, err error) { + return getxattr(link, attr, xattrPointer(dest), len(dest), 0, XATTR_NOFOLLOW) + } //sys fgetxattr(fd int, attr string, dest *byte, size int, position uint32, options int) (sz int, err error) func Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) { + return fgetxattr(fd, attr, xattrPointer(dest), len(dest), 0, 0) + } //sys setxattr(path string, attr string, data *byte, size int, position uint32, options int) (err error) func Setxattr(path string, attr string, data []byte, flags int) (err error) { + // The parameters for the OS X implementation vary slightly compared to the + // linux system call, specifically the position parameter: + // + // linux: + // int setxattr( + // const char *path, + // const char *name, + // const void *value, + // size_t size, + // int flags + // ); + // + // darwin: + // int setxattr( + // const char *path, + // const char *name, + // void *value, + // size_t size, + // u_int32_t position, + // int options + // ); + // + // position specifies the offset within the extended attribute. In the + // current implementation, only the resource fork extended attribute makes + // use of this argument. For all others, position is reserved. We simply + // default to setting it to zero. + return setxattr(path, attr, xattrPointer(data), len(data), 0, flags) + } func Lsetxattr(link string, attr string, data []byte, flags int) (err error) { + return setxattr(link, attr, xattrPointer(data), len(data), 0, flags|XATTR_NOFOLLOW) + } //sys fsetxattr(fd int, attr string, data *byte, size int, position uint32, options int) (err error) func Fsetxattr(fd int, attr string, data []byte, flags int) (err error) { + return fsetxattr(fd, attr, xattrPointer(data), len(data), 0, 0) + } //sys removexattr(path string, attr string, options int) (err error) func Removexattr(path string, attr string) (err error) { + // We wrap around and explicitly zero out the options provided to the OS X + // implementation of removexattr, we do so for interoperability with the + // linux variant. + return removexattr(path, attr, 0) + } func Lremovexattr(link string, attr string) (err error) { + return removexattr(link, attr, XATTR_NOFOLLOW) + } //sys fremovexattr(fd int, attr string, options int) (err error) func Fremovexattr(fd int, attr string) (err error) { + return fremovexattr(fd, attr, 0) + } //sys listxattr(path string, dest *byte, size int, options int) (sz int, err error) func Listxattr(path string, dest []byte) (sz int, err error) { + return listxattr(path, xattrPointer(dest), len(dest), 0) + } func Llistxattr(link string, dest []byte) (sz int, err error) { + return listxattr(link, xattrPointer(dest), len(dest), XATTR_NOFOLLOW) + } //sys flistxattr(fd int, dest *byte, size int, options int) (sz int, err error) func Flistxattr(fd int, dest []byte) (sz int, err error) { + return flistxattr(fd, xattrPointer(dest), len(dest), 0) + } //sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) /* + * Wrapped + */ //sys fcntl(fd int, cmd int, arg int) (val int, err error) @@ -375,272 +621,487 @@ func Flistxattr(fd int, dest []byte) (sz int, err error) { func Kill(pid int, signum syscall.Signal) (err error) { return kill(pid, int(signum), 1) } //sys ioctl(fd int, req uint, arg uintptr) (err error) + //sys ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) = SYS_IOCTL func IoctlCtlInfo(fd int, ctlInfo *CtlInfo) error { + return ioctlPtr(fd, CTLIOCGINFO, unsafe.Pointer(ctlInfo)) + } // IfreqMTU is struct ifreq used to get or set a network device's MTU. + type IfreqMTU struct { Name [IFNAMSIZ]byte - MTU int32 + + MTU int32 } // IoctlGetIfreqMTU performs the SIOCGIFMTU ioctl operation on fd to get the MTU + // of the network device specified by ifname. + func IoctlGetIfreqMTU(fd int, ifname string) (*IfreqMTU, error) { + var ifreq IfreqMTU + copy(ifreq.Name[:], ifname) + err := ioctlPtr(fd, SIOCGIFMTU, unsafe.Pointer(&ifreq)) + return &ifreq, err + } // IoctlSetIfreqMTU performs the SIOCSIFMTU ioctl operation on fd to set the MTU + // of the network device specified by ifreq.Name. + func IoctlSetIfreqMTU(fd int, ifreq *IfreqMTU) error { + return ioctlPtr(fd, SIOCSIFMTU, unsafe.Pointer(ifreq)) + } //sys sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) = SYS_SYSCTL func Uname(uname *Utsname) error { + mib := []_C_int{CTL_KERN, KERN_OSTYPE} + n := unsafe.Sizeof(uname.Sysname) + if err := sysctl(mib, &uname.Sysname[0], &n, nil, 0); err != nil { + return err + } mib = []_C_int{CTL_KERN, KERN_HOSTNAME} + n = unsafe.Sizeof(uname.Nodename) + if err := sysctl(mib, &uname.Nodename[0], &n, nil, 0); err != nil { + return err + } mib = []_C_int{CTL_KERN, KERN_OSRELEASE} + n = unsafe.Sizeof(uname.Release) + if err := sysctl(mib, &uname.Release[0], &n, nil, 0); err != nil { + return err + } mib = []_C_int{CTL_KERN, KERN_VERSION} + n = unsafe.Sizeof(uname.Version) + if err := sysctl(mib, &uname.Version[0], &n, nil, 0); err != nil { + return err + } // The version might have newlines or tabs in it, convert them to + // spaces. + for i, b := range uname.Version { + if b == '\n' || b == '\t' { + if i == len(uname.Version)-1 { + uname.Version[i] = 0 + } else { + uname.Version[i] = ' ' + } + } + } mib = []_C_int{CTL_HW, HW_MACHINE} + n = unsafe.Sizeof(uname.Machine) + if err := sysctl(mib, &uname.Machine[0], &n, nil, 0); err != nil { + return err + } return nil + } func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + if raceenabled { + raceReleaseMerge(unsafe.Pointer(&ioSync)) + } + var length = int64(count) + err = sendfile(infd, outfd, *offset, &length, nil, 0) + written = int(length) + return + } func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) { + var value IPMreqn + vallen := _Socklen(SizeofIPMreqn) + errno := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) + return &value, errno + } func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) { + return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq)) + } // GetsockoptXucred is a getsockopt wrapper that returns an Xucred struct. + // The usual level and opt are SOL_LOCAL and LOCAL_PEERCRED, respectively. + func GetsockoptXucred(fd, level, opt int) (*Xucred, error) { + x := new(Xucred) + vallen := _Socklen(SizeofXucred) + err := getsockopt(fd, level, opt, unsafe.Pointer(x), &vallen) + return x, err + } func GetsockoptTCPConnectionInfo(fd, level, opt int) (*TCPConnectionInfo, error) { + var value TCPConnectionInfo + vallen := _Socklen(SizeofTCPConnectionInfo) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) + return &value, err + } func SysctlKinfoProc(name string, args ...int) (*KinfoProc, error) { + mib, err := sysctlmib(name, args...) + if err != nil { + return nil, err + } var kinfo KinfoProc + n := uintptr(SizeofKinfoProc) + if err := sysctl(mib, (*byte)(unsafe.Pointer(&kinfo)), &n, nil, 0); err != nil { + return nil, err + } + if n != SizeofKinfoProc { + return nil, EIO + } + return &kinfo, nil + } func SysctlKinfoProcSlice(name string, args ...int) ([]KinfoProc, error) { + mib, err := sysctlmib(name, args...) + if err != nil { + return nil, err + } for { + // Find size. + n := uintptr(0) + if err := sysctl(mib, nil, &n, nil, 0); err != nil { + return nil, err + } + if n == 0 { + return nil, nil + } + if n%SizeofKinfoProc != 0 { + return nil, fmt.Errorf("sysctl() returned a size of %d, which is not a multiple of %d", n, SizeofKinfoProc) + } // Read into buffer of that size. + buf := make([]KinfoProc, n/SizeofKinfoProc) + if err := sysctl(mib, (*byte)(unsafe.Pointer(&buf[0])), &n, nil, 0); err != nil { + if err == ENOMEM { + // Process table grew. Try again. + continue + } + return nil, err + } + if n%SizeofKinfoProc != 0 { + return nil, fmt.Errorf("sysctl() returned a size of %d, which is not a multiple of %d", n, SizeofKinfoProc) + } // The actual call may return less than the original reported required + // size so ensure we deal with that. + return buf[:n/SizeofKinfoProc], nil + } + } //sys sendfile(infd int, outfd int, offset int64, len *int64, hdtr unsafe.Pointer, flags int) (err error) //sys shmat(id int, addr uintptr, flag int) (ret uintptr, err error) + //sys shmctl(id int, cmd int, buf *SysvShmDesc) (result int, err error) + //sys shmdt(addr uintptr) (err error) + //sys shmget(key int, size int, flag int) (id int, err error) /* + * Exposed directly + */ + //sys Access(path string, mode uint32) (err error) + //sys Adjtime(delta *Timeval, olddelta *Timeval) (err error) + //sys Chdir(path string) (err error) + //sys Chflags(path string, flags int) (err error) + //sys Chmod(path string, mode uint32) (err error) + //sys Chown(path string, uid int, gid int) (err error) + //sys Chroot(path string) (err error) + //sys ClockGettime(clockid int32, time *Timespec) (err error) + //sys Close(fd int) (err error) + //sys Clonefile(src string, dst string, flags int) (err error) + //sys Clonefileat(srcDirfd int, src string, dstDirfd int, dst string, flags int) (err error) + //sys Dup(fd int) (nfd int, err error) + //sys Dup2(from int, to int) (err error) + //sys Exchangedata(path1 string, path2 string, options int) (err error) + //sys Exit(code int) + //sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error) + //sys Fchdir(fd int) (err error) + //sys Fchflags(fd int, flags int) (err error) + //sys Fchmod(fd int, mode uint32) (err error) + //sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) + //sys Fchown(fd int, uid int, gid int) (err error) + //sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) + //sys Fclonefileat(srcDirfd int, dstDirfd int, dst string, flags int) (err error) + //sys Flock(fd int, how int) (err error) + //sys Fpathconf(fd int, name int) (val int, err error) + //sys Fsync(fd int) (err error) + //sys Ftruncate(fd int, length int64) (err error) + //sys Getcwd(buf []byte) (n int, err error) + //sys Getdtablesize() (size int) + //sysnb Getegid() (egid int) + //sysnb Geteuid() (uid int) + //sysnb Getgid() (gid int) + //sysnb Getpgid(pid int) (pgid int, err error) + //sysnb Getpgrp() (pgrp int) + //sysnb Getpid() (pid int) + //sysnb Getppid() (ppid int) + //sys Getpriority(which int, who int) (prio int, err error) + //sysnb Getrlimit(which int, lim *Rlimit) (err error) + //sysnb Getrusage(who int, rusage *Rusage) (err error) + //sysnb Getsid(pid int) (sid int, err error) + //sysnb Gettimeofday(tp *Timeval) (err error) + //sysnb Getuid() (uid int) + //sysnb Issetugid() (tainted bool) + //sys Kqueue() (fd int, err error) + //sys Lchown(path string, uid int, gid int) (err error) + //sys Link(path string, link string) (err error) + //sys Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) + //sys Listen(s int, backlog int) (err error) + //sys Mkdir(path string, mode uint32) (err error) + //sys Mkdirat(dirfd int, path string, mode uint32) (err error) + //sys Mkfifo(path string, mode uint32) (err error) + //sys Mknod(path string, mode uint32, dev int) (err error) + //sys Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) + //sys Open(path string, mode int, perm uint32) (fd int, err error) + //sys Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) + //sys Pathconf(path string, name int) (val int, err error) + //sys pread(fd int, p []byte, offset int64) (n int, err error) + //sys pwrite(fd int, p []byte, offset int64) (n int, err error) + //sys read(fd int, p []byte) (n int, err error) + //sys Readlink(path string, buf []byte) (n int, err error) + //sys Readlinkat(dirfd int, path string, buf []byte) (n int, err error) + //sys Rename(from string, to string) (err error) + //sys Renameat(fromfd int, from string, tofd int, to string) (err error) + //sys Revoke(path string) (err error) + //sys Rmdir(path string) (err error) + //sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK + //sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) + //sys Setattrlist(path string, attrlist *Attrlist, attrBuf []byte, options int) (err error) + //sys Setegid(egid int) (err error) + //sysnb Seteuid(euid int) (err error) + //sysnb Setgid(gid int) (err error) + //sys Setlogin(name string) (err error) + //sysnb Setpgid(pid int, pgid int) (err error) + //sys Setpriority(which int, who int, prio int) (err error) + //sys Setprivexec(flag int) (err error) + //sysnb Setregid(rgid int, egid int) (err error) + //sysnb Setreuid(ruid int, euid int) (err error) + //sysnb Setsid() (pid int, err error) + //sysnb Settimeofday(tp *Timeval) (err error) + //sysnb Setuid(uid int) (err error) + //sys Symlink(path string, link string) (err error) + //sys Symlinkat(oldpath string, newdirfd int, newpath string) (err error) + //sys Sync() (err error) + //sys Truncate(path string, length int64) (err error) + //sys Umask(newmask int) (oldmask int) + //sys Undelete(path string) (err error) + //sys Unlink(path string) (err error) + //sys Unlinkat(dirfd int, path string, flags int) (err error) + //sys Unmount(path string, flags int) (err error) + //sys write(fd int, p []byte) (n int, err error) + //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) + //sys munmap(addr uintptr, length uintptr) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_dragonfly.go b/vendor/golang.org/x/sys/unix/syscall_dragonfly.go index 97cb916..3613f43 100644 --- a/vendor/golang.org/x/sys/unix/syscall_dragonfly.go +++ b/vendor/golang.org/x/sys/unix/syscall_dragonfly.go @@ -1,13 +1,21 @@ // Copyright 2009 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // DragonFly BSD system calls. + // This file is compiled as ordinary Go code, + // but it is also input to mksyscall, + // which parses the //sys lines and generates system call stubs. + // Note that sometimes we use a lowercase //sys name and wrap + // it in our own nicer implementation, either here or in + // syscall_bsd.go or syscall_unix.go. package unix @@ -18,330 +26,585 @@ import ( ) // See version list in https://github.com/DragonFlyBSD/DragonFlyBSD/blob/master/sys/sys/param.h + var ( osreldateOnce sync.Once - osreldate uint32 + + osreldate uint32 ) // First __DragonFly_version after September 2019 ABI changes + // http://lists.dragonflybsd.org/pipermail/users/2019-September/358280.html + const _dragonflyABIChangeVersion = 500705 func supportsABI(ver uint32) bool { + osreldateOnce.Do(func() { osreldate, _ = SysctlUint32("kern.osreldate") }) + return osreldate >= ver + } // SockaddrDatalink implements the Sockaddr interface for AF_LINK type sockets. + type SockaddrDatalink struct { - Len uint8 + Len uint8 + Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [12]int8 - Rcf uint16 - Route [16]uint16 - raw RawSockaddrDatalink + + Index uint16 + + Type uint8 + + Nlen uint8 + + Alen uint8 + + Slen uint8 + + Data [12]int8 + + Rcf uint16 + + Route [16]uint16 + + raw RawSockaddrDatalink } func anyToSockaddrGOOS(fd int, rsa *RawSockaddrAny) (Sockaddr, error) { + return nil, EAFNOSUPPORT + } // Translate "kern.hostname" to []_C_int{0,1,2,3}. + func nametomib(name string) (mib []_C_int, err error) { + const siz = unsafe.Sizeof(mib[0]) // NOTE(rsc): It seems strange to set the buffer to have + // size CTL_MAXNAME+2 but use only CTL_MAXNAME + // as the size. I don't know why the +2 is here, but the + // kernel uses +2 for its own implementation of this function. + // I am scared that if we don't include the +2 here, the kernel + // will silently write 2 words farther than we specify + // and we'll get memory corruption. + var buf [CTL_MAXNAME + 2]_C_int + n := uintptr(CTL_MAXNAME) * siz p := (*byte)(unsafe.Pointer(&buf[0])) + bytes, err := ByteSliceFromString(name) + if err != nil { + return nil, err + } // Magic sysctl: "setting" 0.3 to a string name + // lets you read back the array of integers form. + if err = sysctl([]_C_int{0, 3}, p, &n, &bytes[0], uintptr(len(name))); err != nil { + return nil, err + } + return buf[0 : n/siz], nil + } func direntIno(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Fileno), unsafe.Sizeof(Dirent{}.Fileno)) + } func direntReclen(buf []byte) (uint64, bool) { + namlen, ok := direntNamlen(buf) + if !ok { + return 0, false + } + return (16 + namlen + 1 + 7) &^ 7, true + } func direntNamlen(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen)) + } //sysnb pipe() (r int, w int, err error) func Pipe(p []int) (err error) { + if len(p) != 2 { + return EINVAL + } + r, w, err := pipe() + if err == nil { + p[0], p[1] = r, w + } + return + } //sysnb pipe2(p *[2]_C_int, flags int) (r int, w int, err error) func Pipe2(p []int, flags int) (err error) { + if len(p) != 2 { + return EINVAL + } + var pp [2]_C_int + // pipe2 on dragonfly takes an fds array as an argument, but still + // returns the file descriptors. + r, w, err := pipe2(&pp, flags) + if err == nil { + p[0], p[1] = r, w + } + return err + } //sys extpread(fd int, p []byte, flags int, offset int64) (n int, err error) func pread(fd int, p []byte, offset int64) (n int, err error) { + return extpread(fd, p, 0, offset) + } //sys extpwrite(fd int, p []byte, flags int, offset int64) (n int, err error) func pwrite(fd int, p []byte, offset int64) (n int, err error) { + return extpwrite(fd, p, 0, offset) + } func Accept4(fd, flags int) (nfd int, sa Sockaddr, err error) { + var rsa RawSockaddrAny + var len _Socklen = SizeofSockaddrAny + nfd, err = accept4(fd, &rsa, &len, flags) + if err != nil { + return + } + if len > SizeofSockaddrAny { + panic("RawSockaddrAny too small") + } + sa, err = anyToSockaddr(fd, &rsa) + if err != nil { + Close(nfd) + nfd = 0 + } + return + } //sys Getcwd(buf []byte) (n int, err error) = SYS___GETCWD func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { + var _p0 unsafe.Pointer + var bufsize uintptr + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + bufsize = unsafe.Sizeof(Statfs_t{}) * uintptr(len(buf)) + } + r0, _, e1 := Syscall(SYS_GETFSSTAT, uintptr(_p0), bufsize, uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = e1 + } + return + } //sys ioctl(fd int, req uint, arg uintptr) (err error) + //sys ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) = SYS_IOCTL //sys sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) = SYS___SYSCTL func sysctlUname(mib []_C_int, old *byte, oldlen *uintptr) error { + err := sysctl(mib, old, oldlen, nil, 0) + if err != nil { + // Utsname members on Dragonfly are only 32 bytes and + // the syscall returns ENOMEM in case the actual value + // is longer. + if err == ENOMEM { + err = nil + } + } + return err + } func Uname(uname *Utsname) error { + mib := []_C_int{CTL_KERN, KERN_OSTYPE} + n := unsafe.Sizeof(uname.Sysname) + if err := sysctlUname(mib, &uname.Sysname[0], &n); err != nil { + return err + } + uname.Sysname[unsafe.Sizeof(uname.Sysname)-1] = 0 mib = []_C_int{CTL_KERN, KERN_HOSTNAME} + n = unsafe.Sizeof(uname.Nodename) + if err := sysctlUname(mib, &uname.Nodename[0], &n); err != nil { + return err + } + uname.Nodename[unsafe.Sizeof(uname.Nodename)-1] = 0 mib = []_C_int{CTL_KERN, KERN_OSRELEASE} + n = unsafe.Sizeof(uname.Release) + if err := sysctlUname(mib, &uname.Release[0], &n); err != nil { + return err + } + uname.Release[unsafe.Sizeof(uname.Release)-1] = 0 mib = []_C_int{CTL_KERN, KERN_VERSION} + n = unsafe.Sizeof(uname.Version) + if err := sysctlUname(mib, &uname.Version[0], &n); err != nil { + return err + } // The version might have newlines or tabs in it, convert them to + // spaces. + for i, b := range uname.Version { + if b == '\n' || b == '\t' { + if i == len(uname.Version)-1 { + uname.Version[i] = 0 + } else { + uname.Version[i] = ' ' + } + } + } mib = []_C_int{CTL_HW, HW_MACHINE} + n = unsafe.Sizeof(uname.Machine) + if err := sysctlUname(mib, &uname.Machine[0], &n); err != nil { + return err + } + uname.Machine[unsafe.Sizeof(uname.Machine)-1] = 0 return nil + } func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + if raceenabled { + raceReleaseMerge(unsafe.Pointer(&ioSync)) + } + return sendfile(outfd, infd, offset, count) + } /* + * Exposed directly + */ + //sys Access(path string, mode uint32) (err error) + //sys Adjtime(delta *Timeval, olddelta *Timeval) (err error) + //sys Chdir(path string) (err error) + //sys Chflags(path string, flags int) (err error) + //sys Chmod(path string, mode uint32) (err error) + //sys Chown(path string, uid int, gid int) (err error) + //sys Chroot(path string) (err error) + //sys ClockGettime(clockid int32, time *Timespec) (err error) + //sys Close(fd int) (err error) + //sys Dup(fd int) (nfd int, err error) + //sys Dup2(from int, to int) (err error) + //sys Exit(code int) + //sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error) + //sys Fchdir(fd int) (err error) + //sys Fchflags(fd int, flags int) (err error) + //sys Fchmod(fd int, mode uint32) (err error) + //sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) + //sys Fchown(fd int, uid int, gid int) (err error) + //sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) + //sys Flock(fd int, how int) (err error) + //sys Fpathconf(fd int, name int) (val int, err error) + //sys Fstat(fd int, stat *Stat_t) (err error) + //sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) + //sys Fstatfs(fd int, stat *Statfs_t) (err error) + //sys Fsync(fd int) (err error) + //sys Ftruncate(fd int, length int64) (err error) + //sys Getdents(fd int, buf []byte) (n int, err error) + //sys Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) + //sys Getdtablesize() (size int) + //sysnb Getegid() (egid int) + //sysnb Geteuid() (uid int) + //sysnb Getgid() (gid int) + //sysnb Getpgid(pid int) (pgid int, err error) + //sysnb Getpgrp() (pgrp int) + //sysnb Getpid() (pid int) + //sysnb Getppid() (ppid int) + //sys Getpriority(which int, who int) (prio int, err error) + //sysnb Getrlimit(which int, lim *Rlimit) (err error) + //sysnb Getrusage(who int, rusage *Rusage) (err error) + //sysnb Getsid(pid int) (sid int, err error) + //sysnb Gettimeofday(tv *Timeval) (err error) + //sysnb Getuid() (uid int) + //sys Issetugid() (tainted bool) + //sys Kill(pid int, signum syscall.Signal) (err error) + //sys Kqueue() (fd int, err error) + //sys Lchown(path string, uid int, gid int) (err error) + //sys Link(path string, link string) (err error) + //sys Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) + //sys Listen(s int, backlog int) (err error) + //sys Lstat(path string, stat *Stat_t) (err error) + //sys Mkdir(path string, mode uint32) (err error) + //sys Mkdirat(dirfd int, path string, mode uint32) (err error) + //sys Mkfifo(path string, mode uint32) (err error) + //sys Mknod(path string, mode uint32, dev int) (err error) + //sys Mknodat(fd int, path string, mode uint32, dev int) (err error) + //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) + //sys Open(path string, mode int, perm uint32) (fd int, err error) + //sys Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) + //sys Pathconf(path string, name int) (val int, err error) + //sys read(fd int, p []byte) (n int, err error) + //sys Readlink(path string, buf []byte) (n int, err error) + //sys Rename(from string, to string) (err error) + //sys Renameat(fromfd int, from string, tofd int, to string) (err error) + //sys Revoke(path string) (err error) + //sys Rmdir(path string) (err error) + //sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK + //sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) + //sysnb Setegid(egid int) (err error) + //sysnb Seteuid(euid int) (err error) + //sysnb Setgid(gid int) (err error) + //sys Setlogin(name string) (err error) + //sysnb Setpgid(pid int, pgid int) (err error) + //sys Setpriority(which int, who int, prio int) (err error) + //sysnb Setregid(rgid int, egid int) (err error) + //sysnb Setreuid(ruid int, euid int) (err error) + //sysnb Setresgid(rgid int, egid int, sgid int) (err error) + //sysnb Setresuid(ruid int, euid int, suid int) (err error) + //sysnb Setsid() (pid int, err error) + //sysnb Settimeofday(tp *Timeval) (err error) + //sysnb Setuid(uid int) (err error) + //sys Stat(path string, stat *Stat_t) (err error) + //sys Statfs(path string, stat *Statfs_t) (err error) + //sys Symlink(path string, link string) (err error) + //sys Symlinkat(oldpath string, newdirfd int, newpath string) (err error) + //sys Sync() (err error) + //sys Truncate(path string, length int64) (err error) + //sys Umask(newmask int) (oldmask int) + //sys Undelete(path string) (err error) + //sys Unlink(path string) (err error) + //sys Unlinkat(dirfd int, path string, flags int) (err error) + //sys Unmount(path string, flags int) (err error) + //sys write(fd int, p []byte) (n int, err error) + //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) + //sys munmap(addr uintptr, length uintptr) (err error) + //sys accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) + //sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go b/vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go index 14bab6b..d5a7eb4 100644 --- a/vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go +++ b/vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go @@ -1,5 +1,7 @@ // Copyright 2009 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build amd64 && dragonfly @@ -12,45 +14,67 @@ import ( ) func setTimespec(sec, nsec int64) Timespec { + return Timespec{Sec: sec, Nsec: nsec} + } func setTimeval(sec, usec int64) Timeval { + return Timeval{Sec: sec, Usec: usec} + } func SetKevent(k *Kevent_t, fd, mode, flags int) { + k.Ident = uint64(fd) + k.Filter = int16(mode) + k.Flags = uint16(flags) + } func (iov *Iovec) SetLen(length int) { + iov.Len = uint64(length) + } func (msghdr *Msghdr) SetControllen(length int) { + msghdr.Controllen = uint32(length) + } func (msghdr *Msghdr) SetIovlen(length int) { + msghdr.Iovlen = int32(length) + } func (cmsg *Cmsghdr) SetLen(length int) { + cmsg.Len = uint32(length) + } func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + var writtenOut uint64 = 0 + _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0, 0) written = int(writtenOut) if e1 != 0 { + err = e1 + } + return + } func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd.go b/vendor/golang.org/x/sys/unix/syscall_freebsd.go index 2b57e0f..02f75d5 100644 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_freebsd.go @@ -1,13 +1,21 @@ // Copyright 2009,2010 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // FreeBSD system calls. + // This file is compiled as ordinary Go code, + // but it is also input to mksyscall, + // which parses the //sys lines and generates system call stubs. + // Note that sometimes we use a lowercase //sys name and wrap + // it in our own nicer implementation, either here or in + // syscall_bsd.go or syscall_unix.go. package unix @@ -19,437 +27,760 @@ import ( ) // See https://www.freebsd.org/doc/en_US.ISO8859-1/books/porters-handbook/versions.html. + var ( osreldateOnce sync.Once - osreldate uint32 + + osreldate uint32 ) func supportsABI(ver uint32) bool { + osreldateOnce.Do(func() { osreldate, _ = SysctlUint32("kern.osreldate") }) + return osreldate >= ver + } // SockaddrDatalink implements the Sockaddr interface for AF_LINK type sockets. + type SockaddrDatalink struct { - Len uint8 + Len uint8 + Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [46]int8 - raw RawSockaddrDatalink + + Index uint16 + + Type uint8 + + Nlen uint8 + + Alen uint8 + + Slen uint8 + + Data [46]int8 + + raw RawSockaddrDatalink } func anyToSockaddrGOOS(fd int, rsa *RawSockaddrAny) (Sockaddr, error) { + return nil, EAFNOSUPPORT + } // Translate "kern.hostname" to []_C_int{0,1,2,3}. + func nametomib(name string) (mib []_C_int, err error) { + const siz = unsafe.Sizeof(mib[0]) // NOTE(rsc): It seems strange to set the buffer to have + // size CTL_MAXNAME+2 but use only CTL_MAXNAME + // as the size. I don't know why the +2 is here, but the + // kernel uses +2 for its own implementation of this function. + // I am scared that if we don't include the +2 here, the kernel + // will silently write 2 words farther than we specify + // and we'll get memory corruption. + var buf [CTL_MAXNAME + 2]_C_int + n := uintptr(CTL_MAXNAME) * siz p := (*byte)(unsafe.Pointer(&buf[0])) + bytes, err := ByteSliceFromString(name) + if err != nil { + return nil, err + } // Magic sysctl: "setting" 0.3 to a string name + // lets you read back the array of integers form. + if err = sysctl([]_C_int{0, 3}, p, &n, &bytes[0], uintptr(len(name))); err != nil { + return nil, err + } + return buf[0 : n/siz], nil + } func direntIno(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Fileno), unsafe.Sizeof(Dirent{}.Fileno)) + } func direntReclen(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) + } func direntNamlen(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen)) + } func Pipe(p []int) (err error) { + return Pipe2(p, 0) + } //sysnb pipe2(p *[2]_C_int, flags int) (err error) func Pipe2(p []int, flags int) error { + if len(p) != 2 { + return EINVAL + } + var pp [2]_C_int + err := pipe2(&pp, flags) + if err == nil { + p[0] = int(pp[0]) + p[1] = int(pp[1]) + } + return err + } func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) { + var value IPMreqn + vallen := _Socklen(SizeofIPMreqn) + errno := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) + return &value, errno + } func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) { + return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq)) + } // GetsockoptXucred is a getsockopt wrapper that returns an Xucred struct. + // The usual level and opt are SOL_LOCAL and LOCAL_PEERCRED, respectively. + func GetsockoptXucred(fd, level, opt int) (*Xucred, error) { + x := new(Xucred) + vallen := _Socklen(SizeofXucred) + err := getsockopt(fd, level, opt, unsafe.Pointer(x), &vallen) + return x, err + } func Accept4(fd, flags int) (nfd int, sa Sockaddr, err error) { + var rsa RawSockaddrAny + var len _Socklen = SizeofSockaddrAny + nfd, err = accept4(fd, &rsa, &len, flags) + if err != nil { + return + } + if len > SizeofSockaddrAny { + panic("RawSockaddrAny too small") + } + sa, err = anyToSockaddr(fd, &rsa) + if err != nil { + Close(nfd) + nfd = 0 + } + return + } //sys Getcwd(buf []byte) (n int, err error) = SYS___GETCWD func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { + var ( - _p0 unsafe.Pointer + _p0 unsafe.Pointer + bufsize uintptr ) + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + bufsize = unsafe.Sizeof(Statfs_t{}) * uintptr(len(buf)) + } + r0, _, e1 := Syscall(SYS_GETFSSTAT, uintptr(_p0), bufsize, uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = e1 + } + return + } //sys ioctl(fd int, req uint, arg uintptr) (err error) = SYS_IOCTL + //sys ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) = SYS_IOCTL //sys sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) = SYS___SYSCTL func Uname(uname *Utsname) error { + mib := []_C_int{CTL_KERN, KERN_OSTYPE} + n := unsafe.Sizeof(uname.Sysname) + // Suppress ENOMEM errors to be compatible with the C library __xuname() implementation. + if err := sysctl(mib, &uname.Sysname[0], &n, nil, 0); err != nil && !errors.Is(err, ENOMEM) { + return err + } mib = []_C_int{CTL_KERN, KERN_HOSTNAME} + n = unsafe.Sizeof(uname.Nodename) + if err := sysctl(mib, &uname.Nodename[0], &n, nil, 0); err != nil && !errors.Is(err, ENOMEM) { + return err + } mib = []_C_int{CTL_KERN, KERN_OSRELEASE} + n = unsafe.Sizeof(uname.Release) + if err := sysctl(mib, &uname.Release[0], &n, nil, 0); err != nil && !errors.Is(err, ENOMEM) { + return err + } mib = []_C_int{CTL_KERN, KERN_VERSION} + n = unsafe.Sizeof(uname.Version) + if err := sysctl(mib, &uname.Version[0], &n, nil, 0); err != nil && !errors.Is(err, ENOMEM) { + return err + } // The version might have newlines or tabs in it, convert them to + // spaces. + for i, b := range uname.Version { + if b == '\n' || b == '\t' { + if i == len(uname.Version)-1 { + uname.Version[i] = 0 + } else { + uname.Version[i] = ' ' + } + } + } mib = []_C_int{CTL_HW, HW_MACHINE} + n = unsafe.Sizeof(uname.Machine) + if err := sysctl(mib, &uname.Machine[0], &n, nil, 0); err != nil && !errors.Is(err, ENOMEM) { + return err + } return nil + } func Stat(path string, st *Stat_t) (err error) { + return Fstatat(AT_FDCWD, path, st, 0) + } func Lstat(path string, st *Stat_t) (err error) { + return Fstatat(AT_FDCWD, path, st, AT_SYMLINK_NOFOLLOW) + } func Getdents(fd int, buf []byte) (n int, err error) { + return Getdirentries(fd, buf, nil) + } func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { + if basep == nil || unsafe.Sizeof(*basep) == 8 { + return getdirentries(fd, buf, (*uint64)(unsafe.Pointer(basep))) + } + // The syscall needs a 64-bit base. On 32-bit machines + // we can't just use the basep passed in. See #32498. + var base uint64 = uint64(*basep) + n, err = getdirentries(fd, buf, &base) + *basep = uintptr(base) + if base>>32 != 0 { + // We can't stuff the base back into a uintptr, so any + // future calls would be suspect. Generate an error. + // EIO is allowed by getdirentries. + err = EIO + } + return + } func Mknod(path string, mode uint32, dev uint64) (err error) { + return Mknodat(AT_FDCWD, path, mode, dev) + } func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + if raceenabled { + raceReleaseMerge(unsafe.Pointer(&ioSync)) + } + return sendfile(outfd, infd, offset, count) + } //sys ptrace(request int, pid int, addr uintptr, data int) (err error) + //sys ptracePtr(request int, pid int, addr unsafe.Pointer, data int) (err error) = SYS_PTRACE func PtraceAttach(pid int) (err error) { + return ptrace(PT_ATTACH, pid, 0, 0) + } func PtraceCont(pid int, signal int) (err error) { + return ptrace(PT_CONTINUE, pid, 1, signal) + } func PtraceDetach(pid int) (err error) { + return ptrace(PT_DETACH, pid, 1, 0) + } func PtraceGetFpRegs(pid int, fpregsout *FpReg) (err error) { + return ptracePtr(PT_GETFPREGS, pid, unsafe.Pointer(fpregsout), 0) + } func PtraceGetRegs(pid int, regsout *Reg) (err error) { + return ptracePtr(PT_GETREGS, pid, unsafe.Pointer(regsout), 0) + } func PtraceIO(req int, pid int, offs uintptr, out []byte, countin int) (count int, err error) { + ioDesc := PtraceIoDesc{ - Op: int32(req), + + Op: int32(req), + Offs: offs, } + if countin > 0 { + _ = out[:countin] // check bounds + ioDesc.Addr = &out[0] + } else if out != nil { + ioDesc.Addr = (*byte)(unsafe.Pointer(&_zero)) + } + ioDesc.SetLen(countin) err = ptracePtr(PT_IO, pid, unsafe.Pointer(&ioDesc), 0) + return int(ioDesc.Len), err + } func PtraceLwpEvents(pid int, enable int) (err error) { + return ptrace(PT_LWP_EVENTS, pid, 0, enable) + } func PtraceLwpInfo(pid int, info *PtraceLwpInfoStruct) (err error) { + return ptracePtr(PT_LWPINFO, pid, unsafe.Pointer(info), int(unsafe.Sizeof(*info))) + } func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error) { + return PtraceIO(PIOD_READ_D, pid, addr, out, SizeofLong) + } func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error) { + return PtraceIO(PIOD_READ_I, pid, addr, out, SizeofLong) + } func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error) { + return PtraceIO(PIOD_WRITE_D, pid, addr, data, SizeofLong) + } func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error) { + return PtraceIO(PIOD_WRITE_I, pid, addr, data, SizeofLong) + } func PtraceSetRegs(pid int, regs *Reg) (err error) { + return ptracePtr(PT_SETREGS, pid, unsafe.Pointer(regs), 0) + } func PtraceSingleStep(pid int) (err error) { + return ptrace(PT_STEP, pid, 1, 0) + } func Dup3(oldfd, newfd, flags int) error { + if oldfd == newfd || flags&^O_CLOEXEC != 0 { + return EINVAL + } + how := F_DUP2FD + if flags&O_CLOEXEC != 0 { + how = F_DUP2FD_CLOEXEC + } + _, err := fcntl(oldfd, how, newfd) + return err + } /* + * Exposed directly + */ + //sys Access(path string, mode uint32) (err error) + //sys Adjtime(delta *Timeval, olddelta *Timeval) (err error) + //sys CapEnter() (err error) + //sys capRightsGet(version int, fd int, rightsp *CapRights) (err error) = SYS___CAP_RIGHTS_GET + //sys capRightsLimit(fd int, rightsp *CapRights) (err error) + //sys Chdir(path string) (err error) + //sys Chflags(path string, flags int) (err error) + //sys Chmod(path string, mode uint32) (err error) + //sys Chown(path string, uid int, gid int) (err error) + //sys Chroot(path string) (err error) + //sys ClockGettime(clockid int32, time *Timespec) (err error) + //sys Close(fd int) (err error) + //sys Dup(fd int) (nfd int, err error) + //sys Dup2(from int, to int) (err error) + //sys Exit(code int) + //sys ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) + //sys ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) + //sys ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error) + //sys ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) + //sys ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) + //sys ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) + //sys ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error) + //sys ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) + //sys ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) + //sys ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) + //sys ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) + //sys ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) + //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_POSIX_FADVISE + //sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error) + //sys Fchdir(fd int) (err error) + //sys Fchflags(fd int, flags int) (err error) + //sys Fchmod(fd int, mode uint32) (err error) + //sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) + //sys Fchown(fd int, uid int, gid int) (err error) + //sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) + //sys Flock(fd int, how int) (err error) + //sys Fpathconf(fd int, name int) (val int, err error) + //sys Fstat(fd int, stat *Stat_t) (err error) + //sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) + //sys Fstatfs(fd int, stat *Statfs_t) (err error) + //sys Fsync(fd int) (err error) + //sys Ftruncate(fd int, length int64) (err error) + //sys getdirentries(fd int, buf []byte, basep *uint64) (n int, err error) + //sys Getdtablesize() (size int) + //sysnb Getegid() (egid int) + //sysnb Geteuid() (uid int) + //sysnb Getgid() (gid int) + //sysnb Getpgid(pid int) (pgid int, err error) + //sysnb Getpgrp() (pgrp int) + //sysnb Getpid() (pid int) + //sysnb Getppid() (ppid int) + //sys Getpriority(which int, who int) (prio int, err error) + //sysnb Getrlimit(which int, lim *Rlimit) (err error) + //sysnb Getrusage(who int, rusage *Rusage) (err error) + //sysnb Getsid(pid int) (sid int, err error) + //sysnb Gettimeofday(tv *Timeval) (err error) + //sysnb Getuid() (uid int) + //sys Issetugid() (tainted bool) + //sys Kill(pid int, signum syscall.Signal) (err error) + //sys Kqueue() (fd int, err error) + //sys Lchown(path string, uid int, gid int) (err error) + //sys Link(path string, link string) (err error) + //sys Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) + //sys Listen(s int, backlog int) (err error) + //sys Mkdir(path string, mode uint32) (err error) + //sys Mkdirat(dirfd int, path string, mode uint32) (err error) + //sys Mkfifo(path string, mode uint32) (err error) + //sys Mknodat(fd int, path string, mode uint32, dev uint64) (err error) + //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) + //sys Open(path string, mode int, perm uint32) (fd int, err error) + //sys Openat(fdat int, path string, mode int, perm uint32) (fd int, err error) + //sys Pathconf(path string, name int) (val int, err error) + //sys pread(fd int, p []byte, offset int64) (n int, err error) + //sys pwrite(fd int, p []byte, offset int64) (n int, err error) + //sys read(fd int, p []byte) (n int, err error) + //sys Readlink(path string, buf []byte) (n int, err error) + //sys Readlinkat(dirfd int, path string, buf []byte) (n int, err error) + //sys Rename(from string, to string) (err error) + //sys Renameat(fromfd int, from string, tofd int, to string) (err error) + //sys Revoke(path string) (err error) + //sys Rmdir(path string) (err error) + //sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK + //sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) + //sysnb Setegid(egid int) (err error) + //sysnb Seteuid(euid int) (err error) + //sysnb Setgid(gid int) (err error) + //sys Setlogin(name string) (err error) + //sysnb Setpgid(pid int, pgid int) (err error) + //sys Setpriority(which int, who int, prio int) (err error) + //sysnb Setregid(rgid int, egid int) (err error) + //sysnb Setreuid(ruid int, euid int) (err error) + //sysnb Setresgid(rgid int, egid int, sgid int) (err error) + //sysnb Setresuid(ruid int, euid int, suid int) (err error) + //sysnb Setsid() (pid int, err error) + //sysnb Settimeofday(tp *Timeval) (err error) + //sysnb Setuid(uid int) (err error) + //sys Statfs(path string, stat *Statfs_t) (err error) + //sys Symlink(path string, link string) (err error) + //sys Symlinkat(oldpath string, newdirfd int, newpath string) (err error) + //sys Sync() (err error) + //sys Truncate(path string, length int64) (err error) + //sys Umask(newmask int) (oldmask int) + //sys Undelete(path string) (err error) + //sys Unlink(path string) (err error) + //sys Unlinkat(dirfd int, path string, flags int) (err error) + //sys Unmount(path string, flags int) (err error) + //sys write(fd int, p []byte) (n int, err error) + //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) + //sys munmap(addr uintptr, length uintptr) (err error) + //sys accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) + //sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go b/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go index 3967bca..2b64a2b 100644 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go @@ -1,5 +1,7 @@ // Copyright 2009 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build 386 && freebsd @@ -12,53 +14,79 @@ import ( ) func setTimespec(sec, nsec int64) Timespec { + return Timespec{Sec: int32(sec), Nsec: int32(nsec)} + } func setTimeval(sec, usec int64) Timeval { + return Timeval{Sec: int32(sec), Usec: int32(usec)} + } func SetKevent(k *Kevent_t, fd, mode, flags int) { + k.Ident = uint32(fd) + k.Filter = int16(mode) + k.Flags = uint16(flags) + } func (iov *Iovec) SetLen(length int) { + iov.Len = uint32(length) + } func (msghdr *Msghdr) SetControllen(length int) { + msghdr.Controllen = uint32(length) + } func (msghdr *Msghdr) SetIovlen(length int) { + msghdr.Iovlen = int32(length) + } func (cmsg *Cmsghdr) SetLen(length int) { + cmsg.Len = uint32(length) + } func (d *PtraceIoDesc) SetLen(length int) { + d.Len = uint32(length) + } func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + var writtenOut uint64 = 0 + _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr((*offset)>>32), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0) written = int(writtenOut) if e1 != 0 { + err = e1 + } + return + } func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) func PtraceGetFsBase(pid int, fsbase *int64) (err error) { + return ptracePtr(PT_GETFSBASE, pid, unsafe.Pointer(fsbase), 0) + } diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go index eff19ad..15cde84 100644 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go @@ -1,5 +1,7 @@ // Copyright 2009 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build amd64 && freebsd @@ -12,53 +14,79 @@ import ( ) func setTimespec(sec, nsec int64) Timespec { + return Timespec{Sec: sec, Nsec: nsec} + } func setTimeval(sec, usec int64) Timeval { + return Timeval{Sec: sec, Usec: usec} + } func SetKevent(k *Kevent_t, fd, mode, flags int) { + k.Ident = uint64(fd) + k.Filter = int16(mode) + k.Flags = uint16(flags) + } func (iov *Iovec) SetLen(length int) { + iov.Len = uint64(length) + } func (msghdr *Msghdr) SetControllen(length int) { + msghdr.Controllen = uint32(length) + } func (msghdr *Msghdr) SetIovlen(length int) { + msghdr.Iovlen = int32(length) + } func (cmsg *Cmsghdr) SetLen(length int) { + cmsg.Len = uint32(length) + } func (d *PtraceIoDesc) SetLen(length int) { + d.Len = uint64(length) + } func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + var writtenOut uint64 = 0 + _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0, 0) written = int(writtenOut) if e1 != 0 { + err = e1 + } + return + } func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) func PtraceGetFsBase(pid int, fsbase *int64) (err error) { + return ptracePtr(PT_GETFSBASE, pid, unsafe.Pointer(fsbase), 0) + } diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go b/vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go index 4f24b51..6251a61 100644 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go +++ b/vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go @@ -1,5 +1,7 @@ // Copyright 2012 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build arm && freebsd @@ -12,49 +14,73 @@ import ( ) func setTimespec(sec, nsec int64) Timespec { + return Timespec{Sec: sec, Nsec: int32(nsec)} + } func setTimeval(sec, usec int64) Timeval { + return Timeval{Sec: sec, Usec: int32(usec)} + } func SetKevent(k *Kevent_t, fd, mode, flags int) { + k.Ident = uint32(fd) + k.Filter = int16(mode) + k.Flags = uint16(flags) + } func (iov *Iovec) SetLen(length int) { + iov.Len = uint32(length) + } func (msghdr *Msghdr) SetControllen(length int) { + msghdr.Controllen = uint32(length) + } func (msghdr *Msghdr) SetIovlen(length int) { + msghdr.Iovlen = int32(length) + } func (cmsg *Cmsghdr) SetLen(length int) { + cmsg.Len = uint32(length) + } func (d *PtraceIoDesc) SetLen(length int) { + d.Len = uint32(length) + } func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + var writtenOut uint64 = 0 + _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr((*offset)>>32), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0) written = int(writtenOut) if e1 != 0 { + err = e1 + } + return + } func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd_arm64.go b/vendor/golang.org/x/sys/unix/syscall_freebsd_arm64.go index ac30759..f1bcabc 100644 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd_arm64.go +++ b/vendor/golang.org/x/sys/unix/syscall_freebsd_arm64.go @@ -1,5 +1,7 @@ // Copyright 2018 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build arm64 && freebsd @@ -12,49 +14,73 @@ import ( ) func setTimespec(sec, nsec int64) Timespec { + return Timespec{Sec: sec, Nsec: nsec} + } func setTimeval(sec, usec int64) Timeval { + return Timeval{Sec: sec, Usec: usec} + } func SetKevent(k *Kevent_t, fd, mode, flags int) { + k.Ident = uint64(fd) + k.Filter = int16(mode) + k.Flags = uint16(flags) + } func (iov *Iovec) SetLen(length int) { + iov.Len = uint64(length) + } func (msghdr *Msghdr) SetControllen(length int) { + msghdr.Controllen = uint32(length) + } func (msghdr *Msghdr) SetIovlen(length int) { + msghdr.Iovlen = int32(length) + } func (cmsg *Cmsghdr) SetLen(length int) { + cmsg.Len = uint32(length) + } func (d *PtraceIoDesc) SetLen(length int) { + d.Len = uint64(length) + } func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + var writtenOut uint64 = 0 + _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0, 0) written = int(writtenOut) if e1 != 0 { + err = e1 + } + return + } func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd_riscv64.go b/vendor/golang.org/x/sys/unix/syscall_freebsd_riscv64.go index aab725c..5b51fc8 100644 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd_riscv64.go +++ b/vendor/golang.org/x/sys/unix/syscall_freebsd_riscv64.go @@ -1,5 +1,7 @@ // Copyright 2022 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build riscv64 && freebsd @@ -12,49 +14,73 @@ import ( ) func setTimespec(sec, nsec int64) Timespec { + return Timespec{Sec: sec, Nsec: nsec} + } func setTimeval(sec, usec int64) Timeval { + return Timeval{Sec: sec, Usec: usec} + } func SetKevent(k *Kevent_t, fd, mode, flags int) { + k.Ident = uint64(fd) + k.Filter = int16(mode) + k.Flags = uint16(flags) + } func (iov *Iovec) SetLen(length int) { + iov.Len = uint64(length) + } func (msghdr *Msghdr) SetControllen(length int) { + msghdr.Controllen = uint32(length) + } func (msghdr *Msghdr) SetIovlen(length int) { + msghdr.Iovlen = int32(length) + } func (cmsg *Cmsghdr) SetLen(length int) { + cmsg.Len = uint32(length) + } func (d *PtraceIoDesc) SetLen(length int) { + d.Len = uint64(length) + } func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + var writtenOut uint64 = 0 + _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0, 0) written = int(writtenOut) if e1 != 0 { + err = e1 + } + return + } func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux.go b/vendor/golang.org/x/sys/unix/syscall_linux.go index 5682e26..c2d0462 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux.go @@ -1,12 +1,19 @@ // Copyright 2009 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Linux system calls. + // This file is compiled as ordinary Go code, + // but it is also input to mksyscall, + // which parses the //sys lines and generates system call stubs. + // Note that sometimes we use a lowercase //sys name and + // wrap it in our own nicer implementation. package unix @@ -20,229 +27,371 @@ import ( ) /* + * Wrapped + */ func Access(path string, mode uint32) (err error) { + return Faccessat(AT_FDCWD, path, mode, 0) + } func Chmod(path string, mode uint32) (err error) { + return Fchmodat(AT_FDCWD, path, mode, 0) + } func Chown(path string, uid int, gid int) (err error) { + return Fchownat(AT_FDCWD, path, uid, gid, 0) + } func Creat(path string, mode uint32) (fd int, err error) { + return Open(path, O_CREAT|O_WRONLY|O_TRUNC, mode) + } func EpollCreate(size int) (fd int, err error) { + if size <= 0 { + return -1, EINVAL + } + return EpollCreate1(0) + } //sys FanotifyInit(flags uint, event_f_flags uint) (fd int, err error) + //sys fanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname *byte) (err error) func FanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname string) (err error) { + if pathname == "" { + return fanotifyMark(fd, flags, mask, dirFd, nil) + } + p, err := BytePtrFromString(pathname) + if err != nil { + return err + } + return fanotifyMark(fd, flags, mask, dirFd, p) + } //sys fchmodat(dirfd int, path string, mode uint32) (err error) + //sys fchmodat2(dirfd int, path string, mode uint32, flags int) (err error) func Fchmodat(dirfd int, path string, mode uint32, flags int) error { + // Linux fchmodat doesn't support the flags parameter, but fchmodat2 does. + // Try fchmodat2 if flags are specified. + if flags != 0 { + err := fchmodat2(dirfd, path, mode, flags) + if err == ENOSYS { + // fchmodat2 isn't available. If the flags are known to be valid, + // return EOPNOTSUPP to indicate that fchmodat doesn't support them. + if flags&^(AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH) != 0 { + return EINVAL + } else if flags&(AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH) != 0 { + return EOPNOTSUPP + } + } + return err + } + return fchmodat(dirfd, path, mode) + } func InotifyInit() (fd int, err error) { + return InotifyInit1(0) + } //sys ioctl(fd int, req uint, arg uintptr) (err error) = SYS_IOCTL + //sys ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) = SYS_IOCTL // ioctl itself should not be exposed directly, but additional get/set functions + // for specific types are permissible. These are defined in ioctl.go and + // ioctl_linux.go. + // + // The third argument to ioctl is often a pointer but sometimes an integer. + // Callers should use ioctlPtr when the third argument is a pointer and ioctl + // when the third argument is an integer. + // + // TODO: some existing code incorrectly uses ioctl when it should use ioctlPtr. //sys Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) func Link(oldpath string, newpath string) (err error) { + return Linkat(AT_FDCWD, oldpath, AT_FDCWD, newpath, 0) + } func Mkdir(path string, mode uint32) (err error) { + return Mkdirat(AT_FDCWD, path, mode) + } func Mknod(path string, mode uint32, dev int) (err error) { + return Mknodat(AT_FDCWD, path, mode, dev) + } func Open(path string, mode int, perm uint32) (fd int, err error) { + return openat(AT_FDCWD, path, mode|O_LARGEFILE, perm) + } //sys openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { + return openat(dirfd, path, flags|O_LARGEFILE, mode) + } //sys openat2(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error) func Openat2(dirfd int, path string, how *OpenHow) (fd int, err error) { + return openat2(dirfd, path, how, SizeofOpenHow) + } func Pipe(p []int) error { + return Pipe2(p, 0) + } //sysnb pipe2(p *[2]_C_int, flags int) (err error) func Pipe2(p []int, flags int) error { + if len(p) != 2 { + return EINVAL + } + var pp [2]_C_int + err := pipe2(&pp, flags) + if err == nil { + p[0] = int(pp[0]) + p[1] = int(pp[1]) + } + return err + } //sys ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) func Ppoll(fds []PollFd, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { + if len(fds) == 0 { + return ppoll(nil, 0, timeout, sigmask) + } + return ppoll(&fds[0], len(fds), timeout, sigmask) + } func Poll(fds []PollFd, timeout int) (n int, err error) { + var ts *Timespec + if timeout >= 0 { + ts = new(Timespec) + *ts = NsecToTimespec(int64(timeout) * 1e6) + } + return Ppoll(fds, ts, nil) + } //sys Readlinkat(dirfd int, path string, buf []byte) (n int, err error) func Readlink(path string, buf []byte) (n int, err error) { + return Readlinkat(AT_FDCWD, path, buf) + } func Rename(oldpath string, newpath string) (err error) { + return Renameat(AT_FDCWD, oldpath, AT_FDCWD, newpath) + } func Rmdir(path string) error { + return Unlinkat(AT_FDCWD, path, AT_REMOVEDIR) + } //sys Symlinkat(oldpath string, newdirfd int, newpath string) (err error) func Symlink(oldpath string, newpath string) (err error) { + return Symlinkat(oldpath, AT_FDCWD, newpath) + } func Unlink(path string) error { + return Unlinkat(AT_FDCWD, path, 0) + } //sys Unlinkat(dirfd int, path string, flags int) (err error) func Utimes(path string, tv []Timeval) error { + if tv == nil { + err := utimensat(AT_FDCWD, path, nil, 0) + if err != ENOSYS { + return err + } + return utimes(path, nil) + } + if len(tv) != 2 { + return EINVAL + } + var ts [2]Timespec + ts[0] = NsecToTimespec(TimevalToNsec(tv[0])) + ts[1] = NsecToTimespec(TimevalToNsec(tv[1])) + err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0) + if err != ENOSYS { + return err + } + return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) + } //sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) func UtimesNano(path string, ts []Timespec) error { + return UtimesNanoAt(AT_FDCWD, path, ts, 0) + } func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error { + if ts == nil { + return utimensat(dirfd, path, nil, flags) + } + if len(ts) != 2 { + return EINVAL + } + return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags) + } func Futimesat(dirfd int, path string, tv []Timeval) error { + if tv == nil { + return futimesat(dirfd, path, nil) + } + if len(tv) != 2 { + return EINVAL + } + return futimesat(dirfd, path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) + } func Futimes(fd int, tv []Timeval) (err error) { + // Believe it or not, this is the best we can do on Linux + // (and is what glibc does). + return Utimes("/proc/self/fd/"+strconv.Itoa(fd), tv) + } const ImplementsGetwd = true @@ -250,80 +399,135 @@ const ImplementsGetwd = true //sys Getcwd(buf []byte) (n int, err error) func Getwd() (wd string, err error) { + var buf [PathMax]byte + n, err := Getcwd(buf[0:]) + if err != nil { + return "", err + } + // Getcwd returns the number of bytes written to buf, including the NUL. + if n < 1 || n > len(buf) || buf[n-1] != 0 { + return "", EINVAL + } + // In some cases, Linux can return a path that starts with the + // "(unreachable)" prefix, which can potentially be a valid relative + // path. To work around that, return ENOENT if path is not absolute. + if buf[0] != '/' { + return "", ENOENT + } return string(buf[0 : n-1]), nil + } func Getgroups() (gids []int, err error) { + n, err := getgroups(0, nil) + if err != nil { + return nil, err + } + if n == 0 { + return nil, nil + } // Sanity check group count. Max is 1<<16 on Linux. + if n < 0 || n > 1<<20 { + return nil, EINVAL + } a := make([]_Gid_t, n) + n, err = getgroups(n, &a[0]) + if err != nil { + return nil, err + } + gids = make([]int, n) + for i, v := range a[0:n] { + gids[i] = int(v) + } + return + } func Setgroups(gids []int) (err error) { + if len(gids) == 0 { + return setgroups(0, nil) + } a := make([]_Gid_t, len(gids)) + for i, v := range gids { + a[i] = _Gid_t(v) + } + return setgroups(len(a), &a[0]) + } type WaitStatus uint32 // Wait status is 7 bits at bottom, either 0 (exited), + // 0x7F (stopped), or a signal number that caused an exit. + // The 0x80 bit is whether there was a core dump. + // An extra number (exit code, signal causing a stop) + // is in the high bits. At least that's the idea. + // There are various irregularities. For example, the + // "continued" status is 0xFFFF, distinguishing itself + // from stopped via the core dump bit. const ( - mask = 0x7F - core = 0x80 - exited = 0x00 + mask = 0x7F + + core = 0x80 + + exited = 0x00 + stopped = 0x7F - shift = 8 + + shift = 8 ) func (w WaitStatus) Exited() bool { return w&mask == exited } @@ -337,1404 +541,2465 @@ func (w WaitStatus) Continued() bool { return w == 0xFFFF } func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 } func (w WaitStatus) ExitStatus() int { + if !w.Exited() { + return -1 + } + return int(w>>shift) & 0xFF + } func (w WaitStatus) Signal() syscall.Signal { + if !w.Signaled() { + return -1 + } + return syscall.Signal(w & mask) + } func (w WaitStatus) StopSignal() syscall.Signal { + if !w.Stopped() { + return -1 + } + return syscall.Signal(w>>shift) & 0xFF + } func (w WaitStatus) TrapCause() int { + if w.StopSignal() != SIGTRAP { + return -1 + } + return int(w>>shift) >> 8 + } //sys wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) { + var status _C_int + wpid, err = wait4(pid, &status, options, rusage) + if wstatus != nil { + *wstatus = WaitStatus(status) + } + return + } //sys Waitid(idType int, id int, info *Siginfo, options int, rusage *Rusage) (err error) func Mkfifo(path string, mode uint32) error { + return Mknod(path, mode|S_IFIFO, 0) + } func Mkfifoat(dirfd int, path string, mode uint32) error { + return Mknodat(dirfd, path, mode|S_IFIFO, 0) + } func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) { + if sa.Port < 0 || sa.Port > 0xFFFF { + return nil, 0, EINVAL + } + sa.raw.Family = AF_INET + p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) + p[0] = byte(sa.Port >> 8) + p[1] = byte(sa.Port) + sa.raw.Addr = sa.Addr + return unsafe.Pointer(&sa.raw), SizeofSockaddrInet4, nil + } func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) { + if sa.Port < 0 || sa.Port > 0xFFFF { + return nil, 0, EINVAL + } + sa.raw.Family = AF_INET6 + p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) + p[0] = byte(sa.Port >> 8) + p[1] = byte(sa.Port) + sa.raw.Scope_id = sa.ZoneId + sa.raw.Addr = sa.Addr + return unsafe.Pointer(&sa.raw), SizeofSockaddrInet6, nil + } func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) { + name := sa.Name + n := len(name) + if n >= len(sa.raw.Path) { + return nil, 0, EINVAL + } + sa.raw.Family = AF_UNIX + for i := 0; i < n; i++ { + sa.raw.Path[i] = int8(name[i]) + } + // length is family (uint16), name, NUL. + sl := _Socklen(2) + if n > 0 { + sl += _Socklen(n) + 1 + } + if sa.raw.Path[0] == '@' || (sa.raw.Path[0] == 0 && sl > 3) { + // Check sl > 3 so we don't change unnamed socket behavior. + sa.raw.Path[0] = 0 + // Don't count trailing NUL for abstract address. + sl-- + } return unsafe.Pointer(&sa.raw), sl, nil + } // SockaddrLinklayer implements the Sockaddr interface for AF_PACKET type sockets. + type SockaddrLinklayer struct { Protocol uint16 - Ifindex int - Hatype uint16 - Pkttype uint8 - Halen uint8 - Addr [8]byte - raw RawSockaddrLinklayer + + Ifindex int + + Hatype uint16 + + Pkttype uint8 + + Halen uint8 + + Addr [8]byte + + raw RawSockaddrLinklayer } func (sa *SockaddrLinklayer) sockaddr() (unsafe.Pointer, _Socklen, error) { + if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff { + return nil, 0, EINVAL + } + sa.raw.Family = AF_PACKET + sa.raw.Protocol = sa.Protocol + sa.raw.Ifindex = int32(sa.Ifindex) + sa.raw.Hatype = sa.Hatype + sa.raw.Pkttype = sa.Pkttype + sa.raw.Halen = sa.Halen + sa.raw.Addr = sa.Addr + return unsafe.Pointer(&sa.raw), SizeofSockaddrLinklayer, nil + } // SockaddrNetlink implements the Sockaddr interface for AF_NETLINK type sockets. + type SockaddrNetlink struct { Family uint16 - Pad uint16 - Pid uint32 + + Pad uint16 + + Pid uint32 + Groups uint32 - raw RawSockaddrNetlink + + raw RawSockaddrNetlink } func (sa *SockaddrNetlink) sockaddr() (unsafe.Pointer, _Socklen, error) { + sa.raw.Family = AF_NETLINK + sa.raw.Pad = sa.Pad + sa.raw.Pid = sa.Pid + sa.raw.Groups = sa.Groups + return unsafe.Pointer(&sa.raw), SizeofSockaddrNetlink, nil + } // SockaddrHCI implements the Sockaddr interface for AF_BLUETOOTH type sockets + // using the HCI protocol. + type SockaddrHCI struct { - Dev uint16 + Dev uint16 + Channel uint16 - raw RawSockaddrHCI + + raw RawSockaddrHCI } func (sa *SockaddrHCI) sockaddr() (unsafe.Pointer, _Socklen, error) { + sa.raw.Family = AF_BLUETOOTH + sa.raw.Dev = sa.Dev + sa.raw.Channel = sa.Channel + return unsafe.Pointer(&sa.raw), SizeofSockaddrHCI, nil + } // SockaddrL2 implements the Sockaddr interface for AF_BLUETOOTH type sockets + // using the L2CAP protocol. + type SockaddrL2 struct { - PSM uint16 - CID uint16 - Addr [6]uint8 + PSM uint16 + + CID uint16 + + Addr [6]uint8 + AddrType uint8 - raw RawSockaddrL2 + + raw RawSockaddrL2 } func (sa *SockaddrL2) sockaddr() (unsafe.Pointer, _Socklen, error) { + sa.raw.Family = AF_BLUETOOTH + psm := (*[2]byte)(unsafe.Pointer(&sa.raw.Psm)) + psm[0] = byte(sa.PSM) + psm[1] = byte(sa.PSM >> 8) + for i := 0; i < len(sa.Addr); i++ { + sa.raw.Bdaddr[i] = sa.Addr[len(sa.Addr)-1-i] + } + cid := (*[2]byte)(unsafe.Pointer(&sa.raw.Cid)) + cid[0] = byte(sa.CID) + cid[1] = byte(sa.CID >> 8) + sa.raw.Bdaddr_type = sa.AddrType + return unsafe.Pointer(&sa.raw), SizeofSockaddrL2, nil + } // SockaddrRFCOMM implements the Sockaddr interface for AF_BLUETOOTH type sockets + // using the RFCOMM protocol. + // + // Server example: + // + // fd, _ := Socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM) + // _ = unix.Bind(fd, &unix.SockaddrRFCOMM{ + // Channel: 1, + // Addr: [6]uint8{0, 0, 0, 0, 0, 0}, // BDADDR_ANY or 00:00:00:00:00:00 + // }) + // _ = Listen(fd, 1) + // nfd, sa, _ := Accept(fd) + // fmt.Printf("conn addr=%v fd=%d", sa.(*unix.SockaddrRFCOMM).Addr, nfd) + // Read(nfd, buf) + // + // Client example: + // + // fd, _ := Socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM) + // _ = Connect(fd, &SockaddrRFCOMM{ + // Channel: 1, + // Addr: [6]byte{0x11, 0x22, 0x33, 0xaa, 0xbb, 0xcc}, // CC:BB:AA:33:22:11 + // }) + // Write(fd, []byte(`hello`)) + type SockaddrRFCOMM struct { + // Addr represents a bluetooth address, byte ordering is little-endian. + Addr [6]uint8 // Channel is a designated bluetooth channel, only 1-30 are available for use. + // Since Linux 2.6.7 and further zero value is the first available channel. + Channel uint8 raw RawSockaddrRFCOMM } func (sa *SockaddrRFCOMM) sockaddr() (unsafe.Pointer, _Socklen, error) { + sa.raw.Family = AF_BLUETOOTH + sa.raw.Channel = sa.Channel + sa.raw.Bdaddr = sa.Addr + return unsafe.Pointer(&sa.raw), SizeofSockaddrRFCOMM, nil + } // SockaddrCAN implements the Sockaddr interface for AF_CAN type sockets. + // The RxID and TxID fields are used for transport protocol addressing in + // (CAN_TP16, CAN_TP20, CAN_MCNET, and CAN_ISOTP), they can be left with + // zero values for CAN_RAW and CAN_BCM sockets as they have no meaning. + // + // The SockaddrCAN struct must be bound to the socket file descriptor + // using Bind before the CAN socket can be used. + // + // // Read one raw CAN frame + // fd, _ := Socket(AF_CAN, SOCK_RAW, CAN_RAW) + // addr := &SockaddrCAN{Ifindex: index} + // Bind(fd, addr) + // frame := make([]byte, 16) + // Read(fd, frame) + // + // The full SocketCAN documentation can be found in the linux kernel + // archives at: https://www.kernel.org/doc/Documentation/networking/can.txt + type SockaddrCAN struct { Ifindex int - RxID uint32 - TxID uint32 - raw RawSockaddrCAN + + RxID uint32 + + TxID uint32 + + raw RawSockaddrCAN } func (sa *SockaddrCAN) sockaddr() (unsafe.Pointer, _Socklen, error) { + if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff { + return nil, 0, EINVAL + } + sa.raw.Family = AF_CAN + sa.raw.Ifindex = int32(sa.Ifindex) + rx := (*[4]byte)(unsafe.Pointer(&sa.RxID)) + for i := 0; i < 4; i++ { + sa.raw.Addr[i] = rx[i] + } + tx := (*[4]byte)(unsafe.Pointer(&sa.TxID)) + for i := 0; i < 4; i++ { + sa.raw.Addr[i+4] = tx[i] + } + return unsafe.Pointer(&sa.raw), SizeofSockaddrCAN, nil + } // SockaddrCANJ1939 implements the Sockaddr interface for AF_CAN using J1939 + // protocol (https://en.wikipedia.org/wiki/SAE_J1939). For more information + // on the purposes of the fields, check the official linux kernel documentation + // available here: https://www.kernel.org/doc/Documentation/networking/j1939.rst + type SockaddrCANJ1939 struct { Ifindex int - Name uint64 - PGN uint32 - Addr uint8 - raw RawSockaddrCAN + + Name uint64 + + PGN uint32 + + Addr uint8 + + raw RawSockaddrCAN } func (sa *SockaddrCANJ1939) sockaddr() (unsafe.Pointer, _Socklen, error) { + if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff { + return nil, 0, EINVAL + } + sa.raw.Family = AF_CAN + sa.raw.Ifindex = int32(sa.Ifindex) + n := (*[8]byte)(unsafe.Pointer(&sa.Name)) + for i := 0; i < 8; i++ { + sa.raw.Addr[i] = n[i] + } + p := (*[4]byte)(unsafe.Pointer(&sa.PGN)) + for i := 0; i < 4; i++ { + sa.raw.Addr[i+8] = p[i] + } + sa.raw.Addr[12] = sa.Addr + return unsafe.Pointer(&sa.raw), SizeofSockaddrCAN, nil + } // SockaddrALG implements the Sockaddr interface for AF_ALG type sockets. + // SockaddrALG enables userspace access to the Linux kernel's cryptography + // subsystem. The Type and Name fields specify which type of hash or cipher + // should be used with a given socket. + // + // To create a file descriptor that provides access to a hash or cipher, both + // Bind and Accept must be used. Once the setup process is complete, input + // data can be written to the socket, processed by the kernel, and then read + // back as hash output or ciphertext. + // + // Here is an example of using an AF_ALG socket with SHA1 hashing. + // The initial socket setup process is as follows: + // + // // Open a socket to perform SHA1 hashing. + // fd, _ := unix.Socket(unix.AF_ALG, unix.SOCK_SEQPACKET, 0) + // addr := &unix.SockaddrALG{Type: "hash", Name: "sha1"} + // unix.Bind(fd, addr) + // // Note: unix.Accept does not work at this time; must invoke accept() + // // manually using unix.Syscall. + // hashfd, _, _ := unix.Syscall(unix.SYS_ACCEPT, uintptr(fd), 0, 0) + // + // Once a file descriptor has been returned from Accept, it may be used to + // perform SHA1 hashing. The descriptor is not safe for concurrent use, but + // may be re-used repeatedly with subsequent Write and Read operations. + // + // When hashing a small byte slice or string, a single Write and Read may + // be used: + // + // // Assume hashfd is already configured using the setup process. + // hash := os.NewFile(hashfd, "sha1") + // // Hash an input string and read the results. Each Write discards + // // previous hash state. Read always reads the current state. + // b := make([]byte, 20) + // for i := 0; i < 2; i++ { + // io.WriteString(hash, "Hello, world.") + // hash.Read(b) + // fmt.Println(hex.EncodeToString(b)) + // } + // // Output: + // // 2ae01472317d1935a84797ec1983ae243fc6aa28 + // // 2ae01472317d1935a84797ec1983ae243fc6aa28 + // + // For hashing larger byte slices, or byte streams such as those read from + // a file or socket, use Sendto with MSG_MORE to instruct the kernel to update + // the hash digest instead of creating a new one for a given chunk and finalizing it. + // + // // Assume hashfd and addr are already configured using the setup process. + // hash := os.NewFile(hashfd, "sha1") + // // Hash the contents of a file. + // f, _ := os.Open("/tmp/linux-4.10-rc7.tar.xz") + // b := make([]byte, 4096) + // for { + // n, err := f.Read(b) + // if err == io.EOF { + // break + // } + // unix.Sendto(hashfd, b[:n], unix.MSG_MORE, addr) + // } + // hash.Read(b) + // fmt.Println(hex.EncodeToString(b)) + // // Output: 85cdcad0c06eef66f805ecce353bec9accbeecc5 + // + // For more information, see: http://www.chronox.de/crypto-API/crypto/userspace-if.html. + type SockaddrALG struct { - Type string - Name string + Type string + + Name string + Feature uint32 - Mask uint32 - raw RawSockaddrALG + + Mask uint32 + + raw RawSockaddrALG } func (sa *SockaddrALG) sockaddr() (unsafe.Pointer, _Socklen, error) { + // Leave room for NUL byte terminator. + if len(sa.Type) > len(sa.raw.Type)-1 { + return nil, 0, EINVAL + } + if len(sa.Name) > len(sa.raw.Name)-1 { + return nil, 0, EINVAL + } sa.raw.Family = AF_ALG + sa.raw.Feat = sa.Feature + sa.raw.Mask = sa.Mask copy(sa.raw.Type[:], sa.Type) + copy(sa.raw.Name[:], sa.Name) return unsafe.Pointer(&sa.raw), SizeofSockaddrALG, nil + } // SockaddrVM implements the Sockaddr interface for AF_VSOCK type sockets. + // SockaddrVM provides access to Linux VM sockets: a mechanism that enables + // bidirectional communication between a hypervisor and its guest virtual + // machines. + type SockaddrVM struct { + // CID and Port specify a context ID and port address for a VM socket. + // Guests have a unique CID, and hosts may have a well-known CID of: + // - VMADDR_CID_HYPERVISOR: refers to the hypervisor process. + // - VMADDR_CID_LOCAL: refers to local communication (loopback). + // - VMADDR_CID_HOST: refers to other processes on the host. - CID uint32 - Port uint32 + + CID uint32 + + Port uint32 + Flags uint8 - raw RawSockaddrVM + + raw RawSockaddrVM } func (sa *SockaddrVM) sockaddr() (unsafe.Pointer, _Socklen, error) { + sa.raw.Family = AF_VSOCK + sa.raw.Port = sa.Port + sa.raw.Cid = sa.CID + sa.raw.Flags = sa.Flags return unsafe.Pointer(&sa.raw), SizeofSockaddrVM, nil + } type SockaddrXDP struct { - Flags uint16 - Ifindex uint32 - QueueID uint32 + Flags uint16 + + Ifindex uint32 + + QueueID uint32 + SharedUmemFD uint32 - raw RawSockaddrXDP + + raw RawSockaddrXDP } func (sa *SockaddrXDP) sockaddr() (unsafe.Pointer, _Socklen, error) { + sa.raw.Family = AF_XDP + sa.raw.Flags = sa.Flags + sa.raw.Ifindex = sa.Ifindex + sa.raw.Queue_id = sa.QueueID + sa.raw.Shared_umem_fd = sa.SharedUmemFD return unsafe.Pointer(&sa.raw), SizeofSockaddrXDP, nil + } // This constant mirrors the #define of PX_PROTO_OE in + // linux/if_pppox.h. We're defining this by hand here instead of + // autogenerating through mkerrors.sh because including + // linux/if_pppox.h causes some declaration conflicts with other + // includes (linux/if_pppox.h includes linux/in.h, which conflicts + // with netinet/in.h). Given that we only need a single zero constant + // out of that file, it's cleaner to just define it by hand here. + const px_proto_oe = 0 type SockaddrPPPoE struct { - SID uint16 + SID uint16 + Remote []byte - Dev string - raw RawSockaddrPPPoX + + Dev string + + raw RawSockaddrPPPoX } func (sa *SockaddrPPPoE) sockaddr() (unsafe.Pointer, _Socklen, error) { + if len(sa.Remote) != 6 { + return nil, 0, EINVAL + } + if len(sa.Dev) > IFNAMSIZ-1 { + return nil, 0, EINVAL + } *(*uint16)(unsafe.Pointer(&sa.raw[0])) = AF_PPPOX + // This next field is in host-endian byte order. We can't use the + // same unsafe pointer cast as above, because this value is not + // 32-bit aligned and some architectures don't allow unaligned + // access. + // + // However, the value of px_proto_oe is 0, so we can use + // encoding/binary helpers to write the bytes without worrying + // about the ordering. + binary.BigEndian.PutUint32(sa.raw[2:6], px_proto_oe) + // This field is deliberately big-endian, unlike the previous + // one. The kernel expects SID to be in network byte order. + binary.BigEndian.PutUint16(sa.raw[6:8], sa.SID) + copy(sa.raw[8:14], sa.Remote) + for i := 14; i < 14+IFNAMSIZ; i++ { + sa.raw[i] = 0 + } + copy(sa.raw[14:], sa.Dev) + return unsafe.Pointer(&sa.raw), SizeofSockaddrPPPoX, nil + } // SockaddrTIPC implements the Sockaddr interface for AF_TIPC type sockets. + // For more information on TIPC, see: http://tipc.sourceforge.net/. + type SockaddrTIPC struct { + // Scope is the publication scopes when binding service/service range. + // Should be set to TIPC_CLUSTER_SCOPE or TIPC_NODE_SCOPE. + Scope int // Addr is the type of address used to manipulate a socket. Addr must be + // one of: + // - *TIPCSocketAddr: "id" variant in the C addr union + // - *TIPCServiceRange: "nameseq" variant in the C addr union + // - *TIPCServiceName: "name" variant in the C addr union + // + // If nil, EINVAL will be returned when the structure is used. + Addr TIPCAddr raw RawSockaddrTIPC } // TIPCAddr is implemented by types that can be used as an address for + // SockaddrTIPC. It is only implemented by *TIPCSocketAddr, *TIPCServiceRange, + // and *TIPCServiceName. + type TIPCAddr interface { tipcAddrtype() uint8 + tipcAddr() [12]byte } func (sa *TIPCSocketAddr) tipcAddr() [12]byte { + var out [12]byte + copy(out[:], (*(*[unsafe.Sizeof(TIPCSocketAddr{})]byte)(unsafe.Pointer(sa)))[:]) + return out + } func (sa *TIPCSocketAddr) tipcAddrtype() uint8 { return TIPC_SOCKET_ADDR } func (sa *TIPCServiceRange) tipcAddr() [12]byte { + var out [12]byte + copy(out[:], (*(*[unsafe.Sizeof(TIPCServiceRange{})]byte)(unsafe.Pointer(sa)))[:]) + return out + } func (sa *TIPCServiceRange) tipcAddrtype() uint8 { return TIPC_SERVICE_RANGE } func (sa *TIPCServiceName) tipcAddr() [12]byte { + var out [12]byte + copy(out[:], (*(*[unsafe.Sizeof(TIPCServiceName{})]byte)(unsafe.Pointer(sa)))[:]) + return out + } func (sa *TIPCServiceName) tipcAddrtype() uint8 { return TIPC_SERVICE_ADDR } func (sa *SockaddrTIPC) sockaddr() (unsafe.Pointer, _Socklen, error) { + if sa.Addr == nil { + return nil, 0, EINVAL + } + sa.raw.Family = AF_TIPC + sa.raw.Scope = int8(sa.Scope) + sa.raw.Addrtype = sa.Addr.tipcAddrtype() + sa.raw.Addr = sa.Addr.tipcAddr() + return unsafe.Pointer(&sa.raw), SizeofSockaddrTIPC, nil + } // SockaddrL2TPIP implements the Sockaddr interface for IPPROTO_L2TP/AF_INET sockets. + type SockaddrL2TPIP struct { - Addr [4]byte + Addr [4]byte + ConnId uint32 - raw RawSockaddrL2TPIP + + raw RawSockaddrL2TPIP } func (sa *SockaddrL2TPIP) sockaddr() (unsafe.Pointer, _Socklen, error) { + sa.raw.Family = AF_INET + sa.raw.Conn_id = sa.ConnId + sa.raw.Addr = sa.Addr + return unsafe.Pointer(&sa.raw), SizeofSockaddrL2TPIP, nil + } // SockaddrL2TPIP6 implements the Sockaddr interface for IPPROTO_L2TP/AF_INET6 sockets. + type SockaddrL2TPIP6 struct { - Addr [16]byte + Addr [16]byte + ZoneId uint32 + ConnId uint32 - raw RawSockaddrL2TPIP6 + + raw RawSockaddrL2TPIP6 } func (sa *SockaddrL2TPIP6) sockaddr() (unsafe.Pointer, _Socklen, error) { + sa.raw.Family = AF_INET6 + sa.raw.Conn_id = sa.ConnId + sa.raw.Scope_id = sa.ZoneId + sa.raw.Addr = sa.Addr + return unsafe.Pointer(&sa.raw), SizeofSockaddrL2TPIP6, nil + } // SockaddrIUCV implements the Sockaddr interface for AF_IUCV sockets. + type SockaddrIUCV struct { UserID string - Name string - raw RawSockaddrIUCV + + Name string + + raw RawSockaddrIUCV } func (sa *SockaddrIUCV) sockaddr() (unsafe.Pointer, _Socklen, error) { + sa.raw.Family = AF_IUCV + // These are EBCDIC encoded by the kernel, but we still need to pad them + // with blanks. Initializing with blanks allows the caller to feed in either + // a padded or an unpadded string. + for i := 0; i < 8; i++ { + sa.raw.Nodeid[i] = ' ' + sa.raw.User_id[i] = ' ' + sa.raw.Name[i] = ' ' + } + if len(sa.UserID) > 8 || len(sa.Name) > 8 { + return nil, 0, EINVAL + } + for i, b := range []byte(sa.UserID[:]) { + sa.raw.User_id[i] = int8(b) + } + for i, b := range []byte(sa.Name[:]) { + sa.raw.Name[i] = int8(b) + } + return unsafe.Pointer(&sa.raw), SizeofSockaddrIUCV, nil + } type SockaddrNFC struct { - DeviceIdx uint32 - TargetIdx uint32 + DeviceIdx uint32 + + TargetIdx uint32 + NFCProtocol uint32 - raw RawSockaddrNFC + + raw RawSockaddrNFC } func (sa *SockaddrNFC) sockaddr() (unsafe.Pointer, _Socklen, error) { + sa.raw.Sa_family = AF_NFC + sa.raw.Dev_idx = sa.DeviceIdx + sa.raw.Target_idx = sa.TargetIdx + sa.raw.Nfc_protocol = sa.NFCProtocol + return unsafe.Pointer(&sa.raw), SizeofSockaddrNFC, nil + } type SockaddrNFCLLCP struct { - DeviceIdx uint32 - TargetIdx uint32 - NFCProtocol uint32 + DeviceIdx uint32 + + TargetIdx uint32 + + NFCProtocol uint32 + DestinationSAP uint8 - SourceSAP uint8 - ServiceName string - raw RawSockaddrNFCLLCP + + SourceSAP uint8 + + ServiceName string + + raw RawSockaddrNFCLLCP } func (sa *SockaddrNFCLLCP) sockaddr() (unsafe.Pointer, _Socklen, error) { + sa.raw.Sa_family = AF_NFC + sa.raw.Dev_idx = sa.DeviceIdx + sa.raw.Target_idx = sa.TargetIdx + sa.raw.Nfc_protocol = sa.NFCProtocol + sa.raw.Dsap = sa.DestinationSAP + sa.raw.Ssap = sa.SourceSAP + if len(sa.ServiceName) > len(sa.raw.Service_name) { + return nil, 0, EINVAL + } + copy(sa.raw.Service_name[:], sa.ServiceName) + sa.raw.SetServiceNameLen(len(sa.ServiceName)) + return unsafe.Pointer(&sa.raw), SizeofSockaddrNFCLLCP, nil + } var socketProtocol = func(fd int) (int, error) { + return GetsockoptInt(fd, SOL_SOCKET, SO_PROTOCOL) + } func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) { + switch rsa.Addr.Family { + case AF_NETLINK: + pp := (*RawSockaddrNetlink)(unsafe.Pointer(rsa)) + sa := new(SockaddrNetlink) + sa.Family = pp.Family + sa.Pad = pp.Pad + sa.Pid = pp.Pid + sa.Groups = pp.Groups + return sa, nil case AF_PACKET: + pp := (*RawSockaddrLinklayer)(unsafe.Pointer(rsa)) + sa := new(SockaddrLinklayer) + sa.Protocol = pp.Protocol + sa.Ifindex = int(pp.Ifindex) + sa.Hatype = pp.Hatype + sa.Pkttype = pp.Pkttype + sa.Halen = pp.Halen + sa.Addr = pp.Addr + return sa, nil case AF_UNIX: + pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa)) + sa := new(SockaddrUnix) + if pp.Path[0] == 0 { + // "Abstract" Unix domain socket. + // Rewrite leading NUL as @ for textual display. + // (This is the standard convention.) + // Not friendly to overwrite in place, + // but the callers below don't care. + pp.Path[0] = '@' + } // Assume path ends at NUL. + // This is not technically the Linux semantics for + // abstract Unix domain sockets--they are supposed + // to be uninterpreted fixed-size binary blobs--but + // everyone uses this convention. + n := 0 + for n < len(pp.Path) && pp.Path[n] != 0 { + n++ + } + sa.Name = string(unsafe.Slice((*byte)(unsafe.Pointer(&pp.Path[0])), n)) + return sa, nil case AF_INET: + proto, err := socketProtocol(fd) + if err != nil { + return nil, err + } switch proto { + case IPPROTO_L2TP: + pp := (*RawSockaddrL2TPIP)(unsafe.Pointer(rsa)) + sa := new(SockaddrL2TPIP) + sa.ConnId = pp.Conn_id + sa.Addr = pp.Addr + return sa, nil + default: + pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa)) + sa := new(SockaddrInet4) + p := (*[2]byte)(unsafe.Pointer(&pp.Port)) + sa.Port = int(p[0])<<8 + int(p[1]) + sa.Addr = pp.Addr + return sa, nil + } case AF_INET6: + proto, err := socketProtocol(fd) + if err != nil { + return nil, err + } switch proto { + case IPPROTO_L2TP: + pp := (*RawSockaddrL2TPIP6)(unsafe.Pointer(rsa)) + sa := new(SockaddrL2TPIP6) + sa.ConnId = pp.Conn_id + sa.ZoneId = pp.Scope_id + sa.Addr = pp.Addr + return sa, nil + default: + pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa)) + sa := new(SockaddrInet6) + p := (*[2]byte)(unsafe.Pointer(&pp.Port)) + sa.Port = int(p[0])<<8 + int(p[1]) + sa.ZoneId = pp.Scope_id + sa.Addr = pp.Addr + return sa, nil + } case AF_VSOCK: + pp := (*RawSockaddrVM)(unsafe.Pointer(rsa)) + sa := &SockaddrVM{ - CID: pp.Cid, - Port: pp.Port, + + CID: pp.Cid, + + Port: pp.Port, + Flags: pp.Flags, } + return sa, nil + case AF_BLUETOOTH: + proto, err := socketProtocol(fd) + if err != nil { + return nil, err + } + // only BTPROTO_L2CAP and BTPROTO_RFCOMM can accept connections + switch proto { + case BTPROTO_L2CAP: + pp := (*RawSockaddrL2)(unsafe.Pointer(rsa)) + sa := &SockaddrL2{ - PSM: pp.Psm, - CID: pp.Cid, - Addr: pp.Bdaddr, + + PSM: pp.Psm, + + CID: pp.Cid, + + Addr: pp.Bdaddr, + AddrType: pp.Bdaddr_type, } + return sa, nil + case BTPROTO_RFCOMM: + pp := (*RawSockaddrRFCOMM)(unsafe.Pointer(rsa)) + sa := &SockaddrRFCOMM{ + Channel: pp.Channel, - Addr: pp.Bdaddr, + + Addr: pp.Bdaddr, } + return sa, nil + } + case AF_XDP: + pp := (*RawSockaddrXDP)(unsafe.Pointer(rsa)) + sa := &SockaddrXDP{ - Flags: pp.Flags, - Ifindex: pp.Ifindex, - QueueID: pp.Queue_id, + + Flags: pp.Flags, + + Ifindex: pp.Ifindex, + + QueueID: pp.Queue_id, + SharedUmemFD: pp.Shared_umem_fd, } + return sa, nil + case AF_PPPOX: + pp := (*RawSockaddrPPPoX)(unsafe.Pointer(rsa)) + if binary.BigEndian.Uint32(pp[2:6]) != px_proto_oe { + return nil, EINVAL + } + sa := &SockaddrPPPoE{ - SID: binary.BigEndian.Uint16(pp[6:8]), + + SID: binary.BigEndian.Uint16(pp[6:8]), + Remote: pp[8:14], } + for i := 14; i < 14+IFNAMSIZ; i++ { + if pp[i] == 0 { + sa.Dev = string(pp[14:i]) + break + } + } + return sa, nil + case AF_TIPC: + pp := (*RawSockaddrTIPC)(unsafe.Pointer(rsa)) sa := &SockaddrTIPC{ + Scope: int(pp.Scope), } // Determine which union variant is present in pp.Addr by checking + // pp.Addrtype. + switch pp.Addrtype { + case TIPC_SERVICE_RANGE: + sa.Addr = (*TIPCServiceRange)(unsafe.Pointer(&pp.Addr)) + case TIPC_SERVICE_ADDR: + sa.Addr = (*TIPCServiceName)(unsafe.Pointer(&pp.Addr)) + case TIPC_SOCKET_ADDR: + sa.Addr = (*TIPCSocketAddr)(unsafe.Pointer(&pp.Addr)) + default: + return nil, EINVAL + } return sa, nil + case AF_IUCV: + pp := (*RawSockaddrIUCV)(unsafe.Pointer(rsa)) var user [8]byte + var name [8]byte for i := 0; i < 8; i++ { + user[i] = byte(pp.User_id[i]) + name[i] = byte(pp.Name[i]) + } sa := &SockaddrIUCV{ + UserID: string(user[:]), - Name: string(name[:]), + + Name: string(name[:]), } + return sa, nil case AF_CAN: + proto, err := socketProtocol(fd) + if err != nil { + return nil, err + } pp := (*RawSockaddrCAN)(unsafe.Pointer(rsa)) switch proto { + case CAN_J1939: + sa := &SockaddrCANJ1939{ + Ifindex: int(pp.Ifindex), } + name := (*[8]byte)(unsafe.Pointer(&sa.Name)) + for i := 0; i < 8; i++ { + name[i] = pp.Addr[i] + } + pgn := (*[4]byte)(unsafe.Pointer(&sa.PGN)) + for i := 0; i < 4; i++ { + pgn[i] = pp.Addr[i+8] + } + addr := (*[1]byte)(unsafe.Pointer(&sa.Addr)) + addr[0] = pp.Addr[12] + return sa, nil + default: + sa := &SockaddrCAN{ + Ifindex: int(pp.Ifindex), } + rx := (*[4]byte)(unsafe.Pointer(&sa.RxID)) + for i := 0; i < 4; i++ { + rx[i] = pp.Addr[i] + } + tx := (*[4]byte)(unsafe.Pointer(&sa.TxID)) + for i := 0; i < 4; i++ { + tx[i] = pp.Addr[i+4] + } + return sa, nil + } + case AF_NFC: + proto, err := socketProtocol(fd) + if err != nil { + return nil, err + } + switch proto { + case NFC_SOCKPROTO_RAW: + pp := (*RawSockaddrNFC)(unsafe.Pointer(rsa)) + sa := &SockaddrNFC{ - DeviceIdx: pp.Dev_idx, - TargetIdx: pp.Target_idx, + + DeviceIdx: pp.Dev_idx, + + TargetIdx: pp.Target_idx, + NFCProtocol: pp.Nfc_protocol, } + return sa, nil + case NFC_SOCKPROTO_LLCP: + pp := (*RawSockaddrNFCLLCP)(unsafe.Pointer(rsa)) + if uint64(pp.Service_name_len) > uint64(len(pp.Service_name)) { + return nil, EINVAL + } + sa := &SockaddrNFCLLCP{ - DeviceIdx: pp.Dev_idx, - TargetIdx: pp.Target_idx, - NFCProtocol: pp.Nfc_protocol, + + DeviceIdx: pp.Dev_idx, + + TargetIdx: pp.Target_idx, + + NFCProtocol: pp.Nfc_protocol, + DestinationSAP: pp.Dsap, - SourceSAP: pp.Ssap, - ServiceName: string(pp.Service_name[:pp.Service_name_len]), + + SourceSAP: pp.Ssap, + + ServiceName: string(pp.Service_name[:pp.Service_name_len]), } + return sa, nil + default: + return nil, EINVAL + } + } + return nil, EAFNOSUPPORT + } func Accept(fd int) (nfd int, sa Sockaddr, err error) { + var rsa RawSockaddrAny + var len _Socklen = SizeofSockaddrAny + nfd, err = accept4(fd, &rsa, &len, 0) + if err != nil { + return + } + sa, err = anyToSockaddr(fd, &rsa) + if err != nil { + Close(nfd) + nfd = 0 + } + return + } func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error) { + var rsa RawSockaddrAny + var len _Socklen = SizeofSockaddrAny + nfd, err = accept4(fd, &rsa, &len, flags) + if err != nil { + return + } + if len > SizeofSockaddrAny { + panic("RawSockaddrAny too small") + } + sa, err = anyToSockaddr(fd, &rsa) + if err != nil { + Close(nfd) + nfd = 0 + } + return + } func Getsockname(fd int) (sa Sockaddr, err error) { + var rsa RawSockaddrAny + var len _Socklen = SizeofSockaddrAny + if err = getsockname(fd, &rsa, &len); err != nil { + return + } + return anyToSockaddr(fd, &rsa) + } func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) { + var value IPMreqn + vallen := _Socklen(SizeofIPMreqn) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) + return &value, err + } func GetsockoptUcred(fd, level, opt int) (*Ucred, error) { + var value Ucred + vallen := _Socklen(SizeofUcred) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) + return &value, err + } func GetsockoptTCPInfo(fd, level, opt int) (*TCPInfo, error) { + var value TCPInfo + vallen := _Socklen(SizeofTCPInfo) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) + return &value, err + } // GetsockoptString returns the string value of the socket option opt for the + // socket associated with fd at the given socket level. + func GetsockoptString(fd, level, opt int) (string, error) { + buf := make([]byte, 256) + vallen := _Socklen(len(buf)) + err := getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen) + if err != nil { + if err == ERANGE { + buf = make([]byte, vallen) + err = getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen) + } + if err != nil { + return "", err + } + } + return ByteSliceToString(buf[:vallen]), nil + } func GetsockoptTpacketStats(fd, level, opt int) (*TpacketStats, error) { + var value TpacketStats + vallen := _Socklen(SizeofTpacketStats) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) + return &value, err + } func GetsockoptTpacketStatsV3(fd, level, opt int) (*TpacketStatsV3, error) { + var value TpacketStatsV3 + vallen := _Socklen(SizeofTpacketStatsV3) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) + return &value, err + } func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) { + return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq)) + } func SetsockoptPacketMreq(fd, level, opt int, mreq *PacketMreq) error { + return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq)) + } // SetsockoptSockFprog attaches a classic BPF or an extended BPF program to a + // socket to filter incoming packets. See 'man 7 socket' for usage information. + func SetsockoptSockFprog(fd, level, opt int, fprog *SockFprog) error { + return setsockopt(fd, level, opt, unsafe.Pointer(fprog), unsafe.Sizeof(*fprog)) + } func SetsockoptCanRawFilter(fd, level, opt int, filter []CanFilter) error { + var p unsafe.Pointer + if len(filter) > 0 { + p = unsafe.Pointer(&filter[0]) + } + return setsockopt(fd, level, opt, p, uintptr(len(filter)*SizeofCanFilter)) + } func SetsockoptTpacketReq(fd, level, opt int, tp *TpacketReq) error { + return setsockopt(fd, level, opt, unsafe.Pointer(tp), unsafe.Sizeof(*tp)) + } func SetsockoptTpacketReq3(fd, level, opt int, tp *TpacketReq3) error { + return setsockopt(fd, level, opt, unsafe.Pointer(tp), unsafe.Sizeof(*tp)) + } func SetsockoptTCPRepairOpt(fd, level, opt int, o []TCPRepairOpt) (err error) { + if len(o) == 0 { + return EINVAL + } + return setsockopt(fd, level, opt, unsafe.Pointer(&o[0]), uintptr(SizeofTCPRepairOpt*len(o))) + } func SetsockoptTCPMD5Sig(fd, level, opt int, s *TCPMD5Sig) error { + return setsockopt(fd, level, opt, unsafe.Pointer(s), unsafe.Sizeof(*s)) + } // Keyctl Commands (http://man7.org/linux/man-pages/man2/keyctl.2.html) // KeyctlInt calls keyctl commands in which each argument is an int. + // These commands are KEYCTL_REVOKE, KEYCTL_CHOWN, KEYCTL_CLEAR, KEYCTL_LINK, + // KEYCTL_UNLINK, KEYCTL_NEGATE, KEYCTL_SET_REQKEY_KEYRING, KEYCTL_SET_TIMEOUT, + // KEYCTL_ASSUME_AUTHORITY, KEYCTL_SESSION_TO_PARENT, KEYCTL_REJECT, + // KEYCTL_INVALIDATE, and KEYCTL_GET_PERSISTENT. + //sys KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) = SYS_KEYCTL // KeyctlBuffer calls keyctl commands in which the third and fourth + // arguments are a buffer and its length, respectively. + // These commands are KEYCTL_UPDATE, KEYCTL_READ, and KEYCTL_INSTANTIATE. + //sys KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) = SYS_KEYCTL // KeyctlString calls keyctl commands which return a string. + // These commands are KEYCTL_DESCRIBE and KEYCTL_GET_SECURITY. + func KeyctlString(cmd int, id int) (string, error) { + // We must loop as the string data may change in between the syscalls. + // We could allocate a large buffer here to reduce the chance that the + // syscall needs to be called twice; however, this is unnecessary as + // the performance loss is negligible. + var buffer []byte + for { + // Try to fill the buffer with data + length, err := KeyctlBuffer(cmd, id, buffer, 0) + if err != nil { + return "", err + } // Check if the data was written + if length <= len(buffer) { + // Exclude the null terminator + return string(buffer[:length-1]), nil + } // Make a bigger buffer if needed + buffer = make([]byte, length) + } + } // Keyctl commands with special signatures. // KeyctlGetKeyringID implements the KEYCTL_GET_KEYRING_ID command. + // See the full documentation at: + // http://man7.org/linux/man-pages/man3/keyctl_get_keyring_ID.3.html + func KeyctlGetKeyringID(id int, create bool) (ringid int, err error) { + createInt := 0 + if create { + createInt = 1 + } + return KeyctlInt(KEYCTL_GET_KEYRING_ID, id, createInt, 0, 0) + } // KeyctlSetperm implements the KEYCTL_SETPERM command. The perm value is the + // key handle permission mask as described in the "keyctl setperm" section of + // http://man7.org/linux/man-pages/man1/keyctl.1.html. + // See the full documentation at: + // http://man7.org/linux/man-pages/man3/keyctl_setperm.3.html + func KeyctlSetperm(id int, perm uint32) error { + _, err := KeyctlInt(KEYCTL_SETPERM, id, int(perm), 0, 0) + return err + } //sys keyctlJoin(cmd int, arg2 string) (ret int, err error) = SYS_KEYCTL // KeyctlJoinSessionKeyring implements the KEYCTL_JOIN_SESSION_KEYRING command. + // See the full documentation at: + // http://man7.org/linux/man-pages/man3/keyctl_join_session_keyring.3.html + func KeyctlJoinSessionKeyring(name string) (ringid int, err error) { + return keyctlJoin(KEYCTL_JOIN_SESSION_KEYRING, name) + } //sys keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) = SYS_KEYCTL // KeyctlSearch implements the KEYCTL_SEARCH command. + // See the full documentation at: + // http://man7.org/linux/man-pages/man3/keyctl_search.3.html + func KeyctlSearch(ringid int, keyType, description string, destRingid int) (id int, err error) { + return keyctlSearch(KEYCTL_SEARCH, ringid, keyType, description, destRingid) + } //sys keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) = SYS_KEYCTL // KeyctlInstantiateIOV implements the KEYCTL_INSTANTIATE_IOV command. This + // command is similar to KEYCTL_INSTANTIATE, except that the payload is a slice + // of Iovec (each of which represents a buffer) instead of a single buffer. + // See the full documentation at: + // http://man7.org/linux/man-pages/man3/keyctl_instantiate_iov.3.html + func KeyctlInstantiateIOV(id int, payload []Iovec, ringid int) error { + return keyctlIOV(KEYCTL_INSTANTIATE_IOV, id, payload, ringid) + } //sys keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) = SYS_KEYCTL // KeyctlDHCompute implements the KEYCTL_DH_COMPUTE command. This command + // computes a Diffie-Hellman shared secret based on the provide params. The + // secret is written to the provided buffer and the returned size is the number + // of bytes written (returning an error if there is insufficient space in the + // buffer). If a nil buffer is passed in, this function returns the minimum + // buffer length needed to store the appropriate data. Note that this differs + // from KEYCTL_READ's behavior which always returns the requested payload size. + // See the full documentation at: + // http://man7.org/linux/man-pages/man3/keyctl_dh_compute.3.html + func KeyctlDHCompute(params *KeyctlDHParams, buffer []byte) (size int, err error) { + return keyctlDH(KEYCTL_DH_COMPUTE, params, buffer) + } // KeyctlRestrictKeyring implements the KEYCTL_RESTRICT_KEYRING command. This + // command limits the set of keys that can be linked to the keyring, regardless + // of keyring permissions. The command requires the "setattr" permission. + // + // When called with an empty keyType the command locks the keyring, preventing + // any further keys from being linked to the keyring. + // + // The "asymmetric" keyType defines restrictions requiring key payloads to be + // DER encoded X.509 certificates signed by keys in another keyring. Restrictions + // for "asymmetric" include "builtin_trusted", "builtin_and_secondary_trusted", + // "key_or_keyring:", and "key_or_keyring::chain". + // + // As of Linux 4.12, only the "asymmetric" keyType defines type-specific + // restrictions. + // + // See the full documentation at: + // http://man7.org/linux/man-pages/man3/keyctl_restrict_keyring.3.html + // http://man7.org/linux/man-pages/man2/keyctl.2.html + func KeyctlRestrictKeyring(ringid int, keyType string, restriction string) error { + if keyType == "" { + return keyctlRestrictKeyring(KEYCTL_RESTRICT_KEYRING, ringid) + } + return keyctlRestrictKeyringByType(KEYCTL_RESTRICT_KEYRING, ringid, keyType, restriction) + } //sys keyctlRestrictKeyringByType(cmd int, arg2 int, keyType string, restriction string) (err error) = SYS_KEYCTL + //sys keyctlRestrictKeyring(cmd int, arg2 int) (err error) = SYS_KEYCTL func recvmsgRaw(fd int, iov []Iovec, oob []byte, flags int, rsa *RawSockaddrAny) (n, oobn int, recvflags int, err error) { + var msg Msghdr + msg.Name = (*byte)(unsafe.Pointer(rsa)) + msg.Namelen = uint32(SizeofSockaddrAny) + var dummy byte + if len(oob) > 0 { + if emptyIovecs(iov) { + var sockType int + sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE) + if err != nil { + return + } + // receive at least one normal byte + if sockType != SOCK_DGRAM { + var iova [1]Iovec + iova[0].Base = &dummy + iova[0].SetLen(1) + iov = iova[:] + } + } + msg.Control = &oob[0] + msg.SetControllen(len(oob)) + } + if len(iov) > 0 { + msg.Iov = &iov[0] + msg.SetIovlen(len(iov)) + } + if n, err = recvmsg(fd, &msg, flags); err != nil { + return + } + oobn = int(msg.Controllen) + recvflags = int(msg.Flags) + return + } func sendmsgN(fd int, iov []Iovec, oob []byte, ptr unsafe.Pointer, salen _Socklen, flags int) (n int, err error) { + var msg Msghdr + msg.Name = (*byte)(ptr) + msg.Namelen = uint32(salen) + var dummy byte + var empty bool + if len(oob) > 0 { + empty = emptyIovecs(iov) + if empty { + var sockType int + sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE) + if err != nil { + return 0, err + } + // send at least one normal byte + if sockType != SOCK_DGRAM { + var iova [1]Iovec + iova[0].Base = &dummy + iova[0].SetLen(1) + iov = iova[:] + } + } + msg.Control = &oob[0] + msg.SetControllen(len(oob)) + } + if len(iov) > 0 { + msg.Iov = &iov[0] + msg.SetIovlen(len(iov)) + } + if n, err = sendmsg(fd, &msg, flags); err != nil { + return 0, err + } + if len(oob) > 0 && empty { + n = 0 + } + return n, nil + } // BindToDevice binds the socket associated with fd to device. + func BindToDevice(fd int, device string) (err error) { + return SetsockoptString(fd, SOL_SOCKET, SO_BINDTODEVICE, device) + } //sys ptrace(request int, pid int, addr uintptr, data uintptr) (err error) + //sys ptracePtr(request int, pid int, addr uintptr, data unsafe.Pointer) (err error) = SYS_PTRACE func ptracePeek(req int, pid int, addr uintptr, out []byte) (count int, err error) { + // The peek requests are machine-size oriented, so we wrap it + // to retrieve arbitrary-length data. // The ptrace syscall differs from glibc's ptrace. + // Peeks returns the word in *data, not as the return value. var buf [SizeofPtr]byte // Leading edge. PEEKTEXT/PEEKDATA don't require aligned + // access (PEEKUSER warns that it might), but if we don't + // align our reads, we might straddle an unmapped page + // boundary and not get the bytes leading up to the page + // boundary. + n := 0 + if addr%SizeofPtr != 0 { + err = ptracePtr(req, pid, addr-addr%SizeofPtr, unsafe.Pointer(&buf[0])) + if err != nil { + return 0, err + } + n += copy(out, buf[addr%SizeofPtr:]) + out = out[n:] + } // Remainder. + for len(out) > 0 { + // We use an internal buffer to guarantee alignment. + // It's not documented if this is necessary, but we're paranoid. + err = ptracePtr(req, pid, addr+uintptr(n), unsafe.Pointer(&buf[0])) + if err != nil { + return n, err + } + copied := copy(out, buf[0:]) + n += copied + out = out[copied:] + } return n, nil + } func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error) { + return ptracePeek(PTRACE_PEEKTEXT, pid, addr, out) + } func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error) { + return ptracePeek(PTRACE_PEEKDATA, pid, addr, out) + } func PtracePeekUser(pid int, addr uintptr, out []byte) (count int, err error) { + return ptracePeek(PTRACE_PEEKUSR, pid, addr, out) + } func ptracePoke(pokeReq int, peekReq int, pid int, addr uintptr, data []byte) (count int, err error) { + // As for ptracePeek, we need to align our accesses to deal + // with the possibility of straddling an invalid page. // Leading edge. + n := 0 + if addr%SizeofPtr != 0 { + var buf [SizeofPtr]byte + err = ptracePtr(peekReq, pid, addr-addr%SizeofPtr, unsafe.Pointer(&buf[0])) + if err != nil { + return 0, err + } + n += copy(buf[addr%SizeofPtr:], data) + word := *((*uintptr)(unsafe.Pointer(&buf[0]))) + err = ptrace(pokeReq, pid, addr-addr%SizeofPtr, word) + if err != nil { + return 0, err + } + data = data[n:] + } // Interior. + for len(data) > SizeofPtr { + word := *((*uintptr)(unsafe.Pointer(&data[0]))) + err = ptrace(pokeReq, pid, addr+uintptr(n), word) + if err != nil { + return n, err + } + n += SizeofPtr + data = data[SizeofPtr:] + } // Trailing edge. + if len(data) > 0 { + var buf [SizeofPtr]byte + err = ptracePtr(peekReq, pid, addr+uintptr(n), unsafe.Pointer(&buf[0])) + if err != nil { + return n, err + } + copy(buf[0:], data) + word := *((*uintptr)(unsafe.Pointer(&buf[0]))) + err = ptrace(pokeReq, pid, addr+uintptr(n), word) + if err != nil { + return n, err + } + n += len(data) + } return n, nil + } func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error) { + return ptracePoke(PTRACE_POKETEXT, PTRACE_PEEKTEXT, pid, addr, data) + } func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error) { + return ptracePoke(PTRACE_POKEDATA, PTRACE_PEEKDATA, pid, addr, data) + } func PtracePokeUser(pid int, addr uintptr, data []byte) (count int, err error) { + return ptracePoke(PTRACE_POKEUSR, PTRACE_PEEKUSR, pid, addr, data) + } // elfNT_PRSTATUS is a copy of the debug/elf.NT_PRSTATUS constant so + // x/sys/unix doesn't need to depend on debug/elf and thus + // compress/zlib, debug/dwarf, and other packages. + const elfNT_PRSTATUS = 1 func PtraceGetRegs(pid int, regsout *PtraceRegs) (err error) { + var iov Iovec + iov.Base = (*byte)(unsafe.Pointer(regsout)) + iov.SetLen(int(unsafe.Sizeof(*regsout))) + return ptracePtr(PTRACE_GETREGSET, pid, uintptr(elfNT_PRSTATUS), unsafe.Pointer(&iov)) + } func PtraceSetRegs(pid int, regs *PtraceRegs) (err error) { + var iov Iovec + iov.Base = (*byte)(unsafe.Pointer(regs)) + iov.SetLen(int(unsafe.Sizeof(*regs))) + return ptracePtr(PTRACE_SETREGSET, pid, uintptr(elfNT_PRSTATUS), unsafe.Pointer(&iov)) + } func PtraceSetOptions(pid int, options int) (err error) { + return ptrace(PTRACE_SETOPTIONS, pid, 0, uintptr(options)) + } func PtraceGetEventMsg(pid int) (msg uint, err error) { + var data _C_long + err = ptracePtr(PTRACE_GETEVENTMSG, pid, 0, unsafe.Pointer(&data)) + msg = uint(data) + return + } func PtraceCont(pid int, signal int) (err error) { + return ptrace(PTRACE_CONT, pid, 0, uintptr(signal)) + } func PtraceSyscall(pid int, signal int) (err error) { + return ptrace(PTRACE_SYSCALL, pid, 0, uintptr(signal)) + } func PtraceSingleStep(pid int) (err error) { return ptrace(PTRACE_SINGLESTEP, pid, 0, 0) } @@ -1750,845 +3015,1461 @@ func PtraceDetach(pid int) (err error) { return ptrace(PTRACE_DETACH, pid, 0, 0) //sys reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) func Reboot(cmd int) (err error) { + return reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, cmd, "") + } func direntIno(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino)) + } func direntReclen(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) + } func direntNamlen(buf []byte) (uint64, bool) { + reclen, ok := direntReclen(buf) + if !ok { + return 0, false + } + return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true + } //sys mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) func Mount(source string, target string, fstype string, flags uintptr, data string) (err error) { + // Certain file systems get rather angry and EINVAL if you give + // them an empty string of data, rather than NULL. + if data == "" { + return mount(source, target, fstype, flags, nil) + } + datap, err := BytePtrFromString(data) + if err != nil { + return err + } + return mount(source, target, fstype, flags, datap) + } //sys mountSetattr(dirfd int, pathname string, flags uint, attr *MountAttr, size uintptr) (err error) = SYS_MOUNT_SETATTR // MountSetattr is a wrapper for mount_setattr(2). + // https://man7.org/linux/man-pages/man2/mount_setattr.2.html + // + // Requires kernel >= 5.12. + func MountSetattr(dirfd int, pathname string, flags uint, attr *MountAttr) error { + return mountSetattr(dirfd, pathname, flags, attr, unsafe.Sizeof(*attr)) + } func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + if raceenabled { + raceReleaseMerge(unsafe.Pointer(&ioSync)) + } + return sendfile(outfd, infd, offset, count) + } // Sendto + // Recvfrom + // Socketpair /* + * Direct access + */ + //sys Acct(path string) (err error) + //sys AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) + //sys Adjtimex(buf *Timex) (state int, err error) + //sysnb Capget(hdr *CapUserHeader, data *CapUserData) (err error) + //sysnb Capset(hdr *CapUserHeader, data *CapUserData) (err error) + //sys Chdir(path string) (err error) + //sys Chroot(path string) (err error) + //sys ClockAdjtime(clockid int32, buf *Timex) (state int, err error) + //sys ClockGetres(clockid int32, res *Timespec) (err error) + //sys ClockGettime(clockid int32, time *Timespec) (err error) + //sys ClockNanosleep(clockid int32, flags int, request *Timespec, remain *Timespec) (err error) + //sys Close(fd int) (err error) + //sys CloseRange(first uint, last uint, flags uint) (err error) + //sys CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) + //sys DeleteModule(name string, flags int) (err error) + //sys Dup(oldfd int) (fd int, err error) func Dup2(oldfd, newfd int) error { + return Dup3(oldfd, newfd, 0) + } //sys Dup3(oldfd int, newfd int, flags int) (err error) + //sysnb EpollCreate1(flag int) (fd int, err error) + //sysnb EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) + //sys Eventfd(initval uint, flags int) (fd int, err error) = SYS_EVENTFD2 + //sys Exit(code int) = SYS_EXIT_GROUP + //sys Fallocate(fd int, mode uint32, off int64, len int64) (err error) + //sys Fchdir(fd int) (err error) + //sys Fchmod(fd int, mode uint32) (err error) + //sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) + //sys Fdatasync(fd int) (err error) + //sys Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) + //sys FinitModule(fd int, params string, flags int) (err error) + //sys Flistxattr(fd int, dest []byte) (sz int, err error) + //sys Flock(fd int, how int) (err error) + //sys Fremovexattr(fd int, attr string) (err error) + //sys Fsetxattr(fd int, attr string, dest []byte, flags int) (err error) + //sys Fsync(fd int) (err error) + //sys Fsmount(fd int, flags int, mountAttrs int) (fsfd int, err error) + //sys Fsopen(fsName string, flags int) (fd int, err error) + //sys Fspick(dirfd int, pathName string, flags int) (fd int, err error) //sys fsconfig(fd int, cmd uint, key *byte, value *byte, aux int) (err error) func fsconfigCommon(fd int, cmd uint, key string, value *byte, aux int) (err error) { + var keyp *byte + if keyp, err = BytePtrFromString(key); err != nil { + return + } + return fsconfig(fd, cmd, keyp, value, aux) + } // FsconfigSetFlag is equivalent to fsconfig(2) called + // with cmd == FSCONFIG_SET_FLAG. + // + // fd is the filesystem context to act upon. + // key the parameter key to set. + func FsconfigSetFlag(fd int, key string) (err error) { + return fsconfigCommon(fd, FSCONFIG_SET_FLAG, key, nil, 0) + } // FsconfigSetString is equivalent to fsconfig(2) called + // with cmd == FSCONFIG_SET_STRING. + // + // fd is the filesystem context to act upon. + // key the parameter key to set. + // value is the parameter value to set. + func FsconfigSetString(fd int, key string, value string) (err error) { + var valuep *byte + if valuep, err = BytePtrFromString(value); err != nil { + return + } + return fsconfigCommon(fd, FSCONFIG_SET_STRING, key, valuep, 0) + } // FsconfigSetBinary is equivalent to fsconfig(2) called + // with cmd == FSCONFIG_SET_BINARY. + // + // fd is the filesystem context to act upon. + // key the parameter key to set. + // value is the parameter value to set. + func FsconfigSetBinary(fd int, key string, value []byte) (err error) { + if len(value) == 0 { + return EINVAL + } + return fsconfigCommon(fd, FSCONFIG_SET_BINARY, key, &value[0], len(value)) + } // FsconfigSetPath is equivalent to fsconfig(2) called + // with cmd == FSCONFIG_SET_PATH. + // + // fd is the filesystem context to act upon. + // key the parameter key to set. + // path is a non-empty path for specified key. + // atfd is a file descriptor at which to start lookup from or AT_FDCWD. + func FsconfigSetPath(fd int, key string, path string, atfd int) (err error) { + var valuep *byte + if valuep, err = BytePtrFromString(path); err != nil { + return + } + return fsconfigCommon(fd, FSCONFIG_SET_PATH, key, valuep, atfd) + } // FsconfigSetPathEmpty is equivalent to fsconfig(2) called + // with cmd == FSCONFIG_SET_PATH_EMPTY. The same as + // FconfigSetPath but with AT_PATH_EMPTY implied. + func FsconfigSetPathEmpty(fd int, key string, path string, atfd int) (err error) { + var valuep *byte + if valuep, err = BytePtrFromString(path); err != nil { + return + } + return fsconfigCommon(fd, FSCONFIG_SET_PATH_EMPTY, key, valuep, atfd) + } // FsconfigSetFd is equivalent to fsconfig(2) called + // with cmd == FSCONFIG_SET_FD. + // + // fd is the filesystem context to act upon. + // key the parameter key to set. + // value is a file descriptor to be assigned to specified key. + func FsconfigSetFd(fd int, key string, value int) (err error) { + return fsconfigCommon(fd, FSCONFIG_SET_FD, key, nil, value) + } // FsconfigCreate is equivalent to fsconfig(2) called + // with cmd == FSCONFIG_CMD_CREATE. + // + // fd is the filesystem context to act upon. + func FsconfigCreate(fd int) (err error) { + return fsconfig(fd, FSCONFIG_CMD_CREATE, nil, nil, 0) + } // FsconfigReconfigure is equivalent to fsconfig(2) called + // with cmd == FSCONFIG_CMD_RECONFIGURE. + // + // fd is the filesystem context to act upon. + func FsconfigReconfigure(fd int) (err error) { + return fsconfig(fd, FSCONFIG_CMD_RECONFIGURE, nil, nil, 0) + } //sys Getdents(fd int, buf []byte) (n int, err error) = SYS_GETDENTS64 + //sysnb Getpgid(pid int) (pgid int, err error) func Getpgrp() (pid int) { + pid, _ = Getpgid(0) + return + } //sysnb Getpid() (pid int) + //sysnb Getppid() (ppid int) + //sys Getpriority(which int, who int) (prio int, err error) + //sys Getrandom(buf []byte, flags int) (n int, err error) + //sysnb Getrusage(who int, rusage *Rusage) (err error) + //sysnb Getsid(pid int) (sid int, err error) + //sysnb Gettid() (tid int) + //sys Getxattr(path string, attr string, dest []byte) (sz int, err error) + //sys InitModule(moduleImage []byte, params string) (err error) + //sys InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) + //sysnb InotifyInit1(flags int) (fd int, err error) + //sysnb InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) + //sysnb Kill(pid int, sig syscall.Signal) (err error) + //sys Klogctl(typ int, buf []byte) (n int, err error) = SYS_SYSLOG + //sys Lgetxattr(path string, attr string, dest []byte) (sz int, err error) + //sys Listxattr(path string, dest []byte) (sz int, err error) + //sys Llistxattr(path string, dest []byte) (sz int, err error) + //sys Lremovexattr(path string, attr string) (err error) + //sys Lsetxattr(path string, attr string, data []byte, flags int) (err error) + //sys MemfdCreate(name string, flags int) (fd int, err error) + //sys Mkdirat(dirfd int, path string, mode uint32) (err error) + //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error) + //sys MoveMount(fromDirfd int, fromPathName string, toDirfd int, toPathName string, flags int) (err error) + //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) + //sys OpenTree(dfd int, fileName string, flags uint) (r int, err error) + //sys PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error) + //sys PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT + //sys Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) + //sys pselect6(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *sigset_argpack) (n int, err error) + //sys read(fd int, p []byte) (n int, err error) + //sys Removexattr(path string, attr string) (err error) + //sys Renameat2(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error) + //sys RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) + //sys Setdomainname(p []byte) (err error) + //sys Sethostname(p []byte) (err error) + //sysnb Setpgid(pid int, pgid int) (err error) + //sysnb Setsid() (pid int, err error) + //sysnb Settimeofday(tv *Timeval) (err error) + //sys Setns(fd int, nstype int) (err error) //go:linkname syscall_prlimit syscall.prlimit + func syscall_prlimit(pid, resource int, newlimit, old *syscall.Rlimit) error func Prlimit(pid, resource int, newlimit, old *Rlimit) error { + // Just call the syscall version, because as of Go 1.21 + // it will affect starting a new process. + return syscall_prlimit(pid, resource, (*syscall.Rlimit)(newlimit), (*syscall.Rlimit)(old)) + } // PrctlRetInt performs a prctl operation specified by option and further + // optional arguments arg2 through arg5 depending on option. It returns a + // non-negative integer that is returned by the prctl syscall. + func PrctlRetInt(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (int, error) { + ret, _, err := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) + if err != 0 { + return 0, err + } + return int(ret), nil + } func Setuid(uid int) (err error) { + return syscall.Setuid(uid) + } func Setgid(gid int) (err error) { + return syscall.Setgid(gid) + } func Setreuid(ruid, euid int) (err error) { + return syscall.Setreuid(ruid, euid) + } func Setregid(rgid, egid int) (err error) { + return syscall.Setregid(rgid, egid) + } func Setresuid(ruid, euid, suid int) (err error) { + return syscall.Setresuid(ruid, euid, suid) + } func Setresgid(rgid, egid, sgid int) (err error) { + return syscall.Setresgid(rgid, egid, sgid) + } // SetfsgidRetGid sets fsgid for current thread and returns previous fsgid set. + // setfsgid(2) will return a non-nil error only if its caller lacks CAP_SETUID capability. + // If the call fails due to other reasons, current fsgid will be returned. + func SetfsgidRetGid(gid int) (int, error) { + return setfsgid(gid) + } // SetfsuidRetUid sets fsuid for current thread and returns previous fsuid set. + // setfsgid(2) will return a non-nil error only if its caller lacks CAP_SETUID capability + // If the call fails due to other reasons, current fsuid will be returned. + func SetfsuidRetUid(uid int) (int, error) { + return setfsuid(uid) + } func Setfsgid(gid int) error { + _, err := setfsgid(gid) + return err + } func Setfsuid(uid int) error { + _, err := setfsuid(uid) + return err + } func Signalfd(fd int, sigmask *Sigset_t, flags int) (newfd int, err error) { + return signalfd(fd, sigmask, _C__NSIG/8, flags) + } //sys Setpriority(which int, who int, prio int) (err error) + //sys Setxattr(path string, attr string, data []byte, flags int) (err error) + //sys signalfd(fd int, sigmask *Sigset_t, maskSize uintptr, flags int) (newfd int, err error) = SYS_SIGNALFD4 + //sys Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error) + //sys Sync() + //sys Syncfs(fd int) (err error) + //sysnb Sysinfo(info *Sysinfo_t) (err error) + //sys Tee(rfd int, wfd int, len int, flags int) (n int64, err error) + //sysnb TimerfdCreate(clockid int, flags int) (fd int, err error) + //sysnb TimerfdGettime(fd int, currValue *ItimerSpec) (err error) + //sysnb TimerfdSettime(fd int, flags int, newValue *ItimerSpec, oldValue *ItimerSpec) (err error) + //sysnb Tgkill(tgid int, tid int, sig syscall.Signal) (err error) + //sysnb Times(tms *Tms) (ticks uintptr, err error) + //sysnb Umask(mask int) (oldmask int) + //sysnb Uname(buf *Utsname) (err error) + //sys Unmount(target string, flags int) (err error) = SYS_UMOUNT2 + //sys Unshare(flags int) (err error) + //sys write(fd int, p []byte) (n int, err error) + //sys exitThread(code int) (err error) = SYS_EXIT + //sys readv(fd int, iovs []Iovec) (n int, err error) = SYS_READV + //sys writev(fd int, iovs []Iovec) (n int, err error) = SYS_WRITEV + //sys preadv(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr) (n int, err error) = SYS_PREADV + //sys pwritev(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr) (n int, err error) = SYS_PWRITEV + //sys preadv2(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr, flags int) (n int, err error) = SYS_PREADV2 + //sys pwritev2(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr, flags int) (n int, err error) = SYS_PWRITEV2 // minIovec is the size of the small initial allocation used by + // Readv, Writev, etc. + // + // This small allocation gets stack allocated, which lets the + // common use case of len(iovs) <= minIovs avoid more expensive + // heap allocations. + const minIovec = 8 // appendBytes converts bs to Iovecs and appends them to vecs. + func appendBytes(vecs []Iovec, bs [][]byte) []Iovec { + for _, b := range bs { + var v Iovec + v.SetLen(len(b)) + if len(b) > 0 { + v.Base = &b[0] + } else { + v.Base = (*byte)(unsafe.Pointer(&_zero)) + } + vecs = append(vecs, v) + } + return vecs + } // offs2lohi splits offs into its low and high order bits. + func offs2lohi(offs int64) (lo, hi uintptr) { + const longBits = SizeofLong * 8 + return uintptr(offs), uintptr(uint64(offs) >> (longBits - 1) >> 1) // two shifts to avoid false positive in vet + } func Readv(fd int, iovs [][]byte) (n int, err error) { + iovecs := make([]Iovec, 0, minIovec) + iovecs = appendBytes(iovecs, iovs) + n, err = readv(fd, iovecs) + readvRacedetect(iovecs, n, err) + return n, err + } func Preadv(fd int, iovs [][]byte, offset int64) (n int, err error) { + iovecs := make([]Iovec, 0, minIovec) + iovecs = appendBytes(iovecs, iovs) + lo, hi := offs2lohi(offset) + n, err = preadv(fd, iovecs, lo, hi) + readvRacedetect(iovecs, n, err) + return n, err + } func Preadv2(fd int, iovs [][]byte, offset int64, flags int) (n int, err error) { + iovecs := make([]Iovec, 0, minIovec) + iovecs = appendBytes(iovecs, iovs) + lo, hi := offs2lohi(offset) + n, err = preadv2(fd, iovecs, lo, hi, flags) + readvRacedetect(iovecs, n, err) + return n, err + } func readvRacedetect(iovecs []Iovec, n int, err error) { + if !raceenabled { + return + } + for i := 0; n > 0 && i < len(iovecs); i++ { + m := int(iovecs[i].Len) + if m > n { + m = n + } + n -= m + if m > 0 { + raceWriteRange(unsafe.Pointer(iovecs[i].Base), m) + } + } + if err == nil { + raceAcquire(unsafe.Pointer(&ioSync)) + } + } func Writev(fd int, iovs [][]byte) (n int, err error) { + iovecs := make([]Iovec, 0, minIovec) + iovecs = appendBytes(iovecs, iovs) + if raceenabled { + raceReleaseMerge(unsafe.Pointer(&ioSync)) + } + n, err = writev(fd, iovecs) + writevRacedetect(iovecs, n) + return n, err + } func Pwritev(fd int, iovs [][]byte, offset int64) (n int, err error) { + iovecs := make([]Iovec, 0, minIovec) + iovecs = appendBytes(iovecs, iovs) + if raceenabled { + raceReleaseMerge(unsafe.Pointer(&ioSync)) + } + lo, hi := offs2lohi(offset) + n, err = pwritev(fd, iovecs, lo, hi) + writevRacedetect(iovecs, n) + return n, err + } func Pwritev2(fd int, iovs [][]byte, offset int64, flags int) (n int, err error) { + iovecs := make([]Iovec, 0, minIovec) + iovecs = appendBytes(iovecs, iovs) + if raceenabled { + raceReleaseMerge(unsafe.Pointer(&ioSync)) + } + lo, hi := offs2lohi(offset) + n, err = pwritev2(fd, iovecs, lo, hi, flags) + writevRacedetect(iovecs, n) + return n, err + } func writevRacedetect(iovecs []Iovec, n int) { + if !raceenabled { + return + } + for i := 0; n > 0 && i < len(iovecs); i++ { + m := int(iovecs[i].Len) + if m > n { + m = n + } + n -= m + if m > 0 { + raceReadRange(unsafe.Pointer(iovecs[i].Base), m) + } + } + } // mmap varies by architecture; see syscall_linux_*.go. + //sys munmap(addr uintptr, length uintptr) (err error) + //sys mremap(oldaddr uintptr, oldlength uintptr, newlength uintptr, flags int, newaddr uintptr) (xaddr uintptr, err error) + //sys Madvise(b []byte, advice int) (err error) + //sys Mprotect(b []byte, prot int) (err error) + //sys Mlock(b []byte) (err error) + //sys Mlockall(flags int) (err error) + //sys Msync(b []byte, flags int) (err error) + //sys Munlock(b []byte) (err error) + //sys Munlockall() (err error) const ( - mremapFixed = MREMAP_FIXED + mremapFixed = MREMAP_FIXED + mremapDontunmap = MREMAP_DONTUNMAP - mremapMaymove = MREMAP_MAYMOVE + + mremapMaymove = MREMAP_MAYMOVE ) // Vmsplice splices user pages from a slice of Iovecs into a pipe specified by fd, + // using the specified flags. + func Vmsplice(fd int, iovs []Iovec, flags int) (int, error) { + var p unsafe.Pointer + if len(iovs) > 0 { + p = unsafe.Pointer(&iovs[0]) + } n, _, errno := Syscall6(SYS_VMSPLICE, uintptr(fd), uintptr(p), uintptr(len(iovs)), uintptr(flags), 0, 0) + if errno != 0 { + return 0, syscall.Errno(errno) + } return int(n), nil + } func isGroupMember(gid int) bool { + groups, err := Getgroups() + if err != nil { + return false + } for _, g := range groups { + if g == gid { + return true + } + } + return false + } func isCapDacOverrideSet() bool { + hdr := CapUserHeader{Version: LINUX_CAPABILITY_VERSION_3} + data := [2]CapUserData{} + err := Capget(&hdr, &data[0]) return err == nil && data[0].Effective&(1<> 6) & 7 + } else { + var gid int + if flags&AT_EACCESS != 0 { + gid = Getegid() + } else { + gid = Getgid() + } if uint32(gid) == st.Gid || isGroupMember(int(st.Gid)) { + fmode = (st.Mode >> 3) & 7 + } else { + fmode = st.Mode & 7 + } + } if fmode&mode == mode { + return nil + } return EACCES + } //sys nameToHandleAt(dirFD int, pathname string, fh *fileHandle, mountID *_C_int, flags int) (err error) = SYS_NAME_TO_HANDLE_AT + //sys openByHandleAt(mountFD int, fh *fileHandle, flags int) (fd int, err error) = SYS_OPEN_BY_HANDLE_AT // fileHandle is the argument to nameToHandleAt and openByHandleAt. We + // originally tried to generate it via unix/linux/types.go with "type + // fileHandle C.struct_file_handle" but that generated empty structs + // for mips64 and mips64le. Instead, hard code it for now (it's the + // same everywhere else) until the mips64 generator issue is fixed. + type fileHandle struct { Bytes uint32 - Type int32 + + Type int32 } // FileHandle represents the C struct file_handle used by + // name_to_handle_at (see NameToHandleAt) and open_by_handle_at (see + // OpenByHandleAt). + type FileHandle struct { *fileHandle } // NewFileHandle constructs a FileHandle. + func NewFileHandle(handleType int32, handle []byte) FileHandle { + const hdrSize = unsafe.Sizeof(fileHandle{}) + buf := make([]byte, hdrSize+uintptr(len(handle))) + copy(buf[hdrSize:], handle) + fh := (*fileHandle)(unsafe.Pointer(&buf[0])) + fh.Type = handleType + fh.Bytes = uint32(len(handle)) + return FileHandle{fh} + } -func (fh *FileHandle) Size() int { return int(fh.fileHandle.Bytes) } +func (fh *FileHandle) Size() int { return int(fh.fileHandle.Bytes) } + func (fh *FileHandle) Type() int32 { return fh.fileHandle.Type } + func (fh *FileHandle) Bytes() []byte { + n := fh.Size() + if n == 0 { + return nil + } + return unsafe.Slice((*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(&fh.fileHandle.Type))+4)), n) + } // NameToHandleAt wraps the name_to_handle_at system call; it obtains + // a handle for a path name. + func NameToHandleAt(dirfd int, path string, flags int) (handle FileHandle, mountID int, err error) { + var mid _C_int + // Try first with a small buffer, assuming the handle will + // only be 32 bytes. + size := uint32(32 + unsafe.Sizeof(fileHandle{})) + didResize := false + for { + buf := make([]byte, size) + fh := (*fileHandle)(unsafe.Pointer(&buf[0])) + fh.Bytes = size - uint32(unsafe.Sizeof(fileHandle{})) + err = nameToHandleAt(dirfd, path, fh, &mid, flags) + if err == EOVERFLOW { + if didResize { + // We shouldn't need to resize more than once + return + } + didResize = true + size = fh.Bytes + uint32(unsafe.Sizeof(fileHandle{})) + continue + } + if err != nil { + return + } + return FileHandle{fh}, int(mid), nil + } + } // OpenByHandleAt wraps the open_by_handle_at system call; it opens a + // file via a handle as previously returned by NameToHandleAt. + func OpenByHandleAt(mountFD int, handle FileHandle, flags int) (fd int, err error) { + return openByHandleAt(mountFD, handle.fileHandle, flags) + } // Klogset wraps the sys_syslog system call; it sets console_loglevel to + // the value specified by arg and passes a dummy pointer to bufp. + func Klogset(typ int, arg int) (err error) { + var p unsafe.Pointer + _, _, errno := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(p), uintptr(arg)) + if errno != 0 { + return errnoErr(errno) + } + return nil + } // RemoteIovec is Iovec with the pointer replaced with an integer. + // It is used for ProcessVMReadv and ProcessVMWritev, where the pointer + // refers to a location in a different process' address space, which + // would confuse the Go garbage collector. + type RemoteIovec struct { Base uintptr - Len int + + Len int } //sys ProcessVMReadv(pid int, localIov []Iovec, remoteIov []RemoteIovec, flags uint) (n int, err error) = SYS_PROCESS_VM_READV + //sys ProcessVMWritev(pid int, localIov []Iovec, remoteIov []RemoteIovec, flags uint) (n int, err error) = SYS_PROCESS_VM_WRITEV //sys PidfdOpen(pid int, flags int) (fd int, err error) = SYS_PIDFD_OPEN + //sys PidfdGetfd(pidfd int, targetfd int, flags int) (fd int, err error) = SYS_PIDFD_GETFD + //sys PidfdSendSignal(pidfd int, sig Signal, info *Siginfo, flags int) (err error) = SYS_PIDFD_SEND_SIGNAL //sys shmat(id int, addr uintptr, flag int) (ret uintptr, err error) + //sys shmctl(id int, cmd int, buf *SysvShmDesc) (result int, err error) + //sys shmdt(addr uintptr) (err error) + //sys shmget(key int, size int, flag int) (id int, err error) //sys getitimer(which int, currValue *Itimerval) (err error) + //sys setitimer(which int, newValue *Itimerval, oldValue *Itimerval) (err error) // MakeItimerval creates an Itimerval from interval and value durations. + func MakeItimerval(interval, value time.Duration) Itimerval { + return Itimerval{ + Interval: NsecToTimeval(interval.Nanoseconds()), - Value: NsecToTimeval(value.Nanoseconds()), + + Value: NsecToTimeval(value.Nanoseconds()), } + } // A value which may be passed to the which parameter for Getitimer and + // Setitimer. + type ItimerWhich int // Possible which values for Getitimer and Setitimer. + const ( - ItimerReal ItimerWhich = ITIMER_REAL + ItimerReal ItimerWhich = ITIMER_REAL + ItimerVirtual ItimerWhich = ITIMER_VIRTUAL - ItimerProf ItimerWhich = ITIMER_PROF + + ItimerProf ItimerWhich = ITIMER_PROF ) // Getitimer wraps getitimer(2) to return the current value of the timer + // specified by which. + func Getitimer(which ItimerWhich) (Itimerval, error) { + var it Itimerval + if err := getitimer(int(which), &it); err != nil { + return Itimerval{}, err + } return it, nil + } // Setitimer wraps setitimer(2) to arm or disarm the timer specified by which. + // It returns the previous value of the timer. + // + // If the Itimerval argument is the zero value, the timer will be disarmed. + func Setitimer(which ItimerWhich, it Itimerval) (Itimerval, error) { + var prev Itimerval + if err := setitimer(int(which), &it, &prev); err != nil { + return Itimerval{}, err + } return prev, nil + } //sysnb rtSigprocmask(how int, set *Sigset_t, oldset *Sigset_t, sigsetsize uintptr) (err error) = SYS_RT_SIGPROCMASK func PthreadSigmask(how int, set, oldset *Sigset_t) error { + if oldset != nil { + // Explicitly clear in case Sigset_t is larger than _C__NSIG. + *oldset = Sigset_t{} + } + return rtSigprocmask(how, set, oldset, _C__NSIG/8) + } //sysnb getresuid(ruid *_C_int, euid *_C_int, suid *_C_int) + //sysnb getresgid(rgid *_C_int, egid *_C_int, sgid *_C_int) func Getresuid() (ruid, euid, suid int) { + var r, e, s _C_int + getresuid(&r, &e, &s) + return int(r), int(e), int(s) + } func Getresgid() (rgid, egid, sgid int) { + var r, e, s _C_int + getresgid(&r, &e, &s) + return int(r), int(e), int(s) + } // Pselect is a wrapper around the Linux pselect6 system call. + // This version does not modify the timeout argument. + func Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { + // Per https://man7.org/linux/man-pages/man2/select.2.html#NOTES, + // The Linux pselect6() system call modifies its timeout argument. + // [Not modifying the argument] is the behavior required by POSIX.1-2001. + var mutableTimeout *Timespec + if timeout != nil { + mutableTimeout = new(Timespec) + *mutableTimeout = *timeout + } // The final argument of the pselect6() system call is not a + // sigset_t * pointer, but is instead a structure + var kernelMask *sigset_argpack + if sigmask != nil { + wordBits := 32 << (^uintptr(0) >> 63) // see math.intSize // A sigset stores one bit per signal, + // offset by 1 (because signal 0 does not exist). + // So the number of words needed is ⌈__C_NSIG - 1 / wordBits⌉. + sigsetWords := (_C__NSIG - 1 + wordBits - 1) / (wordBits) sigsetBytes := uintptr(sigsetWords * (wordBits / 8)) + kernelMask = &sigset_argpack{ - ss: sigmask, + + ss: sigmask, + ssLen: sigsetBytes, } + } return pselect6(nfd, r, w, e, mutableTimeout, kernelMask) + } //sys schedSetattr(pid int, attr *SchedAttr, flags uint) (err error) + //sys schedGetattr(pid int, attr *SchedAttr, size uint, flags uint) (err error) // SchedSetAttr is a wrapper for sched_setattr(2) syscall. + // https://man7.org/linux/man-pages/man2/sched_setattr.2.html + func SchedSetAttr(pid int, attr *SchedAttr, flags uint) error { + if attr == nil { + return EINVAL + } + attr.Size = SizeofSchedAttr + return schedSetattr(pid, attr, flags) + } // SchedGetAttr is a wrapper for sched_getattr(2) syscall. + // https://man7.org/linux/man-pages/man2/sched_getattr.2.html + func SchedGetAttr(pid int, flags uint) (*SchedAttr, error) { + attr := &SchedAttr{} + if err := schedGetattr(pid, attr, SizeofSchedAttr, flags); err != nil { + return nil, err + } + return attr, nil + } //sys Cachestat(fd uint, crange *CachestatRange, cstat *Cachestat_t, flags uint) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_gccgo_386.go b/vendor/golang.org/x/sys/unix/syscall_linux_gccgo_386.go index d1a3ad8..86f8bc9 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_gccgo_386.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_gccgo_386.go @@ -1,5 +1,7 @@ // Copyright 2018 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build linux && gccgo && 386 @@ -12,19 +14,31 @@ import ( ) func seek(fd int, offset int64, whence int) (int64, syscall.Errno) { + var newoffset int64 + offsetLow := uint32(offset & 0xffffffff) + offsetHigh := uint32((offset >> 32) & 0xffffffff) + _, _, err := Syscall6(SYS__LLSEEK, uintptr(fd), uintptr(offsetHigh), uintptr(offsetLow), uintptr(unsafe.Pointer(&newoffset)), uintptr(whence), 0) + return newoffset, err + } func socketcall(call int, a0, a1, a2, a3, a4, a5 uintptr) (int, syscall.Errno) { + fd, _, err := Syscall(SYS_SOCKETCALL, uintptr(call), uintptr(unsafe.Pointer(&a0)), 0) + return int(fd), err + } func rawsocketcall(call int, a0, a1, a2, a3, a4, a5 uintptr) (int, syscall.Errno) { + fd, _, err := RawSyscall(SYS_SOCKETCALL, uintptr(call), uintptr(unsafe.Pointer(&a0)), 0) + return int(fd), err + } diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_gccgo_arm.go b/vendor/golang.org/x/sys/unix/syscall_linux_gccgo_arm.go index f2f6742..8f57407 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_gccgo_arm.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_gccgo_arm.go @@ -1,5 +1,7 @@ // Copyright 2018 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build linux && gccgo && arm @@ -12,9 +14,15 @@ import ( ) func seek(fd int, offset int64, whence int) (int64, syscall.Errno) { + var newoffset int64 + offsetLow := uint32(offset & 0xffffffff) + offsetHigh := uint32((offset >> 32) & 0xffffffff) + _, _, err := Syscall6(SYS__LLSEEK, uintptr(fd), uintptr(offsetHigh), uintptr(offsetLow), uintptr(unsafe.Pointer(&newoffset)), uintptr(whence), 0) + return newoffset, err + } diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go b/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go index c218ebd..f5f50ac 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go @@ -1,5 +1,7 @@ // Copyright 2016 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build linux && (mips || mipsle) @@ -14,139 +16,235 @@ import ( func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) + //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 + //sys Fchown(fd int, uid int, gid int) (err error) + //sys Ftruncate(fd int, length int64) (err error) = SYS_FTRUNCATE64 + //sysnb Getegid() (egid int) + //sysnb Geteuid() (euid int) + //sysnb Getgid() (gid int) + //sysnb Getuid() (uid int) + //sys Lchown(path string, uid int, gid int) (err error) + //sys Listen(s int, n int) (err error) + //sys pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 + //sys pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 + //sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) + //sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS__NEWSELECT + //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64 + //sys setfsgid(gid int) (prev int, err error) + //sys setfsuid(uid int) (prev int, err error) + //sys Shutdown(fd int, how int) (err error) + //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) + //sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) + //sys Truncate(path string, length int64) (err error) = SYS_TRUNCATE64 + //sys Ustat(dev int, ubuf *Ustat_t) (err error) + //sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) + //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) + //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) + //sysnb getgroups(n int, list *_Gid_t) (nn int, err error) + //sysnb setgroups(n int, list *_Gid_t) (err error) + //sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) + //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) + //sysnb socket(domain int, typ int, proto int) (fd int, err error) + //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) + //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) + //sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) + //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) + //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) + //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) + //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys Ioperm(from int, num int, on int) (err error) + //sys Iopl(level int) (err error) //sys futimesat(dirfd int, path string, times *[2]Timeval) (err error) + //sysnb Gettimeofday(tv *Timeval) (err error) + //sysnb Time(t *Time_t) (tt Time_t, err error) + //sys Utime(path string, buf *Utimbuf) (err error) + //sys utimes(path string, times *[2]Timeval) (err error) //sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64 + //sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 + //sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64 + //sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64 //sys Pause() (err error) func Fstatfs(fd int, buf *Statfs_t) (err error) { + _, _, e := Syscall(SYS_FSTATFS64, uintptr(fd), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf))) + if e != 0 { + err = errnoErr(e) + } + return + } func Statfs(path string, buf *Statfs_t) (err error) { + p, err := BytePtrFromString(path) + if err != nil { + return err + } + _, _, e := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(p)), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf))) + if e != 0 { + err = errnoErr(e) + } + return + } func Seek(fd int, offset int64, whence int) (off int64, err error) { + _, _, e := Syscall6(SYS__LLSEEK, uintptr(fd), uintptr(offset>>32), uintptr(offset), uintptr(unsafe.Pointer(&off)), uintptr(whence), 0) + if e != 0 { + err = errnoErr(e) + } + return + } func setTimespec(sec, nsec int64) Timespec { + return Timespec{Sec: int32(sec), Nsec: int32(nsec)} + } func setTimeval(sec, usec int64) Timeval { + return Timeval{Sec: int32(sec), Usec: int32(usec)} + } //sys mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { + page := uintptr(offset / 4096) + if offset != int64(page)*4096 { + return 0, EINVAL + } + return mmap2(addr, length, prot, flags, fd, page) + } const rlimInf32 = ^uint32(0) + const rlimInf64 = ^uint64(0) type rlimit32 struct { Cur uint32 + Max uint32 } //sysnb getrlimit(resource int, rlim *rlimit32) (err error) = SYS_GETRLIMIT func Getrlimit(resource int, rlim *Rlimit) (err error) { + err = Prlimit(0, resource, nil, rlim) + if err != ENOSYS { + return err + } rl := rlimit32{} + err = getrlimit(resource, &rl) + if err != nil { + return + } if rl.Cur == rlimInf32 { + rlim.Cur = rlimInf64 + } else { + rlim.Cur = uint64(rl.Cur) + } if rl.Max == rlimInf32 { + rlim.Max = rlimInf64 + } else { + rlim.Max = uint64(rl.Max) + } + return + } func (r *PtraceRegs) PC() uint64 { return r.Epc } @@ -154,21 +252,31 @@ func (r *PtraceRegs) PC() uint64 { return r.Epc } func (r *PtraceRegs) SetPC(pc uint64) { r.Epc = pc } func (iov *Iovec) SetLen(length int) { + iov.Len = uint32(length) + } func (msghdr *Msghdr) SetControllen(length int) { + msghdr.Controllen = uint32(length) + } func (msghdr *Msghdr) SetIovlen(length int) { + msghdr.Iovlen = uint32(length) + } func (cmsg *Cmsghdr) SetLen(length int) { + cmsg.Len = uint32(length) + } func (rsa *RawSockaddrNFCLLCP) SetServiceNameLen(length int) { + rsa.Service_name_len = uint32(length) + } diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_ppc.go b/vendor/golang.org/x/sys/unix/syscall_linux_ppc.go index e6c4850..7b20bdd 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_ppc.go @@ -1,5 +1,7 @@ // Copyright 2021 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build linux && ppc @@ -12,150 +14,259 @@ import ( ) //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) + //sys Fchown(fd int, uid int, gid int) (err error) + //sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 + //sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64 + //sys Ftruncate(fd int, length int64) (err error) = SYS_FTRUNCATE64 + //sysnb Getegid() (egid int) + //sysnb Geteuid() (euid int) + //sysnb Getgid() (gid int) + //sysnb Getuid() (uid int) + //sys Ioperm(from int, num int, on int) (err error) + //sys Iopl(level int) (err error) + //sys Lchown(path string, uid int, gid int) (err error) + //sys Listen(s int, n int) (err error) + //sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64 + //sys Pause() (err error) + //sys pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 + //sys pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 + //sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) + //sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS__NEWSELECT + //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64 + //sys setfsgid(gid int) (prev int, err error) + //sys setfsuid(uid int) (prev int, err error) + //sys Shutdown(fd int, how int) (err error) + //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) + //sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64 + //sys Truncate(path string, length int64) (err error) = SYS_TRUNCATE64 + //sys Ustat(dev int, ubuf *Ustat_t) (err error) + //sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) + //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) + //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) + //sysnb getgroups(n int, list *_Gid_t) (nn int, err error) + //sysnb setgroups(n int, list *_Gid_t) (err error) + //sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) + //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) + //sysnb socket(domain int, typ int, proto int) (fd int, err error) + //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) + //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) + //sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) + //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) + //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) + //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) + //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys futimesat(dirfd int, path string, times *[2]Timeval) (err error) + //sysnb Gettimeofday(tv *Timeval) (err error) + //sysnb Time(t *Time_t) (tt Time_t, err error) + //sys Utime(path string, buf *Utimbuf) (err error) + //sys utimes(path string, times *[2]Timeval) (err error) func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_FADVISE64_64, uintptr(fd), uintptr(advice), uintptr(offset>>32), uintptr(offset), uintptr(length>>32), uintptr(length)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } func seek(fd int, offset int64, whence int) (int64, syscall.Errno) { + var newoffset int64 + offsetLow := uint32(offset & 0xffffffff) + offsetHigh := uint32((offset >> 32) & 0xffffffff) + _, _, err := Syscall6(SYS__LLSEEK, uintptr(fd), uintptr(offsetHigh), uintptr(offsetLow), uintptr(unsafe.Pointer(&newoffset)), uintptr(whence), 0) + return newoffset, err + } func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + newoffset, errno := seek(fd, offset, whence) + if errno != 0 { + return 0, errno + } + return newoffset, nil + } func Fstatfs(fd int, buf *Statfs_t) (err error) { + _, _, e := Syscall(SYS_FSTATFS64, uintptr(fd), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf))) + if e != 0 { + err = e + } + return + } func Statfs(path string, buf *Statfs_t) (err error) { + pathp, err := BytePtrFromString(path) + if err != nil { + return err + } + _, _, e := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(pathp)), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf))) + if e != 0 { + err = e + } + return + } //sys mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { + page := uintptr(offset / 4096) + if offset != int64(page)*4096 { + return 0, EINVAL + } + return mmap2(addr, length, prot, flags, fd, page) + } func setTimespec(sec, nsec int64) Timespec { + return Timespec{Sec: int32(sec), Nsec: int32(nsec)} + } func setTimeval(sec, usec int64) Timeval { + return Timeval{Sec: int32(sec), Usec: int32(usec)} + } type rlimit32 struct { Cur uint32 + Max uint32 } //sysnb getrlimit(resource int, rlim *rlimit32) (err error) = SYS_UGETRLIMIT const rlimInf32 = ^uint32(0) + const rlimInf64 = ^uint64(0) func Getrlimit(resource int, rlim *Rlimit) (err error) { + err = Prlimit(0, resource, nil, rlim) + if err != ENOSYS { + return err + } rl := rlimit32{} + err = getrlimit(resource, &rl) + if err != nil { + return + } if rl.Cur == rlimInf32 { + rlim.Cur = rlimInf64 + } else { + rlim.Cur = uint64(rl.Cur) + } if rl.Max == rlimInf32 { + rlim.Max = rlimInf64 + } else { + rlim.Max = uint64(rl.Max) + } + return + } func (r *PtraceRegs) PC() uint32 { return r.Nip } @@ -163,42 +274,65 @@ func (r *PtraceRegs) PC() uint32 { return r.Nip } func (r *PtraceRegs) SetPC(pc uint32) { r.Nip = pc } func (iov *Iovec) SetLen(length int) { + iov.Len = uint32(length) + } func (msghdr *Msghdr) SetControllen(length int) { + msghdr.Controllen = uint32(length) + } func (msghdr *Msghdr) SetIovlen(length int) { + msghdr.Iovlen = uint32(length) + } func (cmsg *Cmsghdr) SetLen(length int) { + cmsg.Len = uint32(length) + } func (rsa *RawSockaddrNFCLLCP) SetServiceNameLen(length int) { + rsa.Service_name_len = uint32(length) + } //sys syncFileRange2(fd int, flags int, off int64, n int64) (err error) = SYS_SYNC_FILE_RANGE2 func SyncFileRange(fd int, off int64, n int64, flags int) error { + // The sync_file_range and sync_file_range2 syscalls differ only in the + // order of their arguments. + return syncFileRange2(fd, flags, off, n) + } //sys kexecFileLoad(kernelFd int, initrdFd int, cmdlineLen int, cmdline string, flags int) (err error) func KexecFileLoad(kernelFd int, initrdFd int, cmdline string, flags int) error { + cmdlineLen := len(cmdline) + if cmdlineLen > 0 { + // Account for the additional NULL byte added by + // BytePtrFromString in kexecFileLoad. The kexec_file_load + // syscall expects a NULL-terminated string. + cmdlineLen++ + } + return kexecFileLoad(kernelFd, initrdFd, cmdlineLen, cmdline, flags) + } diff --git a/vendor/golang.org/x/sys/unix/syscall_netbsd.go b/vendor/golang.org/x/sys/unix/syscall_netbsd.go index 8816209..de66d4c 100644 --- a/vendor/golang.org/x/sys/unix/syscall_netbsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_netbsd.go @@ -1,13 +1,21 @@ // Copyright 2009,2010 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // NetBSD system calls. + // This file is compiled as ordinary Go code, + // but it is also input to mksyscall, + // which parses the //sys lines and generates system call stubs. + // Note that sometimes we use a lowercase //sys name and wrap + // it in our own nicer implementation, either here or in + // syscall_bsd.go or syscall_unix.go. package unix @@ -18,354 +26,623 @@ import ( ) // SockaddrDatalink implements the Sockaddr interface for AF_LINK type sockets. + type SockaddrDatalink struct { - Len uint8 + Len uint8 + Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [12]int8 - raw RawSockaddrDatalink + + Index uint16 + + Type uint8 + + Nlen uint8 + + Alen uint8 + + Slen uint8 + + Data [12]int8 + + raw RawSockaddrDatalink } func anyToSockaddrGOOS(fd int, rsa *RawSockaddrAny) (Sockaddr, error) { + return nil, EAFNOSUPPORT + } func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) func sysctlNodes(mib []_C_int) (nodes []Sysctlnode, err error) { + var olen uintptr // Get a list of all sysctl nodes below the given MIB by performing + // a sysctl for the given MIB with CTL_QUERY appended. + mib = append(mib, CTL_QUERY) + qnode := Sysctlnode{Flags: SYSCTL_VERS_1} + qp := (*byte)(unsafe.Pointer(&qnode)) + sz := unsafe.Sizeof(qnode) + if err = sysctl(mib, nil, &olen, qp, sz); err != nil { + return nil, err + } // Now that we know the size, get the actual nodes. + nodes = make([]Sysctlnode, olen/sz) + np := (*byte)(unsafe.Pointer(&nodes[0])) + if err = sysctl(mib, np, &olen, qp, sz); err != nil { + return nil, err + } return nodes, nil + } func nametomib(name string) (mib []_C_int, err error) { + // Split name into components. + var parts []string + last := 0 + for i := 0; i < len(name); i++ { + if name[i] == '.' { + parts = append(parts, name[last:i]) + last = i + 1 + } + } + parts = append(parts, name[last:]) // Discover the nodes and construct the MIB OID. + for partno, part := range parts { + nodes, err := sysctlNodes(mib) + if err != nil { + return nil, err + } + for _, node := range nodes { + n := make([]byte, 0) + for i := range node.Name { + if node.Name[i] != 0 { + n = append(n, byte(node.Name[i])) + } + } + if string(n) == part { + mib = append(mib, _C_int(node.Num)) + break + } + } + if len(mib) != partno+1 { + return nil, EINVAL + } + } return mib, nil + } func direntIno(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Fileno), unsafe.Sizeof(Dirent{}.Fileno)) + } func direntReclen(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) + } func direntNamlen(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen)) + } func SysctlUvmexp(name string) (*Uvmexp, error) { + mib, err := sysctlmib(name) + if err != nil { + return nil, err + } n := uintptr(SizeofUvmexp) + var u Uvmexp + if err := sysctl(mib, (*byte)(unsafe.Pointer(&u)), &n, nil, 0); err != nil { + return nil, err + } + return &u, nil + } func Pipe(p []int) (err error) { + return Pipe2(p, 0) + } //sysnb pipe2(p *[2]_C_int, flags int) (err error) func Pipe2(p []int, flags int) error { + if len(p) != 2 { + return EINVAL + } + var pp [2]_C_int + err := pipe2(&pp, flags) + if err == nil { + p[0] = int(pp[0]) + p[1] = int(pp[1]) + } + return err + } //sys Getdents(fd int, buf []byte) (n int, err error) func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { + n, err = Getdents(fd, buf) + if err != nil || basep == nil { + return + } var off int64 + off, err = Seek(fd, 0, 1 /* SEEK_CUR */) + if err != nil { + *basep = ^uintptr(0) + return + } + *basep = uintptr(off) + if unsafe.Sizeof(*basep) == 8 { + return + } + if off>>32 != 0 { + // We can't stuff the offset back into a uintptr, so any + // future calls would be suspect. Generate an error. + // EIO is allowed by getdirentries. + err = EIO + } + return + } //sys Getcwd(buf []byte) (n int, err error) = SYS___GETCWD // TODO + func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + return -1, ENOSYS + } //sys ioctl(fd int, req uint, arg uintptr) (err error) + //sys ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) = SYS_IOCTL //sys sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) = SYS___SYSCTL func IoctlGetPtmget(fd int, req uint) (*Ptmget, error) { + var value Ptmget + err := ioctlPtr(fd, req, unsafe.Pointer(&value)) + return &value, err + } func Uname(uname *Utsname) error { + mib := []_C_int{CTL_KERN, KERN_OSTYPE} + n := unsafe.Sizeof(uname.Sysname) + if err := sysctl(mib, &uname.Sysname[0], &n, nil, 0); err != nil { + return err + } mib = []_C_int{CTL_KERN, KERN_HOSTNAME} + n = unsafe.Sizeof(uname.Nodename) + if err := sysctl(mib, &uname.Nodename[0], &n, nil, 0); err != nil { + return err + } mib = []_C_int{CTL_KERN, KERN_OSRELEASE} + n = unsafe.Sizeof(uname.Release) + if err := sysctl(mib, &uname.Release[0], &n, nil, 0); err != nil { + return err + } mib = []_C_int{CTL_KERN, KERN_VERSION} + n = unsafe.Sizeof(uname.Version) + if err := sysctl(mib, &uname.Version[0], &n, nil, 0); err != nil { + return err + } // The version might have newlines or tabs in it, convert them to + // spaces. + for i, b := range uname.Version { + if b == '\n' || b == '\t' { + if i == len(uname.Version)-1 { + uname.Version[i] = 0 + } else { + uname.Version[i] = ' ' + } + } + } mib = []_C_int{CTL_HW, HW_MACHINE} + n = unsafe.Sizeof(uname.Machine) + if err := sysctl(mib, &uname.Machine[0], &n, nil, 0); err != nil { + return err + } return nil + } func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + if raceenabled { + raceReleaseMerge(unsafe.Pointer(&ioSync)) + } + return sendfile(outfd, infd, offset, count) + } func Fstatvfs(fd int, buf *Statvfs_t) (err error) { + return Fstatvfs1(fd, buf, ST_WAIT) + } func Statvfs(path string, buf *Statvfs_t) (err error) { + return Statvfs1(path, buf, ST_WAIT) + } /* + * Exposed directly + */ + //sys Access(path string, mode uint32) (err error) + //sys Adjtime(delta *Timeval, olddelta *Timeval) (err error) + //sys Chdir(path string) (err error) + //sys Chflags(path string, flags int) (err error) + //sys Chmod(path string, mode uint32) (err error) + //sys Chown(path string, uid int, gid int) (err error) + //sys Chroot(path string) (err error) + //sys ClockGettime(clockid int32, time *Timespec) (err error) + //sys Close(fd int) (err error) + //sys Dup(fd int) (nfd int, err error) + //sys Dup2(from int, to int) (err error) + //sys Dup3(from int, to int, flags int) (err error) + //sys Exit(code int) + //sys ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) + //sys ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) + //sys ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error) + //sys ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) + //sys ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) + //sys ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) + //sys ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error) + //sys ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) + //sys ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) + //sys ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) + //sys ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) + //sys ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) + //sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error) + //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_POSIX_FADVISE + //sys Fchdir(fd int) (err error) + //sys Fchflags(fd int, flags int) (err error) + //sys Fchmod(fd int, mode uint32) (err error) + //sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) + //sys Fchown(fd int, uid int, gid int) (err error) + //sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) + //sys Flock(fd int, how int) (err error) + //sys Fpathconf(fd int, name int) (val int, err error) + //sys Fstat(fd int, stat *Stat_t) (err error) + //sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) + //sys Fstatvfs1(fd int, buf *Statvfs_t, flags int) (err error) = SYS_FSTATVFS1 + //sys Fsync(fd int) (err error) + //sys Ftruncate(fd int, length int64) (err error) + //sysnb Getegid() (egid int) + //sysnb Geteuid() (uid int) + //sysnb Getgid() (gid int) + //sysnb Getpgid(pid int) (pgid int, err error) + //sysnb Getpgrp() (pgrp int) + //sysnb Getpid() (pid int) + //sysnb Getppid() (ppid int) + //sys Getpriority(which int, who int) (prio int, err error) + //sysnb Getrlimit(which int, lim *Rlimit) (err error) + //sysnb Getrusage(who int, rusage *Rusage) (err error) + //sysnb Getsid(pid int) (sid int, err error) + //sysnb Gettimeofday(tv *Timeval) (err error) + //sysnb Getuid() (uid int) + //sys Issetugid() (tainted bool) + //sys Kill(pid int, signum syscall.Signal) (err error) + //sys Kqueue() (fd int, err error) + //sys Lchown(path string, uid int, gid int) (err error) + //sys Link(path string, link string) (err error) + //sys Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) + //sys Listen(s int, backlog int) (err error) + //sys Lstat(path string, stat *Stat_t) (err error) + //sys Mkdir(path string, mode uint32) (err error) + //sys Mkdirat(dirfd int, path string, mode uint32) (err error) + //sys Mkfifo(path string, mode uint32) (err error) + //sys Mkfifoat(dirfd int, path string, mode uint32) (err error) + //sys Mknod(path string, mode uint32, dev int) (err error) + //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error) + //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) + //sys Open(path string, mode int, perm uint32) (fd int, err error) + //sys Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) + //sys Pathconf(path string, name int) (val int, err error) + //sys pread(fd int, p []byte, offset int64) (n int, err error) + //sys pwrite(fd int, p []byte, offset int64) (n int, err error) + //sys read(fd int, p []byte) (n int, err error) + //sys Readlink(path string, buf []byte) (n int, err error) + //sys Readlinkat(dirfd int, path string, buf []byte) (n int, err error) + //sys Rename(from string, to string) (err error) + //sys Renameat(fromfd int, from string, tofd int, to string) (err error) + //sys Revoke(path string) (err error) + //sys Rmdir(path string) (err error) + //sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK + //sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) + //sysnb Setegid(egid int) (err error) + //sysnb Seteuid(euid int) (err error) + //sysnb Setgid(gid int) (err error) + //sysnb Setpgid(pid int, pgid int) (err error) + //sys Setpriority(which int, who int, prio int) (err error) + //sysnb Setregid(rgid int, egid int) (err error) + //sysnb Setreuid(ruid int, euid int) (err error) + //sysnb Setsid() (pid int, err error) + //sysnb Settimeofday(tp *Timeval) (err error) + //sysnb Setuid(uid int) (err error) + //sys Stat(path string, stat *Stat_t) (err error) + //sys Statvfs1(path string, buf *Statvfs_t, flags int) (err error) = SYS_STATVFS1 + //sys Symlink(path string, link string) (err error) + //sys Symlinkat(oldpath string, newdirfd int, newpath string) (err error) + //sys Sync() (err error) + //sys Truncate(path string, length int64) (err error) + //sys Umask(newmask int) (oldmask int) + //sys Unlink(path string) (err error) + //sys Unlinkat(dirfd int, path string, flags int) (err error) + //sys Unmount(path string, flags int) (err error) + //sys write(fd int, p []byte) (n int, err error) + //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) + //sys munmap(addr uintptr, length uintptr) (err error) + //sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) const ( - mremapFixed = MAP_FIXED + mremapFixed = MAP_FIXED + mremapDontunmap = 0 - mremapMaymove = 0 + + mremapMaymove = 0 ) //sys mremapNetBSD(oldp uintptr, oldsize uintptr, newp uintptr, newsize uintptr, flags int) (xaddr uintptr, err error) = SYS_MREMAP func mremap(oldaddr uintptr, oldlength uintptr, newlength uintptr, flags int, newaddr uintptr) (uintptr, error) { + return mremapNetBSD(oldaddr, oldlength, newaddr, newlength, flags) + } diff --git a/vendor/golang.org/x/sys/unix/syscall_openbsd.go b/vendor/golang.org/x/sys/unix/syscall_openbsd.go index b25343c..19a9923 100644 --- a/vendor/golang.org/x/sys/unix/syscall_openbsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_openbsd.go @@ -1,13 +1,21 @@ // Copyright 2009,2010 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // OpenBSD system calls. + // This file is compiled as ordinary Go code, + // but it is also input to mksyscall, + // which parses the //sys lines and generates system call stubs. + // Note that sometimes we use a lowercase //sys name and wrap + // it in our own nicer implementation, either here or in + // syscall_bsd.go or syscall_unix.go. package unix @@ -19,323 +27,569 @@ import ( ) // SockaddrDatalink implements the Sockaddr interface for AF_LINK type sockets. + type SockaddrDatalink struct { - Len uint8 + Len uint8 + Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [24]int8 - raw RawSockaddrDatalink + + Index uint16 + + Type uint8 + + Nlen uint8 + + Alen uint8 + + Slen uint8 + + Data [24]int8 + + raw RawSockaddrDatalink } func anyToSockaddrGOOS(fd int, rsa *RawSockaddrAny) (Sockaddr, error) { + return nil, EAFNOSUPPORT + } func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) func nametomib(name string) (mib []_C_int, err error) { + i := sort.Search(len(sysctlMib), func(i int) bool { + return sysctlMib[i].ctlname >= name + }) + if i < len(sysctlMib) && sysctlMib[i].ctlname == name { + return sysctlMib[i].ctloid, nil + } + return nil, EINVAL + } func direntIno(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Fileno), unsafe.Sizeof(Dirent{}.Fileno)) + } func direntReclen(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) + } func direntNamlen(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen)) + } func SysctlUvmexp(name string) (*Uvmexp, error) { + mib, err := sysctlmib(name) + if err != nil { + return nil, err + } n := uintptr(SizeofUvmexp) + var u Uvmexp + if err := sysctl(mib, (*byte)(unsafe.Pointer(&u)), &n, nil, 0); err != nil { + return nil, err + } + if n != SizeofUvmexp { + return nil, EIO + } + return &u, nil + } func Pipe(p []int) (err error) { + return Pipe2(p, 0) + } //sysnb pipe2(p *[2]_C_int, flags int) (err error) func Pipe2(p []int, flags int) error { + if len(p) != 2 { + return EINVAL + } + var pp [2]_C_int + err := pipe2(&pp, flags) + if err == nil { + p[0] = int(pp[0]) + p[1] = int(pp[1]) + } + return err + } //sys Getdents(fd int, buf []byte) (n int, err error) func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { + n, err = Getdents(fd, buf) + if err != nil || basep == nil { + return + } var off int64 + off, err = Seek(fd, 0, 1 /* SEEK_CUR */) + if err != nil { + *basep = ^uintptr(0) + return + } + *basep = uintptr(off) + if unsafe.Sizeof(*basep) == 8 { + return + } + if off>>32 != 0 { + // We can't stuff the offset back into a uintptr, so any + // future calls would be suspect. Generate an error. + // EIO was allowed by getdirentries. + err = EIO + } + return + } //sys Getcwd(buf []byte) (n int, err error) = SYS___GETCWD func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + if raceenabled { + raceReleaseMerge(unsafe.Pointer(&ioSync)) + } + return sendfile(outfd, infd, offset, count) + } // TODO + func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + return -1, ENOSYS + } func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { + var bufptr *Statfs_t + var bufsize uintptr + if len(buf) > 0 { + bufptr = &buf[0] + bufsize = unsafe.Sizeof(Statfs_t{}) * uintptr(len(buf)) + } + return getfsstat(bufptr, bufsize, flags) + } //sysnb getresuid(ruid *_C_int, euid *_C_int, suid *_C_int) + //sysnb getresgid(rgid *_C_int, egid *_C_int, sgid *_C_int) func Getresuid() (ruid, euid, suid int) { + var r, e, s _C_int + getresuid(&r, &e, &s) + return int(r), int(e), int(s) + } func Getresgid() (rgid, egid, sgid int) { + var r, e, s _C_int + getresgid(&r, &e, &s) + return int(r), int(e), int(s) + } //sys ioctl(fd int, req uint, arg uintptr) (err error) + //sys ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) = SYS_IOCTL //sys sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) = SYS___SYSCTL //sys fcntl(fd int, cmd int, arg int) (n int, err error) + //sys fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) = SYS_FCNTL // FcntlInt performs a fcntl syscall on fd with the provided command and argument. + func FcntlInt(fd uintptr, cmd, arg int) (int, error) { + return fcntl(int(fd), cmd, arg) + } // FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command. + func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error { + _, err := fcntlPtr(int(fd), cmd, unsafe.Pointer(lk)) + return err + } //sys ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) func Ppoll(fds []PollFd, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { + if len(fds) == 0 { + return ppoll(nil, 0, timeout, sigmask) + } + return ppoll(&fds[0], len(fds), timeout, sigmask) + } func Uname(uname *Utsname) error { + mib := []_C_int{CTL_KERN, KERN_OSTYPE} + n := unsafe.Sizeof(uname.Sysname) + if err := sysctl(mib, &uname.Sysname[0], &n, nil, 0); err != nil { + return err + } mib = []_C_int{CTL_KERN, KERN_HOSTNAME} + n = unsafe.Sizeof(uname.Nodename) + if err := sysctl(mib, &uname.Nodename[0], &n, nil, 0); err != nil { + return err + } mib = []_C_int{CTL_KERN, KERN_OSRELEASE} + n = unsafe.Sizeof(uname.Release) + if err := sysctl(mib, &uname.Release[0], &n, nil, 0); err != nil { + return err + } mib = []_C_int{CTL_KERN, KERN_VERSION} + n = unsafe.Sizeof(uname.Version) + if err := sysctl(mib, &uname.Version[0], &n, nil, 0); err != nil { + return err + } // The version might have newlines or tabs in it, convert them to + // spaces. + for i, b := range uname.Version { + if b == '\n' || b == '\t' { + if i == len(uname.Version)-1 { + uname.Version[i] = 0 + } else { + uname.Version[i] = ' ' + } + } + } mib = []_C_int{CTL_HW, HW_MACHINE} + n = unsafe.Sizeof(uname.Machine) + if err := sysctl(mib, &uname.Machine[0], &n, nil, 0); err != nil { + return err + } return nil + } /* + * Exposed directly + */ + //sys Access(path string, mode uint32) (err error) + //sys Adjtime(delta *Timeval, olddelta *Timeval) (err error) + //sys Chdir(path string) (err error) + //sys Chflags(path string, flags int) (err error) + //sys Chmod(path string, mode uint32) (err error) + //sys Chown(path string, uid int, gid int) (err error) + //sys Chroot(path string) (err error) + //sys ClockGettime(clockid int32, time *Timespec) (err error) + //sys Close(fd int) (err error) + //sys Dup(fd int) (nfd int, err error) + //sys Dup2(from int, to int) (err error) + //sys Dup3(from int, to int, flags int) (err error) + //sys Exit(code int) + //sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error) + //sys Fchdir(fd int) (err error) + //sys Fchflags(fd int, flags int) (err error) + //sys Fchmod(fd int, mode uint32) (err error) + //sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) + //sys Fchown(fd int, uid int, gid int) (err error) + //sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) + //sys Flock(fd int, how int) (err error) + //sys Fpathconf(fd int, name int) (val int, err error) + //sys Fstat(fd int, stat *Stat_t) (err error) + //sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) + //sys Fstatfs(fd int, stat *Statfs_t) (err error) + //sys Fsync(fd int) (err error) + //sys Ftruncate(fd int, length int64) (err error) + //sysnb Getegid() (egid int) + //sysnb Geteuid() (uid int) + //sysnb Getgid() (gid int) + //sysnb Getpgid(pid int) (pgid int, err error) + //sysnb Getpgrp() (pgrp int) + //sysnb Getpid() (pid int) + //sysnb Getppid() (ppid int) + //sys Getpriority(which int, who int) (prio int, err error) + //sysnb Getrlimit(which int, lim *Rlimit) (err error) + //sysnb Getrtable() (rtable int, err error) + //sysnb Getrusage(who int, rusage *Rusage) (err error) + //sysnb Getsid(pid int) (sid int, err error) + //sysnb Gettimeofday(tv *Timeval) (err error) + //sysnb Getuid() (uid int) + //sys Issetugid() (tainted bool) + //sys Kill(pid int, signum syscall.Signal) (err error) + //sys Kqueue() (fd int, err error) + //sys Lchown(path string, uid int, gid int) (err error) + //sys Link(path string, link string) (err error) + //sys Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) + //sys Listen(s int, backlog int) (err error) + //sys Lstat(path string, stat *Stat_t) (err error) + //sys Mkdir(path string, mode uint32) (err error) + //sys Mkdirat(dirfd int, path string, mode uint32) (err error) + //sys Mkfifo(path string, mode uint32) (err error) + //sys Mkfifoat(dirfd int, path string, mode uint32) (err error) + //sys Mknod(path string, mode uint32, dev int) (err error) + //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error) + //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) + //sys Open(path string, mode int, perm uint32) (fd int, err error) + //sys Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) + //sys Pathconf(path string, name int) (val int, err error) + //sys pread(fd int, p []byte, offset int64) (n int, err error) + //sys pwrite(fd int, p []byte, offset int64) (n int, err error) + //sys read(fd int, p []byte) (n int, err error) + //sys Readlink(path string, buf []byte) (n int, err error) + //sys Readlinkat(dirfd int, path string, buf []byte) (n int, err error) + //sys Rename(from string, to string) (err error) + //sys Renameat(fromfd int, from string, tofd int, to string) (err error) + //sys Revoke(path string) (err error) + //sys Rmdir(path string) (err error) + //sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK + //sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) + //sysnb Setegid(egid int) (err error) + //sysnb Seteuid(euid int) (err error) + //sysnb Setgid(gid int) (err error) + //sys Setlogin(name string) (err error) + //sysnb Setpgid(pid int, pgid int) (err error) + //sys Setpriority(which int, who int, prio int) (err error) + //sysnb Setregid(rgid int, egid int) (err error) + //sysnb Setreuid(ruid int, euid int) (err error) + //sysnb Setresgid(rgid int, egid int, sgid int) (err error) + //sysnb Setresuid(ruid int, euid int, suid int) (err error) + //sysnb Setrtable(rtable int) (err error) + //sysnb Setsid() (pid int, err error) + //sysnb Settimeofday(tp *Timeval) (err error) + //sysnb Setuid(uid int) (err error) + //sys Stat(path string, stat *Stat_t) (err error) + //sys Statfs(path string, stat *Statfs_t) (err error) + //sys Symlink(path string, link string) (err error) + //sys Symlinkat(oldpath string, newdirfd int, newpath string) (err error) + //sys Sync() (err error) + //sys Truncate(path string, length int64) (err error) + //sys Umask(newmask int) (oldmask int) + //sys Unlink(path string) (err error) + //sys Unlinkat(dirfd int, path string, flags int) (err error) + //sys Unmount(path string, flags int) (err error) + //sys write(fd int, p []byte) (n int, err error) + //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) + //sys munmap(addr uintptr, length uintptr) (err error) + //sys getfsstat(stat *Statfs_t, bufsize uintptr, flags int) (n int, err error) + //sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) + //sys pledge(promises *byte, execpromises *byte) (err error) + //sys unveil(path *byte, flags *byte) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_solaris.go b/vendor/golang.org/x/sys/unix/syscall_solaris.go index 21974af..0ee054d 100644 --- a/vendor/golang.org/x/sys/unix/syscall_solaris.go +++ b/vendor/golang.org/x/sys/unix/syscall_solaris.go @@ -1,13 +1,21 @@ // Copyright 2009 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Solaris system calls. + // This file is compiled as ordinary Go code, + // but it is also input to mksyscall, + // which parses the //sys lines and generates system call stubs. + // Note that sometimes we use a lowercase //sys name and wrap + // it in our own nicer implementation, either here or in + // syscall_solaris.go or syscall_unix.go. package unix @@ -22,143 +30,247 @@ import ( ) // Implemented in runtime/syscall_solaris.go. + type syscallFunc uintptr func rawSysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) + func sysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) // SockaddrDatalink implements the Sockaddr interface for AF_LINK type sockets. + type SockaddrDatalink struct { Family uint16 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [244]int8 - raw RawSockaddrDatalink + + Index uint16 + + Type uint8 + + Nlen uint8 + + Alen uint8 + + Slen uint8 + + Data [244]int8 + + raw RawSockaddrDatalink } func direntIno(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino)) + } func direntReclen(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) + } func direntNamlen(buf []byte) (uint64, bool) { + reclen, ok := direntReclen(buf) + if !ok { + return 0, false + } + return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true + } //sysnb pipe(p *[2]_C_int) (n int, err error) func Pipe(p []int) (err error) { + if len(p) != 2 { + return EINVAL + } + var pp [2]_C_int + n, err := pipe(&pp) + if n != 0 { + return err + } + if err == nil { + p[0] = int(pp[0]) + p[1] = int(pp[1]) + } + return nil + } //sysnb pipe2(p *[2]_C_int, flags int) (err error) func Pipe2(p []int, flags int) error { + if len(p) != 2 { + return EINVAL + } + var pp [2]_C_int + err := pipe2(&pp, flags) + if err == nil { + p[0] = int(pp[0]) + p[1] = int(pp[1]) + } + return err + } func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) { + if sa.Port < 0 || sa.Port > 0xFFFF { + return nil, 0, EINVAL + } + sa.raw.Family = AF_INET + p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) + p[0] = byte(sa.Port >> 8) + p[1] = byte(sa.Port) + sa.raw.Addr = sa.Addr + return unsafe.Pointer(&sa.raw), SizeofSockaddrInet4, nil + } func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) { + if sa.Port < 0 || sa.Port > 0xFFFF { + return nil, 0, EINVAL + } + sa.raw.Family = AF_INET6 + p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) + p[0] = byte(sa.Port >> 8) + p[1] = byte(sa.Port) + sa.raw.Scope_id = sa.ZoneId + sa.raw.Addr = sa.Addr + return unsafe.Pointer(&sa.raw), SizeofSockaddrInet6, nil + } func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) { + name := sa.Name + n := len(name) + if n >= len(sa.raw.Path) { + return nil, 0, EINVAL + } + sa.raw.Family = AF_UNIX + for i := 0; i < n; i++ { + sa.raw.Path[i] = int8(name[i]) + } + // length is family (uint16), name, NUL. + sl := _Socklen(2) + if n > 0 { + sl += _Socklen(n) + 1 + } + if sa.raw.Path[0] == '@' || (sa.raw.Path[0] == 0 && sl > 3) { + // Check sl > 3 so we don't change unnamed socket behavior. + sa.raw.Path[0] = 0 + // Don't count trailing NUL for abstract address. + sl-- + } return unsafe.Pointer(&sa.raw), sl, nil + } //sys getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) = libsocket.getsockname func Getsockname(fd int) (sa Sockaddr, err error) { + var rsa RawSockaddrAny + var len _Socklen = SizeofSockaddrAny + if err = getsockname(fd, &rsa, &len); err != nil { + return + } + return anyToSockaddr(fd, &rsa) + } // GetsockoptString returns the string value of the socket option opt for the + // socket associated with fd at the given socket level. + func GetsockoptString(fd, level, opt int) (string, error) { + buf := make([]byte, 256) + vallen := _Socklen(len(buf)) + err := getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen) + if err != nil { + return "", err + } + return ByteSliceToString(buf[:vallen]), nil + } const ImplementsGetwd = true @@ -166,104 +278,171 @@ const ImplementsGetwd = true //sys Getcwd(buf []byte) (n int, err error) func Getwd() (wd string, err error) { + var buf [PathMax]byte + // Getcwd will return an error if it failed for any reason. + _, err = Getcwd(buf[0:]) + if err != nil { + return "", err + } + n := clen(buf[:]) + if n < 1 { + return "", EINVAL + } + return string(buf[:n]), nil + } /* + * Wrapped + */ //sysnb getgroups(ngid int, gid *_Gid_t) (n int, err error) + //sysnb setgroups(ngid int, gid *_Gid_t) (err error) func Getgroups() (gids []int, err error) { + n, err := getgroups(0, nil) + // Check for error and sanity check group count. Newer versions of + // Solaris allow up to 1024 (NGROUPS_MAX). + if n < 0 || n > 1024 { + if err != nil { + return nil, err + } + return nil, EINVAL + } else if n == 0 { + return nil, nil + } a := make([]_Gid_t, n) + n, err = getgroups(n, &a[0]) + if n == -1 { + return nil, err + } + gids = make([]int, n) + for i, v := range a[0:n] { + gids[i] = int(v) + } + return + } func Setgroups(gids []int) (err error) { + if len(gids) == 0 { + return setgroups(0, nil) + } a := make([]_Gid_t, len(gids)) + for i, v := range gids { + a[i] = _Gid_t(v) + } + return setgroups(len(a), &a[0]) + } // ReadDirent reads directory entries from fd and writes them into buf. + func ReadDirent(fd int, buf []byte) (n int, err error) { + // Final argument is (basep *uintptr) and the syscall doesn't take nil. + // TODO(rsc): Can we use a single global basep for all calls? + return Getdents(fd, buf, new(uintptr)) + } // Wait status is 7 bits at bottom, either 0 (exited), + // 0x7F (stopped), or a signal number that caused an exit. + // The 0x80 bit is whether there was a core dump. + // An extra number (exit code, signal causing a stop) + // is in the high bits. type WaitStatus uint32 const ( - mask = 0x7F - core = 0x80 + mask = 0x7F + + core = 0x80 + shift = 8 - exited = 0 + exited = 0 + stopped = 0x7F ) func (w WaitStatus) Exited() bool { return w&mask == exited } func (w WaitStatus) ExitStatus() int { + if w&mask != exited { + return -1 + } + return int(w >> shift) + } func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != 0 } func (w WaitStatus) Signal() syscall.Signal { + sig := syscall.Signal(w & mask) + if sig == stopped || sig == 0 { + return -1 + } + return sig + } func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 } @@ -273,10 +452,15 @@ func (w WaitStatus) Stopped() bool { return w&mask == stopped && syscall.Signal( func (w WaitStatus) Continued() bool { return w&mask == stopped && syscall.Signal(w>>shift) == SIGSTOP } func (w WaitStatus) StopSignal() syscall.Signal { + if !w.Stopped() { + return -1 + } + return syscall.Signal(w>>shift) & 0xFF + } func (w WaitStatus) TrapCause() int { return -1 } @@ -284,821 +468,1470 @@ func (w WaitStatus) TrapCause() int { return -1 } //sys wait4(pid int32, statusp *_C_int, options int, rusage *Rusage) (wpid int32, err error) func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (int, error) { + var status _C_int + rpid, err := wait4(int32(pid), &status, options, rusage) + wpid := int(rpid) + if wpid == -1 { + return wpid, err + } + if wstatus != nil { + *wstatus = WaitStatus(status) + } + return wpid, nil + } //sys gethostname(buf []byte) (n int, err error) func Gethostname() (name string, err error) { + var buf [MaxHostNameLen]byte + n, err := gethostname(buf[:]) + if n != 0 { + return "", err + } + n = clen(buf[:]) + if n < 1 { + return "", EFAULT + } + return string(buf[:n]), nil + } //sys utimes(path string, times *[2]Timeval) (err error) func Utimes(path string, tv []Timeval) (err error) { + if tv == nil { + return utimes(path, nil) + } + if len(tv) != 2 { + return EINVAL + } + return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) + } //sys utimensat(fd int, path string, times *[2]Timespec, flag int) (err error) func UtimesNano(path string, ts []Timespec) error { + if ts == nil { + return utimensat(AT_FDCWD, path, nil, 0) + } + if len(ts) != 2 { + return EINVAL + } + return utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0) + } func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error { + if ts == nil { + return utimensat(dirfd, path, nil, flags) + } + if len(ts) != 2 { + return EINVAL + } + return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags) + } //sys fcntl(fd int, cmd int, arg int) (val int, err error) // FcntlInt performs a fcntl syscall on fd with the provided command and argument. + func FcntlInt(fd uintptr, cmd, arg int) (int, error) { + valptr, _, errno := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(arg), 0, 0, 0) + var err error + if errno != 0 { + err = errno + } + return int(valptr), err + } // FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command. + func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(unsafe.Pointer(lk)), 0, 0, 0) + if e1 != 0 { + return e1 + } + return nil + } //sys futimesat(fildes int, path *byte, times *[2]Timeval) (err error) func Futimesat(dirfd int, path string, tv []Timeval) error { + pathp, err := BytePtrFromString(path) + if err != nil { + return err + } + if tv == nil { + return futimesat(dirfd, pathp, nil) + } + if len(tv) != 2 { + return EINVAL + } + return futimesat(dirfd, pathp, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) + } // Solaris doesn't have an futimes function because it allows NULL to be + // specified as the path for futimesat. However, Go doesn't like + // NULL-style string interfaces, so this simple wrapper is provided. + func Futimes(fd int, tv []Timeval) error { + if tv == nil { + return futimesat(fd, nil, nil) + } + if len(tv) != 2 { + return EINVAL + } + return futimesat(fd, nil, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) + } func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) { + switch rsa.Addr.Family { + case AF_UNIX: + pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa)) + sa := new(SockaddrUnix) + // Assume path ends at NUL. + // This is not technically the Solaris semantics for + // abstract Unix domain sockets -- they are supposed + // to be uninterpreted fixed-size binary blobs -- but + // everyone uses this convention. + n := 0 + for n < len(pp.Path) && pp.Path[n] != 0 { + n++ + } + sa.Name = string(unsafe.Slice((*byte)(unsafe.Pointer(&pp.Path[0])), n)) + return sa, nil case AF_INET: + pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa)) + sa := new(SockaddrInet4) + p := (*[2]byte)(unsafe.Pointer(&pp.Port)) + sa.Port = int(p[0])<<8 + int(p[1]) + sa.Addr = pp.Addr + return sa, nil case AF_INET6: + pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa)) + sa := new(SockaddrInet6) + p := (*[2]byte)(unsafe.Pointer(&pp.Port)) + sa.Port = int(p[0])<<8 + int(p[1]) + sa.ZoneId = pp.Scope_id + sa.Addr = pp.Addr + return sa, nil + } + return nil, EAFNOSUPPORT + } //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) = libsocket.accept func Accept(fd int) (nfd int, sa Sockaddr, err error) { + var rsa RawSockaddrAny + var len _Socklen = SizeofSockaddrAny + nfd, err = accept(fd, &rsa, &len) + if nfd == -1 { + return + } + sa, err = anyToSockaddr(fd, &rsa) + if err != nil { + Close(nfd) + nfd = 0 + } + return + } //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) = libsocket.__xnet_recvmsg func recvmsgRaw(fd int, iov []Iovec, oob []byte, flags int, rsa *RawSockaddrAny) (n, oobn int, recvflags int, err error) { + var msg Msghdr + msg.Name = (*byte)(unsafe.Pointer(rsa)) + msg.Namelen = uint32(SizeofSockaddrAny) + var dummy byte + if len(oob) > 0 { + // receive at least one normal byte + if emptyIovecs(iov) { + var iova [1]Iovec + iova[0].Base = &dummy + iova[0].SetLen(1) + iov = iova[:] + } + msg.Accrightslen = int32(len(oob)) + } + if len(iov) > 0 { + msg.Iov = &iov[0] + msg.SetIovlen(len(iov)) + } + if n, err = recvmsg(fd, &msg, flags); n == -1 { + return + } + oobn = int(msg.Accrightslen) + return + } //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) = libsocket.__xnet_sendmsg func sendmsgN(fd int, iov []Iovec, oob []byte, ptr unsafe.Pointer, salen _Socklen, flags int) (n int, err error) { + var msg Msghdr + msg.Name = (*byte)(unsafe.Pointer(ptr)) + msg.Namelen = uint32(salen) + var dummy byte + var empty bool + if len(oob) > 0 { + // send at least one normal byte + empty = emptyIovecs(iov) + if empty { + var iova [1]Iovec + iova[0].Base = &dummy + iova[0].SetLen(1) + iov = iova[:] + } + msg.Accrightslen = int32(len(oob)) + } + if len(iov) > 0 { + msg.Iov = &iov[0] + msg.SetIovlen(len(iov)) + } + if n, err = sendmsg(fd, &msg, flags); err != nil { + return 0, err + } + if len(oob) > 0 && empty { + n = 0 + } + return n, nil + } //sys acct(path *byte) (err error) func Acct(path string) (err error) { + if len(path) == 0 { + // Assume caller wants to disable accounting. + return acct(nil) + } pathp, err := BytePtrFromString(path) + if err != nil { + return err + } + return acct(pathp) + } //sys __makedev(version int, major uint, minor uint) (val uint64) func Mkdev(major, minor uint32) uint64 { + return __makedev(NEWDEV, uint(major), uint(minor)) + } //sys __major(version int, dev uint64) (val uint) func Major(dev uint64) uint32 { + return uint32(__major(NEWDEV, dev)) + } //sys __minor(version int, dev uint64) (val uint) func Minor(dev uint64) uint32 { + return uint32(__minor(NEWDEV, dev)) + } /* + * Expose the ioctl function + */ //sys ioctlRet(fd int, req int, arg uintptr) (ret int, err error) = libc.ioctl + //sys ioctlPtrRet(fd int, req int, arg unsafe.Pointer) (ret int, err error) = libc.ioctl func ioctl(fd int, req int, arg uintptr) (err error) { + _, err = ioctlRet(fd, req, arg) + return err + } func ioctlPtr(fd int, req int, arg unsafe.Pointer) (err error) { + _, err = ioctlPtrRet(fd, req, arg) + return err + } func IoctlSetTermio(fd int, req int, value *Termio) error { + return ioctlPtr(fd, req, unsafe.Pointer(value)) + } func IoctlGetTermio(fd int, req int) (*Termio, error) { + var value Termio + err := ioctlPtr(fd, req, unsafe.Pointer(&value)) + return &value, err + } //sys poll(fds *PollFd, nfds int, timeout int) (n int, err error) func Poll(fds []PollFd, timeout int) (n int, err error) { + if len(fds) == 0 { + return poll(nil, 0, timeout) + } + return poll(&fds[0], len(fds), timeout) + } func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + if raceenabled { + raceReleaseMerge(unsafe.Pointer(&ioSync)) + } + return sendfile(outfd, infd, offset, count) + } /* + * Exposed directly + */ + //sys Access(path string, mode uint32) (err error) + //sys Adjtime(delta *Timeval, olddelta *Timeval) (err error) + //sys Chdir(path string) (err error) + //sys Chmod(path string, mode uint32) (err error) + //sys Chown(path string, uid int, gid int) (err error) + //sys Chroot(path string) (err error) + //sys ClockGettime(clockid int32, time *Timespec) (err error) + //sys Close(fd int) (err error) + //sys Creat(path string, mode uint32) (fd int, err error) + //sys Dup(fd int) (nfd int, err error) + //sys Dup2(oldfd int, newfd int) (err error) + //sys Exit(code int) + //sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error) + //sys Fchdir(fd int) (err error) + //sys Fchmod(fd int, mode uint32) (err error) + //sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) + //sys Fchown(fd int, uid int, gid int) (err error) + //sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) + //sys Fdatasync(fd int) (err error) + //sys Flock(fd int, how int) (err error) + //sys Fpathconf(fd int, name int) (val int, err error) + //sys Fstat(fd int, stat *Stat_t) (err error) + //sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) + //sys Fstatvfs(fd int, vfsstat *Statvfs_t) (err error) + //sys Getdents(fd int, buf []byte, basep *uintptr) (n int, err error) + //sysnb Getgid() (gid int) + //sysnb Getpid() (pid int) + //sysnb Getpgid(pid int) (pgid int, err error) + //sysnb Getpgrp() (pgid int, err error) + //sys Geteuid() (euid int) + //sys Getegid() (egid int) + //sys Getppid() (ppid int) + //sys Getpriority(which int, who int) (n int, err error) + //sysnb Getrlimit(which int, lim *Rlimit) (err error) + //sysnb Getrusage(who int, rusage *Rusage) (err error) + //sysnb Getsid(pid int) (sid int, err error) + //sysnb Gettimeofday(tv *Timeval) (err error) + //sysnb Getuid() (uid int) + //sys Kill(pid int, signum syscall.Signal) (err error) + //sys Lchown(path string, uid int, gid int) (err error) + //sys Link(path string, link string) (err error) + //sys Listen(s int, backlog int) (err error) = libsocket.__xnet_llisten + //sys Lstat(path string, stat *Stat_t) (err error) + //sys Madvise(b []byte, advice int) (err error) + //sys Mkdir(path string, mode uint32) (err error) + //sys Mkdirat(dirfd int, path string, mode uint32) (err error) + //sys Mkfifo(path string, mode uint32) (err error) + //sys Mkfifoat(dirfd int, path string, mode uint32) (err error) + //sys Mknod(path string, mode uint32, dev int) (err error) + //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error) + //sys Mlock(b []byte) (err error) + //sys Mlockall(flags int) (err error) + //sys Mprotect(b []byte, prot int) (err error) + //sys Msync(b []byte, flags int) (err error) + //sys Munlock(b []byte) (err error) + //sys Munlockall() (err error) + //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) + //sys Open(path string, mode int, perm uint32) (fd int, err error) + //sys Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) + //sys Pathconf(path string, name int) (val int, err error) + //sys Pause() (err error) + //sys pread(fd int, p []byte, offset int64) (n int, err error) + //sys pwrite(fd int, p []byte, offset int64) (n int, err error) + //sys read(fd int, p []byte) (n int, err error) + //sys Readlink(path string, buf []byte) (n int, err error) + //sys Rename(from string, to string) (err error) + //sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) + //sys Rmdir(path string) (err error) + //sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = lseek + //sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) + //sysnb Setegid(egid int) (err error) + //sysnb Seteuid(euid int) (err error) + //sysnb Setgid(gid int) (err error) + //sys Sethostname(p []byte) (err error) + //sysnb Setpgid(pid int, pgid int) (err error) + //sys Setpriority(which int, who int, prio int) (err error) + //sysnb Setregid(rgid int, egid int) (err error) + //sysnb Setreuid(ruid int, euid int) (err error) + //sysnb Setsid() (pid int, err error) + //sysnb Setuid(uid int) (err error) + //sys Shutdown(s int, how int) (err error) = libsocket.shutdown + //sys Stat(path string, stat *Stat_t) (err error) + //sys Statvfs(path string, vfsstat *Statvfs_t) (err error) + //sys Symlink(path string, link string) (err error) + //sys Sync() (err error) + //sys Sysconf(which int) (n int64, err error) + //sysnb Times(tms *Tms) (ticks uintptr, err error) + //sys Truncate(path string, length int64) (err error) + //sys Fsync(fd int) (err error) + //sys Ftruncate(fd int, length int64) (err error) + //sys Umask(mask int) (oldmask int) + //sysnb Uname(buf *Utsname) (err error) + //sys Unmount(target string, flags int) (err error) = libc.umount + //sys Unlink(path string) (err error) + //sys Unlinkat(dirfd int, path string, flags int) (err error) + //sys Ustat(dev int, ubuf *Ustat_t) (err error) + //sys Utime(path string, buf *Utimbuf) (err error) + //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.__xnet_bind + //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.__xnet_connect + //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) + //sys munmap(addr uintptr, length uintptr) (err error) + //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = libsendfile.sendfile + //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.__xnet_sendto + //sys socket(domain int, typ int, proto int) (fd int, err error) = libsocket.__xnet_socket + //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) = libsocket.__xnet_socketpair + //sys write(fd int, p []byte) (n int, err error) + //sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) = libsocket.__xnet_getsockopt + //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) = libsocket.getpeername + //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) = libsocket.setsockopt + //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) = libsocket.recvfrom // Event Ports type fileObjCookie struct { - fobj *fileObj + fobj *fileObj + cookie interface{} } // EventPort provides a safe abstraction on top of Solaris/illumos Event Ports. + type EventPort struct { - port int - mu sync.Mutex - fds map[uintptr]*fileObjCookie + port int + + mu sync.Mutex + + fds map[uintptr]*fileObjCookie + paths map[string]*fileObjCookie + // The user cookie presents an interesting challenge from a memory management perspective. + // There are two paths by which we can discover that it is no longer in use: + // 1. The user calls port_dissociate before any events fire + // 2. An event fires and we return it to the user + // The tricky situation is if the event has fired in the kernel but + // the user hasn't requested/received it yet. + // If the user wants to port_dissociate before the event has been processed, + // we should handle things gracefully. To do so, we need to keep an extra + // reference to the cookie around until the event is processed + // thus the otherwise seemingly extraneous "cookies" map + // The key of this map is a pointer to the corresponding fCookie + cookies map[*fileObjCookie]struct{} } // PortEvent is an abstraction of the port_event C struct. + // Compare Source against PORT_SOURCE_FILE or PORT_SOURCE_FD + // to see if Path or Fd was the event source. The other will be + // uninitialized. + type PortEvent struct { Cookie interface{} + Events int32 - Fd uintptr - Path string + + Fd uintptr + + Path string + Source uint16 - fobj *fileObj + + fobj *fileObj } // NewEventPort creates a new EventPort including the + // underlying call to port_create(3c). + func NewEventPort() (*EventPort, error) { + port, err := port_create() + if err != nil { + return nil, err + } + e := &EventPort{ - port: port, - fds: make(map[uintptr]*fileObjCookie), - paths: make(map[string]*fileObjCookie), + + port: port, + + fds: make(map[uintptr]*fileObjCookie), + + paths: make(map[string]*fileObjCookie), + cookies: make(map[*fileObjCookie]struct{}), } + return e, nil + } //sys port_create() (n int, err error) + //sys port_associate(port int, source int, object uintptr, events int, user *byte) (n int, err error) + //sys port_dissociate(port int, source int, object uintptr) (n int, err error) + //sys port_get(port int, pe *portEvent, timeout *Timespec) (n int, err error) + //sys port_getn(port int, pe *portEvent, max uint32, nget *uint32, timeout *Timespec) (n int, err error) // Close closes the event port. + func (e *EventPort) Close() error { + e.mu.Lock() + defer e.mu.Unlock() + err := Close(e.port) + if err != nil { + return err + } + e.fds = nil + e.paths = nil + e.cookies = nil + return nil + } // PathIsWatched checks to see if path is associated with this EventPort. + func (e *EventPort) PathIsWatched(path string) bool { + e.mu.Lock() + defer e.mu.Unlock() + _, found := e.paths[path] + return found + } // FdIsWatched checks to see if fd is associated with this EventPort. + func (e *EventPort) FdIsWatched(fd uintptr) bool { + e.mu.Lock() + defer e.mu.Unlock() + _, found := e.fds[fd] + return found + } // AssociatePath wraps port_associate(3c) for a filesystem path including + // creating the necessary file_obj from the provided stat information. + func (e *EventPort) AssociatePath(path string, stat os.FileInfo, events int, cookie interface{}) error { + e.mu.Lock() + defer e.mu.Unlock() + if _, found := e.paths[path]; found { + return fmt.Errorf("%v is already associated with this Event Port", path) + } + fCookie, err := createFileObjCookie(path, stat, cookie) + if err != nil { + return err + } + _, err = port_associate(e.port, PORT_SOURCE_FILE, uintptr(unsafe.Pointer(fCookie.fobj)), events, (*byte)(unsafe.Pointer(fCookie))) + if err != nil { + return err + } + e.paths[path] = fCookie + e.cookies[fCookie] = struct{}{} + return nil + } // DissociatePath wraps port_dissociate(3c) for a filesystem path. + func (e *EventPort) DissociatePath(path string) error { + e.mu.Lock() + defer e.mu.Unlock() + f, ok := e.paths[path] + if !ok { + return fmt.Errorf("%v is not associated with this Event Port", path) + } + _, err := port_dissociate(e.port, PORT_SOURCE_FILE, uintptr(unsafe.Pointer(f.fobj))) + // If the path is no longer associated with this event port (ENOENT) + // we should delete it from our map. We can still return ENOENT to the caller. + // But we need to save the cookie + if err != nil && err != ENOENT { + return err + } + if err == nil { + // dissociate was successful, safe to delete the cookie + fCookie := e.paths[path] + delete(e.cookies, fCookie) + } + delete(e.paths, path) + return err + } // AssociateFd wraps calls to port_associate(3c) on file descriptors. + func (e *EventPort) AssociateFd(fd uintptr, events int, cookie interface{}) error { + e.mu.Lock() + defer e.mu.Unlock() + if _, found := e.fds[fd]; found { + return fmt.Errorf("%v is already associated with this Event Port", fd) + } + fCookie, err := createFileObjCookie("", nil, cookie) + if err != nil { + return err + } + _, err = port_associate(e.port, PORT_SOURCE_FD, fd, events, (*byte)(unsafe.Pointer(fCookie))) + if err != nil { + return err + } + e.fds[fd] = fCookie + e.cookies[fCookie] = struct{}{} + return nil + } // DissociateFd wraps calls to port_dissociate(3c) on file descriptors. + func (e *EventPort) DissociateFd(fd uintptr) error { + e.mu.Lock() + defer e.mu.Unlock() + _, ok := e.fds[fd] + if !ok { + return fmt.Errorf("%v is not associated with this Event Port", fd) + } + _, err := port_dissociate(e.port, PORT_SOURCE_FD, fd) + if err != nil && err != ENOENT { + return err + } + if err == nil { + // dissociate was successful, safe to delete the cookie + fCookie := e.fds[fd] + delete(e.cookies, fCookie) + } + delete(e.fds, fd) + return err + } func createFileObjCookie(name string, stat os.FileInfo, cookie interface{}) (*fileObjCookie, error) { + fCookie := new(fileObjCookie) + fCookie.cookie = cookie + if name != "" && stat != nil { + fCookie.fobj = new(fileObj) + bs, err := ByteSliceFromString(name) + if err != nil { + return nil, err + } + fCookie.fobj.Name = (*int8)(unsafe.Pointer(&bs[0])) + s := stat.Sys().(*syscall.Stat_t) + fCookie.fobj.Atim.Sec = s.Atim.Sec + fCookie.fobj.Atim.Nsec = s.Atim.Nsec + fCookie.fobj.Mtim.Sec = s.Mtim.Sec + fCookie.fobj.Mtim.Nsec = s.Mtim.Nsec + fCookie.fobj.Ctim.Sec = s.Ctim.Sec + fCookie.fobj.Ctim.Nsec = s.Ctim.Nsec + } + return fCookie, nil + } // GetOne wraps port_get(3c) and returns a single PortEvent. + func (e *EventPort) GetOne(t *Timespec) (*PortEvent, error) { + pe := new(portEvent) + _, err := port_get(e.port, pe, t) + if err != nil { + return nil, err + } + p := new(PortEvent) + e.mu.Lock() + defer e.mu.Unlock() + err = e.peIntToExt(pe, p) + if err != nil { + return nil, err + } + return p, nil + } // peIntToExt converts a cgo portEvent struct into the friendlier PortEvent + // NOTE: Always call this function while holding the e.mu mutex + func (e *EventPort) peIntToExt(peInt *portEvent, peExt *PortEvent) error { + if e.cookies == nil { + return fmt.Errorf("this EventPort is already closed") + } + peExt.Events = peInt.Events + peExt.Source = peInt.Source + fCookie := (*fileObjCookie)(unsafe.Pointer(peInt.User)) + _, found := e.cookies[fCookie] if !found { + panic("unexpected event port address; may be due to kernel bug; see https://go.dev/issue/54254") + } + peExt.Cookie = fCookie.cookie + delete(e.cookies, fCookie) switch peInt.Source { + case PORT_SOURCE_FD: + peExt.Fd = uintptr(peInt.Object) + // Only remove the fds entry if it exists and this cookie matches + if fobj, ok := e.fds[peExt.Fd]; ok { + if fobj == fCookie { + delete(e.fds, peExt.Fd) + } + } + case PORT_SOURCE_FILE: + peExt.fobj = fCookie.fobj + peExt.Path = BytePtrToString((*byte)(unsafe.Pointer(peExt.fobj.Name))) + // Only remove the paths entry if it exists and this cookie matches + if fobj, ok := e.paths[peExt.Path]; ok { + if fobj == fCookie { + delete(e.paths, peExt.Path) + } + } + } + return nil + } // Pending wraps port_getn(3c) and returns how many events are pending. + func (e *EventPort) Pending() (int, error) { + var n uint32 = 0 + _, err := port_getn(e.port, nil, 0, &n, nil) + return int(n), err + } // Get wraps port_getn(3c) and fills a slice of PortEvent. + // It will block until either min events have been received + // or the timeout has been exceeded. It will return how many + // events were actually received along with any error information. + func (e *EventPort) Get(s []PortEvent, min int, timeout *Timespec) (int, error) { + if min == 0 { + return 0, fmt.Errorf("need to request at least one event or use Pending() instead") + } + if len(s) < min { + return 0, fmt.Errorf("len(s) (%d) is less than min events requested (%d)", len(s), min) + } + got := uint32(min) + max := uint32(len(s)) + var err error + ps := make([]portEvent, max) + _, err = port_getn(e.port, &ps[0], max, &got, timeout) + // got will be trustworthy with ETIME, but not any other error. + if err != nil && err != ETIME { + return 0, err + } + e.mu.Lock() + defer e.mu.Unlock() + valid := 0 + for i := 0; i < int(got); i++ { + err2 := e.peIntToExt(&ps[i], &s[i]) + if err2 != nil { + if valid == 0 && err == nil { + // If err2 is the only error and there are no valid events + // to return, return it to the caller. + err = err2 + } + break + } + valid = i + 1 + } + return valid, err + } //sys putmsg(fd int, clptr *strbuf, dataptr *strbuf, flags int) (err error) func Putmsg(fd int, cl []byte, data []byte, flags int) (err error) { + var clp, datap *strbuf + if len(cl) > 0 { + clp = &strbuf{ + Len: int32(len(cl)), + Buf: (*int8)(unsafe.Pointer(&cl[0])), } + } + if len(data) > 0 { + datap = &strbuf{ + Len: int32(len(data)), + Buf: (*int8)(unsafe.Pointer(&data[0])), } + } + return putmsg(fd, clp, datap, flags) + } //sys getmsg(fd int, clptr *strbuf, dataptr *strbuf, flags *int) (err error) func Getmsg(fd int, cl []byte, data []byte) (retCl []byte, retData []byte, flags int, err error) { + var clp, datap *strbuf + if len(cl) > 0 { + clp = &strbuf{ + Maxlen: int32(len(cl)), - Buf: (*int8)(unsafe.Pointer(&cl[0])), + + Buf: (*int8)(unsafe.Pointer(&cl[0])), } + } + if len(data) > 0 { + datap = &strbuf{ + Maxlen: int32(len(data)), - Buf: (*int8)(unsafe.Pointer(&data[0])), + + Buf: (*int8)(unsafe.Pointer(&data[0])), } + } if err = getmsg(fd, clp, datap, &flags); err != nil { + return nil, nil, 0, err + } if len(cl) > 0 { + retCl = cl[:clp.Len] + } + if len(data) > 0 { + retData = data[:datap.Len] + } + return retCl, retData, flags, nil + } func IoctlSetIntRetInt(fd int, req int, arg int) (int, error) { + return ioctlRet(fd, req, uintptr(arg)) + } func IoctlSetString(fd int, req int, val string) error { + bs := make([]byte, len(val)+1) + copy(bs[:len(bs)-1], val) + err := ioctlPtr(fd, req, unsafe.Pointer(&bs[0])) + runtime.KeepAlive(&bs[0]) + return err + } // Lifreq Helpers func (l *Lifreq) SetName(name string) error { + if len(name) >= len(l.Name) { + return fmt.Errorf("name cannot be more than %d characters", len(l.Name)-1) + } + for i := range name { + l.Name[i] = int8(name[i]) + } + return nil + } func (l *Lifreq) SetLifruInt(d int) { + *(*int)(unsafe.Pointer(&l.Lifru[0])) = d + } func (l *Lifreq) GetLifruInt() int { + return *(*int)(unsafe.Pointer(&l.Lifru[0])) + } func (l *Lifreq) SetLifruUint(d uint) { + *(*uint)(unsafe.Pointer(&l.Lifru[0])) = d + } func (l *Lifreq) GetLifruUint() uint { + return *(*uint)(unsafe.Pointer(&l.Lifru[0])) + } func IoctlLifreq(fd int, req int, l *Lifreq) error { + return ioctlPtr(fd, req, unsafe.Pointer(l)) + } // Strioctl Helpers func (s *Strioctl) SetInt(i int) { + s.Len = int32(unsafe.Sizeof(i)) + s.Dp = (*int8)(unsafe.Pointer(&i)) + } func IoctlSetStrioctlRetInt(fd int, req int, s *Strioctl) (int, error) { + return ioctlPtrRet(fd, req, unsafe.Pointer(s)) + } diff --git a/vendor/golang.org/x/sys/unix/syscall_unix.go b/vendor/golang.org/x/sys/unix/syscall_unix.go index 77081de..3044709 100644 --- a/vendor/golang.org/x/sys/unix/syscall_unix.go +++ b/vendor/golang.org/x/sys/unix/syscall_unix.go @@ -1,5 +1,7 @@ // Copyright 2009 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris @@ -15,528 +17,916 @@ import ( ) var ( - Stdin = 0 + Stdin = 0 + Stdout = 1 + Stderr = 2 ) // Do the interface allocations only once for common + // Errno values. + var ( errEAGAIN error = syscall.EAGAIN + errEINVAL error = syscall.EINVAL + errENOENT error = syscall.ENOENT ) var ( signalNameMapOnce sync.Once - signalNameMap map[string]syscall.Signal + + signalNameMap map[string]syscall.Signal ) // errnoErr returns common boxed Errno values, to prevent + // allocations at runtime. + func errnoErr(e syscall.Errno) error { + switch e { + case 0: + return nil + case EAGAIN: + return errEAGAIN + case EINVAL: + return errEINVAL + case ENOENT: + return errENOENT + } + return e + } // ErrnoName returns the error name for error number e. + func ErrnoName(e syscall.Errno) string { + i := sort.Search(len(errorList), func(i int) bool { + return errorList[i].num >= e + }) + if i < len(errorList) && errorList[i].num == e { + return errorList[i].name + } + return "" + } // SignalName returns the signal name for signal number s. + func SignalName(s syscall.Signal) string { + i := sort.Search(len(signalList), func(i int) bool { + return signalList[i].num >= s + }) + if i < len(signalList) && signalList[i].num == s { + return signalList[i].name + } + return "" + } // SignalNum returns the syscall.Signal for signal named s, + // or 0 if a signal with such name is not found. + // The signal name should start with "SIG". + func SignalNum(s string) syscall.Signal { + signalNameMapOnce.Do(func() { + signalNameMap = make(map[string]syscall.Signal, len(signalList)) + for _, signal := range signalList { + signalNameMap[signal.name] = signal.num + } + }) + return signalNameMap[s] + } // clen returns the index of the first NULL byte in n or len(n) if n contains no NULL byte. + func clen(n []byte) int { + i := bytes.IndexByte(n, 0) + if i == -1 { + i = len(n) + } + return i + } // Mmap manager, for use by operating system-specific implementations. type mmapper struct { sync.Mutex + active map[*byte][]byte // active mappings; key is last byte in mapping - mmap func(addr, length uintptr, prot, flags, fd int, offset int64) (uintptr, error) + + mmap func(addr, length uintptr, prot, flags, fd int, offset int64) (uintptr, error) + munmap func(addr uintptr, length uintptr) error } func (m *mmapper) Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { + if length <= 0 { + return nil, EINVAL + } // Map the requested memory. + addr, errno := m.mmap(0, uintptr(length), prot, flags, fd, offset) + if errno != nil { + return nil, errno + } // Use unsafe to convert addr into a []byte. + b := unsafe.Slice((*byte)(unsafe.Pointer(addr)), length) // Register mapping in m and return it. + p := &b[cap(b)-1] + m.Lock() + defer m.Unlock() + m.active[p] = b + return b, nil + } func (m *mmapper) Munmap(data []byte) (err error) { + if len(data) == 0 || len(data) != cap(data) { + return EINVAL + } // Find the base of the mapping. + p := &data[cap(data)-1] + m.Lock() + defer m.Unlock() + b := m.active[p] + if b == nil || &b[0] != &data[0] { + return EINVAL + } // Unmap the memory and update m. + if errno := m.munmap(uintptr(unsafe.Pointer(&b[0])), uintptr(len(b))); errno != nil { + return errno + } + delete(m.active, p) + return nil + } func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { + return mapper.Mmap(fd, offset, length, prot, flags) + } func Munmap(b []byte) (err error) { + return mapper.Munmap(b) + } func Read(fd int, p []byte) (n int, err error) { + n, err = read(fd, p) + if raceenabled { + if n > 0 { + raceWriteRange(unsafe.Pointer(&p[0]), n) + } + if err == nil { + raceAcquire(unsafe.Pointer(&ioSync)) + } + } + return + } func Write(fd int, p []byte) (n int, err error) { + if raceenabled { + raceReleaseMerge(unsafe.Pointer(&ioSync)) + } + n, err = write(fd, p) + if raceenabled && n > 0 { + raceReadRange(unsafe.Pointer(&p[0]), n) + } + return + } func Pread(fd int, p []byte, offset int64) (n int, err error) { + n, err = pread(fd, p, offset) + if raceenabled { + if n > 0 { + raceWriteRange(unsafe.Pointer(&p[0]), n) + } + if err == nil { + raceAcquire(unsafe.Pointer(&ioSync)) + } + } + return + } func Pwrite(fd int, p []byte, offset int64) (n int, err error) { + if raceenabled { + raceReleaseMerge(unsafe.Pointer(&ioSync)) + } + n, err = pwrite(fd, p, offset) + if raceenabled && n > 0 { + raceReadRange(unsafe.Pointer(&p[0]), n) + } + return + } // For testing: clients can set this flag to force + // creation of IPv6 sockets to return EAFNOSUPPORT. + var SocketDisableIPv6 bool // Sockaddr represents a socket address. + type Sockaddr interface { sockaddr() (ptr unsafe.Pointer, len _Socklen, err error) // lowercase; only we can define Sockaddrs + } // SockaddrInet4 implements the Sockaddr interface for AF_INET type sockets. + type SockaddrInet4 struct { Port int + Addr [4]byte - raw RawSockaddrInet4 + + raw RawSockaddrInet4 } // SockaddrInet6 implements the Sockaddr interface for AF_INET6 type sockets. + type SockaddrInet6 struct { - Port int + Port int + ZoneId uint32 - Addr [16]byte - raw RawSockaddrInet6 + + Addr [16]byte + + raw RawSockaddrInet6 } // SockaddrUnix implements the Sockaddr interface for AF_UNIX type sockets. + type SockaddrUnix struct { Name string - raw RawSockaddrUnix + + raw RawSockaddrUnix } func Bind(fd int, sa Sockaddr) (err error) { + ptr, n, err := sa.sockaddr() + if err != nil { + return err + } + return bind(fd, ptr, n) + } func Connect(fd int, sa Sockaddr) (err error) { + ptr, n, err := sa.sockaddr() + if err != nil { + return err + } + return connect(fd, ptr, n) + } func Getpeername(fd int) (sa Sockaddr, err error) { + var rsa RawSockaddrAny + var len _Socklen = SizeofSockaddrAny + if err = getpeername(fd, &rsa, &len); err != nil { + return + } + return anyToSockaddr(fd, &rsa) + } func GetsockoptByte(fd, level, opt int) (value byte, err error) { + var n byte + vallen := _Socklen(1) + err = getsockopt(fd, level, opt, unsafe.Pointer(&n), &vallen) + return n, err + } func GetsockoptInt(fd, level, opt int) (value int, err error) { + var n int32 + vallen := _Socklen(4) + err = getsockopt(fd, level, opt, unsafe.Pointer(&n), &vallen) + return int(n), err + } func GetsockoptInet4Addr(fd, level, opt int) (value [4]byte, err error) { + vallen := _Socklen(4) + err = getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen) + return value, err + } func GetsockoptIPMreq(fd, level, opt int) (*IPMreq, error) { + var value IPMreq + vallen := _Socklen(SizeofIPMreq) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) + return &value, err + } func GetsockoptIPv6Mreq(fd, level, opt int) (*IPv6Mreq, error) { + var value IPv6Mreq + vallen := _Socklen(SizeofIPv6Mreq) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) + return &value, err + } func GetsockoptIPv6MTUInfo(fd, level, opt int) (*IPv6MTUInfo, error) { + var value IPv6MTUInfo + vallen := _Socklen(SizeofIPv6MTUInfo) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) + return &value, err + } func GetsockoptICMPv6Filter(fd, level, opt int) (*ICMPv6Filter, error) { + var value ICMPv6Filter + vallen := _Socklen(SizeofICMPv6Filter) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) + return &value, err + } func GetsockoptLinger(fd, level, opt int) (*Linger, error) { + var linger Linger + vallen := _Socklen(SizeofLinger) + err := getsockopt(fd, level, opt, unsafe.Pointer(&linger), &vallen) + return &linger, err + } func GetsockoptTimeval(fd, level, opt int) (*Timeval, error) { + var tv Timeval + vallen := _Socklen(unsafe.Sizeof(tv)) + err := getsockopt(fd, level, opt, unsafe.Pointer(&tv), &vallen) + return &tv, err + } func GetsockoptUint64(fd, level, opt int) (value uint64, err error) { + var n uint64 + vallen := _Socklen(8) + err = getsockopt(fd, level, opt, unsafe.Pointer(&n), &vallen) + return n, err + } func Recvfrom(fd int, p []byte, flags int) (n int, from Sockaddr, err error) { + var rsa RawSockaddrAny + var len _Socklen = SizeofSockaddrAny + if n, err = recvfrom(fd, p, flags, &rsa, &len); err != nil { + return + } + if rsa.Addr.Family != AF_UNSPEC { + from, err = anyToSockaddr(fd, &rsa) + } + return + } // Recvmsg receives a message from a socket using the recvmsg system call. The + // received non-control data will be written to p, and any "out of band" + // control data will be written to oob. The flags are passed to recvmsg. + // + // The results are: + // - n is the number of non-control data bytes read into p + // - oobn is the number of control data bytes read into oob; this may be interpreted using [ParseSocketControlMessage] + // - recvflags is flags returned by recvmsg + // - from is the address of the sender + // + // If the underlying socket type is not SOCK_DGRAM, a received message + // containing oob data and a single '\0' of non-control data is treated as if + // the message contained only control data, i.e. n will be zero on return. + func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) { + var iov [1]Iovec + if len(p) > 0 { + iov[0].Base = &p[0] + iov[0].SetLen(len(p)) + } + var rsa RawSockaddrAny + n, oobn, recvflags, err = recvmsgRaw(fd, iov[:], oob, flags, &rsa) + // source address is only specified if the socket is unconnected + if rsa.Addr.Family != AF_UNSPEC { + from, err = anyToSockaddr(fd, &rsa) + } + return + } // RecvmsgBuffers receives a message from a socket using the recvmsg system + // call. This function is equivalent to Recvmsg, but non-control data read is + // scattered into the buffers slices. + func RecvmsgBuffers(fd int, buffers [][]byte, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) { + iov := make([]Iovec, len(buffers)) + for i := range buffers { + if len(buffers[i]) > 0 { + iov[i].Base = &buffers[i][0] + iov[i].SetLen(len(buffers[i])) + } else { + iov[i].Base = (*byte)(unsafe.Pointer(&_zero)) + } + } + var rsa RawSockaddrAny + n, oobn, recvflags, err = recvmsgRaw(fd, iov, oob, flags, &rsa) + if err == nil && rsa.Addr.Family != AF_UNSPEC { + from, err = anyToSockaddr(fd, &rsa) + } + return + } // Sendmsg sends a message on a socket to an address using the sendmsg system + // call. This function is equivalent to SendmsgN, but does not return the + // number of bytes actually sent. + func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) { + _, err = SendmsgN(fd, p, oob, to, flags) + return + } // SendmsgN sends a message on a socket to an address using the sendmsg system + // call. p contains the non-control data to send, and oob contains the "out of + // band" control data. The flags are passed to sendmsg. The number of + // non-control bytes actually written to the socket is returned. + // + // Some socket types do not support sending control data without accompanying + // non-control data. If p is empty, and oob contains control data, and the + // underlying socket type is not SOCK_DGRAM, p will be treated as containing a + // single '\0' and the return value will indicate zero bytes sent. + // + // The Go function Recvmsg, if called with an empty p and a non-empty oob, + // will read and ignore this additional '\0'. If the message is received by + // code that does not use Recvmsg, or that does not use Go at all, that code + // will need to be written to expect and ignore the additional '\0'. + // + // If you need to send non-empty oob with p actually empty, and if the + // underlying socket type supports it, you can do so via a raw system call as + // follows: + // + // msg := &unix.Msghdr{ + // Control: &oob[0], + // } + // msg.SetControllen(len(oob)) + // n, _, errno := unix.Syscall(unix.SYS_SENDMSG, uintptr(fd), uintptr(unsafe.Pointer(msg)), flags) + func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) { + var iov [1]Iovec + if len(p) > 0 { + iov[0].Base = &p[0] + iov[0].SetLen(len(p)) + } + var ptr unsafe.Pointer + var salen _Socklen + if to != nil { + ptr, salen, err = to.sockaddr() + if err != nil { + return 0, err + } + } + return sendmsgN(fd, iov[:], oob, ptr, salen, flags) + } // SendmsgBuffers sends a message on a socket to an address using the sendmsg + // system call. This function is equivalent to SendmsgN, but the non-control + // data is gathered from buffers. + func SendmsgBuffers(fd int, buffers [][]byte, oob []byte, to Sockaddr, flags int) (n int, err error) { + iov := make([]Iovec, len(buffers)) + for i := range buffers { + if len(buffers[i]) > 0 { + iov[i].Base = &buffers[i][0] + iov[i].SetLen(len(buffers[i])) + } else { + iov[i].Base = (*byte)(unsafe.Pointer(&_zero)) + } + } + var ptr unsafe.Pointer + var salen _Socklen + if to != nil { + ptr, salen, err = to.sockaddr() + if err != nil { + return 0, err + } + } + return sendmsgN(fd, iov, oob, ptr, salen, flags) + } func Send(s int, buf []byte, flags int) (err error) { + return sendto(s, buf, flags, nil, 0) + } func Sendto(fd int, p []byte, flags int, to Sockaddr) (err error) { + var ptr unsafe.Pointer + var salen _Socklen + if to != nil { + ptr, salen, err = to.sockaddr() + if err != nil { + return err + } + } + return sendto(fd, p, flags, ptr, salen) + } func SetsockoptByte(fd, level, opt int, value byte) (err error) { + return setsockopt(fd, level, opt, unsafe.Pointer(&value), 1) + } func SetsockoptInt(fd, level, opt int, value int) (err error) { + var n = int32(value) + return setsockopt(fd, level, opt, unsafe.Pointer(&n), 4) + } func SetsockoptInet4Addr(fd, level, opt int, value [4]byte) (err error) { + return setsockopt(fd, level, opt, unsafe.Pointer(&value[0]), 4) + } func SetsockoptIPMreq(fd, level, opt int, mreq *IPMreq) (err error) { + return setsockopt(fd, level, opt, unsafe.Pointer(mreq), SizeofIPMreq) + } func SetsockoptIPv6Mreq(fd, level, opt int, mreq *IPv6Mreq) (err error) { + return setsockopt(fd, level, opt, unsafe.Pointer(mreq), SizeofIPv6Mreq) + } func SetsockoptICMPv6Filter(fd, level, opt int, filter *ICMPv6Filter) error { + return setsockopt(fd, level, opt, unsafe.Pointer(filter), SizeofICMPv6Filter) + } func SetsockoptLinger(fd, level, opt int, l *Linger) (err error) { + return setsockopt(fd, level, opt, unsafe.Pointer(l), SizeofLinger) + } func SetsockoptString(fd, level, opt int, s string) (err error) { + var p unsafe.Pointer + if len(s) > 0 { + p = unsafe.Pointer(&[]byte(s)[0]) + } + return setsockopt(fd, level, opt, p, uintptr(len(s))) + } func SetsockoptTimeval(fd, level, opt int, tv *Timeval) (err error) { + return setsockopt(fd, level, opt, unsafe.Pointer(tv), unsafe.Sizeof(*tv)) + } func SetsockoptUint64(fd, level, opt int, value uint64) (err error) { + return setsockopt(fd, level, opt, unsafe.Pointer(&value), 8) + } func Socket(domain, typ, proto int) (fd int, err error) { + if domain == AF_INET6 && SocketDisableIPv6 { + return -1, EAFNOSUPPORT + } + fd, err = socket(domain, typ, proto) + return + } func Socketpair(domain, typ, proto int) (fd [2]int, err error) { + var fdx [2]int32 + err = socketpair(domain, typ, proto, &fdx) + if err == nil { + fd[0] = int(fdx[0]) + fd[1] = int(fdx[1]) + } + return + } var ioSync int64 @@ -544,63 +934,114 @@ var ioSync int64 func CloseOnExec(fd int) { fcntl(fd, F_SETFD, FD_CLOEXEC) } func SetNonblock(fd int, nonblocking bool) (err error) { + flag, err := fcntl(fd, F_GETFL, 0) + if err != nil { + return err + } + if (flag&O_NONBLOCK != 0) == nonblocking { + return nil + } + if nonblocking { + flag |= O_NONBLOCK + } else { + flag &= ^O_NONBLOCK + } + _, err = fcntl(fd, F_SETFL, flag) + return err + } // Exec calls execve(2), which replaces the calling executable in the process + // tree. argv0 should be the full path to an executable ("/bin/ls") and the + // executable name should also be the first argument in argv (["ls", "-l"]). + // envv are the environment variables that should be passed to the new + // process (["USER=go", "PWD=/tmp"]). + func Exec(argv0 string, argv []string, envv []string) error { + return syscall.Exec(argv0, argv, envv) + } // Lutimes sets the access and modification times tv on path. If path refers to + // a symlink, it is not dereferenced and the timestamps are set on the symlink. + // If tv is nil, the access and modification times are set to the current time. + // Otherwise tv must contain exactly 2 elements, with access time as the first + // element and modification time as the second element. + func Lutimes(path string, tv []Timeval) error { + if tv == nil { + return UtimesNanoAt(AT_FDCWD, path, nil, AT_SYMLINK_NOFOLLOW) + } + if len(tv) != 2 { + return EINVAL + } + ts := []Timespec{ + NsecToTimespec(TimevalToNsec(tv[0])), + NsecToTimespec(TimevalToNsec(tv[1])), } + return UtimesNanoAt(AT_FDCWD, path, ts, AT_SYMLINK_NOFOLLOW) + } // emptyIovecs reports whether there are no bytes in the slice of Iovec. + func emptyIovecs(iov []Iovec) bool { + for i := range iov { + if iov[i].Len > 0 { + return false + } + } + return true + } // Setrlimit sets a resource limit. + func Setrlimit(resource int, rlim *Rlimit) error { + // Just call the syscall version, because as of Go 1.21 + // it will affect starting a new process. + return syscall.Setrlimit(resource, (*syscall.Rlimit)(rlim)) + } diff --git a/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go b/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go index 312ae6a..e9f04f4 100644 --- a/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go @@ -1,14 +1,21 @@ // Copyright 2020 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build zos && s390x // Many of the following syscalls are not available on all versions of z/OS. + // Some missing calls have legacy implementations/simulations but others + // will be missing completely. To achieve consistent failing behaviour on + // legacy systems, we first test the function pointer via a safeloading + // mechanism to see if the function exists on a given system. Then execution + // is branched to either continue the function call, or return an error. package unix @@ -28,663 +35,1160 @@ import ( ) //go:noescape + func initZosLibVec() //go:noescape + func GetZosLibVec() uintptr func init() { + initZosLibVec() + r0, _, _ := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS_____GETENV_A<<4, uintptr(unsafe.Pointer(&([]byte("__ZOS_XSYSTRACE\x00"))[0]))) + if r0 != 0 { + n, _, _ := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS___ATOI_A<<4, r0) + ZosTraceLevel = int(n) + r0, _, _ := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS_____GETENV_A<<4, uintptr(unsafe.Pointer(&([]byte("__ZOS_XSYSTRACEFD\x00"))[0]))) + if r0 != 0 { + fd, _, _ := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS___ATOI_A<<4, r0) + f := os.NewFile(fd, "zostracefile") + if f != nil { + ZosTracefile = f + } + } } + } //go:noescape + func CallLeFuncWithErr(funcdesc uintptr, parms ...uintptr) (ret, errno2 uintptr, err Errno) //go:noescape + func CallLeFuncWithPtrReturn(funcdesc uintptr, parms ...uintptr) (ret, errno2 uintptr, err Errno) // ------------------------------- + // pointer validity test + // good pointer returns 0 + // bad pointer returns 1 + // + //go:nosplit + func ptrtest(uintptr) uint64 // Load memory at ptr location with error handling if the location is invalid + // + //go:noescape + func safeload(ptr uintptr) (value uintptr, error uintptr) const ( entrypointLocationOffset = 8 // From function descriptor - xplinkEyecatcher = 0x00c300c500c500f1 // ".C.E.E.1" - eyecatcherOffset = 16 // From function entrypoint (negative) - ppa1LocationOffset = 8 // From function entrypoint (negative) + xplinkEyecatcher = 0x00c300c500c500f1 // ".C.E.E.1" + + eyecatcherOffset = 16 // From function entrypoint (negative) + + ppa1LocationOffset = 8 // From function entrypoint (negative) nameLenOffset = 0x14 // From PPA1 start - nameOffset = 0x16 // From PPA1 start + + nameOffset = 0x16 // From PPA1 start + ) func getPpaOffset(funcptr uintptr) int64 { + entrypoint, err := safeload(funcptr + entrypointLocationOffset) + if err != 0 { + return -1 + } // XPLink functions have ".C.E.E.1" as the first 8 bytes (EBCDIC) + val, err := safeload(entrypoint - eyecatcherOffset) + if err != 0 { + return -1 + } + if val != xplinkEyecatcher { + return -1 + } ppaoff, err := safeload(entrypoint - ppa1LocationOffset) + if err != 0 { + return -1 + } ppaoff >>= 32 + return int64(ppaoff) + } //------------------------------- + // function descriptor pointer validity test + // good pointer returns 0 + // bad pointer returns 1 // TODO: currently mksyscall_zos_s390x.go generate empty string for funcName + // have correct funcName pass to the funcptrtest function + func funcptrtest(funcptr uintptr, funcName string) uint64 { + entrypoint, err := safeload(funcptr + entrypointLocationOffset) + if err != 0 { + return 1 + } ppaoff := getPpaOffset(funcptr) + if ppaoff == -1 { + return 1 + } // PPA1 offset value is from the start of the entire function block, not the entrypoint + ppa1 := (entrypoint - eyecatcherOffset) + uintptr(ppaoff) nameLen, err := safeload(ppa1 + nameLenOffset) + if err != 0 { + return 1 + } nameLen >>= 48 + if nameLen > 128 { + return 1 + } // no function name input to argument end here + if funcName == "" { + return 0 + } var funcname [128]byte + for i := 0; i < int(nameLen); i += 8 { + v, err := safeload(ppa1 + nameOffset + uintptr(i)) + if err != 0 { + return 1 + } + funcname[i] = byte(v >> 56) + funcname[i+1] = byte(v >> 48) + funcname[i+2] = byte(v >> 40) + funcname[i+3] = byte(v >> 32) + funcname[i+4] = byte(v >> 24) + funcname[i+5] = byte(v >> 16) + funcname[i+6] = byte(v >> 8) + funcname[i+7] = byte(v) + } runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___E2A_L<<4, // __e2a_l + []uintptr{uintptr(unsafe.Pointer(&funcname[0])), nameLen}) name := string(funcname[:nameLen]) + if name != funcName { + return 1 + } return 0 + } // For detection of capabilities on a system. + // Is function descriptor f a valid function? + func isValidLeFunc(f uintptr) error { + ret := funcptrtest(f, "") + if ret != 0 { + return fmt.Errorf("Bad pointer, not an LE function ") + } + return nil + } // Retrieve function name from descriptor + func getLeFuncName(f uintptr) (string, error) { + // assume it has been checked, only check ppa1 validity here + entry := ((*[2]uintptr)(unsafe.Pointer(f)))[1] + preamp := ((*[4]uint32)(unsafe.Pointer(entry - eyecatcherOffset))) offsetPpa1 := preamp[2] + if offsetPpa1 > 0x0ffff { + return "", fmt.Errorf("PPA1 offset seems too big 0x%x\n", offsetPpa1) + } ppa1 := uintptr(unsafe.Pointer(preamp)) + uintptr(offsetPpa1) + res := ptrtest(ppa1) + if res != 0 { + return "", fmt.Errorf("PPA1 address not valid") + } size := *(*uint16)(unsafe.Pointer(ppa1 + nameLenOffset)) + if size > 128 { + return "", fmt.Errorf("Function name seems too long, length=%d\n", size) + } var name [128]byte + funcname := (*[128]byte)(unsafe.Pointer(ppa1 + nameOffset)) + copy(name[0:size], funcname[0:size]) runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___E2A_L<<4, // __e2a_l + []uintptr{uintptr(unsafe.Pointer(&name[0])), uintptr(size)}) return string(name[:size]), nil + } // Check z/OS version + func zosLeVersion() (version, release uint32) { + p1 := (*(*uintptr)(unsafe.Pointer(uintptr(1208)))) >> 32 + p1 = *(*uintptr)(unsafe.Pointer(uintptr(p1 + 88))) + p1 = *(*uintptr)(unsafe.Pointer(uintptr(p1 + 8))) + p1 = *(*uintptr)(unsafe.Pointer(uintptr(p1 + 984))) + vrm := *(*uint32)(unsafe.Pointer(p1 + 80)) + version = (vrm & 0x00ff0000) >> 16 + release = (vrm & 0x0000ff00) >> 8 + return + } // returns a zos C FILE * for stdio fd 0, 1, 2 + func ZosStdioFilep(fd int32) uintptr { + return uintptr(*(*uint64)(unsafe.Pointer(uintptr(*(*uint64)(unsafe.Pointer(uintptr(*(*uint64)(unsafe.Pointer(uintptr(uint64(*(*uint32)(unsafe.Pointer(uintptr(1208)))) + 80))) + uint64((fd+2)<<3)))))))) + } func copyStat(stat *Stat_t, statLE *Stat_LE_t) { + stat.Dev = uint64(statLE.Dev) + stat.Ino = uint64(statLE.Ino) + stat.Nlink = uint64(statLE.Nlink) + stat.Mode = uint32(statLE.Mode) + stat.Uid = uint32(statLE.Uid) + stat.Gid = uint32(statLE.Gid) + stat.Rdev = uint64(statLE.Rdev) + stat.Size = statLE.Size + stat.Atim.Sec = int64(statLE.Atim) + stat.Atim.Nsec = 0 //zos doesn't return nanoseconds + stat.Mtim.Sec = int64(statLE.Mtim) + stat.Mtim.Nsec = 0 //zos doesn't return nanoseconds + stat.Ctim.Sec = int64(statLE.Ctim) + stat.Ctim.Nsec = 0 //zos doesn't return nanoseconds + stat.Blksize = int64(statLE.Blksize) + stat.Blocks = statLE.Blocks + } func svcCall(fnptr unsafe.Pointer, argv *unsafe.Pointer, dsa *uint64) + func svcLoad(name *byte) unsafe.Pointer + func svcUnload(name *byte, fnptr unsafe.Pointer) int64 func (d *Dirent) NameString() string { + if d == nil { + return "" + } + s := string(d.Name[:]) + idx := strings.IndexByte(s, 0) + if idx == -1 { + return s + } else { + return s[:idx] + } + } func DecodeData(dest []byte, sz int, val uint64) { + for i := 0; i < sz; i++ { + dest[sz-1-i] = byte((val >> (uint64(i * 8))) & 0xff) + } + } func EncodeData(data []byte) uint64 { + var value uint64 + sz := len(data) + for i := 0; i < sz; i++ { + value |= uint64(data[i]) << uint64(((sz - i - 1) * 8)) + } + return value + } func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) { + if sa.Port < 0 || sa.Port > 0xFFFF { + return nil, 0, EINVAL + } + sa.raw.Len = SizeofSockaddrInet4 + sa.raw.Family = AF_INET + p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) + p[0] = byte(sa.Port >> 8) + p[1] = byte(sa.Port) + for i := 0; i < len(sa.Addr); i++ { + sa.raw.Addr[i] = sa.Addr[i] + } + return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil + } func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) { + if sa.Port < 0 || sa.Port > 0xFFFF { + return nil, 0, EINVAL + } + sa.raw.Len = SizeofSockaddrInet6 + sa.raw.Family = AF_INET6 + p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) + p[0] = byte(sa.Port >> 8) + p[1] = byte(sa.Port) + sa.raw.Scope_id = sa.ZoneId + for i := 0; i < len(sa.Addr); i++ { + sa.raw.Addr[i] = sa.Addr[i] + } + return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil + } func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) { + name := sa.Name + n := len(name) + if n >= len(sa.raw.Path) || n == 0 { + return nil, 0, EINVAL + } + sa.raw.Len = byte(3 + n) // 2 for Family, Len; 1 for NUL + sa.raw.Family = AF_UNIX + for i := 0; i < n; i++ { + sa.raw.Path[i] = int8(name[i]) + } + return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil + } func anyToSockaddr(_ int, rsa *RawSockaddrAny) (Sockaddr, error) { + // TODO(neeilan): Implement use of first param (fd) + switch rsa.Addr.Family { + case AF_UNIX: + pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa)) + sa := new(SockaddrUnix) + // For z/OS, only replace NUL with @ when the + // length is not zero. + if pp.Len != 0 && pp.Path[0] == 0 { + // "Abstract" Unix domain socket. + // Rewrite leading NUL as @ for textual display. + // (This is the standard convention.) + // Not friendly to overwrite in place, + // but the callers below don't care. + pp.Path[0] = '@' + } // Assume path ends at NUL. + // + // For z/OS, the length of the name is a field + // in the structure. To be on the safe side, we + // will still scan the name for a NUL but only + // to the length provided in the structure. + // + // This is not technically the Linux semantics for + // abstract Unix domain sockets--they are supposed + // to be uninterpreted fixed-size binary blobs--but + // everyone uses this convention. + n := 0 + for n < int(pp.Len) && pp.Path[n] != 0 { + n++ + } + sa.Name = string(unsafe.Slice((*byte)(unsafe.Pointer(&pp.Path[0])), n)) + return sa, nil case AF_INET: + pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa)) + sa := new(SockaddrInet4) + p := (*[2]byte)(unsafe.Pointer(&pp.Port)) + sa.Port = int(p[0])<<8 + int(p[1]) + for i := 0; i < len(sa.Addr); i++ { + sa.Addr[i] = pp.Addr[i] + } + return sa, nil case AF_INET6: + pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa)) + sa := new(SockaddrInet6) + p := (*[2]byte)(unsafe.Pointer(&pp.Port)) + sa.Port = int(p[0])<<8 + int(p[1]) + sa.ZoneId = pp.Scope_id + for i := 0; i < len(sa.Addr); i++ { + sa.Addr[i] = pp.Addr[i] + } + return sa, nil + } + return nil, EAFNOSUPPORT + } func Accept(fd int) (nfd int, sa Sockaddr, err error) { + var rsa RawSockaddrAny + var len _Socklen = SizeofSockaddrAny + nfd, err = accept(fd, &rsa, &len) + if err != nil { + return + } + // TODO(neeilan): Remove 0 in call + sa, err = anyToSockaddr(0, &rsa) + if err != nil { + Close(nfd) + nfd = 0 + } + return + } func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error) { + var rsa RawSockaddrAny + var len _Socklen = SizeofSockaddrAny + nfd, err = accept4(fd, &rsa, &len, flags) + if err != nil { + return + } + if len > SizeofSockaddrAny { + panic("RawSockaddrAny too small") + } + // TODO(neeilan): Remove 0 in call + sa, err = anyToSockaddr(0, &rsa) + if err != nil { + Close(nfd) + nfd = 0 + } + return + } func Ctermid() (tty string, err error) { + var termdev [1025]byte + runtime.EnterSyscall() + r0, err2, err1 := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS___CTERMID_A<<4, uintptr(unsafe.Pointer(&termdev[0]))) + runtime.ExitSyscall() + if r0 == 0 { + return "", fmt.Errorf("%s (errno2=0x%x)\n", err1.Error(), err2) + } + s := string(termdev[:]) + idx := strings.Index(s, string(rune(0))) + if idx == -1 { + tty = s + } else { + tty = s[:idx] + } + return + } func (iov *Iovec) SetLen(length int) { + iov.Len = uint64(length) + } func (msghdr *Msghdr) SetControllen(length int) { + msghdr.Controllen = int32(length) + } func (cmsg *Cmsghdr) SetLen(length int) { + cmsg.Len = int32(length) + } //sys fcntl(fd int, cmd int, arg int) (val int, err error) + //sys Flistxattr(fd int, dest []byte) (sz int, err error) = SYS___FLISTXATTR_A + //sys Fremovexattr(fd int, attr string) (err error) = SYS___FREMOVEXATTR_A + //sys read(fd int, p []byte) (n int, err error) + //sys write(fd int, p []byte) (n int, err error) //sys Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) = SYS___FGETXATTR_A + //sys Fsetxattr(fd int, attr string, data []byte, flag int) (err error) = SYS___FSETXATTR_A //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) = SYS___ACCEPT_A + //sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) = SYS___ACCEPT4_A + //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = SYS___BIND_A + //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = SYS___CONNECT_A + //sysnb getgroups(n int, list *_Gid_t) (nn int, err error) + //sysnb setgroups(n int, list *_Gid_t) (err error) + //sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) + //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) + //sysnb socket(domain int, typ int, proto int) (fd int, err error) + //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) + //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) = SYS___GETPEERNAME_A + //sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) = SYS___GETSOCKNAME_A + //sys Removexattr(path string, attr string) (err error) = SYS___REMOVEXATTR_A + //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) = SYS___RECVFROM_A + //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) = SYS___SENDTO_A + //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) = SYS___RECVMSG_A + //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) = SYS___SENDMSG_A + //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) = SYS_MMAP + //sys munmap(addr uintptr, length uintptr) (err error) = SYS_MUNMAP + //sys ioctl(fd int, req int, arg uintptr) (err error) = SYS_IOCTL + //sys ioctlPtr(fd int, req int, arg unsafe.Pointer) (err error) = SYS_IOCTL + //sys shmat(id int, addr uintptr, flag int) (ret uintptr, err error) = SYS_SHMAT + //sys shmctl(id int, cmd int, buf *SysvShmDesc) (result int, err error) = SYS_SHMCTL64 + //sys shmdt(addr uintptr) (err error) = SYS_SHMDT + //sys shmget(key int, size int, flag int) (id int, err error) = SYS_SHMGET //sys Access(path string, mode uint32) (err error) = SYS___ACCESS_A + //sys Chdir(path string) (err error) = SYS___CHDIR_A + //sys Chown(path string, uid int, gid int) (err error) = SYS___CHOWN_A + //sys Chmod(path string, mode uint32) (err error) = SYS___CHMOD_A + //sys Creat(path string, mode uint32) (fd int, err error) = SYS___CREAT_A + //sys Dup(oldfd int) (fd int, err error) + //sys Dup2(oldfd int, newfd int) (err error) + //sys Dup3(oldfd int, newfd int, flags int) (err error) = SYS_DUP3 + //sys Dirfd(dirp uintptr) (fd int, err error) = SYS_DIRFD + //sys EpollCreate(size int) (fd int, err error) = SYS_EPOLL_CREATE + //sys EpollCreate1(flags int) (fd int, err error) = SYS_EPOLL_CREATE1 + //sys EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) = SYS_EPOLL_CTL + //sys EpollPwait(epfd int, events []EpollEvent, msec int, sigmask *int) (n int, err error) = SYS_EPOLL_PWAIT + //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) = SYS_EPOLL_WAIT + //sys Errno2() (er2 int) = SYS___ERRNO2 + //sys Eventfd(initval uint, flags int) (fd int, err error) = SYS_EVENTFD + //sys Exit(code int) + //sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error) = SYS___FACCESSAT_A func Faccessat2(dirfd int, path string, mode uint32, flags int) (err error) { + return Faccessat(dirfd, path, mode, flags) + } //sys Fchdir(fd int) (err error) + //sys Fchmod(fd int, mode uint32) (err error) + //sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) = SYS___FCHMODAT_A + //sys Fchown(fd int, uid int, gid int) (err error) + //sys Fchownat(fd int, path string, uid int, gid int, flags int) (err error) = SYS___FCHOWNAT_A + //sys FcntlInt(fd uintptr, cmd int, arg int) (retval int, err error) = SYS_FCNTL + //sys Fdatasync(fd int) (err error) = SYS_FDATASYNC + //sys fstat(fd int, stat *Stat_LE_t) (err error) + //sys fstatat(dirfd int, path string, stat *Stat_LE_t, flags int) (err error) = SYS___FSTATAT_A func Fstat(fd int, stat *Stat_t) (err error) { + var statLE Stat_LE_t + err = fstat(fd, &statLE) + copyStat(stat, &statLE) + return + } func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var statLE Stat_LE_t + err = fstatat(dirfd, path, &statLE, flags) + copyStat(stat, &statLE) + return + } func impl_Getxattr(path string, attr string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(dest) > 0 { + _p2 = unsafe.Pointer(&dest[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___GETXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest))) + sz = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_GetxattrAddr() *(func(path string, attr string, dest []byte) (sz int, err error)) var Getxattr = enter_Getxattr func enter_Getxattr(path string, attr string, dest []byte) (sz int, err error) { + funcref := get_GetxattrAddr() + if validGetxattr() { + *funcref = impl_Getxattr + } else { + *funcref = error_Getxattr + } + return (*funcref)(path, attr, dest) + } func error_Getxattr(path string, attr string, dest []byte) (sz int, err error) { + return -1, ENOSYS + } func validGetxattr() bool { + if funcptrtest(GetZosLibVec()+SYS___GETXATTR_A<<4, "") == 0 { + if name, err := getLeFuncName(GetZosLibVec() + SYS___GETXATTR_A<<4); err == nil { + return name == "__getxattr_a" + } + } + return false + } //sys Lgetxattr(link string, attr string, dest []byte) (sz int, err error) = SYS___LGETXATTR_A + //sys Lsetxattr(path string, attr string, data []byte, flags int) (err error) = SYS___LSETXATTR_A func impl_Setxattr(path string, attr string, data []byte, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(data) > 0 { + _p2 = unsafe.Pointer(&data[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___SETXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_SetxattrAddr() *(func(path string, attr string, data []byte, flags int) (err error)) var Setxattr = enter_Setxattr func enter_Setxattr(path string, attr string, data []byte, flags int) (err error) { + funcref := get_SetxattrAddr() + if validSetxattr() { + *funcref = impl_Setxattr + } else { + *funcref = error_Setxattr + } + return (*funcref)(path, attr, data, flags) + } func error_Setxattr(path string, attr string, data []byte, flags int) (err error) { + return ENOSYS + } func validSetxattr() bool { + if funcptrtest(GetZosLibVec()+SYS___SETXATTR_A<<4, "") == 0 { + if name, err := getLeFuncName(GetZosLibVec() + SYS___SETXATTR_A<<4); err == nil { + return name == "__setxattr_a" + } + } + return false + } //sys Fstatfs(fd int, buf *Statfs_t) (err error) = SYS_FSTATFS + //sys Fstatvfs(fd int, stat *Statvfs_t) (err error) = SYS_FSTATVFS + //sys Fsync(fd int) (err error) + //sys Futimes(fd int, tv []Timeval) (err error) = SYS_FUTIMES + //sys Futimesat(dirfd int, path string, tv []Timeval) (err error) = SYS___FUTIMESAT_A + //sys Ftruncate(fd int, length int64) (err error) + //sys Getrandom(buf []byte, flags int) (n int, err error) = SYS_GETRANDOM + //sys InotifyInit() (fd int, err error) = SYS_INOTIFY_INIT + //sys InotifyInit1(flags int) (fd int, err error) = SYS_INOTIFY_INIT1 + //sys InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) = SYS___INOTIFY_ADD_WATCH_A + //sys InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) = SYS_INOTIFY_RM_WATCH + //sys Listxattr(path string, dest []byte) (sz int, err error) = SYS___LISTXATTR_A + //sys Llistxattr(path string, dest []byte) (sz int, err error) = SYS___LLISTXATTR_A + //sys Lremovexattr(path string, attr string) (err error) = SYS___LREMOVEXATTR_A + //sys Lutimes(path string, tv []Timeval) (err error) = SYS___LUTIMES_A + //sys Mprotect(b []byte, prot int) (err error) = SYS_MPROTECT + //sys Msync(b []byte, flags int) (err error) = SYS_MSYNC + //sys Console2(cmsg *ConsMsg2, modstr *byte, concmd *uint32) (err error) = SYS___CONSOLE2 // Pipe2 begin //go:nosplit + func getPipe2Addr() *(func([]int, int) error) var Pipe2 = pipe2Enter func pipe2Enter(p []int, flags int) (err error) { + if funcptrtest(GetZosLibVec()+SYS_PIPE2<<4, "") == 0 { + *getPipe2Addr() = pipe2Impl + } else { + *getPipe2Addr() = pipe2Error + } + return (*getPipe2Addr())(p, flags) + } func pipe2Impl(p []int, flags int) (err error) { + var pp [2]_C_int + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_PIPE2<<4, uintptr(unsafe.Pointer(&pp[0])), uintptr(flags)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } else { + p[0] = int(pp[0]) + p[1] = int(pp[1]) + } + return + } + func pipe2Error(p []int, flags int) (err error) { + return fmt.Errorf("Pipe2 is not available on this system") + } // Pipe2 end @@ -692,442 +1196,779 @@ func pipe2Error(p []int, flags int) (err error) { //sys Poll(fds []PollFd, timeout int) (n int, err error) = SYS_POLL func Readdir(dir uintptr) (dirent *Dirent, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___READDIR_A<<4, uintptr(dir)) + runtime.ExitSyscall() + dirent = (*Dirent)(unsafe.Pointer(r0)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //sys Readdir_r(dirp uintptr, entry *direntLE, result **direntLE) (err error) = SYS___READDIR_R_A + //sys Statfs(path string, buf *Statfs_t) (err error) = SYS___STATFS_A + //sys Syncfs(fd int) (err error) = SYS_SYNCFS + //sys Times(tms *Tms) (ticks uintptr, err error) = SYS_TIMES + //sys W_Getmntent(buff *byte, size int) (lastsys int, err error) = SYS_W_GETMNTENT + //sys W_Getmntent_A(buff *byte, size int) (lastsys int, err error) = SYS___W_GETMNTENT_A //sys mount_LE(path string, filesystem string, fstype string, mtm uint32, parmlen int32, parm string) (err error) = SYS___MOUNT_A + //sys unmount_LE(filesystem string, mtm int) (err error) = SYS___UMOUNT_A + //sys Chroot(path string) (err error) = SYS___CHROOT_A + //sys Select(nmsgsfds int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (ret int, err error) = SYS_SELECT + //sysnb Uname(buf *Utsname) (err error) = SYS_____OSNAME_A + //sys Unshare(flags int) (err error) = SYS_UNSHARE func Ptsname(fd int) (name string, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS___PTSNAME_A<<4, uintptr(fd)) + runtime.ExitSyscall() + if r0 == 0 { + err = errnoErr2(e1, e2) + } else { + name = u2s(unsafe.Pointer(r0)) + } + return + } func u2s(cstr unsafe.Pointer) string { + str := (*[1024]uint8)(cstr) + i := 0 + for str[i] != 0 { + i++ + } + return string(str[:i]) + } func Close(fd int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_CLOSE<<4, uintptr(fd)) + runtime.ExitSyscall() + for i := 0; e1 == EAGAIN && i < 10; i++ { + runtime.EnterSyscall() + CallLeFuncWithErr(GetZosLibVec()+SYS_USLEEP<<4, uintptr(10)) + runtime.ExitSyscall() + runtime.EnterSyscall() + r0, e2, e1 = CallLeFuncWithErr(GetZosLibVec()+SYS_CLOSE<<4, uintptr(fd)) + runtime.ExitSyscall() + } + if r0 != 0 { + err = errnoErr2(e1, e2) + } + return + } // Dummy function: there are no semantics for Madvise on z/OS + func Madvise(b []byte, advice int) (err error) { + return + } func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { + return mapper.Mmap(fd, offset, length, prot, flags) + } func Munmap(b []byte) (err error) { + return mapper.Munmap(b) + } //sys Gethostname(buf []byte) (err error) = SYS___GETHOSTNAME_A + //sysnb Getgid() (gid int) + //sysnb Getpid() (pid int) + //sysnb Getpgid(pid int) (pgid int, err error) = SYS_GETPGID func Getpgrp() (pid int) { + pid, _ = Getpgid(0) + return + } //sysnb Getppid() (pid int) + //sys Getpriority(which int, who int) (prio int, err error) + //sysnb Getrlimit(resource int, rlim *Rlimit) (err error) = SYS_GETRLIMIT //sysnb getrusage(who int, rusage *rusage_zos) (err error) = SYS_GETRUSAGE func Getrusage(who int, rusage *Rusage) (err error) { + var ruz rusage_zos + err = getrusage(who, &ruz) + //Only the first two fields of Rusage are set + rusage.Utime.Sec = ruz.Utime.Sec + rusage.Utime.Usec = int64(ruz.Utime.Usec) + rusage.Stime.Sec = ruz.Stime.Sec + rusage.Stime.Usec = int64(ruz.Stime.Usec) + return + } //sys Getegid() (egid int) = SYS_GETEGID + //sys Geteuid() (euid int) = SYS_GETEUID + //sysnb Getsid(pid int) (sid int, err error) = SYS_GETSID + //sysnb Getuid() (uid int) + //sysnb Kill(pid int, sig Signal) (err error) + //sys Lchown(path string, uid int, gid int) (err error) = SYS___LCHOWN_A + //sys Link(path string, link string) (err error) = SYS___LINK_A + //sys Linkat(oldDirFd int, oldPath string, newDirFd int, newPath string, flags int) (err error) = SYS___LINKAT_A + //sys Listen(s int, n int) (err error) + //sys lstat(path string, stat *Stat_LE_t) (err error) = SYS___LSTAT_A func Lstat(path string, stat *Stat_t) (err error) { + var statLE Stat_LE_t + err = lstat(path, &statLE) + copyStat(stat, &statLE) + return + } // for checking symlinks begins with $VERSION/ $SYSNAME/ $SYSSYMR/ $SYSSYMA/ + func isSpecialPath(path []byte) (v bool) { + var special = [4][8]byte{ + [8]byte{'V', 'E', 'R', 'S', 'I', 'O', 'N', '/'}, + [8]byte{'S', 'Y', 'S', 'N', 'A', 'M', 'E', '/'}, + [8]byte{'S', 'Y', 'S', 'S', 'Y', 'M', 'R', '/'}, + [8]byte{'S', 'Y', 'S', 'S', 'Y', 'M', 'A', '/'}} var i, j int + for i = 0; i < len(special); i++ { + for j = 0; j < len(special[i]); j++ { + if path[j] != special[i][j] { + break + } + } + if j == len(special[i]) { + return true + } + } + return false + } func realpath(srcpath string, abspath []byte) (pathlen int, errno int) { + var source [1024]byte + copy(source[:], srcpath) + source[len(srcpath)] = 0 + ret := runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___REALPATH_A<<4, //__realpath_a() + []uintptr{uintptr(unsafe.Pointer(&source[0])), + uintptr(unsafe.Pointer(&abspath[0]))}) + if ret != 0 { + index := bytes.IndexByte(abspath[:], byte(0)) + if index != -1 { + return index, 0 + } + } else { + errptr := (*int)(unsafe.Pointer(runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___ERRNO<<4, []uintptr{}))) //__errno() + return 0, *errptr + } + return 0, 245 // EBADDATA 245 + } func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + n = int(runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___READLINK_A<<4, + []uintptr{uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))})) + runtime.KeepAlive(unsafe.Pointer(_p0)) + if n == -1 { + value := *(*int32)(unsafe.Pointer(runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___ERRNO<<4, []uintptr{}))) + err = errnoErr(Errno(value)) + } else { + if buf[0] == '$' { + if isSpecialPath(buf[1:9]) { + cnt, err1 := realpath(path, buf) + if err1 == 0 { + n = cnt + } + } + } + } + return + } func impl_Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___READLINKAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + return n, err + } else { + if buf[0] == '$' { + if isSpecialPath(buf[1:9]) { + cnt, err1 := realpath(path, buf) + if err1 == 0 { + n = cnt + } + } + } + } + return + } //go:nosplit + func get_ReadlinkatAddr() *(func(dirfd int, path string, buf []byte) (n int, err error)) var Readlinkat = enter_Readlinkat func enter_Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + funcref := get_ReadlinkatAddr() + if funcptrtest(GetZosLibVec()+SYS___READLINKAT_A<<4, "") == 0 { + *funcref = impl_Readlinkat + } else { + *funcref = error_Readlinkat + } + return (*funcref)(dirfd, path, buf) + } func error_Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + n = -1 + err = ENOSYS + return + } //sys Mkdir(path string, mode uint32) (err error) = SYS___MKDIR_A + //sys Mkdirat(dirfd int, path string, mode uint32) (err error) = SYS___MKDIRAT_A + //sys Mkfifo(path string, mode uint32) (err error) = SYS___MKFIFO_A + //sys Mknod(path string, mode uint32, dev int) (err error) = SYS___MKNOD_A + //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error) = SYS___MKNODAT_A + //sys PivotRoot(newroot string, oldroot string) (err error) = SYS___PIVOT_ROOT_A + //sys Pread(fd int, p []byte, offset int64) (n int, err error) + //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) + //sys Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) = SYS___PRCTL_A + //sysnb Prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) = SYS_PRLIMIT + //sys Rename(from string, to string) (err error) = SYS___RENAME_A + //sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) = SYS___RENAMEAT_A + //sys Renameat2(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error) = SYS___RENAMEAT2_A + //sys Rmdir(path string) (err error) = SYS___RMDIR_A + //sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK + //sys Setegid(egid int) (err error) = SYS_SETEGID + //sys Seteuid(euid int) (err error) = SYS_SETEUID + //sys Sethostname(p []byte) (err error) = SYS___SETHOSTNAME_A + //sys Setns(fd int, nstype int) (err error) = SYS_SETNS + //sys Setpriority(which int, who int, prio int) (err error) + //sysnb Setpgid(pid int, pgid int) (err error) = SYS_SETPGID + //sysnb Setrlimit(resource int, lim *Rlimit) (err error) + //sysnb Setregid(rgid int, egid int) (err error) = SYS_SETREGID + //sysnb Setreuid(ruid int, euid int) (err error) = SYS_SETREUID + //sysnb Setsid() (pid int, err error) = SYS_SETSID + //sys Setuid(uid int) (err error) = SYS_SETUID + //sys Setgid(uid int) (err error) = SYS_SETGID + //sys Shutdown(fd int, how int) (err error) + //sys stat(path string, statLE *Stat_LE_t) (err error) = SYS___STAT_A func Stat(path string, sta *Stat_t) (err error) { + var statLE Stat_LE_t + err = stat(path, &statLE) + copyStat(sta, &statLE) + return + } //sys Symlink(path string, link string) (err error) = SYS___SYMLINK_A + //sys Symlinkat(oldPath string, dirfd int, newPath string) (err error) = SYS___SYMLINKAT_A + //sys Sync() = SYS_SYNC + //sys Truncate(path string, length int64) (err error) = SYS___TRUNCATE_A + //sys Tcgetattr(fildes int, termptr *Termios) (err error) = SYS_TCGETATTR + //sys Tcsetattr(fildes int, when int, termptr *Termios) (err error) = SYS_TCSETATTR + //sys Umask(mask int) (oldmask int) + //sys Unlink(path string) (err error) = SYS___UNLINK_A + //sys Unlinkat(dirfd int, path string, flags int) (err error) = SYS___UNLINKAT_A + //sys Utime(path string, utim *Utimbuf) (err error) = SYS___UTIME_A //sys open(path string, mode int, perm uint32) (fd int, err error) = SYS___OPEN_A func Open(path string, mode int, perm uint32) (fd int, err error) { + if mode&O_ACCMODE == 0 { + mode |= O_RDONLY + } + return open(path, mode, perm) + } //sys openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) = SYS___OPENAT_A func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { + if flags&O_ACCMODE == 0 { + flags |= O_RDONLY + } + return openat(dirfd, path, flags, mode) + } //sys openat2(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error) = SYS___OPENAT2_A func Openat2(dirfd int, path string, how *OpenHow) (fd int, err error) { + if how.Flags&O_ACCMODE == 0 { + how.Flags |= O_RDONLY + } + return openat2(dirfd, path, how, SizeofOpenHow) + } func ZosFdToPath(dirfd int) (path string, err error) { + var buffer [1024]byte + runtime.EnterSyscall() + ret, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_W_IOCTL<<4, uintptr(dirfd), 17, 1024, uintptr(unsafe.Pointer(&buffer[0]))) + runtime.ExitSyscall() + if ret == 0 { + zb := bytes.IndexByte(buffer[:], 0) + if zb == -1 { + zb = len(buffer) + } + CallLeFuncWithErr(GetZosLibVec()+SYS___E2A_L<<4, uintptr(unsafe.Pointer(&buffer[0])), uintptr(zb)) + return string(buffer[:zb]), nil + } + return "", errnoErr2(e1, e2) + } //sys remove(path string) (err error) func Remove(path string) error { + return remove(path) + } const ImplementsGetwd = true func Getcwd(buf []byte) (n int, err error) { + var p unsafe.Pointer + if len(buf) > 0 { + p = unsafe.Pointer(&buf[0]) + } else { + p = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS___GETCWD_A<<4, uintptr(p), uintptr(len(buf))) + runtime.ExitSyscall() + n = clen(buf) + 1 + if r0 == 0 { + err = errnoErr2(e1, e2) + } + return + } func Getwd() (wd string, err error) { + var buf [PathMax]byte + n, err := Getcwd(buf[0:]) + if err != nil { + return "", err + } + // Getcwd returns the number of bytes written to buf, including the NUL. + if n < 1 || n > len(buf) || buf[n-1] != 0 { + return "", EINVAL + } + return string(buf[0 : n-1]), nil + } func Getgroups() (gids []int, err error) { + n, err := getgroups(0, nil) + if err != nil { + return nil, err + } + if n == 0 { + return nil, nil + } // Sanity check group count. Max is 1<<16 on Linux. + if n < 0 || n > 1<<20 { + return nil, EINVAL + } a := make([]_Gid_t, n) + n, err = getgroups(n, &a[0]) + if err != nil { + return nil, err + } + gids = make([]int, n) + for i, v := range a[0:n] { + gids[i] = int(v) + } + return + } func Setgroups(gids []int) (err error) { + if len(gids) == 0 { + return setgroups(0, nil) + } a := make([]_Gid_t, len(gids)) + for i, v := range gids { + a[i] = _Gid_t(v) + } + return setgroups(len(a), &a[0]) + } func gettid() uint64 func Gettid() (tid int) { + return int(gettid()) + } type WaitStatus uint32 // Wait status is 7 bits at bottom, either 0 (exited), + // 0x7F (stopped), or a signal number that caused an exit. + // The 0x80 bit is whether there was a core dump. + // An extra number (exit code, signal causing a stop) + // is in the high bits. At least that's the idea. + // There are various irregularities. For example, the + // "continued" status is 0xFFFF, distinguishing itself + // from stopped via the core dump bit. const ( - mask = 0x7F - core = 0x80 - exited = 0x00 + mask = 0x7F + + core = 0x80 + + exited = 0x00 + stopped = 0x7F - shift = 8 + + shift = 8 ) func (w WaitStatus) Exited() bool { return w&mask == exited } @@ -1141,24 +1982,39 @@ func (w WaitStatus) Continued() bool { return w == 0xFFFF } func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 } func (w WaitStatus) ExitStatus() int { + if !w.Exited() { + return -1 + } + return int(w>>shift) & 0xFF + } func (w WaitStatus) Signal() Signal { + if !w.Signaled() { + return -1 + } + return Signal(w & mask) + } func (w WaitStatus) StopSignal() Signal { + if !w.Stopped() { + return -1 + } + return Signal(w>>shift) & 0xFF + } func (w WaitStatus) TrapCause() int { return -1 } @@ -1166,152 +2022,252 @@ func (w WaitStatus) TrapCause() int { return -1 } //sys waitid(idType int, id int, info *Siginfo, options int) (err error) func Waitid(idType int, id int, info *Siginfo, options int, rusage *Rusage) (err error) { + return waitid(idType, id, info, options) + } //sys waitpid(pid int, wstatus *_C_int, options int) (wpid int, err error) func impl_Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_WAIT4<<4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage))) + runtime.ExitSyscall() + wpid = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_Wait4Addr() *(func(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error)) var Wait4 = enter_Wait4 func enter_Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) { + funcref := get_Wait4Addr() + if funcptrtest(GetZosLibVec()+SYS_WAIT4<<4, "") == 0 { + *funcref = impl_Wait4 + } else { + *funcref = legacyWait4 + } + return (*funcref)(pid, wstatus, options, rusage) + } func legacyWait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) { + // TODO(mundaym): z/OS doesn't have wait4. I don't think getrusage does what we want. + // At the moment rusage will not be touched. + var status _C_int + wpid, err = waitpid(pid, &status, options) + if wstatus != nil { + *wstatus = WaitStatus(status) + } + return + } //sysnb gettimeofday(tv *timeval_zos) (err error) func Gettimeofday(tv *Timeval) (err error) { + var tvz timeval_zos + err = gettimeofday(&tvz) + tv.Sec = tvz.Sec + tv.Usec = int64(tvz.Usec) + return + } func Time(t *Time_t) (tt Time_t, err error) { + var tv Timeval + err = Gettimeofday(&tv) + if err != nil { + return 0, err + } + if t != nil { + *t = Time_t(tv.Sec) + } + return Time_t(tv.Sec), nil + } func setTimespec(sec, nsec int64) Timespec { + return Timespec{Sec: sec, Nsec: nsec} + } func setTimeval(sec, usec int64) Timeval { //fix + return Timeval{Sec: sec, Usec: usec} + } //sysnb pipe(p *[2]_C_int) (err error) func Pipe(p []int) (err error) { + if len(p) != 2 { + return EINVAL + } + var pp [2]_C_int + err = pipe(&pp) + p[0] = int(pp[0]) + p[1] = int(pp[1]) + return + } //sys utimes(path string, timeval *[2]Timeval) (err error) = SYS___UTIMES_A func Utimes(path string, tv []Timeval) (err error) { + if tv == nil { + return utimes(path, nil) + } + if len(tv) != 2 { + return EINVAL + } + return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) + } //sys utimensat(dirfd int, path string, ts *[2]Timespec, flags int) (err error) = SYS___UTIMENSAT_A func validUtimensat() bool { + if funcptrtest(GetZosLibVec()+SYS___UTIMENSAT_A<<4, "") == 0 { + if name, err := getLeFuncName(GetZosLibVec() + SYS___UTIMENSAT_A<<4); err == nil { + return name == "__utimensat_a" + } + } + return false + } // Begin UtimesNano //go:nosplit + func get_UtimesNanoAddr() *(func(path string, ts []Timespec) (err error)) var UtimesNano = enter_UtimesNano func enter_UtimesNano(path string, ts []Timespec) (err error) { + funcref := get_UtimesNanoAddr() + if validUtimensat() { + *funcref = utimesNanoImpl + } else { + *funcref = legacyUtimesNano + } + return (*funcref)(path, ts) + } func utimesNanoImpl(path string, ts []Timespec) (err error) { + if ts == nil { + return utimensat(AT_FDCWD, path, nil, 0) + } + if len(ts) != 2 { + return EINVAL + } + return utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0) + } func legacyUtimesNano(path string, ts []Timespec) (err error) { + if len(ts) != 2 { + return EINVAL + } + // Not as efficient as it could be because Timespec and + // Timeval have different types in the different OSes + tv := [2]Timeval{ + NsecToTimeval(TimespecToNsec(ts[0])), + NsecToTimeval(TimespecToNsec(ts[1])), } + return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) + } // End UtimesNano @@ -1319,354 +2275,643 @@ func legacyUtimesNano(path string, ts []Timespec) (err error) { // Begin UtimesNanoAt //go:nosplit + func get_UtimesNanoAtAddr() *(func(dirfd int, path string, ts []Timespec, flags int) (err error)) var UtimesNanoAt = enter_UtimesNanoAt func enter_UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) (err error) { + funcref := get_UtimesNanoAtAddr() + if validUtimensat() { + *funcref = utimesNanoAtImpl + } else { + *funcref = legacyUtimesNanoAt + } + return (*funcref)(dirfd, path, ts, flags) + } func utimesNanoAtImpl(dirfd int, path string, ts []Timespec, flags int) (err error) { + if ts == nil { + return utimensat(dirfd, path, nil, flags) + } + if len(ts) != 2 { + return EINVAL + } + return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags) + } func legacyUtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) (err error) { + if path[0] != '/' { + dirPath, err := ZosFdToPath(dirfd) + if err != nil { + return err + } + path = dirPath + "/" + path + } + if flags == AT_SYMLINK_NOFOLLOW { + if len(ts) != 2 { + return EINVAL + } if ts[0].Nsec >= 5e8 { + ts[0].Sec++ + } + ts[0].Nsec = 0 + if ts[1].Nsec >= 5e8 { + ts[1].Sec++ + } + ts[1].Nsec = 0 // Not as efficient as it could be because Timespec and + // Timeval have different types in the different OSes + tv := []Timeval{ + NsecToTimeval(TimespecToNsec(ts[0])), + NsecToTimeval(TimespecToNsec(ts[1])), } + return Lutimes(path, tv) + } + return UtimesNano(path, ts) + } // End UtimesNanoAt func Getsockname(fd int) (sa Sockaddr, err error) { + var rsa RawSockaddrAny + var len _Socklen = SizeofSockaddrAny + if err = getsockname(fd, &rsa, &len); err != nil { + return + } + // TODO(neeilan) : Remove this 0 ( added to get sys/unix compiling on z/OS ) + return anyToSockaddr(0, &rsa) + } const ( + // identifier constants - nwmHeaderIdentifier = 0xd5e6d4c8 - nwmFilterIdentifier = 0xd5e6d4c6 - nwmTCPConnIdentifier = 0xd5e6d4c3 + + nwmHeaderIdentifier = 0xd5e6d4c8 + + nwmFilterIdentifier = 0xd5e6d4c6 + + nwmTCPConnIdentifier = 0xd5e6d4c3 + nwmRecHeaderIdentifier = 0xd5e6d4d9 - nwmIPStatsIdentifier = 0xd5e6d4c9d7e2e340 - nwmIPGStatsIdentifier = 0xd5e6d4c9d7c7e2e3 - nwmTCPStatsIdentifier = 0xd5e6d4e3c3d7e2e3 - nwmUDPStatsIdentifier = 0xd5e6d4e4c4d7e2e3 - nwmICMPGStatsEntry = 0xd5e6d4c9c3d4d7c7 - nwmICMPTStatsEntry = 0xd5e6d4c9c3d4d7e3 + + nwmIPStatsIdentifier = 0xd5e6d4c9d7e2e340 + + nwmIPGStatsIdentifier = 0xd5e6d4c9d7c7e2e3 + + nwmTCPStatsIdentifier = 0xd5e6d4e3c3d7e2e3 + + nwmUDPStatsIdentifier = 0xd5e6d4e4c4d7e2e3 + + nwmICMPGStatsEntry = 0xd5e6d4c9c3d4d7c7 + + nwmICMPTStatsEntry = 0xd5e6d4c9c3d4d7e3 // nwmHeader constants - nwmVersion1 = 1 - nwmVersion2 = 2 + + nwmVersion1 = 1 + + nwmVersion2 = 2 + nwmCurrentVer = 2 - nwmTCPConnType = 1 + nwmTCPConnType = 1 + nwmGlobalStatsType = 14 // nwmFilter constants + nwmFilterLclAddrMask = 0x20000000 // Local address + nwmFilterSrcAddrMask = 0x20000000 // Source address + nwmFilterLclPortMask = 0x10000000 // Local port + nwmFilterSrcPortMask = 0x10000000 // Source port // nwmConnEntry constants - nwmTCPStateClosed = 1 - nwmTCPStateListen = 2 - nwmTCPStateSynSent = 3 - nwmTCPStateSynRcvd = 4 - nwmTCPStateEstab = 5 + + nwmTCPStateClosed = 1 + + nwmTCPStateListen = 2 + + nwmTCPStateSynSent = 3 + + nwmTCPStateSynRcvd = 4 + + nwmTCPStateEstab = 5 + nwmTCPStateFinWait1 = 6 + nwmTCPStateFinWait2 = 7 + nwmTCPStateClosWait = 8 - nwmTCPStateLastAck = 9 - nwmTCPStateClosing = 10 + + nwmTCPStateLastAck = 9 + + nwmTCPStateClosing = 10 + nwmTCPStateTimeWait = 11 + nwmTCPStateDeletTCB = 12 // Existing constants on linux - BPF_TCP_CLOSE = 1 - BPF_TCP_LISTEN = 2 - BPF_TCP_SYN_SENT = 3 - BPF_TCP_SYN_RECV = 4 - BPF_TCP_ESTABLISHED = 5 - BPF_TCP_FIN_WAIT1 = 6 - BPF_TCP_FIN_WAIT2 = 7 - BPF_TCP_CLOSE_WAIT = 8 - BPF_TCP_LAST_ACK = 9 - BPF_TCP_CLOSING = 10 - BPF_TCP_TIME_WAIT = 11 + + BPF_TCP_CLOSE = 1 + + BPF_TCP_LISTEN = 2 + + BPF_TCP_SYN_SENT = 3 + + BPF_TCP_SYN_RECV = 4 + + BPF_TCP_ESTABLISHED = 5 + + BPF_TCP_FIN_WAIT1 = 6 + + BPF_TCP_FIN_WAIT2 = 7 + + BPF_TCP_CLOSE_WAIT = 8 + + BPF_TCP_LAST_ACK = 9 + + BPF_TCP_CLOSING = 10 + + BPF_TCP_TIME_WAIT = 11 + BPF_TCP_NEW_SYN_RECV = -1 - BPF_TCP_MAX_STATES = -2 + + BPF_TCP_MAX_STATES = -2 ) type nwmTriplet struct { offset uint32 + length uint32 + number uint32 } type nwmQuadruplet struct { offset uint32 + length uint32 + number uint32 - match uint32 + + match uint32 } type nwmHeader struct { - ident uint32 - length uint32 - version uint16 - nwmType uint16 + ident uint32 + + length uint32 + + version uint16 + + nwmType uint16 + bytesNeeded uint32 - options uint32 - _ [16]byte - inputDesc nwmTriplet - outputDesc nwmQuadruplet + + options uint32 + + _ [16]byte + + inputDesc nwmTriplet + + outputDesc nwmQuadruplet } type nwmFilter struct { - ident uint32 - flags uint32 - resourceName [8]byte - resourceId uint32 - listenerId uint32 - local [28]byte // union of sockaddr4 and sockaddr6 - remote [28]byte // union of sockaddr4 and sockaddr6 - _ uint16 - _ uint16 - asid uint16 - _ [2]byte - tnLuName [8]byte - tnMonGrp uint32 - tnAppl [8]byte - applData [40]byte - nInterface [16]byte - dVipa [16]byte - dVipaPfx uint16 - dVipaPort uint16 - dVipaFamily byte - _ [3]byte - destXCF [16]byte - destXCFPfx uint16 + ident uint32 + + flags uint32 + + resourceName [8]byte + + resourceId uint32 + + listenerId uint32 + + local [28]byte // union of sockaddr4 and sockaddr6 + + remote [28]byte // union of sockaddr4 and sockaddr6 + + _ uint16 + + _ uint16 + + asid uint16 + + _ [2]byte + + tnLuName [8]byte + + tnMonGrp uint32 + + tnAppl [8]byte + + applData [40]byte + + nInterface [16]byte + + dVipa [16]byte + + dVipaPfx uint16 + + dVipaPort uint16 + + dVipaFamily byte + + _ [3]byte + + destXCF [16]byte + + destXCFPfx uint16 + destXCFFamily byte - _ [1]byte - targIP [16]byte - targIPPfx uint16 - targIPFamily byte - _ [1]byte - _ [20]byte + + _ [1]byte + + targIP [16]byte + + targIPPfx uint16 + + targIPFamily byte + + _ [1]byte + + _ [20]byte } type nwmRecHeader struct { - ident uint32 + ident uint32 + length uint32 + number byte - _ [3]byte + + _ [3]byte } type nwmTCPStatsEntry struct { - ident uint64 - currEstab uint32 - activeOpened uint32 - passiveOpened uint32 - connClosed uint32 - estabResets uint32 - attemptFails uint32 - passiveDrops uint32 - timeWaitReused uint32 - inSegs uint64 - predictAck uint32 - predictData uint32 - inDupAck uint32 - inBadSum uint32 - inBadLen uint32 - inShort uint32 - inDiscOldTime uint32 - inAllBeforeWin uint32 - inSomeBeforeWin uint32 - inAllAfterWin uint32 - inSomeAfterWin uint32 - inOutOfOrder uint32 - inAfterClose uint32 - inWinProbes uint32 - inWinUpdates uint32 - outWinUpdates uint32 - outSegs uint64 - outDelayAcks uint32 - outRsts uint32 - retransSegs uint32 - retransTimeouts uint32 - retransDrops uint32 - pmtuRetrans uint32 - pmtuErrors uint32 - outWinProbes uint32 - probeDrops uint32 - keepAliveProbes uint32 - keepAliveDrops uint32 - finwait2Drops uint32 - acceptCount uint64 - inBulkQSegs uint64 - inDiscards uint64 - connFloods uint32 - connStalls uint32 - cfgEphemDef uint16 - ephemInUse uint16 - ephemHiWater uint16 - flags byte - _ [1]byte - ephemExhaust uint32 + ident uint64 + + currEstab uint32 + + activeOpened uint32 + + passiveOpened uint32 + + connClosed uint32 + + estabResets uint32 + + attemptFails uint32 + + passiveDrops uint32 + + timeWaitReused uint32 + + inSegs uint64 + + predictAck uint32 + + predictData uint32 + + inDupAck uint32 + + inBadSum uint32 + + inBadLen uint32 + + inShort uint32 + + inDiscOldTime uint32 + + inAllBeforeWin uint32 + + inSomeBeforeWin uint32 + + inAllAfterWin uint32 + + inSomeAfterWin uint32 + + inOutOfOrder uint32 + + inAfterClose uint32 + + inWinProbes uint32 + + inWinUpdates uint32 + + outWinUpdates uint32 + + outSegs uint64 + + outDelayAcks uint32 + + outRsts uint32 + + retransSegs uint32 + + retransTimeouts uint32 + + retransDrops uint32 + + pmtuRetrans uint32 + + pmtuErrors uint32 + + outWinProbes uint32 + + probeDrops uint32 + + keepAliveProbes uint32 + + keepAliveDrops uint32 + + finwait2Drops uint32 + + acceptCount uint64 + + inBulkQSegs uint64 + + inDiscards uint64 + + connFloods uint32 + + connStalls uint32 + + cfgEphemDef uint16 + + ephemInUse uint16 + + ephemHiWater uint16 + + flags byte + + _ [1]byte + + ephemExhaust uint32 + smcRCurrEstabLnks uint32 + smcRLnkActTimeOut uint32 - smcRActLnkOpened uint32 - smcRPasLnkOpened uint32 - smcRLnksClosed uint32 - smcRCurrEstab uint32 - smcRActiveOpened uint32 + + smcRActLnkOpened uint32 + + smcRPasLnkOpened uint32 + + smcRLnksClosed uint32 + + smcRCurrEstab uint32 + + smcRActiveOpened uint32 + smcRPassiveOpened uint32 - smcRConnClosed uint32 - smcRInSegs uint64 - smcROutSegs uint64 - smcRInRsts uint32 - smcROutRsts uint32 + + smcRConnClosed uint32 + + smcRInSegs uint64 + + smcROutSegs uint64 + + smcRInRsts uint32 + + smcROutRsts uint32 + smcDCurrEstabLnks uint32 - smcDActLnkOpened uint32 - smcDPasLnkOpened uint32 - smcDLnksClosed uint32 - smcDCurrEstab uint32 - smcDActiveOpened uint32 + + smcDActLnkOpened uint32 + + smcDPasLnkOpened uint32 + + smcDLnksClosed uint32 + + smcDCurrEstab uint32 + + smcDActiveOpened uint32 + smcDPassiveOpened uint32 - smcDConnClosed uint32 - smcDInSegs uint64 - smcDOutSegs uint64 - smcDInRsts uint32 - smcDOutRsts uint32 + + smcDConnClosed uint32 + + smcDInSegs uint64 + + smcDOutSegs uint64 + + smcDInRsts uint32 + + smcDOutRsts uint32 } type nwmConnEntry struct { - ident uint32 - local [28]byte // union of sockaddr4 and sockaddr6 - remote [28]byte // union of sockaddr4 and sockaddr6 - startTime [8]byte // uint64, changed to prevent padding from being inserted - lastActivity [8]byte // uint64 - bytesIn [8]byte // uint64 - bytesOut [8]byte // uint64 - inSegs [8]byte // uint64 - outSegs [8]byte // uint64 - state uint16 - activeOpen byte - flag01 byte - outBuffered uint32 - inBuffered uint32 - maxSndWnd uint32 - reXmtCount uint32 - congestionWnd uint32 - ssThresh uint32 - roundTripTime uint32 - roundTripVar uint32 - sendMSS uint32 - sndWnd uint32 - rcvBufSize uint32 - sndBufSize uint32 - outOfOrderCount uint32 - lcl0WindowCount uint32 - rmt0WindowCount uint32 - dupacks uint32 - flag02 byte - sockOpt6Cont byte - asid uint16 - resourceName [8]byte - resourceId uint32 - subtask uint32 - sockOpt byte - sockOpt6 byte - clusterConnFlag byte - proto byte - targetAppl [8]byte - luName [8]byte - clientUserId [8]byte - logMode [8]byte - timeStamp uint32 - timeStampAge uint32 - serverResourceId uint32 - intfName [16]byte - ttlsStatPol byte - ttlsStatConn byte - ttlsSSLProt uint16 - ttlsNegCiph [2]byte - ttlsSecType byte - ttlsFIPS140Mode byte - ttlsUserID [8]byte - applData [40]byte - inOldestTime [8]byte // uint64 - outOldestTime [8]byte // uint64 + ident uint32 + + local [28]byte // union of sockaddr4 and sockaddr6 + + remote [28]byte // union of sockaddr4 and sockaddr6 + + startTime [8]byte // uint64, changed to prevent padding from being inserted + + lastActivity [8]byte // uint64 + + bytesIn [8]byte // uint64 + + bytesOut [8]byte // uint64 + + inSegs [8]byte // uint64 + + outSegs [8]byte // uint64 + + state uint16 + + activeOpen byte + + flag01 byte + + outBuffered uint32 + + inBuffered uint32 + + maxSndWnd uint32 + + reXmtCount uint32 + + congestionWnd uint32 + + ssThresh uint32 + + roundTripTime uint32 + + roundTripVar uint32 + + sendMSS uint32 + + sndWnd uint32 + + rcvBufSize uint32 + + sndBufSize uint32 + + outOfOrderCount uint32 + + lcl0WindowCount uint32 + + rmt0WindowCount uint32 + + dupacks uint32 + + flag02 byte + + sockOpt6Cont byte + + asid uint16 + + resourceName [8]byte + + resourceId uint32 + + subtask uint32 + + sockOpt byte + + sockOpt6 byte + + clusterConnFlag byte + + proto byte + + targetAppl [8]byte + + luName [8]byte + + clientUserId [8]byte + + logMode [8]byte + + timeStamp uint32 + + timeStampAge uint32 + + serverResourceId uint32 + + intfName [16]byte + + ttlsStatPol byte + + ttlsStatConn byte + + ttlsSSLProt uint16 + + ttlsNegCiph [2]byte + + ttlsSecType byte + + ttlsFIPS140Mode byte + + ttlsUserID [8]byte + + applData [40]byte + + inOldestTime [8]byte // uint64 + + outOldestTime [8]byte // uint64 + tcpTrustedPartner byte - _ [3]byte - bulkDataIntfName [16]byte - ttlsNegCiph4 [4]byte - smcReason uint32 - lclSMCLinkId uint32 - rmtSMCLinkId uint32 - smcStatus byte - smcFlags byte - _ [2]byte - rcvWnd uint32 - lclSMCBufSz uint32 - rmtSMCBufSz uint32 - ttlsSessID [32]byte - ttlsSessIDLen int16 - _ [1]byte - smcDStatus byte - smcDReason uint32 + + _ [3]byte + + bulkDataIntfName [16]byte + + ttlsNegCiph4 [4]byte + + smcReason uint32 + + lclSMCLinkId uint32 + + rmtSMCLinkId uint32 + + smcStatus byte + + smcFlags byte + + _ [2]byte + + rcvWnd uint32 + + lclSMCBufSz uint32 + + rmtSMCBufSz uint32 + + ttlsSessID [32]byte + + ttlsSessIDLen int16 + + _ [1]byte + + smcDStatus byte + + smcDReason uint32 } var svcNameTable [][]byte = [][]byte{ + []byte("\xc5\xe9\xc2\xd5\xd4\xc9\xc6\xf4"), // svc_EZBNMIF4 + } const ( @@ -1674,536 +2919,956 @@ const ( ) func GetsockoptTCPInfo(fd, level, opt int) (*TCPInfo, error) { + jobname := []byte("\x5c\x40\x40\x40\x40\x40\x40\x40") // "*" + responseBuffer := [4096]byte{0} + var bufferAlet, reasonCode uint32 = 0, 0 + var bufferLen, returnValue, returnCode int32 = 4096, 0, 0 dsa := [18]uint64{0} + var argv [7]unsafe.Pointer + argv[0] = unsafe.Pointer(&jobname[0]) + argv[1] = unsafe.Pointer(&responseBuffer[0]) + argv[2] = unsafe.Pointer(&bufferAlet) + argv[3] = unsafe.Pointer(&bufferLen) + argv[4] = unsafe.Pointer(&returnValue) + argv[5] = unsafe.Pointer(&returnCode) + argv[6] = unsafe.Pointer(&reasonCode) request := (*struct { header nwmHeader + filter nwmFilter })(unsafe.Pointer(&responseBuffer[0])) EZBNMIF4 := svcLoad(&svcNameTable[svc_EZBNMIF4][0]) + if EZBNMIF4 == nil { + return nil, errnoErr(EINVAL) + } // GetGlobalStats EZBNMIF4 call + request.header.ident = nwmHeaderIdentifier + request.header.length = uint32(unsafe.Sizeof(request.header)) + request.header.version = nwmCurrentVer + request.header.nwmType = nwmGlobalStatsType + request.header.options = 0x80000000 svcCall(EZBNMIF4, &argv[0], &dsa[0]) // outputDesc field is filled by EZBNMIF4 on success + if returnCode != 0 || request.header.outputDesc.offset == 0 { + return nil, errnoErr(EINVAL) + } // Check that EZBNMIF4 returned a nwmRecHeader + recHeader := (*nwmRecHeader)(unsafe.Pointer(&responseBuffer[request.header.outputDesc.offset])) + if recHeader.ident != nwmRecHeaderIdentifier { + return nil, errnoErr(EINVAL) + } // Parse nwmTriplets to get offsets of returned entries + var sections []*uint64 + var sectionDesc *nwmTriplet = (*nwmTriplet)(unsafe.Pointer(&responseBuffer[0])) + for i := uint32(0); i < uint32(recHeader.number); i++ { + offset := request.header.outputDesc.offset + uint32(unsafe.Sizeof(*recHeader)) + i*uint32(unsafe.Sizeof(*sectionDesc)) + sectionDesc = (*nwmTriplet)(unsafe.Pointer(&responseBuffer[offset])) + for j := uint32(0); j < sectionDesc.number; j++ { + offset = request.header.outputDesc.offset + sectionDesc.offset + j*sectionDesc.length + sections = append(sections, (*uint64)(unsafe.Pointer(&responseBuffer[offset]))) + } + } // Find nwmTCPStatsEntry in returned entries + var tcpStats *nwmTCPStatsEntry = nil + for _, ptr := range sections { + switch *ptr { + case nwmTCPStatsIdentifier: + if tcpStats != nil { + return nil, errnoErr(EINVAL) + } + tcpStats = (*nwmTCPStatsEntry)(unsafe.Pointer(ptr)) + case nwmIPStatsIdentifier: + case nwmIPGStatsIdentifier: + case nwmUDPStatsIdentifier: + case nwmICMPGStatsEntry: + case nwmICMPTStatsEntry: + default: + return nil, errnoErr(EINVAL) + } + } + if tcpStats == nil { + return nil, errnoErr(EINVAL) + } // GetConnectionDetail EZBNMIF4 call + responseBuffer = [4096]byte{0} + dsa = [18]uint64{0} + bufferAlet, reasonCode = 0, 0 + bufferLen, returnValue, returnCode = 4096, 0, 0 + nameptr := (*uint32)(unsafe.Pointer(uintptr(0x21c))) // Get jobname of current process + nameptr = (*uint32)(unsafe.Pointer(uintptr(*nameptr + 12))) + argv[0] = unsafe.Pointer(uintptr(*nameptr)) request.header.ident = nwmHeaderIdentifier + request.header.length = uint32(unsafe.Sizeof(request.header)) + request.header.version = nwmCurrentVer + request.header.nwmType = nwmTCPConnType + request.header.options = 0x80000000 request.filter.ident = nwmFilterIdentifier var localSockaddr RawSockaddrAny + socklen := _Socklen(SizeofSockaddrAny) + err := getsockname(fd, &localSockaddr, &socklen) + if err != nil { + return nil, errnoErr(EINVAL) + } + if localSockaddr.Addr.Family == AF_INET { + localSockaddr := (*RawSockaddrInet4)(unsafe.Pointer(&localSockaddr.Addr)) + localSockFilter := (*RawSockaddrInet4)(unsafe.Pointer(&request.filter.local[0])) + localSockFilter.Family = AF_INET + var i int + for i = 0; i < 4; i++ { + if localSockaddr.Addr[i] != 0 { + break + } + } + if i != 4 { + request.filter.flags |= nwmFilterLclAddrMask + for i = 0; i < 4; i++ { + localSockFilter.Addr[i] = localSockaddr.Addr[i] + } + } + if localSockaddr.Port != 0 { + request.filter.flags |= nwmFilterLclPortMask + localSockFilter.Port = localSockaddr.Port + } + } else if localSockaddr.Addr.Family == AF_INET6 { + localSockaddr := (*RawSockaddrInet6)(unsafe.Pointer(&localSockaddr.Addr)) + localSockFilter := (*RawSockaddrInet6)(unsafe.Pointer(&request.filter.local[0])) + localSockFilter.Family = AF_INET6 + var i int + for i = 0; i < 16; i++ { + if localSockaddr.Addr[i] != 0 { + break + } + } + if i != 16 { + request.filter.flags |= nwmFilterLclAddrMask + for i = 0; i < 16; i++ { + localSockFilter.Addr[i] = localSockaddr.Addr[i] + } + } + if localSockaddr.Port != 0 { + request.filter.flags |= nwmFilterLclPortMask + localSockFilter.Port = localSockaddr.Port + } + } svcCall(EZBNMIF4, &argv[0], &dsa[0]) // outputDesc field is filled by EZBNMIF4 on success + if returnCode != 0 || request.header.outputDesc.offset == 0 { + return nil, errnoErr(EINVAL) + } // Check that EZBNMIF4 returned a nwmConnEntry + conn := (*nwmConnEntry)(unsafe.Pointer(&responseBuffer[request.header.outputDesc.offset])) + if conn.ident != nwmTCPConnIdentifier { + return nil, errnoErr(EINVAL) + } // Copy data from the returned data structures into tcpInfo + // Stats from nwmConnEntry are specific to that connection. + // Stats from nwmTCPStatsEntry are global (to the interface?) + // Fields may not be an exact match. Some fields have no equivalent. + var tcpinfo TCPInfo + tcpinfo.State = uint8(conn.state) + tcpinfo.Ca_state = 0 // dummy + tcpinfo.Retransmits = uint8(tcpStats.retransSegs) + tcpinfo.Probes = uint8(tcpStats.outWinProbes) + tcpinfo.Backoff = 0 // dummy + tcpinfo.Options = 0 // dummy + tcpinfo.Rto = tcpStats.retransTimeouts + tcpinfo.Ato = tcpStats.outDelayAcks + tcpinfo.Snd_mss = conn.sendMSS + tcpinfo.Rcv_mss = conn.sendMSS // dummy - tcpinfo.Unacked = 0 // dummy - tcpinfo.Sacked = 0 // dummy - tcpinfo.Lost = 0 // dummy + + tcpinfo.Unacked = 0 // dummy + + tcpinfo.Sacked = 0 // dummy + + tcpinfo.Lost = 0 // dummy + tcpinfo.Retrans = conn.reXmtCount + tcpinfo.Fackets = 0 // dummy + tcpinfo.Last_data_sent = uint32(*(*uint64)(unsafe.Pointer(&conn.lastActivity[0]))) + tcpinfo.Last_ack_sent = uint32(*(*uint64)(unsafe.Pointer(&conn.outOldestTime[0]))) + tcpinfo.Last_data_recv = uint32(*(*uint64)(unsafe.Pointer(&conn.inOldestTime[0]))) + tcpinfo.Last_ack_recv = uint32(*(*uint64)(unsafe.Pointer(&conn.inOldestTime[0]))) + tcpinfo.Pmtu = conn.sendMSS // dummy, NWMIfRouteMtu is a candidate + tcpinfo.Rcv_ssthresh = conn.ssThresh + tcpinfo.Rtt = conn.roundTripTime + tcpinfo.Rttvar = conn.roundTripVar + tcpinfo.Snd_ssthresh = conn.ssThresh // dummy + tcpinfo.Snd_cwnd = conn.congestionWnd - tcpinfo.Advmss = conn.sendMSS // dummy - tcpinfo.Reordering = 0 // dummy + + tcpinfo.Advmss = conn.sendMSS // dummy + + tcpinfo.Reordering = 0 // dummy + tcpinfo.Rcv_rtt = conn.roundTripTime // dummy - tcpinfo.Rcv_space = conn.sendMSS // dummy + + tcpinfo.Rcv_space = conn.sendMSS // dummy + tcpinfo.Total_retrans = conn.reXmtCount svcUnload(&svcNameTable[svc_EZBNMIF4][0], EZBNMIF4) return &tcpinfo, nil + } // GetsockoptString returns the string value of the socket option opt for the + // socket associated with fd at the given socket level. + func GetsockoptString(fd, level, opt int) (string, error) { + buf := make([]byte, 256) + vallen := _Socklen(len(buf)) + err := getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen) + if err != nil { + return "", err + } return ByteSliceToString(buf[:vallen]), nil + } func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) { + var msg Msghdr + var rsa RawSockaddrAny + msg.Name = (*byte)(unsafe.Pointer(&rsa)) + msg.Namelen = SizeofSockaddrAny + var iov Iovec + if len(p) > 0 { + iov.Base = (*byte)(unsafe.Pointer(&p[0])) + iov.SetLen(len(p)) + } + var dummy byte + if len(oob) > 0 { + // receive at least one normal byte + if len(p) == 0 { + iov.Base = &dummy + iov.SetLen(1) + } + msg.Control = (*byte)(unsafe.Pointer(&oob[0])) + msg.SetControllen(len(oob)) + } + msg.Iov = &iov + msg.Iovlen = 1 + if n, err = recvmsg(fd, &msg, flags); err != nil { + return + } + oobn = int(msg.Controllen) + recvflags = int(msg.Flags) + // source address is only specified if the socket is unconnected + if rsa.Addr.Family != AF_UNSPEC { + // TODO(neeilan): Remove 0 arg added to get this compiling on z/OS + from, err = anyToSockaddr(0, &rsa) + } + return + } func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) { + _, err = SendmsgN(fd, p, oob, to, flags) + return + } func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) { + var ptr unsafe.Pointer + var salen _Socklen + if to != nil { + var err error + ptr, salen, err = to.sockaddr() + if err != nil { + return 0, err + } + } + var msg Msghdr + msg.Name = (*byte)(unsafe.Pointer(ptr)) + msg.Namelen = int32(salen) + var iov Iovec + if len(p) > 0 { + iov.Base = (*byte)(unsafe.Pointer(&p[0])) + iov.SetLen(len(p)) + } + var dummy byte + if len(oob) > 0 { + // send at least one normal byte + if len(p) == 0 { + iov.Base = &dummy + iov.SetLen(1) + } + msg.Control = (*byte)(unsafe.Pointer(&oob[0])) + msg.SetControllen(len(oob)) + } + msg.Iov = &iov + msg.Iovlen = 1 + if n, err = sendmsg(fd, &msg, flags); err != nil { + return 0, err + } + if len(oob) > 0 && len(p) == 0 { + n = 0 + } + return n, nil + } func Opendir(name string) (uintptr, error) { + p, err := BytePtrFromString(name) + if err != nil { + return 0, err + } + err = nil + runtime.EnterSyscall() + dir, e2, e1 := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS___OPENDIR_A<<4, uintptr(unsafe.Pointer(p))) + runtime.ExitSyscall() + runtime.KeepAlive(unsafe.Pointer(p)) + if dir == 0 { + err = errnoErr2(e1, e2) + } + return dir, err + } // clearsyscall.Errno resets the errno value to 0. + func clearErrno() func Closedir(dir uintptr) error { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_CLOSEDIR<<4, dir) + runtime.ExitSyscall() + if r0 != 0 { + return errnoErr2(e1, e2) + } + return nil + } func Seekdir(dir uintptr, pos int) { + runtime.EnterSyscall() + CallLeFuncWithErr(GetZosLibVec()+SYS_SEEKDIR<<4, dir, uintptr(pos)) + runtime.ExitSyscall() + } func Telldir(dir uintptr) (int, error) { + p, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_TELLDIR<<4, dir) + pos := int(p) + if int64(p) == -1 { + return pos, errnoErr2(e1, e2) + } + return pos, nil + } // FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command. + func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error { + // struct flock is packed on z/OS. We can't emulate that in Go so + // instead we pack it here. + var flock [24]byte + *(*int16)(unsafe.Pointer(&flock[0])) = lk.Type + *(*int16)(unsafe.Pointer(&flock[2])) = lk.Whence + *(*int64)(unsafe.Pointer(&flock[4])) = lk.Start + *(*int64)(unsafe.Pointer(&flock[12])) = lk.Len + *(*int32)(unsafe.Pointer(&flock[20])) = lk.Pid + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCNTL<<4, fd, uintptr(cmd), uintptr(unsafe.Pointer(&flock))) + runtime.ExitSyscall() + lk.Type = *(*int16)(unsafe.Pointer(&flock[0])) + lk.Whence = *(*int16)(unsafe.Pointer(&flock[2])) + lk.Start = *(*int64)(unsafe.Pointer(&flock[4])) + lk.Len = *(*int64)(unsafe.Pointer(&flock[12])) + lk.Pid = *(*int32)(unsafe.Pointer(&flock[20])) + if r0 == 0 { + return nil + } + return errnoErr2(e1, e2) + } func impl_Flock(fd int, how int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FLOCK<<4, uintptr(fd), uintptr(how)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_FlockAddr() *(func(fd int, how int) (err error)) var Flock = enter_Flock func validFlock(fp uintptr) bool { + if funcptrtest(GetZosLibVec()+SYS_FLOCK<<4, "") == 0 { + if name, err := getLeFuncName(GetZosLibVec() + SYS_FLOCK<<4); err == nil { + return name == "flock" + } + } + return false + } func enter_Flock(fd int, how int) (err error) { + funcref := get_FlockAddr() + if validFlock(GetZosLibVec() + SYS_FLOCK<<4) { + *funcref = impl_Flock + } else { + *funcref = legacyFlock + } + return (*funcref)(fd, how) + } func legacyFlock(fd int, how int) error { var flock_type int16 + var fcntl_cmd int switch how { + case LOCK_SH | LOCK_NB: + flock_type = F_RDLCK + fcntl_cmd = F_SETLK + case LOCK_EX | LOCK_NB: + flock_type = F_WRLCK + fcntl_cmd = F_SETLK + case LOCK_EX: + flock_type = F_WRLCK + fcntl_cmd = F_SETLKW + case LOCK_UN: + flock_type = F_UNLCK + fcntl_cmd = F_SETLKW + default: + } flock := Flock_t{ - Type: int16(flock_type), + + Type: int16(flock_type), + Whence: int16(0), - Start: int64(0), - Len: int64(0), - Pid: int32(Getppid()), + + Start: int64(0), + + Len: int64(0), + + Pid: int32(Getppid()), } err := FcntlFlock(uintptr(fd), fcntl_cmd, &flock) + return err + } func Mlock(b []byte) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MLOCKALL<<4, _BPX_NONSWAP) + runtime.ExitSyscall() + if r0 != 0 { + err = errnoErr2(e1, e2) + } + return + } func Mlock2(b []byte, flags int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MLOCKALL<<4, _BPX_NONSWAP) + runtime.ExitSyscall() + if r0 != 0 { + err = errnoErr2(e1, e2) + } + return + } func Mlockall(flags int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MLOCKALL<<4, _BPX_NONSWAP) + runtime.ExitSyscall() + if r0 != 0 { + err = errnoErr2(e1, e2) + } + return + } func Munlock(b []byte) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MLOCKALL<<4, _BPX_SWAP) + runtime.ExitSyscall() + if r0 != 0 { + err = errnoErr2(e1, e2) + } + return + } func Munlockall() (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MLOCKALL<<4, _BPX_SWAP) + runtime.ExitSyscall() + if r0 != 0 { + err = errnoErr2(e1, e2) + } + return + } func ClockGettime(clockid int32, ts *Timespec) error { var ticks_per_sec uint32 = 100 //TODO(kenan): value is currently hardcoded; need sysconf() call otherwise + var nsec_per_sec int64 = 1000000000 if ts == nil { + return EFAULT + } + if clockid == CLOCK_REALTIME || clockid == CLOCK_MONOTONIC { + var nanotime int64 = runtime.Nanotime1() + ts.Sec = nanotime / nsec_per_sec + ts.Nsec = nanotime % nsec_per_sec + } else if clockid == CLOCK_PROCESS_CPUTIME_ID || clockid == CLOCK_THREAD_CPUTIME_ID { + var tm Tms + _, err := Times(&tm) + if err != nil { + return EFAULT + } + ts.Sec = int64(tm.Utime / ticks_per_sec) + ts.Nsec = int64(tm.Utime) * nsec_per_sec / int64(ticks_per_sec) + } else { + return EINVAL + } + return nil + } // Chtag //go:nosplit + func get_ChtagAddr() *(func(path string, ccsid uint64, textbit uint64) error) var Chtag = enter_Chtag func enter_Chtag(path string, ccsid uint64, textbit uint64) error { + funcref := get_ChtagAddr() + if validSetxattr() { + *funcref = impl_Chtag + } else { + *funcref = legacy_Chtag + } + return (*funcref)(path, ccsid, textbit) + } func legacy_Chtag(path string, ccsid uint64, textbit uint64) error { + tag := ccsid<<16 | textbit<<15 + var tag_buff [8]byte + DecodeData(tag_buff[:], 8, tag) + return Setxattr(path, "filetag", tag_buff[:], XATTR_REPLACE) + } func impl_Chtag(path string, ccsid uint64, textbit uint64) error { + tag := ccsid<<16 | textbit<<15 + var tag_buff [4]byte + DecodeData(tag_buff[:], 4, tag) + return Setxattr(path, "system.filetag", tag_buff[:], XATTR_REPLACE) + } // End of Chtag @@ -2211,492 +3876,840 @@ func impl_Chtag(path string, ccsid uint64, textbit uint64) error { // Nanosleep //go:nosplit + func get_NanosleepAddr() *(func(time *Timespec, leftover *Timespec) error) var Nanosleep = enter_Nanosleep func enter_Nanosleep(time *Timespec, leftover *Timespec) error { + funcref := get_NanosleepAddr() + if funcptrtest(GetZosLibVec()+SYS_NANOSLEEP<<4, "") == 0 { + *funcref = impl_Nanosleep + } else { + *funcref = legacyNanosleep + } + return (*funcref)(time, leftover) + } func impl_Nanosleep(time *Timespec, leftover *Timespec) error { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_NANOSLEEP<<4, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover))) + runtime.ExitSyscall() + if int64(r0) == -1 { + return errnoErr2(e1, e2) + } + return nil + } func legacyNanosleep(time *Timespec, leftover *Timespec) error { + t0 := runtime.Nanotime1() + var secrem uint32 + var nsecrem uint32 + total := time.Sec*1000000000 + time.Nsec + elapsed := runtime.Nanotime1() - t0 + var rv int32 + var rc int32 + var err error + // repeatedly sleep for 1 second until less than 1 second left + for total-elapsed > 1000000000 { + rv, rc, _ = BpxCondTimedWait(uint32(1), uint32(0), uint32(CW_CONDVAR), &secrem, &nsecrem) + if rv != 0 && rc != 112 { // 112 is EAGAIN + if leftover != nil && rc == 120 { // 120 is EINTR + leftover.Sec = int64(secrem) + leftover.Nsec = int64(nsecrem) + } + err = Errno(rc) + return err + } + elapsed = runtime.Nanotime1() - t0 + } + // sleep the remainder + if total > elapsed { + rv, rc, _ = BpxCondTimedWait(uint32(0), uint32(total-elapsed), uint32(CW_CONDVAR), &secrem, &nsecrem) + } + if leftover != nil && rc == 120 { + leftover.Sec = int64(secrem) + leftover.Nsec = int64(nsecrem) + } + if rv != 0 && rc != 112 { + err = Errno(rc) + } + return err + } // End of Nanosleep var ( - Stdin = 0 + Stdin = 0 + Stdout = 1 + Stderr = 2 ) // Do the interface allocations only once for common + // Errno values. + var ( errEAGAIN error = syscall.EAGAIN + errEINVAL error = syscall.EINVAL + errENOENT error = syscall.ENOENT ) var ZosTraceLevel int + var ZosTracefile *os.File var ( signalNameMapOnce sync.Once - signalNameMap map[string]syscall.Signal + + signalNameMap map[string]syscall.Signal ) // errnoErr returns common boxed Errno values, to prevent + // allocations at runtime. + func errnoErr(e Errno) error { + switch e { + case 0: + return nil + case EAGAIN: + return errEAGAIN + case EINVAL: + return errEINVAL + case ENOENT: + return errENOENT + } + return e + } var reg *regexp.Regexp // enhanced with zos specific errno2 + func errnoErr2(e Errno, e2 uintptr) error { + switch e { + case 0: + return nil + case EAGAIN: + return errEAGAIN + /* + Allow the retrieval of errno2 for EINVAL and ENOENT on zos + case EINVAL: + return errEINVAL + case ENOENT: + return errENOENT + */ + } + if ZosTraceLevel > 0 { + var name string + if reg == nil { + reg = regexp.MustCompile("(^unix\\.[^/]+$|.*\\/unix\\.[^/]+$)") + } + i := 1 + pc, file, line, ok := runtime.Caller(i) + if ok { + name = runtime.FuncForPC(pc).Name() + } + for ok && reg.MatchString(runtime.FuncForPC(pc).Name()) { + i += 1 + pc, file, line, ok = runtime.Caller(i) + } + if ok { + if ZosTracefile == nil { + ZosConsolePrintf("From %s:%d\n", file, line) + ZosConsolePrintf("%s: %s (errno2=0x%x)\n", name, e.Error(), e2) + } else { + fmt.Fprintf(ZosTracefile, "From %s:%d\n", file, line) + fmt.Fprintf(ZosTracefile, "%s: %s (errno2=0x%x)\n", name, e.Error(), e2) + } + } else { + if ZosTracefile == nil { + ZosConsolePrintf("%s (errno2=0x%x)\n", e.Error(), e2) + } else { + fmt.Fprintf(ZosTracefile, "%s (errno2=0x%x)\n", e.Error(), e2) + } + } + } + return e + } // ErrnoName returns the error name for error number e. + func ErrnoName(e Errno) string { + i := sort.Search(len(errorList), func(i int) bool { + return errorList[i].num >= e + }) + if i < len(errorList) && errorList[i].num == e { + return errorList[i].name + } + return "" + } // SignalName returns the signal name for signal number s. + func SignalName(s syscall.Signal) string { + i := sort.Search(len(signalList), func(i int) bool { + return signalList[i].num >= s + }) + if i < len(signalList) && signalList[i].num == s { + return signalList[i].name + } + return "" + } // SignalNum returns the syscall.Signal for signal named s, + // or 0 if a signal with such name is not found. + // The signal name should start with "SIG". + func SignalNum(s string) syscall.Signal { + signalNameMapOnce.Do(func() { + signalNameMap = make(map[string]syscall.Signal, len(signalList)) + for _, signal := range signalList { + signalNameMap[signal.name] = signal.num + } + }) + return signalNameMap[s] + } // clen returns the index of the first NULL byte in n or len(n) if n contains no NULL byte. + func clen(n []byte) int { + i := bytes.IndexByte(n, 0) + if i == -1 { + i = len(n) + } + return i + } // Mmap manager, for use by operating system-specific implementations. type mmapper struct { sync.Mutex + active map[*byte][]byte // active mappings; key is last byte in mapping - mmap func(addr, length uintptr, prot, flags, fd int, offset int64) (uintptr, error) + + mmap func(addr, length uintptr, prot, flags, fd int, offset int64) (uintptr, error) + munmap func(addr uintptr, length uintptr) error } func (m *mmapper) Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { + if length <= 0 { + return nil, EINVAL + } // Set __MAP_64 by default + flags |= __MAP_64 // Map the requested memory. + addr, errno := m.mmap(0, uintptr(length), prot, flags, fd, offset) + if errno != nil { + return nil, errno + } // Slice memory layout + var sl = struct { addr uintptr - len int - cap int + + len int + + cap int }{addr, length, length} // Use unsafe to turn sl into a []byte. + b := *(*[]byte)(unsafe.Pointer(&sl)) // Register mapping in m and return it. + p := &b[cap(b)-1] + m.Lock() + defer m.Unlock() + m.active[p] = b + return b, nil + } func (m *mmapper) Munmap(data []byte) (err error) { + if len(data) == 0 || len(data) != cap(data) { + return EINVAL + } // Find the base of the mapping. + p := &data[cap(data)-1] + m.Lock() + defer m.Unlock() + b := m.active[p] + if b == nil || &b[0] != &data[0] { + return EINVAL + } // Unmap the memory and update m. + if errno := m.munmap(uintptr(unsafe.Pointer(&b[0])), uintptr(len(b))); errno != nil { + return errno + } + delete(m.active, p) + return nil + } func Read(fd int, p []byte) (n int, err error) { + n, err = read(fd, p) + if raceenabled { + if n > 0 { + raceWriteRange(unsafe.Pointer(&p[0]), n) + } + if err == nil { + raceAcquire(unsafe.Pointer(&ioSync)) + } + } + return + } func Write(fd int, p []byte) (n int, err error) { + if raceenabled { + raceReleaseMerge(unsafe.Pointer(&ioSync)) + } + n, err = write(fd, p) + if raceenabled && n > 0 { + raceReadRange(unsafe.Pointer(&p[0]), n) + } + return + } // For testing: clients can set this flag to force + // creation of IPv6 sockets to return EAFNOSUPPORT. + var SocketDisableIPv6 bool // Sockaddr represents a socket address. + type Sockaddr interface { sockaddr() (ptr unsafe.Pointer, len _Socklen, err error) // lowercase; only we can define Sockaddrs + } // SockaddrInet4 implements the Sockaddr interface for AF_INET type sockets. + type SockaddrInet4 struct { Port int + Addr [4]byte - raw RawSockaddrInet4 + + raw RawSockaddrInet4 } // SockaddrInet6 implements the Sockaddr interface for AF_INET6 type sockets. + type SockaddrInet6 struct { - Port int + Port int + ZoneId uint32 - Addr [16]byte - raw RawSockaddrInet6 + + Addr [16]byte + + raw RawSockaddrInet6 } // SockaddrUnix implements the Sockaddr interface for AF_UNIX type sockets. + type SockaddrUnix struct { Name string - raw RawSockaddrUnix + + raw RawSockaddrUnix } func Bind(fd int, sa Sockaddr) (err error) { + ptr, n, err := sa.sockaddr() + if err != nil { + return err + } + return bind(fd, ptr, n) + } func Connect(fd int, sa Sockaddr) (err error) { + ptr, n, err := sa.sockaddr() + if err != nil { + return err + } + return connect(fd, ptr, n) + } func Getpeername(fd int) (sa Sockaddr, err error) { + var rsa RawSockaddrAny + var len _Socklen = SizeofSockaddrAny + if err = getpeername(fd, &rsa, &len); err != nil { + return + } + return anyToSockaddr(fd, &rsa) + } func GetsockoptByte(fd, level, opt int) (value byte, err error) { + var n byte + vallen := _Socklen(1) + err = getsockopt(fd, level, opt, unsafe.Pointer(&n), &vallen) + return n, err + } func GetsockoptInt(fd, level, opt int) (value int, err error) { + var n int32 + vallen := _Socklen(4) + err = getsockopt(fd, level, opt, unsafe.Pointer(&n), &vallen) + return int(n), err + } func GetsockoptInet4Addr(fd, level, opt int) (value [4]byte, err error) { + vallen := _Socklen(4) + err = getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen) + return value, err + } func GetsockoptIPMreq(fd, level, opt int) (*IPMreq, error) { + var value IPMreq + vallen := _Socklen(SizeofIPMreq) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) + return &value, err + } func GetsockoptIPv6Mreq(fd, level, opt int) (*IPv6Mreq, error) { + var value IPv6Mreq + vallen := _Socklen(SizeofIPv6Mreq) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) + return &value, err + } func GetsockoptIPv6MTUInfo(fd, level, opt int) (*IPv6MTUInfo, error) { + var value IPv6MTUInfo + vallen := _Socklen(SizeofIPv6MTUInfo) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) + return &value, err + } func GetsockoptICMPv6Filter(fd, level, opt int) (*ICMPv6Filter, error) { + var value ICMPv6Filter + vallen := _Socklen(SizeofICMPv6Filter) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) + return &value, err + } func GetsockoptLinger(fd, level, opt int) (*Linger, error) { + var linger Linger + vallen := _Socklen(SizeofLinger) + err := getsockopt(fd, level, opt, unsafe.Pointer(&linger), &vallen) + return &linger, err + } func GetsockoptTimeval(fd, level, opt int) (*Timeval, error) { + var tv Timeval + vallen := _Socklen(unsafe.Sizeof(tv)) + err := getsockopt(fd, level, opt, unsafe.Pointer(&tv), &vallen) + return &tv, err + } func GetsockoptUint64(fd, level, opt int) (value uint64, err error) { + var n uint64 + vallen := _Socklen(8) + err = getsockopt(fd, level, opt, unsafe.Pointer(&n), &vallen) + return n, err + } func Recvfrom(fd int, p []byte, flags int) (n int, from Sockaddr, err error) { + var rsa RawSockaddrAny + var len _Socklen = SizeofSockaddrAny + if n, err = recvfrom(fd, p, flags, &rsa, &len); err != nil { + return + } + if rsa.Addr.Family != AF_UNSPEC { + from, err = anyToSockaddr(fd, &rsa) + } + return + } func Sendto(fd int, p []byte, flags int, to Sockaddr) (err error) { + ptr, n, err := to.sockaddr() + if err != nil { + return err + } + return sendto(fd, p, flags, ptr, n) + } func SetsockoptByte(fd, level, opt int, value byte) (err error) { + return setsockopt(fd, level, opt, unsafe.Pointer(&value), 1) + } func SetsockoptInt(fd, level, opt int, value int) (err error) { + var n = int32(value) + return setsockopt(fd, level, opt, unsafe.Pointer(&n), 4) + } func SetsockoptInet4Addr(fd, level, opt int, value [4]byte) (err error) { + return setsockopt(fd, level, opt, unsafe.Pointer(&value[0]), 4) + } func SetsockoptIPMreq(fd, level, opt int, mreq *IPMreq) (err error) { + return setsockopt(fd, level, opt, unsafe.Pointer(mreq), SizeofIPMreq) + } func SetsockoptIPv6Mreq(fd, level, opt int, mreq *IPv6Mreq) (err error) { + return setsockopt(fd, level, opt, unsafe.Pointer(mreq), SizeofIPv6Mreq) + } func SetsockoptICMPv6Filter(fd, level, opt int, filter *ICMPv6Filter) error { + return setsockopt(fd, level, opt, unsafe.Pointer(filter), SizeofICMPv6Filter) + } func SetsockoptLinger(fd, level, opt int, l *Linger) (err error) { + return setsockopt(fd, level, opt, unsafe.Pointer(l), SizeofLinger) + } func SetsockoptString(fd, level, opt int, s string) (err error) { + var p unsafe.Pointer + if len(s) > 0 { + p = unsafe.Pointer(&[]byte(s)[0]) + } + return setsockopt(fd, level, opt, p, uintptr(len(s))) + } func SetsockoptTimeval(fd, level, opt int, tv *Timeval) (err error) { + return setsockopt(fd, level, opt, unsafe.Pointer(tv), unsafe.Sizeof(*tv)) + } func SetsockoptUint64(fd, level, opt int, value uint64) (err error) { + return setsockopt(fd, level, opt, unsafe.Pointer(&value), 8) + } func Socket(domain, typ, proto int) (fd int, err error) { + if domain == AF_INET6 && SocketDisableIPv6 { + return -1, EAFNOSUPPORT + } + fd, err = socket(domain, typ, proto) + return + } func Socketpair(domain, typ, proto int) (fd [2]int, err error) { + var fdx [2]int32 + err = socketpair(domain, typ, proto, &fdx) + if err == nil { + fd[0] = int(fdx[0]) + fd[1] = int(fdx[1]) + } + return + } var ioSync int64 @@ -2704,414 +4717,739 @@ var ioSync int64 func CloseOnExec(fd int) { fcntl(fd, F_SETFD, FD_CLOEXEC) } func SetNonblock(fd int, nonblocking bool) (err error) { + flag, err := fcntl(fd, F_GETFL, 0) + if err != nil { + return err + } + if nonblocking { + flag |= O_NONBLOCK + } else { + flag &= ^O_NONBLOCK + } + _, err = fcntl(fd, F_SETFL, flag) + return err + } // Exec calls execve(2), which replaces the calling executable in the process + // tree. argv0 should be the full path to an executable ("/bin/ls") and the + // executable name should also be the first argument in argv (["ls", "-l"]). + // envv are the environment variables that should be passed to the new + // process (["USER=go", "PWD=/tmp"]). + func Exec(argv0 string, argv []string, envv []string) error { + return syscall.Exec(argv0, argv, envv) + } func Getag(path string) (ccsid uint16, flag uint16, err error) { + var val [8]byte + sz, err := Getxattr(path, "ccsid", val[:]) + if err != nil { + return + } + ccsid = uint16(EncodeData(val[0:sz])) + sz, err = Getxattr(path, "flags", val[:]) + if err != nil { + return + } + flag = uint16(EncodeData(val[0:sz]) >> 15) + return + } // Mount begin + func impl_Mount(source string, target string, fstype string, flags uintptr, data string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(source) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(target) + if err != nil { + return + } + var _p2 *byte + _p2, err = BytePtrFromString(fstype) + if err != nil { + return + } + var _p3 *byte + _p3, err = BytePtrFromString(data) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MOUNT1_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(_p3))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_MountAddr() *(func(source string, target string, fstype string, flags uintptr, data string) (err error)) var Mount = enter_Mount func enter_Mount(source string, target string, fstype string, flags uintptr, data string) (err error) { + funcref := get_MountAddr() + if validMount() { + *funcref = impl_Mount + } else { + *funcref = legacyMount + } + return (*funcref)(source, target, fstype, flags, data) + } func legacyMount(source string, target string, fstype string, flags uintptr, data string) (err error) { + if needspace := 8 - len(fstype); needspace <= 0 { + fstype = fstype[0:8] + } else { + fstype += " "[0:needspace] + } + return mount_LE(target, source, fstype, uint32(flags), int32(len(data)), data) + } func validMount() bool { + if funcptrtest(GetZosLibVec()+SYS___MOUNT1_A<<4, "") == 0 { + if name, err := getLeFuncName(GetZosLibVec() + SYS___MOUNT1_A<<4); err == nil { + return name == "__mount1_a" + } + } + return false + } // Mount end // Unmount begin + func impl_Unmount(target string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(target) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UMOUNT2_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_UnmountAddr() *(func(target string, flags int) (err error)) var Unmount = enter_Unmount func enter_Unmount(target string, flags int) (err error) { + funcref := get_UnmountAddr() + if funcptrtest(GetZosLibVec()+SYS___UMOUNT2_A<<4, "") == 0 { + *funcref = impl_Unmount + } else { + *funcref = legacyUnmount + } + return (*funcref)(target, flags) + } func legacyUnmount(name string, mtm int) (err error) { + // mountpoint is always a full path and starts with a '/' + // check if input string is not a mountpoint but a filesystem name + if name[0] != '/' { + return unmount_LE(name, mtm) + } + // treat name as mountpoint + b2s := func(arr []byte) string { + var str string + for i := 0; i < len(arr); i++ { + if arr[i] == 0 { + str = string(arr[:i]) + break + } + } + return str + } + var buffer struct { header W_Mnth + fsinfo [64]W_Mntent } + fs_count, err := W_Getmntent_A((*byte)(unsafe.Pointer(&buffer)), int(unsafe.Sizeof(buffer))) + if err == nil { + err = EINVAL + for i := 0; i < fs_count; i++ { + if b2s(buffer.fsinfo[i].Mountpoint[:]) == name { + err = unmount_LE(b2s(buffer.fsinfo[i].Fsname[:]), mtm) + break + } + } + } else if fs_count == 0 { + err = EINVAL + } + return err + } // Unmount end func direntIno(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino)) + } func direntReclen(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) + } func direntNamlen(buf []byte) (uint64, bool) { + reclen, ok := direntReclen(buf) + if !ok { + return 0, false + } + return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true + } func direntLeToDirentUnix(dirent *direntLE, dir uintptr, path string) (Dirent, error) { + var d Dirent d.Ino = uint64(dirent.Ino) + offset, err := Telldir(dir) + if err != nil { + return d, err + } d.Off = int64(offset) + s := string(bytes.Split(dirent.Name[:], []byte{0})[0]) + copy(d.Name[:], s) d.Reclen = uint16(24 + len(d.NameString())) + var st Stat_t + path = path + "/" + s + err = Lstat(path, &st) + if err != nil { + return d, err + } d.Type = uint8(st.Mode >> 24) + return d, err + } func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { + // Simulation of Getdirentries port from the Darwin implementation. + // COMMENTS FROM DARWIN: + // It's not the full required semantics, but should handle the case + // of calling Getdirentries or ReadDirent repeatedly. + // It won't handle assigning the results of lseek to *basep, or handle + // the directory being edited underfoot. skip, err := Seek(fd, 0, 1 /* SEEK_CUR */) + if err != nil { + return 0, err + } // Get path from fd to avoid unavailable call (fdopendir) + path, err := ZosFdToPath(fd) + if err != nil { + return 0, err + } + d, err := Opendir(path) + if err != nil { + return 0, err + } + defer Closedir(d) var cnt int64 + for { + var entryLE direntLE + var entrypLE *direntLE + e := Readdir_r(d, &entryLE, &entrypLE) + if e != nil { + return n, e + } + if entrypLE == nil { + break + } + if skip > 0 { + skip-- + cnt++ + continue + } // Dirent on zos has a different structure + entry, e := direntLeToDirentUnix(&entryLE, d, path) + if e != nil { + return n, e + } reclen := int(entry.Reclen) + if reclen > len(buf) { + // Not enough room. Return for now. + // The counter will let us know where we should start up again. + // Note: this strategy for suspending in the middle and + // restarting is O(n^2) in the length of the directory. Oh well. + break + } // Copy entry into return buffer. + s := unsafe.Slice((*byte)(unsafe.Pointer(&entry)), reclen) + copy(buf, s) buf = buf[reclen:] + n += reclen + cnt++ + } + // Set the seek offset of the input fd to record + // how many files we've already returned. + _, err = Seek(fd, cnt, 0 /* SEEK_SET */) + if err != nil { + return n, err + } return n, nil + } func Err2ad() (eadd *int) { + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS___ERR2AD<<4) + eadd = (*int)(unsafe.Pointer(r0)) + return + } func ZosConsolePrintf(format string, v ...interface{}) (int, error) { + type __cmsg struct { - _ uint16 - _ [2]uint8 + _ uint16 + + _ [2]uint8 + __msg_length uint32 - __msg uintptr - _ [4]uint8 + + __msg uintptr + + _ [4]uint8 } + msg := fmt.Sprintf(format, v...) + strptr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&msg)).Data) + len := (*reflect.StringHeader)(unsafe.Pointer(&msg)).Len + cmsg := __cmsg{__msg_length: uint32(len), __msg: uintptr(strptr)} + cmd := uint32(0) + runtime.EnterSyscall() + rc, err2, err1 := CallLeFuncWithErr(GetZosLibVec()+SYS_____CONSOLE_A<<4, uintptr(unsafe.Pointer(&cmsg)), 0, uintptr(unsafe.Pointer(&cmd))) + runtime.ExitSyscall() + if rc != 0 { + return 0, fmt.Errorf("%s (errno2=0x%x)\n", err1.Error(), err2) + } + return 0, nil + } + func ZosStringToEbcdicBytes(str string, nullterm bool) (ebcdicBytes []byte) { + if nullterm { + ebcdicBytes = []byte(str + "\x00") + } else { + ebcdicBytes = []byte(str) + } + A2e(ebcdicBytes) + return + } + func ZosEbcdicBytesToString(b []byte, trimRight bool) (str string) { + res := make([]byte, len(b)) + copy(res, b) + E2a(res) + if trimRight { + str = string(bytes.TrimRight(res, " \x00")) + } else { + str = string(res) + } + return + } func fdToPath(dirfd int) (path string, err error) { + var buffer [1024]byte + // w_ctrl() + ret := runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS_W_IOCTL<<4, + []uintptr{uintptr(dirfd), 17, 1024, uintptr(unsafe.Pointer(&buffer[0]))}) + if ret == 0 { + zb := bytes.IndexByte(buffer[:], 0) + if zb == -1 { + zb = len(buffer) + } + // __e2a_l() + runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___E2A_L<<4, + []uintptr{uintptr(unsafe.Pointer(&buffer[0])), uintptr(zb)}) + return string(buffer[:zb]), nil + } + // __errno() + errno := int(*(*int32)(unsafe.Pointer(runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___ERRNO<<4, + []uintptr{})))) + // __errno2() + errno2 := int(runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___ERRNO2<<4, + []uintptr{})) + // strerror_r() + ret = runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS_STRERROR_R<<4, + []uintptr{uintptr(errno), uintptr(unsafe.Pointer(&buffer[0])), 1024}) + if ret == 0 { + zb := bytes.IndexByte(buffer[:], 0) + if zb == -1 { + zb = len(buffer) + } + return "", fmt.Errorf("%s (errno2=0x%x)", buffer[:zb], errno2) + } else { + return "", fmt.Errorf("fdToPath errno %d (errno2=0x%x)", errno, errno2) + } + } func impl_Mkfifoat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MKFIFOAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_MkfifoatAddr() *(func(dirfd int, path string, mode uint32) (err error)) var Mkfifoat = enter_Mkfifoat func enter_Mkfifoat(dirfd int, path string, mode uint32) (err error) { + funcref := get_MkfifoatAddr() + if funcptrtest(GetZosLibVec()+SYS___MKFIFOAT_A<<4, "") == 0 { + *funcref = impl_Mkfifoat + } else { + *funcref = legacy_Mkfifoat + } + return (*funcref)(dirfd, path, mode) + } func legacy_Mkfifoat(dirfd int, path string, mode uint32) (err error) { + dirname, err := ZosFdToPath(dirfd) + if err != nil { + return err + } + return Mkfifo(dirname+"/"+path, mode) + } //sys Posix_openpt(oflag int) (fd int, err error) = SYS_POSIX_OPENPT + //sys Grantpt(fildes int) (rc int, err error) = SYS_GRANTPT + //sys Unlockpt(fildes int) (rc int, err error) = SYS_UNLOCKPT diff --git a/vendor/golang.org/x/sys/unix/xattr_bsd.go b/vendor/golang.org/x/sys/unix/xattr_bsd.go index e168793..4fed070 100644 --- a/vendor/golang.org/x/sys/unix/xattr_bsd.go +++ b/vendor/golang.org/x/sys/unix/xattr_bsd.go @@ -1,5 +1,7 @@ // Copyright 2018 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build freebsd || netbsd @@ -14,267 +16,425 @@ import ( // Derive extattr namespace and attribute name func xattrnamespace(fullattr string) (ns int, attr string, err error) { + s := strings.IndexByte(fullattr, '.') + if s == -1 { + return -1, "", ENOATTR + } namespace := fullattr[0:s] + attr = fullattr[s+1:] switch namespace { + case "user": + return EXTATTR_NAMESPACE_USER, attr, nil + case "system": + return EXTATTR_NAMESPACE_SYSTEM, attr, nil + default: + return -1, "", ENOATTR + } + } func initxattrdest(dest []byte, idx int) (d unsafe.Pointer) { + if len(dest) > idx { + return unsafe.Pointer(&dest[idx]) + } + if dest != nil { + // extattr_get_file and extattr_list_file treat NULL differently from + // a non-NULL pointer of length zero. Preserve the property of nilness, + // even if we can't use dest directly. + return unsafe.Pointer(&_zero) + } + return nil + } // FreeBSD and NetBSD implement their own syscalls to handle extended attributes func Getxattr(file string, attr string, dest []byte) (sz int, err error) { + d := initxattrdest(dest, 0) + destsize := len(dest) nsid, a, err := xattrnamespace(attr) + if err != nil { + return -1, err + } return ExtattrGetFile(file, nsid, a, uintptr(d), destsize) + } func Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) { + d := initxattrdest(dest, 0) + destsize := len(dest) nsid, a, err := xattrnamespace(attr) + if err != nil { + return -1, err + } return ExtattrGetFd(fd, nsid, a, uintptr(d), destsize) + } func Lgetxattr(link string, attr string, dest []byte) (sz int, err error) { + d := initxattrdest(dest, 0) + destsize := len(dest) nsid, a, err := xattrnamespace(attr) + if err != nil { + return -1, err + } return ExtattrGetLink(link, nsid, a, uintptr(d), destsize) + } // flags are unused on FreeBSD func Fsetxattr(fd int, attr string, data []byte, flags int) (err error) { + var d unsafe.Pointer + if len(data) > 0 { + d = unsafe.Pointer(&data[0]) + } + datasiz := len(data) nsid, a, err := xattrnamespace(attr) + if err != nil { + return + } _, err = ExtattrSetFd(fd, nsid, a, uintptr(d), datasiz) + return + } func Setxattr(file string, attr string, data []byte, flags int) (err error) { + var d unsafe.Pointer + if len(data) > 0 { + d = unsafe.Pointer(&data[0]) + } + datasiz := len(data) nsid, a, err := xattrnamespace(attr) + if err != nil { + return + } _, err = ExtattrSetFile(file, nsid, a, uintptr(d), datasiz) + return + } func Lsetxattr(link string, attr string, data []byte, flags int) (err error) { + var d unsafe.Pointer + if len(data) > 0 { + d = unsafe.Pointer(&data[0]) + } + datasiz := len(data) nsid, a, err := xattrnamespace(attr) + if err != nil { + return + } _, err = ExtattrSetLink(link, nsid, a, uintptr(d), datasiz) + return + } func Removexattr(file string, attr string) (err error) { + nsid, a, err := xattrnamespace(attr) + if err != nil { + return + } err = ExtattrDeleteFile(file, nsid, a) + return + } func Fremovexattr(fd int, attr string) (err error) { + nsid, a, err := xattrnamespace(attr) + if err != nil { + return + } err = ExtattrDeleteFd(fd, nsid, a) + return + } func Lremovexattr(link string, attr string) (err error) { + nsid, a, err := xattrnamespace(attr) + if err != nil { + return + } err = ExtattrDeleteLink(link, nsid, a) + return + } func Listxattr(file string, dest []byte) (sz int, err error) { + destsiz := len(dest) // FreeBSD won't allow you to list xattrs from multiple namespaces + s, pos := 0, 0 + for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} { + stmp, e := ListxattrNS(file, nsid, dest[pos:]) /* Errors accessing system attrs are ignored so that + * we can implement the Linux-like behavior of omitting errors that + * we don't have read permissions on + * + * Linux will still error if we ask for user attributes on a file that + * we don't have read permissions on, so don't ignore those errors + */ + if e != nil { + if e == EPERM && nsid != EXTATTR_NAMESPACE_USER { + continue + } + return s, e + } s += stmp + pos = s + if pos > destsiz { + pos = destsiz + } + } return s, nil + } func ListxattrNS(file string, nsid int, dest []byte) (sz int, err error) { + d := initxattrdest(dest, 0) + destsiz := len(dest) s, e := ExtattrListFile(file, nsid, uintptr(d), destsiz) + if e != nil { + return 0, err + } return s, nil + } func Flistxattr(fd int, dest []byte) (sz int, err error) { + destsiz := len(dest) s, pos := 0, 0 + for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} { + stmp, e := FlistxattrNS(fd, nsid, dest[pos:]) if e != nil { + if e == EPERM && nsid != EXTATTR_NAMESPACE_USER { + continue + } + return s, e + } s += stmp + pos = s + if pos > destsiz { + pos = destsiz + } + } return s, nil + } func FlistxattrNS(fd int, nsid int, dest []byte) (sz int, err error) { + d := initxattrdest(dest, 0) + destsiz := len(dest) s, e := ExtattrListFd(fd, nsid, uintptr(d), destsiz) + if e != nil { + return 0, err + } return s, nil + } func Llistxattr(link string, dest []byte) (sz int, err error) { + destsiz := len(dest) s, pos := 0, 0 + for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} { + stmp, e := LlistxattrNS(link, nsid, dest[pos:]) if e != nil { + if e == EPERM && nsid != EXTATTR_NAMESPACE_USER { + continue + } + return s, e + } s += stmp + pos = s + if pos > destsiz { + pos = destsiz + } + } return s, nil + } func LlistxattrNS(link string, nsid int, dest []byte) (sz int, err error) { + d := initxattrdest(dest, 0) + destsiz := len(dest) s, e := ExtattrListLink(link, nsid, uintptr(d), destsiz) + if e != nil { + return 0, err + } return s, nil + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gccgo.go b/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gccgo.go index d46b706..76f3951 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gccgo.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gccgo.go @@ -1,4 +1,5 @@ // go run mksyscall_aix_ppc64.go -aix -tags aix,ppc64 syscall_aix.go syscall_aix_ppc64.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build aix && ppc64 && gccgo @@ -6,126 +7,247 @@ package unix /* + #include + int utimes(uintptr_t, uintptr_t); + int utimensat(int, uintptr_t, uintptr_t, int); + int getcwd(uintptr_t, size_t); + int accept(int, uintptr_t, uintptr_t); + int getdirent(int, uintptr_t, size_t); + int wait4(int, uintptr_t, int, uintptr_t); + int ioctl(int, int, uintptr_t); + int fcntl(uintptr_t, int, uintptr_t); + int fsync_range(int, int, long long, long long); + int acct(uintptr_t); + int chdir(uintptr_t); + int chroot(uintptr_t); + int close(int); + int dup(int); + void exit(int); + int faccessat(int, uintptr_t, unsigned int, int); + int fchdir(int); + int fchmod(int, unsigned int); + int fchmodat(int, uintptr_t, unsigned int, int); + int fchownat(int, uintptr_t, int, int, int); + int fdatasync(int); + int getpgid(int); + int getpgrp(); + int getpid(); + int getppid(); + int getpriority(int, int); + int getrusage(int, uintptr_t); + int getsid(int); + int kill(int, int); + int syslog(int, uintptr_t, size_t); + int mkdir(int, uintptr_t, unsigned int); + int mkdirat(int, uintptr_t, unsigned int); + int mkfifo(uintptr_t, unsigned int); + int mknod(uintptr_t, unsigned int, int); + int mknodat(int, uintptr_t, unsigned int, int); + int nanosleep(uintptr_t, uintptr_t); + int open64(uintptr_t, int, unsigned int); + int openat(int, uintptr_t, int, unsigned int); + int read(int, uintptr_t, size_t); + int readlink(uintptr_t, uintptr_t, size_t); + int renameat(int, uintptr_t, int, uintptr_t); + int setdomainname(uintptr_t, size_t); + int sethostname(uintptr_t, size_t); + int setpgid(int, int); + int setsid(); + int settimeofday(uintptr_t); + int setuid(int); + int setgid(int); + int setpriority(int, int, int); + int statx(int, uintptr_t, int, int, uintptr_t); + int sync(); + uintptr_t times(uintptr_t); + int umask(int); + int uname(uintptr_t); + int unlink(uintptr_t); + int unlinkat(int, uintptr_t, int); + int ustat(int, uintptr_t); + int write(int, uintptr_t, size_t); + int dup2(int, int); + int posix_fadvise64(int, long long, long long, int); + int fchown(int, int, int); + int fstat(int, uintptr_t); + int fstatat(int, uintptr_t, uintptr_t, int); + int fstatfs(int, uintptr_t); + int ftruncate(int, long long); + int getegid(); + int geteuid(); + int getgid(); + int getuid(); + int lchown(uintptr_t, int, int); + int listen(int, int); + int lstat(uintptr_t, uintptr_t); + int pause(); + int pread64(int, uintptr_t, size_t, long long); + int pwrite64(int, uintptr_t, size_t, long long); + #define c_select select + int select(int, uintptr_t, uintptr_t, uintptr_t, uintptr_t); + int pselect(int, uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t); + int setregid(int, int); + int setreuid(int, int); + int shutdown(int, int); + long long splice(int, uintptr_t, int, uintptr_t, int, int); + int stat(uintptr_t, uintptr_t); + int statfs(uintptr_t, uintptr_t); + int truncate(uintptr_t, long long); + int bind(int, uintptr_t, uintptr_t); + int connect(int, uintptr_t, uintptr_t); + int getgroups(int, uintptr_t); + int setgroups(int, uintptr_t); + int getsockopt(int, int, int, uintptr_t, uintptr_t); + int setsockopt(int, int, int, uintptr_t, uintptr_t); + int socket(int, int, int); + int socketpair(int, int, int, uintptr_t); + int getpeername(int, uintptr_t, uintptr_t); + int getsockname(int, uintptr_t, uintptr_t); + int recvfrom(int, uintptr_t, size_t, int, uintptr_t, uintptr_t); + int sendto(int, uintptr_t, size_t, int, uintptr_t, uintptr_t); + int nrecvmsg(int, uintptr_t, int); + int nsendmsg(int, uintptr_t, int); + int munmap(uintptr_t, uintptr_t); + int madvise(uintptr_t, size_t, int); + int mprotect(uintptr_t, size_t, int); + int mlock(uintptr_t, size_t); + int mlockall(int); + int msync(uintptr_t, size_t, int); + int munlock(uintptr_t, size_t); + int munlockall(); + int pipe(uintptr_t); + int poll(uintptr_t, int, int); + int gettimeofday(uintptr_t, uintptr_t); + int time(uintptr_t); + int utime(uintptr_t, uintptr_t); + unsigned long long getsystemcfg(int); + int umount(uintptr_t); + int getrlimit(int, uintptr_t); + long long lseek(int, long long, int); + uintptr_t mmap64(uintptr_t, uintptr_t, int, int, int, long long); + + */ + import "C" import ( @@ -136,935 +258,1403 @@ import ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callutimes(_p0 uintptr, times uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.utimes(C.uintptr_t(_p0), C.uintptr_t(times))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callutimensat(dirfd int, _p0 uintptr, times uintptr, flag int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.utimensat(C.int(dirfd), C.uintptr_t(_p0), C.uintptr_t(times), C.int(flag))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callgetcwd(_p0 uintptr, _lenp0 int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.getcwd(C.uintptr_t(_p0), C.size_t(_lenp0))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callaccept(s int, rsa uintptr, addrlen uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.accept(C.int(s), C.uintptr_t(rsa), C.uintptr_t(addrlen))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callgetdirent(fd int, _p0 uintptr, _lenp0 int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.getdirent(C.int(fd), C.uintptr_t(_p0), C.size_t(_lenp0))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callwait4(pid int, status uintptr, options int, rusage uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.wait4(C.int(pid), C.uintptr_t(status), C.int(options), C.uintptr_t(rusage))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callioctl(fd int, req int, arg uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.ioctl(C.int(fd), C.int(req), C.uintptr_t(arg))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callioctl_ptr(fd int, req int, arg unsafe.Pointer) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.ioctl(C.int(fd), C.int(req), C.uintptr_t(uintptr(arg)))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callfcntl(fd uintptr, cmd int, arg uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.fcntl(C.uintptr_t(fd), C.int(cmd), C.uintptr_t(arg))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callfsync_range(fd int, how int, start int64, length int64) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.fsync_range(C.int(fd), C.int(how), C.longlong(start), C.longlong(length))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callacct(_p0 uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.acct(C.uintptr_t(_p0))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callchdir(_p0 uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.chdir(C.uintptr_t(_p0))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callchroot(_p0 uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.chroot(C.uintptr_t(_p0))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callclose(fd int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.close(C.int(fd))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func calldup(oldfd int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.dup(C.int(oldfd))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callexit(code int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.exit(C.int(code))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callfaccessat(dirfd int, _p0 uintptr, mode uint32, flags int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.faccessat(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode), C.int(flags))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callfchdir(fd int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.fchdir(C.int(fd))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callfchmod(fd int, mode uint32) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.fchmod(C.int(fd), C.uint(mode))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callfchmodat(dirfd int, _p0 uintptr, mode uint32, flags int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.fchmodat(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode), C.int(flags))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callfchownat(dirfd int, _p0 uintptr, uid int, gid int, flags int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.fchownat(C.int(dirfd), C.uintptr_t(_p0), C.int(uid), C.int(gid), C.int(flags))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callfdatasync(fd int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.fdatasync(C.int(fd))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callgetpgid(pid int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.getpgid(C.int(pid))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callgetpgrp() (r1 uintptr, e1 Errno) { + r1 = uintptr(C.getpgrp()) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callgetpid() (r1 uintptr, e1 Errno) { + r1 = uintptr(C.getpid()) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callgetppid() (r1 uintptr, e1 Errno) { + r1 = uintptr(C.getppid()) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callgetpriority(which int, who int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.getpriority(C.int(which), C.int(who))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callgetrusage(who int, rusage uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.getrusage(C.int(who), C.uintptr_t(rusage))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callgetsid(pid int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.getsid(C.int(pid))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callkill(pid int, sig int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.kill(C.int(pid), C.int(sig))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callsyslog(typ int, _p0 uintptr, _lenp0 int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.syslog(C.int(typ), C.uintptr_t(_p0), C.size_t(_lenp0))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callmkdir(dirfd int, _p0 uintptr, mode uint32) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.mkdir(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callmkdirat(dirfd int, _p0 uintptr, mode uint32) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.mkdirat(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callmkfifo(_p0 uintptr, mode uint32) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.mkfifo(C.uintptr_t(_p0), C.uint(mode))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callmknod(_p0 uintptr, mode uint32, dev int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.mknod(C.uintptr_t(_p0), C.uint(mode), C.int(dev))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callmknodat(dirfd int, _p0 uintptr, mode uint32, dev int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.mknodat(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode), C.int(dev))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callnanosleep(time uintptr, leftover uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.nanosleep(C.uintptr_t(time), C.uintptr_t(leftover))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callopen64(_p0 uintptr, mode int, perm uint32) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.open64(C.uintptr_t(_p0), C.int(mode), C.uint(perm))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callopenat(dirfd int, _p0 uintptr, flags int, mode uint32) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.openat(C.int(dirfd), C.uintptr_t(_p0), C.int(flags), C.uint(mode))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callread(fd int, _p0 uintptr, _lenp0 int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.read(C.int(fd), C.uintptr_t(_p0), C.size_t(_lenp0))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callreadlink(_p0 uintptr, _p1 uintptr, _lenp1 int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.readlink(C.uintptr_t(_p0), C.uintptr_t(_p1), C.size_t(_lenp1))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callrenameat(olddirfd int, _p0 uintptr, newdirfd int, _p1 uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.renameat(C.int(olddirfd), C.uintptr_t(_p0), C.int(newdirfd), C.uintptr_t(_p1))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callsetdomainname(_p0 uintptr, _lenp0 int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.setdomainname(C.uintptr_t(_p0), C.size_t(_lenp0))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callsethostname(_p0 uintptr, _lenp0 int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.sethostname(C.uintptr_t(_p0), C.size_t(_lenp0))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callsetpgid(pid int, pgid int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.setpgid(C.int(pid), C.int(pgid))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callsetsid() (r1 uintptr, e1 Errno) { + r1 = uintptr(C.setsid()) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callsettimeofday(tv uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.settimeofday(C.uintptr_t(tv))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callsetuid(uid int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.setuid(C.int(uid))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callsetgid(uid int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.setgid(C.int(uid))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callsetpriority(which int, who int, prio int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.setpriority(C.int(which), C.int(who), C.int(prio))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callstatx(dirfd int, _p0 uintptr, flags int, mask int, stat uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.statx(C.int(dirfd), C.uintptr_t(_p0), C.int(flags), C.int(mask), C.uintptr_t(stat))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callsync() (r1 uintptr, e1 Errno) { + r1 = uintptr(C.sync()) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func calltimes(tms uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.times(C.uintptr_t(tms))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callumask(mask int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.umask(C.int(mask))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func calluname(buf uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.uname(C.uintptr_t(buf))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callunlink(_p0 uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.unlink(C.uintptr_t(_p0))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callunlinkat(dirfd int, _p0 uintptr, flags int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.unlinkat(C.int(dirfd), C.uintptr_t(_p0), C.int(flags))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callustat(dev int, ubuf uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.ustat(C.int(dev), C.uintptr_t(ubuf))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callwrite(fd int, _p0 uintptr, _lenp0 int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.write(C.int(fd), C.uintptr_t(_p0), C.size_t(_lenp0))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func calldup2(oldfd int, newfd int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.dup2(C.int(oldfd), C.int(newfd))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callposix_fadvise64(fd int, offset int64, length int64, advice int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.posix_fadvise64(C.int(fd), C.longlong(offset), C.longlong(length), C.int(advice))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callfchown(fd int, uid int, gid int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.fchown(C.int(fd), C.int(uid), C.int(gid))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callfstat(fd int, stat uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.fstat(C.int(fd), C.uintptr_t(stat))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callfstatat(dirfd int, _p0 uintptr, stat uintptr, flags int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.fstatat(C.int(dirfd), C.uintptr_t(_p0), C.uintptr_t(stat), C.int(flags))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callfstatfs(fd int, buf uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.fstatfs(C.int(fd), C.uintptr_t(buf))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callftruncate(fd int, length int64) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.ftruncate(C.int(fd), C.longlong(length))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callgetegid() (r1 uintptr, e1 Errno) { + r1 = uintptr(C.getegid()) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callgeteuid() (r1 uintptr, e1 Errno) { + r1 = uintptr(C.geteuid()) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callgetgid() (r1 uintptr, e1 Errno) { + r1 = uintptr(C.getgid()) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callgetuid() (r1 uintptr, e1 Errno) { + r1 = uintptr(C.getuid()) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func calllchown(_p0 uintptr, uid int, gid int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.lchown(C.uintptr_t(_p0), C.int(uid), C.int(gid))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func calllisten(s int, n int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.listen(C.int(s), C.int(n))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func calllstat(_p0 uintptr, stat uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.lstat(C.uintptr_t(_p0), C.uintptr_t(stat))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callpause() (r1 uintptr, e1 Errno) { + r1 = uintptr(C.pause()) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callpread64(fd int, _p0 uintptr, _lenp0 int, offset int64) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.pread64(C.int(fd), C.uintptr_t(_p0), C.size_t(_lenp0), C.longlong(offset))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callpwrite64(fd int, _p0 uintptr, _lenp0 int, offset int64) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.pwrite64(C.int(fd), C.uintptr_t(_p0), C.size_t(_lenp0), C.longlong(offset))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callselect(nfd int, r uintptr, w uintptr, e uintptr, timeout uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.c_select(C.int(nfd), C.uintptr_t(r), C.uintptr_t(w), C.uintptr_t(e), C.uintptr_t(timeout))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callpselect(nfd int, r uintptr, w uintptr, e uintptr, timeout uintptr, sigmask uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.pselect(C.int(nfd), C.uintptr_t(r), C.uintptr_t(w), C.uintptr_t(e), C.uintptr_t(timeout), C.uintptr_t(sigmask))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callsetregid(rgid int, egid int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.setregid(C.int(rgid), C.int(egid))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callsetreuid(ruid int, euid int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.setreuid(C.int(ruid), C.int(euid))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callshutdown(fd int, how int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.shutdown(C.int(fd), C.int(how))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callsplice(rfd int, roff uintptr, wfd int, woff uintptr, len int, flags int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.splice(C.int(rfd), C.uintptr_t(roff), C.int(wfd), C.uintptr_t(woff), C.int(len), C.int(flags))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callstat(_p0 uintptr, statptr uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.stat(C.uintptr_t(_p0), C.uintptr_t(statptr))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callstatfs(_p0 uintptr, buf uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.statfs(C.uintptr_t(_p0), C.uintptr_t(buf))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func calltruncate(_p0 uintptr, length int64) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.truncate(C.uintptr_t(_p0), C.longlong(length))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callbind(s int, addr uintptr, addrlen uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.bind(C.int(s), C.uintptr_t(addr), C.uintptr_t(addrlen))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callconnect(s int, addr uintptr, addrlen uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.connect(C.int(s), C.uintptr_t(addr), C.uintptr_t(addrlen))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callgetgroups(n int, list uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.getgroups(C.int(n), C.uintptr_t(list))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callsetgroups(n int, list uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.setgroups(C.int(n), C.uintptr_t(list))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callgetsockopt(s int, level int, name int, val uintptr, vallen uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.getsockopt(C.int(s), C.int(level), C.int(name), C.uintptr_t(val), C.uintptr_t(vallen))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callsetsockopt(s int, level int, name int, val uintptr, vallen uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.setsockopt(C.int(s), C.int(level), C.int(name), C.uintptr_t(val), C.uintptr_t(vallen))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callsocket(domain int, typ int, proto int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.socket(C.int(domain), C.int(typ), C.int(proto))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callsocketpair(domain int, typ int, proto int, fd uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.socketpair(C.int(domain), C.int(typ), C.int(proto), C.uintptr_t(fd))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callgetpeername(fd int, rsa uintptr, addrlen uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.getpeername(C.int(fd), C.uintptr_t(rsa), C.uintptr_t(addrlen))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callgetsockname(fd int, rsa uintptr, addrlen uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.getsockname(C.int(fd), C.uintptr_t(rsa), C.uintptr_t(addrlen))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callrecvfrom(fd int, _p0 uintptr, _lenp0 int, flags int, from uintptr, fromlen uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.recvfrom(C.int(fd), C.uintptr_t(_p0), C.size_t(_lenp0), C.int(flags), C.uintptr_t(from), C.uintptr_t(fromlen))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callsendto(s int, _p0 uintptr, _lenp0 int, flags int, to uintptr, addrlen uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.sendto(C.int(s), C.uintptr_t(_p0), C.size_t(_lenp0), C.int(flags), C.uintptr_t(to), C.uintptr_t(addrlen))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callnrecvmsg(s int, msg uintptr, flags int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.nrecvmsg(C.int(s), C.uintptr_t(msg), C.int(flags))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callnsendmsg(s int, msg uintptr, flags int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.nsendmsg(C.int(s), C.uintptr_t(msg), C.int(flags))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callmunmap(addr uintptr, length uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.munmap(C.uintptr_t(addr), C.uintptr_t(length))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callmadvise(_p0 uintptr, _lenp0 int, advice int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.madvise(C.uintptr_t(_p0), C.size_t(_lenp0), C.int(advice))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callmprotect(_p0 uintptr, _lenp0 int, prot int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.mprotect(C.uintptr_t(_p0), C.size_t(_lenp0), C.int(prot))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callmlock(_p0 uintptr, _lenp0 int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.mlock(C.uintptr_t(_p0), C.size_t(_lenp0))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callmlockall(flags int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.mlockall(C.int(flags))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callmsync(_p0 uintptr, _lenp0 int, flags int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.msync(C.uintptr_t(_p0), C.size_t(_lenp0), C.int(flags))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callmunlock(_p0 uintptr, _lenp0 int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.munlock(C.uintptr_t(_p0), C.size_t(_lenp0))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callmunlockall() (r1 uintptr, e1 Errno) { + r1 = uintptr(C.munlockall()) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callpipe(p uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.pipe(C.uintptr_t(p))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callpoll(fds uintptr, nfds int, timeout int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.poll(C.uintptr_t(fds), C.int(nfds), C.int(timeout))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callgettimeofday(tv uintptr, tzp uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.gettimeofday(C.uintptr_t(tv), C.uintptr_t(tzp))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func calltime(t uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.time(C.uintptr_t(t))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callutime(_p0 uintptr, buf uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.utime(C.uintptr_t(_p0), C.uintptr_t(buf))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callgetsystemcfg(label int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.getsystemcfg(C.int(label))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callumount(_p0 uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.umount(C.uintptr_t(_p0))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callgetrlimit(resource int, rlim uintptr) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.getrlimit(C.int(resource), C.uintptr_t(rlim))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func calllseek(fd int, offset int64, whence int) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.lseek(C.int(fd), C.longlong(offset), C.int(whence))) + e1 = syscall.GetErrno() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func callmmap64(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (r1 uintptr, e1 Errno) { + r1 = uintptr(C.mmap64(C.uintptr_t(addr), C.uintptr_t(length), C.int(prot), C.int(flags), C.int(fd), C.longlong(offset))) + e1 = syscall.GetErrno() + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go index ccb02f2..7bea08b 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go @@ -1,4 +1,5 @@ // go run mksyscall.go -tags darwin,amd64 syscall_bsd.go syscall_darwin.go syscall_darwin_amd64.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build darwin && amd64 @@ -15,12 +16,19 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getgroups_trampoline_addr uintptr @@ -30,11 +38,17 @@ var libc_getgroups_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setgroups_trampoline_addr uintptr @@ -44,12 +58,19 @@ var libc_setgroups_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := syscall_syscall6(libc_wait4_trampoline_addr, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_wait4_trampoline_addr uintptr @@ -59,12 +80,19 @@ var libc_wait4_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := syscall_syscall(libc_accept_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_accept_trampoline_addr uintptr @@ -74,11 +102,17 @@ var libc_accept_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := syscall_syscall(libc_bind_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_bind_trampoline_addr uintptr @@ -88,11 +122,17 @@ var libc_bind_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := syscall_syscall(libc_connect_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_connect_trampoline_addr uintptr @@ -102,12 +142,19 @@ var libc_connect_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_socket_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_socket_trampoline_addr uintptr @@ -117,11 +164,17 @@ var libc_socket_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := syscall_syscall6(libc_getsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsockopt_trampoline_addr uintptr @@ -131,11 +184,17 @@ var libc_getsockopt_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := syscall_syscall6(libc_setsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setsockopt_trampoline_addr uintptr @@ -145,11 +204,17 @@ var libc_setsockopt_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getpeername_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpeername_trampoline_addr uintptr @@ -159,11 +224,17 @@ var libc_getpeername_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getsockname_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsockname_trampoline_addr uintptr @@ -173,11 +244,17 @@ var libc_getsockname_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { + _, _, e1 := syscall_syscall(libc_shutdown_trampoline_addr, uintptr(s), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_shutdown_trampoline_addr uintptr @@ -187,11 +264,17 @@ var libc_shutdown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := syscall_rawSyscall6(libc_socketpair_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_socketpair_trampoline_addr uintptr @@ -201,18 +284,31 @@ var libc_socketpair_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_recvfrom_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_recvfrom_trampoline_addr uintptr @@ -222,17 +318,29 @@ var libc_recvfrom_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall6(libc_sendto_trampoline_addr, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sendto_trampoline_addr uintptr @@ -242,12 +350,19 @@ var libc_sendto_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_recvmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_recvmsg_trampoline_addr uintptr @@ -257,12 +372,19 @@ var libc_recvmsg_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_sendmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sendmsg_trampoline_addr uintptr @@ -272,12 +394,19 @@ var libc_sendmsg_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_kevent_trampoline_addr, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kevent_trampoline_addr uintptr @@ -287,16 +416,27 @@ var libc_kevent_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_utimes_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_utimes_trampoline_addr uintptr @@ -306,11 +446,17 @@ var libc_utimes_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { + _, _, e1 := syscall_syscall(libc_futimes_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_futimes_trampoline_addr uintptr @@ -320,12 +466,19 @@ var libc_futimes_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_poll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_poll_trampoline_addr uintptr @@ -335,17 +488,29 @@ var libc_poll_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_madvise_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_madvise_trampoline_addr uintptr @@ -355,17 +520,29 @@ var libc_madvise_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_mlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mlock_trampoline_addr uintptr @@ -375,11 +552,17 @@ var libc_mlock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := syscall_syscall(libc_mlockall_trampoline_addr, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mlockall_trampoline_addr uintptr @@ -389,17 +572,29 @@ var libc_mlockall_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_mprotect_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mprotect_trampoline_addr uintptr @@ -409,17 +604,29 @@ var libc_mprotect_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_msync_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_msync_trampoline_addr uintptr @@ -429,17 +636,29 @@ var libc_msync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_munlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munlock_trampoline_addr uintptr @@ -449,11 +668,17 @@ var libc_munlock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := syscall_syscall(libc_munlockall_trampoline_addr, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munlockall_trampoline_addr uintptr @@ -463,11 +688,17 @@ var libc_munlockall_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func closedir(dir uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_closedir_trampoline_addr, uintptr(dir), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_closedir_trampoline_addr uintptr @@ -477,9 +708,13 @@ var libc_closedir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readdir_r(dir uintptr, entry *Dirent, result **Dirent) (res Errno) { + r0, _, _ := syscall_syscall(libc_readdir_r_trampoline_addr, uintptr(dir), uintptr(unsafe.Pointer(entry)), uintptr(unsafe.Pointer(result))) + res = Errno(r0) + return + } var libc_readdir_r_trampoline_addr uintptr @@ -489,11 +724,17 @@ var libc_readdir_r_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]int32) (err error) { + _, _, e1 := syscall_rawSyscall(libc_pipe_trampoline_addr, uintptr(unsafe.Pointer(p)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pipe_trampoline_addr uintptr @@ -503,22 +744,39 @@ var libc_pipe_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getxattr(path string, attr string, dest *byte, size int, position uint32, options int) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + r0, _, e1 := syscall_syscall6(libc_getxattr_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(dest)), uintptr(size), uintptr(position), uintptr(options)) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getxattr_trampoline_addr uintptr @@ -528,17 +786,29 @@ var libc_getxattr_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fgetxattr(fd int, attr string, dest *byte, size int, position uint32, options int) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attr) + if err != nil { + return + } + r0, _, e1 := syscall_syscall6(libc_fgetxattr_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(dest)), uintptr(size), uintptr(position), uintptr(options)) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fgetxattr_trampoline_addr uintptr @@ -548,21 +818,37 @@ var libc_fgetxattr_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setxattr(path string, attr string, data *byte, size int, position uint32, options int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_setxattr_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(data)), uintptr(size), uintptr(position), uintptr(options)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setxattr_trampoline_addr uintptr @@ -572,16 +858,27 @@ var libc_setxattr_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fsetxattr(fd int, attr string, data *byte, size int, position uint32, options int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fsetxattr_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(data)), uintptr(size), uintptr(position), uintptr(options)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fsetxattr_trampoline_addr uintptr @@ -591,21 +888,37 @@ var libc_fsetxattr_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func removexattr(path string, attr string, options int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_removexattr_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_removexattr_trampoline_addr uintptr @@ -615,16 +928,27 @@ var libc_removexattr_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fremovexattr(fd int, attr string, options int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_fremovexattr_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(options)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fremovexattr_trampoline_addr uintptr @@ -634,17 +958,29 @@ var libc_fremovexattr_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func listxattr(path string, dest *byte, size int, options int) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall6(libc_listxattr_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(dest)), uintptr(size), uintptr(options), 0, 0) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_listxattr_trampoline_addr uintptr @@ -654,12 +990,19 @@ var libc_listxattr_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func flistxattr(fd int, dest *byte, size int, options int) (sz int, err error) { + r0, _, e1 := syscall_syscall6(libc_flistxattr_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(dest)), uintptr(size), uintptr(options), 0, 0) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_flistxattr_trampoline_addr uintptr @@ -669,16 +1012,27 @@ var libc_flistxattr_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_utimensat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_utimensat_trampoline_addr uintptr @@ -688,12 +1042,19 @@ var libc_utimensat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fcntl_trampoline_addr uintptr @@ -703,11 +1064,17 @@ var libc_fcntl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kill(pid int, signum int, posix int) (err error) { + _, _, e1 := syscall_syscall(libc_kill_trampoline_addr, uintptr(pid), uintptr(signum), uintptr(posix)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kill_trampoline_addr uintptr @@ -717,11 +1084,17 @@ var libc_kill_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ioctl_trampoline_addr uintptr @@ -731,27 +1104,45 @@ var libc_ioctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall6(libc_sysctl_trampoline_addr, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sysctl_trampoline_addr uintptr @@ -761,11 +1152,17 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(infd int, outfd int, offset int64, len *int64, hdtr unsafe.Pointer, flags int) (err error) { + _, _, e1 := syscall_syscall6(libc_sendfile_trampoline_addr, uintptr(infd), uintptr(outfd), uintptr(offset), uintptr(unsafe.Pointer(len)), uintptr(hdtr), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sendfile_trampoline_addr uintptr @@ -775,12 +1172,19 @@ var libc_sendfile_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func shmat(id int, addr uintptr, flag int) (ret uintptr, err error) { + r0, _, e1 := syscall_syscall(libc_shmat_trampoline_addr, uintptr(id), uintptr(addr), uintptr(flag)) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_shmat_trampoline_addr uintptr @@ -790,12 +1194,19 @@ var libc_shmat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func shmctl(id int, cmd int, buf *SysvShmDesc) (result int, err error) { + r0, _, e1 := syscall_syscall(libc_shmctl_trampoline_addr, uintptr(id), uintptr(cmd), uintptr(unsafe.Pointer(buf))) + result = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_shmctl_trampoline_addr uintptr @@ -805,11 +1216,17 @@ var libc_shmctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func shmdt(addr uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_shmdt_trampoline_addr, uintptr(addr), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_shmdt_trampoline_addr uintptr @@ -819,12 +1236,19 @@ var libc_shmdt_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func shmget(key int, size int, flag int) (id int, err error) { + r0, _, e1 := syscall_syscall(libc_shmget_trampoline_addr, uintptr(key), uintptr(size), uintptr(flag)) + id = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_shmget_trampoline_addr uintptr @@ -834,16 +1258,27 @@ var libc_shmget_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_access_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_access_trampoline_addr uintptr @@ -853,11 +1288,17 @@ var libc_access_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { + _, _, e1 := syscall_syscall(libc_adjtime_trampoline_addr, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_adjtime_trampoline_addr uintptr @@ -867,16 +1308,27 @@ var libc_adjtime_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chdir_trampoline_addr uintptr @@ -886,16 +1338,27 @@ var libc_chdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chflags_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chflags_trampoline_addr uintptr @@ -905,16 +1368,27 @@ var libc_chflags_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chmod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chmod_trampoline_addr uintptr @@ -924,16 +1398,27 @@ var libc_chmod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chown_trampoline_addr uintptr @@ -943,16 +1428,27 @@ var libc_chown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chroot_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chroot_trampoline_addr uintptr @@ -962,11 +1458,17 @@ var libc_chroot_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := syscall_syscall(libc_clock_gettime_trampoline_addr, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_clock_gettime_trampoline_addr uintptr @@ -976,11 +1478,17 @@ var libc_clock_gettime_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_close_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_close_trampoline_addr uintptr @@ -990,21 +1498,37 @@ var libc_close_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Clonefile(src string, dst string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(src) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(dst) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_clonefile_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_clonefile_trampoline_addr uintptr @@ -1014,21 +1538,37 @@ var libc_clonefile_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Clonefileat(srcDirfd int, src string, dstDirfd int, dst string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(src) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(dst) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_clonefileat_trampoline_addr, uintptr(srcDirfd), uintptr(unsafe.Pointer(_p0)), uintptr(dstDirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_clonefileat_trampoline_addr uintptr @@ -1038,12 +1578,19 @@ var libc_clonefileat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { + r0, _, e1 := syscall_syscall(libc_dup_trampoline_addr, uintptr(fd), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup_trampoline_addr uintptr @@ -1053,11 +1600,17 @@ var libc_dup_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { + _, _, e1 := syscall_syscall(libc_dup2_trampoline_addr, uintptr(from), uintptr(to), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup2_trampoline_addr uintptr @@ -1067,21 +1620,37 @@ var libc_dup2_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exchangedata(path1 string, path2 string, options int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path1) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(path2) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_exchangedata_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_exchangedata_trampoline_addr uintptr @@ -1091,8 +1660,11 @@ var libc_exchangedata_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + syscall_syscall(libc_exit_trampoline_addr, uintptr(code), 0, 0) + return + } var libc_exit_trampoline_addr uintptr @@ -1102,16 +1674,27 @@ var libc_exit_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_faccessat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_faccessat_trampoline_addr uintptr @@ -1121,11 +1704,17 @@ var libc_faccessat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_fchdir_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchdir_trampoline_addr uintptr @@ -1135,11 +1724,17 @@ var libc_fchdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { + _, _, e1 := syscall_syscall(libc_fchflags_trampoline_addr, uintptr(fd), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchflags_trampoline_addr uintptr @@ -1149,11 +1744,17 @@ var libc_fchflags_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := syscall_syscall(libc_fchmod_trampoline_addr, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchmod_trampoline_addr uintptr @@ -1163,16 +1764,27 @@ var libc_fchmod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fchmodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchmodat_trampoline_addr uintptr @@ -1182,11 +1794,17 @@ var libc_fchmodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := syscall_syscall(libc_fchown_trampoline_addr, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchown_trampoline_addr uintptr @@ -1196,16 +1814,27 @@ var libc_fchown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fchownat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchownat_trampoline_addr uintptr @@ -1215,16 +1844,27 @@ var libc_fchownat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fclonefileat(srcDirfd int, dstDirfd int, dst string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(dst) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fclonefileat_trampoline_addr, uintptr(srcDirfd), uintptr(dstDirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fclonefileat_trampoline_addr uintptr @@ -1234,11 +1874,17 @@ var libc_fclonefileat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := syscall_syscall(libc_flock_trampoline_addr, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_flock_trampoline_addr uintptr @@ -1248,12 +1894,19 @@ var libc_flock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { + r0, _, e1 := syscall_syscall(libc_fpathconf_trampoline_addr, uintptr(fd), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fpathconf_trampoline_addr uintptr @@ -1263,11 +1916,17 @@ var libc_fpathconf_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_fsync_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fsync_trampoline_addr uintptr @@ -1277,11 +1936,17 @@ var libc_fsync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := syscall_syscall(libc_ftruncate_trampoline_addr, uintptr(fd), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ftruncate_trampoline_addr uintptr @@ -1291,18 +1956,31 @@ var libc_ftruncate_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_getcwd_trampoline_addr, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getcwd_trampoline_addr uintptr @@ -1312,9 +1990,13 @@ var libc_getcwd_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdtablesize() (size int) { + r0, _, _ := syscall_syscall(libc_getdtablesize_trampoline_addr, 0, 0, 0) + size = int(r0) + return + } var libc_getdtablesize_trampoline_addr uintptr @@ -1324,9 +2006,13 @@ var libc_getdtablesize_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _, _ := syscall_rawSyscall(libc_getegid_trampoline_addr, 0, 0, 0) + egid = int(r0) + return + } var libc_getegid_trampoline_addr uintptr @@ -1336,9 +2022,13 @@ var libc_getegid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { + r0, _, _ := syscall_rawSyscall(libc_geteuid_trampoline_addr, 0, 0, 0) + uid = int(r0) + return + } var libc_geteuid_trampoline_addr uintptr @@ -1348,9 +2038,13 @@ var libc_geteuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := syscall_rawSyscall(libc_getgid_trampoline_addr, 0, 0, 0) + gid = int(r0) + return + } var libc_getgid_trampoline_addr uintptr @@ -1360,12 +2054,19 @@ var libc_getgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getpgid_trampoline_addr, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpgid_trampoline_addr uintptr @@ -1375,9 +2076,13 @@ var libc_getpgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { + r0, _, _ := syscall_rawSyscall(libc_getpgrp_trampoline_addr, 0, 0, 0) + pgrp = int(r0) + return + } var libc_getpgrp_trampoline_addr uintptr @@ -1387,9 +2092,13 @@ var libc_getpgrp_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := syscall_rawSyscall(libc_getpid_trampoline_addr, 0, 0, 0) + pid = int(r0) + return + } var libc_getpid_trampoline_addr uintptr @@ -1399,9 +2108,13 @@ var libc_getpid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _, _ := syscall_rawSyscall(libc_getppid_trampoline_addr, 0, 0, 0) + ppid = int(r0) + return + } var libc_getppid_trampoline_addr uintptr @@ -1411,12 +2124,19 @@ var libc_getppid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := syscall_syscall(libc_getpriority_trampoline_addr, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpriority_trampoline_addr uintptr @@ -1426,11 +2146,17 @@ var libc_getpriority_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getrlimit_trampoline_addr, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrlimit_trampoline_addr uintptr @@ -1440,11 +2166,17 @@ var libc_getrlimit_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getrusage_trampoline_addr, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrusage_trampoline_addr uintptr @@ -1454,12 +2186,19 @@ var libc_getrusage_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getsid_trampoline_addr, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsid_trampoline_addr uintptr @@ -1469,11 +2208,17 @@ var libc_getsid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tp *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(libc_gettimeofday_trampoline_addr, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_gettimeofday_trampoline_addr uintptr @@ -1483,9 +2228,13 @@ var libc_gettimeofday_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := syscall_rawSyscall(libc_getuid_trampoline_addr, 0, 0, 0) + uid = int(r0) + return + } var libc_getuid_trampoline_addr uintptr @@ -1495,9 +2244,13 @@ var libc_getuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { + r0, _, _ := syscall_rawSyscall(libc_issetugid_trampoline_addr, 0, 0, 0) + tainted = bool(r0 != 0) + return + } var libc_issetugid_trampoline_addr uintptr @@ -1507,12 +2260,19 @@ var libc_issetugid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { + r0, _, e1 := syscall_syscall(libc_kqueue_trampoline_addr, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kqueue_trampoline_addr uintptr @@ -1522,16 +2282,27 @@ var libc_kqueue_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_lchown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lchown_trampoline_addr uintptr @@ -1541,21 +2312,37 @@ var libc_lchown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_link_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_link_trampoline_addr uintptr @@ -1565,21 +2352,37 @@ var libc_link_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_linkat_trampoline_addr, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_linkat_trampoline_addr uintptr @@ -1589,11 +2392,17 @@ var libc_linkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { + _, _, e1 := syscall_syscall(libc_listen_trampoline_addr, uintptr(s), uintptr(backlog), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_listen_trampoline_addr uintptr @@ -1603,16 +2412,27 @@ var libc_listen_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkdir_trampoline_addr uintptr @@ -1622,16 +2442,27 @@ var libc_mkdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkdirat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkdirat_trampoline_addr uintptr @@ -1641,16 +2472,27 @@ var libc_mkdirat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkfifo_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkfifo_trampoline_addr uintptr @@ -1660,16 +2502,27 @@ var libc_mkfifo_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mknod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mknod_trampoline_addr uintptr @@ -1679,21 +2532,37 @@ var libc_mknod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(fsType) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(dir) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flags), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mount_trampoline_addr uintptr @@ -1703,17 +2572,29 @@ var libc_mount_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall(libc_open_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_open_trampoline_addr uintptr @@ -1723,17 +2604,29 @@ var libc_open_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall6(libc_openat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_openat_trampoline_addr uintptr @@ -1743,17 +2636,29 @@ var libc_openat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall(libc_pathconf_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pathconf_trampoline_addr uintptr @@ -1763,18 +2668,31 @@ var libc_pathconf_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_pread_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pread_trampoline_addr uintptr @@ -1784,18 +2702,31 @@ var libc_pread_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_pwrite_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pwrite_trampoline_addr uintptr @@ -1805,18 +2736,31 @@ var libc_pwrite_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_read_trampoline_addr uintptr @@ -1826,23 +2770,41 @@ var libc_read_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_readlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_readlink_trampoline_addr uintptr @@ -1852,23 +2814,41 @@ var libc_readlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_readlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_readlinkat_trampoline_addr uintptr @@ -1878,21 +2858,37 @@ var libc_readlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_rename_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_rename_trampoline_addr uintptr @@ -1902,21 +2898,37 @@ var libc_rename_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_renameat_trampoline_addr, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_renameat_trampoline_addr uintptr @@ -1926,16 +2938,27 @@ var libc_renameat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_revoke_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_revoke_trampoline_addr uintptr @@ -1945,16 +2968,27 @@ var libc_revoke_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_rmdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_rmdir_trampoline_addr uintptr @@ -1964,12 +2998,19 @@ var libc_rmdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, _, e1 := syscall_syscall(libc_lseek_trampoline_addr, uintptr(fd), uintptr(offset), uintptr(whence)) + newoffset = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lseek_trampoline_addr uintptr @@ -1979,12 +3020,19 @@ var libc_lseek_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_select_trampoline_addr, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_select_trampoline_addr uintptr @@ -1994,22 +3042,39 @@ var libc_select_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setattrlist(path string, attrlist *Attrlist, attrBuf []byte, options int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(attrBuf) > 0 { + _p1 = unsafe.Pointer(&attrBuf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall6(libc_setattrlist_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(attrlist)), uintptr(_p1), uintptr(len(attrBuf)), uintptr(options), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setattrlist_trampoline_addr uintptr @@ -2019,11 +3084,17 @@ var libc_setattrlist_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + _, _, e1 := syscall_syscall(libc_setegid_trampoline_addr, uintptr(egid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setegid_trampoline_addr uintptr @@ -2033,11 +3104,17 @@ var libc_setegid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_seteuid_trampoline_addr, uintptr(euid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_seteuid_trampoline_addr uintptr @@ -2047,11 +3124,17 @@ var libc_seteuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setgid_trampoline_addr, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setgid_trampoline_addr uintptr @@ -2061,16 +3144,27 @@ var libc_setgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(name) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_setlogin_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setlogin_trampoline_addr uintptr @@ -2080,11 +3174,17 @@ var libc_setlogin_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setpgid_trampoline_addr, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setpgid_trampoline_addr uintptr @@ -2094,11 +3194,17 @@ var libc_setpgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := syscall_syscall(libc_setpriority_trampoline_addr, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setpriority_trampoline_addr uintptr @@ -2108,11 +3214,17 @@ var libc_setpriority_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setprivexec(flag int) (err error) { + _, _, e1 := syscall_syscall(libc_setprivexec_trampoline_addr, uintptr(flag), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setprivexec_trampoline_addr uintptr @@ -2122,11 +3234,17 @@ var libc_setprivexec_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setregid_trampoline_addr, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setregid_trampoline_addr uintptr @@ -2136,11 +3254,17 @@ var libc_setregid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setreuid_trampoline_addr, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setreuid_trampoline_addr uintptr @@ -2150,12 +3274,19 @@ var libc_setreuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_setsid_trampoline_addr, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setsid_trampoline_addr uintptr @@ -2165,11 +3296,17 @@ var libc_setsid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(libc_settimeofday_trampoline_addr, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_settimeofday_trampoline_addr uintptr @@ -2179,11 +3316,17 @@ var libc_settimeofday_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setuid_trampoline_addr, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setuid_trampoline_addr uintptr @@ -2193,21 +3336,37 @@ var libc_setuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_symlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_symlink_trampoline_addr uintptr @@ -2217,21 +3376,37 @@ var libc_symlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_symlinkat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_symlinkat_trampoline_addr uintptr @@ -2241,11 +3416,17 @@ var libc_symlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { + _, _, e1 := syscall_syscall(libc_sync_trampoline_addr, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sync_trampoline_addr uintptr @@ -2255,16 +3436,27 @@ var libc_sync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_truncate_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_truncate_trampoline_addr uintptr @@ -2274,9 +3466,13 @@ var libc_truncate_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { + r0, _, _ := syscall_syscall(libc_umask_trampoline_addr, uintptr(newmask), 0, 0) + oldmask = int(r0) + return + } var libc_umask_trampoline_addr uintptr @@ -2286,16 +3482,27 @@ var libc_umask_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Undelete(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_undelete_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_undelete_trampoline_addr uintptr @@ -2305,16 +3512,27 @@ var libc_undelete_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unlink_trampoline_addr uintptr @@ -2324,16 +3542,27 @@ var libc_unlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unlinkat_trampoline_addr uintptr @@ -2343,16 +3572,27 @@ var libc_unlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unmount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unmount_trampoline_addr uintptr @@ -2362,18 +3602,31 @@ var libc_unmount_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_write_trampoline_addr uintptr @@ -2383,12 +3636,19 @@ var libc_write_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + r0, _, e1 := syscall_syscall6(libc_mmap_trampoline_addr, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mmap_trampoline_addr uintptr @@ -2398,11 +3658,17 @@ var libc_mmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_munmap_trampoline_addr, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munmap_trampoline_addr uintptr @@ -2412,11 +3678,17 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := syscall_syscall(libc_fstat64_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstat64_trampoline_addr uintptr @@ -2426,16 +3698,27 @@ var libc_fstat64_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fstatat64_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstatat64_trampoline_addr uintptr @@ -2445,11 +3728,17 @@ var libc_fstatat64_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { + _, _, e1 := syscall_syscall(libc_fstatfs64_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstatfs64_trampoline_addr uintptr @@ -2459,12 +3748,19 @@ var libc_fstatfs64_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getfsstat(buf unsafe.Pointer, size uintptr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_getfsstat64_trampoline_addr, uintptr(buf), uintptr(size), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getfsstat64_trampoline_addr uintptr @@ -2474,16 +3770,27 @@ var libc_getfsstat64_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_lstat64_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lstat64_trampoline_addr uintptr @@ -2493,11 +3800,17 @@ var libc_lstat64_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace1(request int, pid int, addr uintptr, data uintptr) (err error) { + _, _, e1 := syscall_syscall6(libc_ptrace_trampoline_addr, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ptrace_trampoline_addr uintptr @@ -2507,16 +3820,27 @@ var libc_ptrace_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_stat64_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_stat64_trampoline_addr uintptr @@ -2526,16 +3850,27 @@ var libc_stat64_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_statfs64_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_statfs64_trampoline_addr uintptr diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go index 1b40b99..1e118ee 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go @@ -1,4 +1,5 @@ // go run mksyscall.go -tags darwin,arm64 syscall_bsd.go syscall_darwin.go syscall_darwin_arm64.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build darwin && arm64 @@ -15,12 +16,19 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getgroups_trampoline_addr uintptr @@ -30,11 +38,17 @@ var libc_getgroups_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setgroups_trampoline_addr uintptr @@ -44,12 +58,19 @@ var libc_setgroups_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := syscall_syscall6(libc_wait4_trampoline_addr, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_wait4_trampoline_addr uintptr @@ -59,12 +80,19 @@ var libc_wait4_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := syscall_syscall(libc_accept_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_accept_trampoline_addr uintptr @@ -74,11 +102,17 @@ var libc_accept_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := syscall_syscall(libc_bind_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_bind_trampoline_addr uintptr @@ -88,11 +122,17 @@ var libc_bind_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := syscall_syscall(libc_connect_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_connect_trampoline_addr uintptr @@ -102,12 +142,19 @@ var libc_connect_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_socket_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_socket_trampoline_addr uintptr @@ -117,11 +164,17 @@ var libc_socket_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := syscall_syscall6(libc_getsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsockopt_trampoline_addr uintptr @@ -131,11 +184,17 @@ var libc_getsockopt_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := syscall_syscall6(libc_setsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setsockopt_trampoline_addr uintptr @@ -145,11 +204,17 @@ var libc_setsockopt_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getpeername_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpeername_trampoline_addr uintptr @@ -159,11 +224,17 @@ var libc_getpeername_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getsockname_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsockname_trampoline_addr uintptr @@ -173,11 +244,17 @@ var libc_getsockname_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { + _, _, e1 := syscall_syscall(libc_shutdown_trampoline_addr, uintptr(s), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_shutdown_trampoline_addr uintptr @@ -187,11 +264,17 @@ var libc_shutdown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := syscall_rawSyscall6(libc_socketpair_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_socketpair_trampoline_addr uintptr @@ -201,18 +284,31 @@ var libc_socketpair_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_recvfrom_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_recvfrom_trampoline_addr uintptr @@ -222,17 +318,29 @@ var libc_recvfrom_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall6(libc_sendto_trampoline_addr, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sendto_trampoline_addr uintptr @@ -242,12 +350,19 @@ var libc_sendto_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_recvmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_recvmsg_trampoline_addr uintptr @@ -257,12 +372,19 @@ var libc_recvmsg_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_sendmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sendmsg_trampoline_addr uintptr @@ -272,12 +394,19 @@ var libc_sendmsg_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_kevent_trampoline_addr, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kevent_trampoline_addr uintptr @@ -287,16 +416,27 @@ var libc_kevent_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_utimes_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_utimes_trampoline_addr uintptr @@ -306,11 +446,17 @@ var libc_utimes_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { + _, _, e1 := syscall_syscall(libc_futimes_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_futimes_trampoline_addr uintptr @@ -320,12 +466,19 @@ var libc_futimes_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_poll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_poll_trampoline_addr uintptr @@ -335,17 +488,29 @@ var libc_poll_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_madvise_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_madvise_trampoline_addr uintptr @@ -355,17 +520,29 @@ var libc_madvise_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_mlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mlock_trampoline_addr uintptr @@ -375,11 +552,17 @@ var libc_mlock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := syscall_syscall(libc_mlockall_trampoline_addr, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mlockall_trampoline_addr uintptr @@ -389,17 +572,29 @@ var libc_mlockall_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_mprotect_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mprotect_trampoline_addr uintptr @@ -409,17 +604,29 @@ var libc_mprotect_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_msync_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_msync_trampoline_addr uintptr @@ -429,17 +636,29 @@ var libc_msync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_munlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munlock_trampoline_addr uintptr @@ -449,11 +668,17 @@ var libc_munlock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := syscall_syscall(libc_munlockall_trampoline_addr, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munlockall_trampoline_addr uintptr @@ -463,11 +688,17 @@ var libc_munlockall_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func closedir(dir uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_closedir_trampoline_addr, uintptr(dir), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_closedir_trampoline_addr uintptr @@ -477,9 +708,13 @@ var libc_closedir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readdir_r(dir uintptr, entry *Dirent, result **Dirent) (res Errno) { + r0, _, _ := syscall_syscall(libc_readdir_r_trampoline_addr, uintptr(dir), uintptr(unsafe.Pointer(entry)), uintptr(unsafe.Pointer(result))) + res = Errno(r0) + return + } var libc_readdir_r_trampoline_addr uintptr @@ -489,11 +724,17 @@ var libc_readdir_r_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]int32) (err error) { + _, _, e1 := syscall_rawSyscall(libc_pipe_trampoline_addr, uintptr(unsafe.Pointer(p)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pipe_trampoline_addr uintptr @@ -503,22 +744,39 @@ var libc_pipe_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getxattr(path string, attr string, dest *byte, size int, position uint32, options int) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + r0, _, e1 := syscall_syscall6(libc_getxattr_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(dest)), uintptr(size), uintptr(position), uintptr(options)) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getxattr_trampoline_addr uintptr @@ -528,17 +786,29 @@ var libc_getxattr_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fgetxattr(fd int, attr string, dest *byte, size int, position uint32, options int) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attr) + if err != nil { + return + } + r0, _, e1 := syscall_syscall6(libc_fgetxattr_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(dest)), uintptr(size), uintptr(position), uintptr(options)) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fgetxattr_trampoline_addr uintptr @@ -548,21 +818,37 @@ var libc_fgetxattr_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setxattr(path string, attr string, data *byte, size int, position uint32, options int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_setxattr_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(data)), uintptr(size), uintptr(position), uintptr(options)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setxattr_trampoline_addr uintptr @@ -572,16 +858,27 @@ var libc_setxattr_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fsetxattr(fd int, attr string, data *byte, size int, position uint32, options int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fsetxattr_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(data)), uintptr(size), uintptr(position), uintptr(options)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fsetxattr_trampoline_addr uintptr @@ -591,21 +888,37 @@ var libc_fsetxattr_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func removexattr(path string, attr string, options int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_removexattr_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_removexattr_trampoline_addr uintptr @@ -615,16 +928,27 @@ var libc_removexattr_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fremovexattr(fd int, attr string, options int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_fremovexattr_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(options)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fremovexattr_trampoline_addr uintptr @@ -634,17 +958,29 @@ var libc_fremovexattr_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func listxattr(path string, dest *byte, size int, options int) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall6(libc_listxattr_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(dest)), uintptr(size), uintptr(options), 0, 0) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_listxattr_trampoline_addr uintptr @@ -654,12 +990,19 @@ var libc_listxattr_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func flistxattr(fd int, dest *byte, size int, options int) (sz int, err error) { + r0, _, e1 := syscall_syscall6(libc_flistxattr_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(dest)), uintptr(size), uintptr(options), 0, 0) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_flistxattr_trampoline_addr uintptr @@ -669,16 +1012,27 @@ var libc_flistxattr_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_utimensat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_utimensat_trampoline_addr uintptr @@ -688,12 +1042,19 @@ var libc_utimensat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fcntl_trampoline_addr uintptr @@ -703,11 +1064,17 @@ var libc_fcntl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kill(pid int, signum int, posix int) (err error) { + _, _, e1 := syscall_syscall(libc_kill_trampoline_addr, uintptr(pid), uintptr(signum), uintptr(posix)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kill_trampoline_addr uintptr @@ -717,11 +1084,17 @@ var libc_kill_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ioctl_trampoline_addr uintptr @@ -731,27 +1104,45 @@ var libc_ioctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall6(libc_sysctl_trampoline_addr, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sysctl_trampoline_addr uintptr @@ -761,11 +1152,17 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(infd int, outfd int, offset int64, len *int64, hdtr unsafe.Pointer, flags int) (err error) { + _, _, e1 := syscall_syscall6(libc_sendfile_trampoline_addr, uintptr(infd), uintptr(outfd), uintptr(offset), uintptr(unsafe.Pointer(len)), uintptr(hdtr), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sendfile_trampoline_addr uintptr @@ -775,12 +1172,19 @@ var libc_sendfile_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func shmat(id int, addr uintptr, flag int) (ret uintptr, err error) { + r0, _, e1 := syscall_syscall(libc_shmat_trampoline_addr, uintptr(id), uintptr(addr), uintptr(flag)) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_shmat_trampoline_addr uintptr @@ -790,12 +1194,19 @@ var libc_shmat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func shmctl(id int, cmd int, buf *SysvShmDesc) (result int, err error) { + r0, _, e1 := syscall_syscall(libc_shmctl_trampoline_addr, uintptr(id), uintptr(cmd), uintptr(unsafe.Pointer(buf))) + result = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_shmctl_trampoline_addr uintptr @@ -805,11 +1216,17 @@ var libc_shmctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func shmdt(addr uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_shmdt_trampoline_addr, uintptr(addr), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_shmdt_trampoline_addr uintptr @@ -819,12 +1236,19 @@ var libc_shmdt_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func shmget(key int, size int, flag int) (id int, err error) { + r0, _, e1 := syscall_syscall(libc_shmget_trampoline_addr, uintptr(key), uintptr(size), uintptr(flag)) + id = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_shmget_trampoline_addr uintptr @@ -834,16 +1258,27 @@ var libc_shmget_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_access_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_access_trampoline_addr uintptr @@ -853,11 +1288,17 @@ var libc_access_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { + _, _, e1 := syscall_syscall(libc_adjtime_trampoline_addr, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_adjtime_trampoline_addr uintptr @@ -867,16 +1308,27 @@ var libc_adjtime_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chdir_trampoline_addr uintptr @@ -886,16 +1338,27 @@ var libc_chdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chflags_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chflags_trampoline_addr uintptr @@ -905,16 +1368,27 @@ var libc_chflags_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chmod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chmod_trampoline_addr uintptr @@ -924,16 +1398,27 @@ var libc_chmod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chown_trampoline_addr uintptr @@ -943,16 +1428,27 @@ var libc_chown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chroot_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chroot_trampoline_addr uintptr @@ -962,11 +1458,17 @@ var libc_chroot_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := syscall_syscall(libc_clock_gettime_trampoline_addr, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_clock_gettime_trampoline_addr uintptr @@ -976,11 +1478,17 @@ var libc_clock_gettime_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_close_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_close_trampoline_addr uintptr @@ -990,21 +1498,37 @@ var libc_close_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Clonefile(src string, dst string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(src) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(dst) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_clonefile_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_clonefile_trampoline_addr uintptr @@ -1014,21 +1538,37 @@ var libc_clonefile_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Clonefileat(srcDirfd int, src string, dstDirfd int, dst string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(src) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(dst) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_clonefileat_trampoline_addr, uintptr(srcDirfd), uintptr(unsafe.Pointer(_p0)), uintptr(dstDirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_clonefileat_trampoline_addr uintptr @@ -1038,12 +1578,19 @@ var libc_clonefileat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { + r0, _, e1 := syscall_syscall(libc_dup_trampoline_addr, uintptr(fd), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup_trampoline_addr uintptr @@ -1053,11 +1600,17 @@ var libc_dup_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { + _, _, e1 := syscall_syscall(libc_dup2_trampoline_addr, uintptr(from), uintptr(to), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup2_trampoline_addr uintptr @@ -1067,21 +1620,37 @@ var libc_dup2_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exchangedata(path1 string, path2 string, options int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path1) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(path2) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_exchangedata_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_exchangedata_trampoline_addr uintptr @@ -1091,8 +1660,11 @@ var libc_exchangedata_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + syscall_syscall(libc_exit_trampoline_addr, uintptr(code), 0, 0) + return + } var libc_exit_trampoline_addr uintptr @@ -1102,16 +1674,27 @@ var libc_exit_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_faccessat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_faccessat_trampoline_addr uintptr @@ -1121,11 +1704,17 @@ var libc_faccessat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_fchdir_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchdir_trampoline_addr uintptr @@ -1135,11 +1724,17 @@ var libc_fchdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { + _, _, e1 := syscall_syscall(libc_fchflags_trampoline_addr, uintptr(fd), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchflags_trampoline_addr uintptr @@ -1149,11 +1744,17 @@ var libc_fchflags_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := syscall_syscall(libc_fchmod_trampoline_addr, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchmod_trampoline_addr uintptr @@ -1163,16 +1764,27 @@ var libc_fchmod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fchmodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchmodat_trampoline_addr uintptr @@ -1182,11 +1794,17 @@ var libc_fchmodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := syscall_syscall(libc_fchown_trampoline_addr, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchown_trampoline_addr uintptr @@ -1196,16 +1814,27 @@ var libc_fchown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fchownat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchownat_trampoline_addr uintptr @@ -1215,16 +1844,27 @@ var libc_fchownat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fclonefileat(srcDirfd int, dstDirfd int, dst string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(dst) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fclonefileat_trampoline_addr, uintptr(srcDirfd), uintptr(dstDirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fclonefileat_trampoline_addr uintptr @@ -1234,11 +1874,17 @@ var libc_fclonefileat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := syscall_syscall(libc_flock_trampoline_addr, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_flock_trampoline_addr uintptr @@ -1248,12 +1894,19 @@ var libc_flock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { + r0, _, e1 := syscall_syscall(libc_fpathconf_trampoline_addr, uintptr(fd), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fpathconf_trampoline_addr uintptr @@ -1263,11 +1916,17 @@ var libc_fpathconf_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_fsync_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fsync_trampoline_addr uintptr @@ -1277,11 +1936,17 @@ var libc_fsync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := syscall_syscall(libc_ftruncate_trampoline_addr, uintptr(fd), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ftruncate_trampoline_addr uintptr @@ -1291,18 +1956,31 @@ var libc_ftruncate_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_getcwd_trampoline_addr, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getcwd_trampoline_addr uintptr @@ -1312,9 +1990,13 @@ var libc_getcwd_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdtablesize() (size int) { + r0, _, _ := syscall_syscall(libc_getdtablesize_trampoline_addr, 0, 0, 0) + size = int(r0) + return + } var libc_getdtablesize_trampoline_addr uintptr @@ -1324,9 +2006,13 @@ var libc_getdtablesize_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _, _ := syscall_rawSyscall(libc_getegid_trampoline_addr, 0, 0, 0) + egid = int(r0) + return + } var libc_getegid_trampoline_addr uintptr @@ -1336,9 +2022,13 @@ var libc_getegid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { + r0, _, _ := syscall_rawSyscall(libc_geteuid_trampoline_addr, 0, 0, 0) + uid = int(r0) + return + } var libc_geteuid_trampoline_addr uintptr @@ -1348,9 +2038,13 @@ var libc_geteuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := syscall_rawSyscall(libc_getgid_trampoline_addr, 0, 0, 0) + gid = int(r0) + return + } var libc_getgid_trampoline_addr uintptr @@ -1360,12 +2054,19 @@ var libc_getgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getpgid_trampoline_addr, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpgid_trampoline_addr uintptr @@ -1375,9 +2076,13 @@ var libc_getpgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { + r0, _, _ := syscall_rawSyscall(libc_getpgrp_trampoline_addr, 0, 0, 0) + pgrp = int(r0) + return + } var libc_getpgrp_trampoline_addr uintptr @@ -1387,9 +2092,13 @@ var libc_getpgrp_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := syscall_rawSyscall(libc_getpid_trampoline_addr, 0, 0, 0) + pid = int(r0) + return + } var libc_getpid_trampoline_addr uintptr @@ -1399,9 +2108,13 @@ var libc_getpid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _, _ := syscall_rawSyscall(libc_getppid_trampoline_addr, 0, 0, 0) + ppid = int(r0) + return + } var libc_getppid_trampoline_addr uintptr @@ -1411,12 +2124,19 @@ var libc_getppid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := syscall_syscall(libc_getpriority_trampoline_addr, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpriority_trampoline_addr uintptr @@ -1426,11 +2146,17 @@ var libc_getpriority_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getrlimit_trampoline_addr, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrlimit_trampoline_addr uintptr @@ -1440,11 +2166,17 @@ var libc_getrlimit_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getrusage_trampoline_addr, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrusage_trampoline_addr uintptr @@ -1454,12 +2186,19 @@ var libc_getrusage_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getsid_trampoline_addr, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsid_trampoline_addr uintptr @@ -1469,11 +2208,17 @@ var libc_getsid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tp *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(libc_gettimeofday_trampoline_addr, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_gettimeofday_trampoline_addr uintptr @@ -1483,9 +2228,13 @@ var libc_gettimeofday_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := syscall_rawSyscall(libc_getuid_trampoline_addr, 0, 0, 0) + uid = int(r0) + return + } var libc_getuid_trampoline_addr uintptr @@ -1495,9 +2244,13 @@ var libc_getuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { + r0, _, _ := syscall_rawSyscall(libc_issetugid_trampoline_addr, 0, 0, 0) + tainted = bool(r0 != 0) + return + } var libc_issetugid_trampoline_addr uintptr @@ -1507,12 +2260,19 @@ var libc_issetugid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { + r0, _, e1 := syscall_syscall(libc_kqueue_trampoline_addr, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kqueue_trampoline_addr uintptr @@ -1522,16 +2282,27 @@ var libc_kqueue_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_lchown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lchown_trampoline_addr uintptr @@ -1541,21 +2312,37 @@ var libc_lchown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_link_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_link_trampoline_addr uintptr @@ -1565,21 +2352,37 @@ var libc_link_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_linkat_trampoline_addr, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_linkat_trampoline_addr uintptr @@ -1589,11 +2392,17 @@ var libc_linkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { + _, _, e1 := syscall_syscall(libc_listen_trampoline_addr, uintptr(s), uintptr(backlog), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_listen_trampoline_addr uintptr @@ -1603,16 +2412,27 @@ var libc_listen_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkdir_trampoline_addr uintptr @@ -1622,16 +2442,27 @@ var libc_mkdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkdirat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkdirat_trampoline_addr uintptr @@ -1641,16 +2472,27 @@ var libc_mkdirat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkfifo_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkfifo_trampoline_addr uintptr @@ -1660,16 +2502,27 @@ var libc_mkfifo_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mknod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mknod_trampoline_addr uintptr @@ -1679,21 +2532,37 @@ var libc_mknod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(fsType) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(dir) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flags), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mount_trampoline_addr uintptr @@ -1703,17 +2572,29 @@ var libc_mount_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall(libc_open_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_open_trampoline_addr uintptr @@ -1723,17 +2604,29 @@ var libc_open_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall6(libc_openat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_openat_trampoline_addr uintptr @@ -1743,17 +2636,29 @@ var libc_openat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall(libc_pathconf_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pathconf_trampoline_addr uintptr @@ -1763,18 +2668,31 @@ var libc_pathconf_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_pread_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pread_trampoline_addr uintptr @@ -1784,18 +2702,31 @@ var libc_pread_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_pwrite_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pwrite_trampoline_addr uintptr @@ -1805,18 +2736,31 @@ var libc_pwrite_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_read_trampoline_addr uintptr @@ -1826,23 +2770,41 @@ var libc_read_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_readlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_readlink_trampoline_addr uintptr @@ -1852,23 +2814,41 @@ var libc_readlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_readlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_readlinkat_trampoline_addr uintptr @@ -1878,21 +2858,37 @@ var libc_readlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_rename_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_rename_trampoline_addr uintptr @@ -1902,21 +2898,37 @@ var libc_rename_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_renameat_trampoline_addr, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_renameat_trampoline_addr uintptr @@ -1926,16 +2938,27 @@ var libc_renameat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_revoke_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_revoke_trampoline_addr uintptr @@ -1945,16 +2968,27 @@ var libc_revoke_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_rmdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_rmdir_trampoline_addr uintptr @@ -1964,12 +2998,19 @@ var libc_rmdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, _, e1 := syscall_syscall(libc_lseek_trampoline_addr, uintptr(fd), uintptr(offset), uintptr(whence)) + newoffset = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lseek_trampoline_addr uintptr @@ -1979,12 +3020,19 @@ var libc_lseek_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_select_trampoline_addr, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_select_trampoline_addr uintptr @@ -1994,22 +3042,39 @@ var libc_select_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setattrlist(path string, attrlist *Attrlist, attrBuf []byte, options int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(attrBuf) > 0 { + _p1 = unsafe.Pointer(&attrBuf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall6(libc_setattrlist_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(attrlist)), uintptr(_p1), uintptr(len(attrBuf)), uintptr(options), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setattrlist_trampoline_addr uintptr @@ -2019,11 +3084,17 @@ var libc_setattrlist_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + _, _, e1 := syscall_syscall(libc_setegid_trampoline_addr, uintptr(egid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setegid_trampoline_addr uintptr @@ -2033,11 +3104,17 @@ var libc_setegid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_seteuid_trampoline_addr, uintptr(euid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_seteuid_trampoline_addr uintptr @@ -2047,11 +3124,17 @@ var libc_seteuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setgid_trampoline_addr, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setgid_trampoline_addr uintptr @@ -2061,16 +3144,27 @@ var libc_setgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(name) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_setlogin_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setlogin_trampoline_addr uintptr @@ -2080,11 +3174,17 @@ var libc_setlogin_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setpgid_trampoline_addr, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setpgid_trampoline_addr uintptr @@ -2094,11 +3194,17 @@ var libc_setpgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := syscall_syscall(libc_setpriority_trampoline_addr, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setpriority_trampoline_addr uintptr @@ -2108,11 +3214,17 @@ var libc_setpriority_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setprivexec(flag int) (err error) { + _, _, e1 := syscall_syscall(libc_setprivexec_trampoline_addr, uintptr(flag), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setprivexec_trampoline_addr uintptr @@ -2122,11 +3234,17 @@ var libc_setprivexec_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setregid_trampoline_addr, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setregid_trampoline_addr uintptr @@ -2136,11 +3254,17 @@ var libc_setregid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setreuid_trampoline_addr, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setreuid_trampoline_addr uintptr @@ -2150,12 +3274,19 @@ var libc_setreuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_setsid_trampoline_addr, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setsid_trampoline_addr uintptr @@ -2165,11 +3296,17 @@ var libc_setsid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(libc_settimeofday_trampoline_addr, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_settimeofday_trampoline_addr uintptr @@ -2179,11 +3316,17 @@ var libc_settimeofday_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setuid_trampoline_addr, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setuid_trampoline_addr uintptr @@ -2193,21 +3336,37 @@ var libc_setuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_symlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_symlink_trampoline_addr uintptr @@ -2217,21 +3376,37 @@ var libc_symlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_symlinkat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_symlinkat_trampoline_addr uintptr @@ -2241,11 +3416,17 @@ var libc_symlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { + _, _, e1 := syscall_syscall(libc_sync_trampoline_addr, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sync_trampoline_addr uintptr @@ -2255,16 +3436,27 @@ var libc_sync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_truncate_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_truncate_trampoline_addr uintptr @@ -2274,9 +3466,13 @@ var libc_truncate_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { + r0, _, _ := syscall_syscall(libc_umask_trampoline_addr, uintptr(newmask), 0, 0) + oldmask = int(r0) + return + } var libc_umask_trampoline_addr uintptr @@ -2286,16 +3482,27 @@ var libc_umask_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Undelete(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_undelete_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_undelete_trampoline_addr uintptr @@ -2305,16 +3512,27 @@ var libc_undelete_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unlink_trampoline_addr uintptr @@ -2324,16 +3542,27 @@ var libc_unlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unlinkat_trampoline_addr uintptr @@ -2343,16 +3572,27 @@ var libc_unlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unmount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unmount_trampoline_addr uintptr @@ -2362,18 +3602,31 @@ var libc_unmount_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_write_trampoline_addr uintptr @@ -2383,12 +3636,19 @@ var libc_write_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + r0, _, e1 := syscall_syscall6(libc_mmap_trampoline_addr, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mmap_trampoline_addr uintptr @@ -2398,11 +3658,17 @@ var libc_mmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_munmap_trampoline_addr, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munmap_trampoline_addr uintptr @@ -2412,11 +3678,17 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := syscall_syscall(libc_fstat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstat_trampoline_addr uintptr @@ -2426,16 +3698,27 @@ var libc_fstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fstatat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstatat_trampoline_addr uintptr @@ -2445,11 +3728,17 @@ var libc_fstatat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { + _, _, e1 := syscall_syscall(libc_fstatfs_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstatfs_trampoline_addr uintptr @@ -2459,12 +3748,19 @@ var libc_fstatfs_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getfsstat(buf unsafe.Pointer, size uintptr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_getfsstat_trampoline_addr, uintptr(buf), uintptr(size), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getfsstat_trampoline_addr uintptr @@ -2474,16 +3770,27 @@ var libc_getfsstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_lstat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lstat_trampoline_addr uintptr @@ -2493,11 +3800,17 @@ var libc_lstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace1(request int, pid int, addr uintptr, data uintptr) (err error) { + _, _, e1 := syscall_syscall6(libc_ptrace_trampoline_addr, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ptrace_trampoline_addr uintptr @@ -2507,16 +3820,27 @@ var libc_ptrace_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_stat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_stat_trampoline_addr uintptr @@ -2526,16 +3850,27 @@ var libc_stat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_statfs_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_statfs_trampoline_addr uintptr diff --git a/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go index aad65fc..4736325 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go @@ -1,4 +1,5 @@ // go run mksyscall.go -dragonfly -tags dragonfly,amd64 syscall_bsd.go syscall_dragonfly.go syscall_dragonfly_amd64.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build dragonfly && amd64 @@ -15,1652 +16,2777 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { + r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { + _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe() (r int, w int, err error) { + r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) + r = int(r0) + w = int(r1) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (r int, w int, err error) { + r0, r1, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + r = int(r0) + w = int(r1) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func extpread(fd int, p []byte, flags int, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EXTPREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(offset), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func extpwrite(fd int, p []byte, flags int, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EXTPWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(offset), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { + _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { + r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { + _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + Syscall(SYS_EXIT, uintptr(code), 0, 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { + _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { + r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { + _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_GETDIRENTRIES, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdtablesize() (size int) { + r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0) + size = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { + r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) + pgrp = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + pid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + ppid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { + r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) + tainted = bool(r0 != 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { + _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { + r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(fd int, path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, _, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(whence), 0, 0) + newoffset = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(name) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { + _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { + r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) + oldmask = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Undelete(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), 0, 0) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go index c009639..a2b8b24 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go @@ -1,4 +1,5 @@ // go run mksyscall.go -l32 -tags freebsd,386 syscall_bsd.go syscall_freebsd.go syscall_freebsd_386.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build freebsd && 386 @@ -15,1872 +16,3161 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { + r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { + _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { + _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data int) (err error) { + _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptracePtr(request int, pid int, addr unsafe.Pointer, data int) (err error) { + _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { + _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CapEnter() (err error) { + _, _, e1 := Syscall(SYS_CAP_ENTER, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func capRightsGet(version int, fd int, rightsp *CapRights) (err error) { + _, _, e1 := Syscall(SYS___CAP_RIGHTS_GET, uintptr(version), uintptr(fd), uintptr(unsafe.Pointer(rightsp))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func capRightsLimit(fd int, rightsp *CapRights) (err error) { + _, _, e1 := Syscall(SYS_CAP_RIGHTS_LIMIT, uintptr(fd), uintptr(unsafe.Pointer(rightsp)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { + r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { + _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + Syscall(SYS_EXIT, uintptr(code), 0, 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_POSIX_FADVISE, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { + _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { + r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { + _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), uintptr(length>>32)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getdirentries(fd int, buf []byte, basep *uint64) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_GETDIRENTRIES, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdtablesize() (size int) { + r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0) + size = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { + r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) + pgrp = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + pid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + ppid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { + r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) + tainted = bool(r0 != 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { + _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { + r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(fd int, path string, mode uint32, dev uint64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), uintptr(dev>>32), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(fdat int, path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(fdat), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(whence), 0, 0) + newoffset = int64(int64(r1)<<32 | int64(r0)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(name) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { + _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), uintptr(length>>32)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { + r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) + oldmask = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Undelete(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos), uintptr(pos>>32), 0, 0) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go index 7664df7..4c05144 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go @@ -1,4 +1,5 @@ // go run mksyscall.go -tags freebsd,amd64 syscall_bsd.go syscall_freebsd.go syscall_freebsd_amd64.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build freebsd && amd64 @@ -15,1872 +16,3161 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { + r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { + _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { + _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data int) (err error) { + _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptracePtr(request int, pid int, addr unsafe.Pointer, data int) (err error) { + _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { + _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CapEnter() (err error) { + _, _, e1 := Syscall(SYS_CAP_ENTER, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func capRightsGet(version int, fd int, rightsp *CapRights) (err error) { + _, _, e1 := Syscall(SYS___CAP_RIGHTS_GET, uintptr(version), uintptr(fd), uintptr(unsafe.Pointer(rightsp))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func capRightsLimit(fd int, rightsp *CapRights) (err error) { + _, _, e1 := Syscall(SYS_CAP_RIGHTS_LIMIT, uintptr(fd), uintptr(unsafe.Pointer(rightsp)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { + r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { + _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + Syscall(SYS_EXIT, uintptr(code), 0, 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_POSIX_FADVISE, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { + _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { + r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { + _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getdirentries(fd int, buf []byte, basep *uint64) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_GETDIRENTRIES, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdtablesize() (size int) { + r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0) + size = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { + r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) + pgrp = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + pid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + ppid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { + r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) + tainted = bool(r0 != 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { + _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { + r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(fd int, path string, mode uint32, dev uint64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(fdat int, path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(fdat), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) + newoffset = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(name) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { + _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { + r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) + oldmask = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Undelete(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go index ae09918..946bc4b 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go @@ -1,4 +1,5 @@ // go run mksyscall.go -l32 -arm -tags freebsd,arm syscall_bsd.go syscall_freebsd.go syscall_freebsd_arm.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build freebsd && arm @@ -15,1872 +16,3161 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { + r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { + _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { + _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data int) (err error) { + _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptracePtr(request int, pid int, addr unsafe.Pointer, data int) (err error) { + _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { + _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CapEnter() (err error) { + _, _, e1 := Syscall(SYS_CAP_ENTER, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func capRightsGet(version int, fd int, rightsp *CapRights) (err error) { + _, _, e1 := Syscall(SYS___CAP_RIGHTS_GET, uintptr(version), uintptr(fd), uintptr(unsafe.Pointer(rightsp))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func capRightsLimit(fd int, rightsp *CapRights) (err error) { + _, _, e1 := Syscall(SYS_CAP_RIGHTS_LIMIT, uintptr(fd), uintptr(unsafe.Pointer(rightsp)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { + r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { + _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + Syscall(SYS_EXIT, uintptr(code), 0, 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall9(SYS_POSIX_FADVISE, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { + _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { + r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { + _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall6(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getdirentries(fd int, buf []byte, basep *uint64) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_GETDIRENTRIES, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdtablesize() (size int) { + r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0) + size = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { + r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) + pgrp = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + pid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + ppid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { + r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) + tainted = bool(r0 != 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { + _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { + r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(fd int, path string, mode uint32, dev uint64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, uintptr(dev), uintptr(dev>>32)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(fdat int, path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(fdat), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0) + newoffset = int64(int64(r1)<<32 | int64(r0)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(name) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { + _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { + r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) + oldmask = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Undelete(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go index 11fd5d4..fc99f8c 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go @@ -1,4 +1,5 @@ // go run mksyscall.go -tags freebsd,arm64 syscall_bsd.go syscall_freebsd.go syscall_freebsd_arm64.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build freebsd && arm64 @@ -15,1872 +16,3161 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { + r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { + _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { + _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data int) (err error) { + _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptracePtr(request int, pid int, addr unsafe.Pointer, data int) (err error) { + _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { + _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CapEnter() (err error) { + _, _, e1 := Syscall(SYS_CAP_ENTER, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func capRightsGet(version int, fd int, rightsp *CapRights) (err error) { + _, _, e1 := Syscall(SYS___CAP_RIGHTS_GET, uintptr(version), uintptr(fd), uintptr(unsafe.Pointer(rightsp))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func capRightsLimit(fd int, rightsp *CapRights) (err error) { + _, _, e1 := Syscall(SYS_CAP_RIGHTS_LIMIT, uintptr(fd), uintptr(unsafe.Pointer(rightsp)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { + r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { + _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + Syscall(SYS_EXIT, uintptr(code), 0, 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_POSIX_FADVISE, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { + _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { + r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { + _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getdirentries(fd int, buf []byte, basep *uint64) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_GETDIRENTRIES, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdtablesize() (size int) { + r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0) + size = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { + r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) + pgrp = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + pid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + ppid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { + r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) + tainted = bool(r0 != 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { + _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { + r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(fd int, path string, mode uint32, dev uint64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(fdat int, path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(fdat), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) + newoffset = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(name) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { + _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { + r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) + oldmask = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Undelete(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go index c3d2d65..4f0f03b 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go @@ -1,4 +1,5 @@ // go run mksyscall.go -tags freebsd,riscv64 syscall_bsd.go syscall_freebsd.go syscall_freebsd_riscv64.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build freebsd && riscv64 @@ -15,1872 +16,3161 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { + r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { + _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { + _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data int) (err error) { + _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptracePtr(request int, pid int, addr unsafe.Pointer, data int) (err error) { + _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { + _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CapEnter() (err error) { + _, _, e1 := Syscall(SYS_CAP_ENTER, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func capRightsGet(version int, fd int, rightsp *CapRights) (err error) { + _, _, e1 := Syscall(SYS___CAP_RIGHTS_GET, uintptr(version), uintptr(fd), uintptr(unsafe.Pointer(rightsp))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func capRightsLimit(fd int, rightsp *CapRights) (err error) { + _, _, e1 := Syscall(SYS_CAP_RIGHTS_LIMIT, uintptr(fd), uintptr(unsafe.Pointer(rightsp)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { + r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { + _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + Syscall(SYS_EXIT, uintptr(code), 0, 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_POSIX_FADVISE, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { + _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { + r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { + _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getdirentries(fd int, buf []byte, basep *uint64) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_GETDIRENTRIES, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdtablesize() (size int) { + r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0) + size = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { + r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) + pgrp = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + pid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + ppid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { + r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) + tainted = bool(r0 != 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { + _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { + r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(fd int, path string, mode uint32, dev uint64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(fdat int, path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(fdat), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) + newoffset = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(name) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { + _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { + r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) + oldmask = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Undelete(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux.go b/vendor/golang.org/x/sys/unix/zsyscall_linux.go index 87d8612..c9254fb 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux.go @@ -12,2220 +12,3797 @@ import ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func FanotifyInit(flags uint, event_f_flags uint) (fd int, err error) { + r0, _, e1 := Syscall(SYS_FANOTIFY_INIT, uintptr(flags), uintptr(event_f_flags), 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fchmodat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fchmodat2(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT2, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat2(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_OPENAT2, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(open_how)), uintptr(size), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { + _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { + r0, _, e1 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Waitid(idType int, id int, info *Siginfo, options int, rusage *Rusage) (err error) { + _, _, e1 := Syscall6(SYS_WAITID, uintptr(idType), uintptr(id), uintptr(unsafe.Pointer(info)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlJoin(cmd int, arg2 string) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(arg2) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(arg3) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(arg4) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) { + var _p0 unsafe.Pointer + if len(payload) > 0 { + _p0 = unsafe.Pointer(&payload[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlRestrictKeyringByType(cmd int, arg2 int, keyType string, restriction string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(keyType) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(restriction) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlRestrictKeyring(cmd int, arg2 int) (err error) { + _, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { + _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptracePtr(request int, pid int, addr uintptr, data unsafe.Pointer) (err error) { + _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(arg) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(source) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(target) + if err != nil { + return + } + var _p2 *byte + _p2, err = BytePtrFromString(fstype) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mountSetattr(dirfd int, pathname string, flags uint, attr *MountAttr, size uintptr) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(pathname) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_MOUNT_SETATTR, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(unsafe.Pointer(attr)), uintptr(size), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(keyType) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(description) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(payload) > 0 { + _p2 = unsafe.Pointer(&payload[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0) + id = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { + r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) + state = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Capget(hdr *CapUserHeader, data *CapUserData) (err error) { + _, _, e1 := RawSyscall(SYS_CAPGET, uintptr(unsafe.Pointer(hdr)), uintptr(unsafe.Pointer(data)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Capset(hdr *CapUserHeader, data *CapUserData) (err error) { + _, _, e1 := RawSyscall(SYS_CAPSET, uintptr(unsafe.Pointer(hdr)), uintptr(unsafe.Pointer(data)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockAdjtime(clockid int32, buf *Timex) (state int, err error) { + r0, _, e1 := Syscall(SYS_CLOCK_ADJTIME, uintptr(clockid), uintptr(unsafe.Pointer(buf)), 0) + state = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGetres(clockid int32, res *Timespec) (err error) { + _, _, e1 := Syscall(SYS_CLOCK_GETRES, uintptr(clockid), uintptr(unsafe.Pointer(res)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockNanosleep(clockid int32, flags int, request *Timespec, remain *Timespec) (err error) { + _, _, e1 := Syscall6(SYS_CLOCK_NANOSLEEP, uintptr(clockid), uintptr(flags), uintptr(unsafe.Pointer(request)), uintptr(unsafe.Pointer(remain)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CloseRange(first uint, last uint, flags uint) (err error) { + _, _, e1 := Syscall(SYS_CLOSE_RANGE, uintptr(first), uintptr(last), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { + r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func DeleteModule(name string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(name) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_DELETE_MODULE, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { + r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { + _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { + _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Eventfd(initval uint, flags int) (fd int, err error) { + r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + SyscallNoError(SYS_EXIT_GROUP, uintptr(code), 0, 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { + _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(dest) > 0 { + _p1 = unsafe.Pointer(&dest[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_FGETXATTR, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest)), 0, 0) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func FinitModule(fd int, params string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(params) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_FINIT_MODULE, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flistxattr(fd int, dest []byte) (sz int, err error) { + var _p0 unsafe.Pointer + if len(dest) > 0 { + _p0 = unsafe.Pointer(&dest[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_FLISTXATTR, uintptr(fd), uintptr(_p0), uintptr(len(dest))) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fremovexattr(fd int, attr string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_FREMOVEXATTR, uintptr(fd), uintptr(unsafe.Pointer(_p0)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsetxattr(fd int, attr string, dest []byte, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(dest) > 0 { + _p1 = unsafe.Pointer(&dest[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_FSETXATTR, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsmount(fd int, flags int, mountAttrs int) (fsfd int, err error) { + r0, _, e1 := Syscall(SYS_FSMOUNT, uintptr(fd), uintptr(flags), uintptr(mountAttrs)) + fsfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsopen(fsName string, flags int) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(fsName) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_FSOPEN, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fspick(dirfd int, pathName string, flags int) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(pathName) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_FSPICK, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fsconfig(fd int, cmd uint, key *byte, value *byte, aux int) (err error) { + _, _, e1 := Syscall6(SYS_FSCONFIG, uintptr(fd), uintptr(cmd), uintptr(unsafe.Pointer(key)), uintptr(unsafe.Pointer(value)), uintptr(aux), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _ := RawSyscallNoError(SYS_GETPID, 0, 0, 0) + pid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _ := RawSyscallNoError(SYS_GETPPID, 0, 0, 0) + ppid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrandom(buf []byte, flags int) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_GETRANDOM, uintptr(_p0), uintptr(len(buf)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { + r0, _ := RawSyscallNoError(SYS_GETTID, 0, 0, 0) + tid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(dest) > 0 { + _p2 = unsafe.Pointer(&dest[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InitModule(moduleImage []byte, params string) (err error) { + var _p0 unsafe.Pointer + if len(moduleImage) > 0 { + _p0 = unsafe.Pointer(&moduleImage[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + var _p1 *byte + _p1, err = BytePtrFromString(params) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_INIT_MODULE, uintptr(_p0), uintptr(len(moduleImage)), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(pathname) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) + watchdesc = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { + r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) + success = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { + _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lgetxattr(path string, attr string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(dest) > 0 { + _p2 = unsafe.Pointer(&dest[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(dest) > 0 { + _p1 = unsafe.Pointer(&dest[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Llistxattr(path string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(dest) > 0 { + _p1 = unsafe.Pointer(&dest[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lremovexattr(path string, attr string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lsetxattr(path string, attr string, data []byte, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(data) > 0 { + _p2 = unsafe.Pointer(&data[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func MemfdCreate(name string, flags int) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(name) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_MEMFD_CREATE, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func MoveMount(fromDirfd int, fromPathName string, toDirfd int, toPathName string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(fromPathName) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(toPathName) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_MOVE_MOUNT, uintptr(fromDirfd), uintptr(unsafe.Pointer(_p0)), uintptr(toDirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func OpenTree(dfd int, fileName string, flags uint) (r int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(fileName) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_OPEN_TREE, uintptr(dfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + r = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_PERF_EVENT_OPEN, uintptr(unsafe.Pointer(attr)), uintptr(pid), uintptr(cpu), uintptr(groupFd), uintptr(flags), 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func PivotRoot(newroot string, putold string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(newroot) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(putold) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { + _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pselect6(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *sigset_argpack) (n int, err error) { + r0, _, e1 := Syscall6(SYS_PSELECT6, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat2(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT2, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(keyType) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(description) + if err != nil { + return + } + var _p2 *byte + _p2, err = BytePtrFromString(callback) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0) + id = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setns(fd int, nstype int) (err error) { + _, _, e1 := Syscall(SYS_SETNS, uintptr(fd), uintptr(nstype), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(data) > 0 { + _p2 = unsafe.Pointer(&data[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func signalfd(fd int, sigmask *Sigset_t, maskSize uintptr, flags int) (newfd int, err error) { + r0, _, e1 := Syscall6(SYS_SIGNALFD4, uintptr(fd), uintptr(unsafe.Pointer(sigmask)), uintptr(maskSize), uintptr(flags), 0, 0) + newfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_STATX, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mask), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { + SyscallNoError(SYS_SYNC, 0, 0, 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Syncfs(fd int) (err error) { + _, _, e1 := Syscall(SYS_SYNCFS, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { + _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func TimerfdCreate(clockid int, flags int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_TIMERFD_CREATE, uintptr(clockid), uintptr(flags), 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func TimerfdGettime(fd int, currValue *ItimerSpec) (err error) { + _, _, e1 := RawSyscall(SYS_TIMERFD_GETTIME, uintptr(fd), uintptr(unsafe.Pointer(currValue)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func TimerfdSettime(fd int, flags int, newValue *ItimerSpec, oldValue *ItimerSpec) (err error) { + _, _, e1 := RawSyscall6(SYS_TIMERFD_SETTIME, uintptr(fd), uintptr(flags), uintptr(unsafe.Pointer(newValue)), uintptr(unsafe.Pointer(oldValue)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { + _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { + r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) + ticks = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { + r0, _ := RawSyscallNoError(SYS_UMASK, uintptr(mask), 0, 0) + oldmask = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { + _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(target string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(target) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { + _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func exitThread(code int) (err error) { + _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readv(fd int, iovs []Iovec) (n int, err error) { + var _p0 unsafe.Pointer + if len(iovs) > 0 { + _p0 = unsafe.Pointer(&iovs[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READV, uintptr(fd), uintptr(_p0), uintptr(len(iovs))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writev(fd int, iovs []Iovec) (n int, err error) { + var _p0 unsafe.Pointer + if len(iovs) > 0 { + _p0 = unsafe.Pointer(&iovs[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_WRITEV, uintptr(fd), uintptr(_p0), uintptr(len(iovs))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func preadv(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr) (n int, err error) { + var _p0 unsafe.Pointer + if len(iovs) > 0 { + _p0 = unsafe.Pointer(&iovs[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREADV, uintptr(fd), uintptr(_p0), uintptr(len(iovs)), uintptr(offs_l), uintptr(offs_h), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwritev(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr) (n int, err error) { + var _p0 unsafe.Pointer + if len(iovs) > 0 { + _p0 = unsafe.Pointer(&iovs[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITEV, uintptr(fd), uintptr(_p0), uintptr(len(iovs)), uintptr(offs_l), uintptr(offs_h), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func preadv2(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr, flags int) (n int, err error) { + var _p0 unsafe.Pointer + if len(iovs) > 0 { + _p0 = unsafe.Pointer(&iovs[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREADV2, uintptr(fd), uintptr(_p0), uintptr(len(iovs)), uintptr(offs_l), uintptr(offs_h), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwritev2(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr, flags int) (n int, err error) { + var _p0 unsafe.Pointer + if len(iovs) > 0 { + _p0 = unsafe.Pointer(&iovs[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITEV2, uintptr(fd), uintptr(_p0), uintptr(len(iovs)), uintptr(offs_l), uintptr(offs_h), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mremap(oldaddr uintptr, oldlength uintptr, newlength uintptr, flags int, newaddr uintptr) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MREMAP, uintptr(oldaddr), uintptr(oldlength), uintptr(newlength), uintptr(flags), uintptr(newaddr), 0) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, advice int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func faccessat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat2(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FACCESSAT2, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func nameToHandleAt(dirFD int, pathname string, fh *fileHandle, mountID *_C_int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(pathname) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_NAME_TO_HANDLE_AT, uintptr(dirFD), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(fh)), uintptr(unsafe.Pointer(mountID)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openByHandleAt(mountFD int, fh *fileHandle, flags int) (fd int, err error) { + r0, _, e1 := Syscall(SYS_OPEN_BY_HANDLE_AT, uintptr(mountFD), uintptr(unsafe.Pointer(fh)), uintptr(flags)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ProcessVMReadv(pid int, localIov []Iovec, remoteIov []RemoteIovec, flags uint) (n int, err error) { + var _p0 unsafe.Pointer + if len(localIov) > 0 { + _p0 = unsafe.Pointer(&localIov[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + var _p1 unsafe.Pointer + if len(remoteIov) > 0 { + _p1 = unsafe.Pointer(&remoteIov[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PROCESS_VM_READV, uintptr(pid), uintptr(_p0), uintptr(len(localIov)), uintptr(_p1), uintptr(len(remoteIov)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ProcessVMWritev(pid int, localIov []Iovec, remoteIov []RemoteIovec, flags uint) (n int, err error) { + var _p0 unsafe.Pointer + if len(localIov) > 0 { + _p0 = unsafe.Pointer(&localIov[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + var _p1 unsafe.Pointer + if len(remoteIov) > 0 { + _p1 = unsafe.Pointer(&remoteIov[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PROCESS_VM_WRITEV, uintptr(pid), uintptr(_p0), uintptr(len(localIov)), uintptr(_p1), uintptr(len(remoteIov)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func PidfdOpen(pid int, flags int) (fd int, err error) { + r0, _, e1 := Syscall(SYS_PIDFD_OPEN, uintptr(pid), uintptr(flags), 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func PidfdGetfd(pidfd int, targetfd int, flags int) (fd int, err error) { + r0, _, e1 := Syscall(SYS_PIDFD_GETFD, uintptr(pidfd), uintptr(targetfd), uintptr(flags)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func PidfdSendSignal(pidfd int, sig Signal, info *Siginfo, flags int) (err error) { + _, _, e1 := Syscall6(SYS_PIDFD_SEND_SIGNAL, uintptr(pidfd), uintptr(sig), uintptr(unsafe.Pointer(info)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func shmat(id int, addr uintptr, flag int) (ret uintptr, err error) { + r0, _, e1 := Syscall(SYS_SHMAT, uintptr(id), uintptr(addr), uintptr(flag)) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func shmctl(id int, cmd int, buf *SysvShmDesc) (result int, err error) { + r0, _, e1 := Syscall(SYS_SHMCTL, uintptr(id), uintptr(cmd), uintptr(unsafe.Pointer(buf))) + result = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func shmdt(addr uintptr) (err error) { + _, _, e1 := Syscall(SYS_SHMDT, uintptr(addr), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func shmget(key int, size int, flag int) (id int, err error) { + r0, _, e1 := Syscall(SYS_SHMGET, uintptr(key), uintptr(size), uintptr(flag)) + id = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getitimer(which int, currValue *Itimerval) (err error) { + _, _, e1 := Syscall(SYS_GETITIMER, uintptr(which), uintptr(unsafe.Pointer(currValue)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setitimer(which int, newValue *Itimerval, oldValue *Itimerval) (err error) { + _, _, e1 := Syscall(SYS_SETITIMER, uintptr(which), uintptr(unsafe.Pointer(newValue)), uintptr(unsafe.Pointer(oldValue))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func rtSigprocmask(how int, set *Sigset_t, oldset *Sigset_t, sigsetsize uintptr) (err error) { + _, _, e1 := RawSyscall6(SYS_RT_SIGPROCMASK, uintptr(how), uintptr(unsafe.Pointer(set)), uintptr(unsafe.Pointer(oldset)), uintptr(sigsetsize), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getresuid(ruid *_C_int, euid *_C_int, suid *_C_int) { + RawSyscallNoError(SYS_GETRESUID, uintptr(unsafe.Pointer(ruid)), uintptr(unsafe.Pointer(euid)), uintptr(unsafe.Pointer(suid))) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getresgid(rgid *_C_int, egid *_C_int, sgid *_C_int) { + RawSyscallNoError(SYS_GETRESGID, uintptr(unsafe.Pointer(rgid)), uintptr(unsafe.Pointer(egid)), uintptr(unsafe.Pointer(sgid))) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func schedSetattr(pid int, attr *SchedAttr, flags uint) (err error) { + _, _, e1 := Syscall(SYS_SCHED_SETATTR, uintptr(pid), uintptr(unsafe.Pointer(attr)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func schedGetattr(pid int, attr *SchedAttr, size uint, flags uint) (err error) { + _, _, e1 := Syscall6(SYS_SCHED_GETATTR, uintptr(pid), uintptr(unsafe.Pointer(attr)), uintptr(size), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Cachestat(fd uint, crange *CachestatRange, cstat *Cachestat_t, flags uint) (err error) { + _, _, e1 := Syscall6(SYS_CACHESTAT, uintptr(fd), uintptr(unsafe.Pointer(crange)), uintptr(unsafe.Pointer(cstat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go index 4def3e9..d484962 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go @@ -1,4 +1,5 @@ // go run mksyscall.go -l32 -tags linux,386 syscall_linux.go syscall_linux_386.go syscall_linux_alarm.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && 386 @@ -15,472 +16,785 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname *byte) (err error) { + _, _, e1 := Syscall6(SYS_FANOTIFY_MARK, uintptr(fd), uintptr(flags), uintptr(mask), uintptr(mask>>32), uintptr(dirFd), uintptr(unsafe.Pointer(pathname))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { + _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(off>>32), uintptr(len), uintptr(len>>32)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { + r0, r1, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) + n = int64(int64(r1)<<32 | int64(r0)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_FADVISE64_64, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN32, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT64, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall(SYS_FTRUNCATE64, uintptr(fd), uintptr(length), uintptr(length>>32)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _ := RawSyscallNoError(SYS_GETEGID32, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { + r0, _ := RawSyscallNoError(SYS_GETEUID32, 0, 0, 0) + euid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _ := RawSyscallNoError(SYS_GETGID32, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _ := RawSyscallNoError(SYS_GETUID32, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ioperm(from int, num int, on int) (err error) { + _, _, e1 := Syscall(SYS_IOPERM, uintptr(from), uintptr(num), uintptr(on)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Iopl(level int) (err error) { + _, _, e1 := Syscall(SYS_IOPL, uintptr(level), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN32, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + r0, _, e1 := Syscall6(SYS_SENDFILE64, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) + written = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsgid(gid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSGID32, uintptr(gid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsuid(uid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSUID32, uintptr(uid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { + r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { + _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(off>>32), uintptr(n), uintptr(n>>32), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_TRUNCATE64, uintptr(unsafe.Pointer(_p0)), uintptr(length), uintptr(length>>32)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { + _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS32, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + nn = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS32, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS__NEWSELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MMAP2, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(pageOffset)) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { + _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getrlimit(resource int, rlim *rlimit32) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Time(t *Time_t) (tt Time_t, err error) { + r0, _, e1 := RawSyscall(SYS_TIME, uintptr(unsafe.Pointer(t)), 0, 0) + tt = Time_t(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Alarm(seconds uint) (remaining uint, err error) { + r0, _, e1 := Syscall(SYS_ALARM, uintptr(seconds), 0, 0) + remaining = uint(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go index fef2bc8..330784f 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go @@ -1,4 +1,5 @@ // go run mksyscall.go -tags linux,amd64 syscall_linux.go syscall_linux_amd64.go syscall_linux_alarm.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && amd64 @@ -15,639 +16,1059 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname *byte) (err error) { + _, _, e1 := Syscall6(SYS_FANOTIFY_MARK, uintptr(fd), uintptr(flags), uintptr(mask), uintptr(dirFd), uintptr(unsafe.Pointer(pathname)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { + _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { + r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_NEWFSTATAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, buf *Statfs_t) (err error) { + _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) + euid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(resource int, rlim *Rlimit) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ioperm(from int, num int, on int) (err error) { + _, _, e1 := Syscall(SYS_IOPERM, uintptr(from), uintptr(num), uintptr(on)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Iopl(level int) (err error) { + _, _, e1 := Syscall(SYS_IOPL, uintptr(level), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func MemfdSecret(flags int) (fd int, err error) { + r0, _, e1 := Syscall(SYS_MEMFD_SECRET, uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { + _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { + r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) + off = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) + written = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsgid(gid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsuid(uid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { + r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, buf *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { + _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { + _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + nn = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kexecFileLoad(kernelFd int, initrdFd int, cmdlineLen int, cmdline string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(cmdline) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_KEXEC_FILE_LOAD, uintptr(kernelFd), uintptr(initrdFd), uintptr(cmdlineLen), uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Alarm(seconds uint) (remaining uint, err error) { + r0, _, e1 := Syscall(SYS_ALARM, uintptr(seconds), 0, 0) + remaining = uint(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go index a9fd76a..eea4e08 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go @@ -1,4 +1,5 @@ // go run mksyscall.go -l32 -arm -tags linux,arm syscall_linux.go syscall_linux_arm.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && arm @@ -15,587 +16,975 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname *byte) (err error) { + _, _, e1 := Syscall6(SYS_FANOTIFY_MARK, uintptr(fd), uintptr(flags), uintptr(mask), uintptr(mask>>32), uintptr(dirFd), uintptr(unsafe.Pointer(pathname))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { + _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(off>>32), uintptr(len), uintptr(len>>32)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { + r0, r1, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) + n = int64(int64(r1)<<32 | int64(r0)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS32, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + nn = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS32, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, flags int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(flags), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN32, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT64, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _ := RawSyscallNoError(SYS_GETEGID32, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { + r0, _ := RawSyscallNoError(SYS_GETEUID32, 0, 0, 0) + euid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _ := RawSyscallNoError(SYS_GETGID32, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _ := RawSyscallNoError(SYS_GETUID32, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN32, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { + _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + r0, _, e1 := Syscall6(SYS_SENDFILE64, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) + written = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS__NEWSELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsgid(gid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSGID32, uintptr(gid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsuid(uid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSUID32, uintptr(uid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { + r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { + _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_TRUNCATE64, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall6(SYS_FTRUNCATE64, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MMAP2, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(pageOffset)) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getrlimit(resource int, rlim *rlimit32) (err error) { + _, _, e1 := RawSyscall(SYS_UGETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func armSyncFileRange(fd int, flags int, off int64, n int64) (err error) { + _, _, e1 := Syscall6(SYS_ARM_SYNC_FILE_RANGE, uintptr(fd), uintptr(flags), uintptr(off), uintptr(off>>32), uintptr(n), uintptr(n>>32)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kexecFileLoad(kernelFd int, initrdFd int, cmdlineLen int, cmdline string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(cmdline) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_KEXEC_FILE_LOAD, uintptr(kernelFd), uintptr(initrdFd), uintptr(cmdlineLen), uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go index 4600650..879e78b 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go @@ -1,4 +1,5 @@ // go run mksyscall.go -tags linux,arm64 syscall_linux.go syscall_linux_arm64.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && arm64 @@ -15,538 +16,889 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname *byte) (err error) { + _, _, e1 := Syscall6(SYS_FANOTIFY_MARK, uintptr(fd), uintptr(flags), uintptr(mask), uintptr(dirFd), uintptr(unsafe.Pointer(pathname)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { + _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { + r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EPOLL_PWAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, buf *Statfs_t) (err error) { + _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) + euid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getrlimit(resource int, rlim *Rlimit) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func MemfdSecret(flags int) (fd int, err error) { + r0, _, e1 := Syscall(SYS_MEMFD_SECRET, uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { + r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) + off = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) + written = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsgid(gid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsuid(uid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { + r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, buf *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { + _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + nn = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kexecFileLoad(kernelFd int, initrdFd int, cmdlineLen int, cmdline string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(cmdline) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_KEXEC_FILE_LOAD, uintptr(kernelFd), uintptr(initrdFd), uintptr(cmdlineLen), uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_loong64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_loong64.go index c8987d2..226c978 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_loong64.go @@ -1,4 +1,5 @@ // go run mksyscall.go -tags linux,loong64 syscall_linux.go syscall_linux_loong64.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && loong64 @@ -15,472 +16,777 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname *byte) (err error) { + _, _, e1 := Syscall6(SYS_FANOTIFY_MARK, uintptr(fd), uintptr(flags), uintptr(mask), uintptr(dirFd), uintptr(unsafe.Pointer(pathname)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { + _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { + r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EPOLL_PWAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, buf *Statfs_t) (err error) { + _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) + euid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { + r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) + off = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) + written = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsgid(gid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsuid(uid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { + r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, buf *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { + _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + nn = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kexecFileLoad(kernelFd int, initrdFd int, cmdlineLen int, cmdline string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(cmdline) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_KEXEC_FILE_LOAD, uintptr(kernelFd), uintptr(initrdFd), uintptr(cmdlineLen), uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go index 921f430..acc4767 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go @@ -1,4 +1,5 @@ // go run mksyscall.go -b32 -arm -tags linux,mips syscall_linux.go syscall_linux_mipsx.go syscall_linux_alarm.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && mips @@ -15,639 +16,1059 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname *byte) (err error) { + _, _, e1 := Syscall6(SYS_FANOTIFY_MARK, uintptr(fd), uintptr(flags), uintptr(mask>>32), uintptr(mask), uintptr(dirFd), uintptr(unsafe.Pointer(pathname))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { + _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off>>32), uintptr(off), uintptr(len>>32), uintptr(len)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { + r0, r1, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) + n = int64(int64(r0)<<32 | int64(r1)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall9(SYS_FADVISE64, uintptr(fd), 0, uintptr(offset>>32), uintptr(offset), uintptr(length>>32), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall6(SYS_FTRUNCATE64, uintptr(fd), 0, uintptr(length>>32), uintptr(length), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) + euid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset>>32), uintptr(offset)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset>>32), uintptr(offset)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS__NEWSELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + r0, _, e1 := Syscall6(SYS_SENDFILE64, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) + written = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsgid(gid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsuid(uid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { + r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { + _, _, e1 := Syscall9(SYS_SYNC_FILE_RANGE, uintptr(fd), 0, uintptr(off>>32), uintptr(off), uintptr(n>>32), uintptr(n), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_TRUNCATE64, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length>>32), uintptr(length), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { + _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + nn = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ioperm(from int, num int, on int) (err error) { + _, _, e1 := Syscall(SYS_IOPERM, uintptr(from), uintptr(num), uintptr(on)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Iopl(level int) (err error) { + _, _, e1 := Syscall(SYS_IOPL, uintptr(level), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Time(t *Time_t) (tt Time_t, err error) { + r0, _, e1 := RawSyscall(SYS_TIME, uintptr(unsafe.Pointer(t)), 0, 0) + tt = Time_t(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT64, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { + _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MMAP2, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(pageOffset)) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getrlimit(resource int, rlim *rlimit32) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Alarm(seconds uint) (remaining uint, err error) { + r0, _, e1 := Syscall(SYS_ALARM, uintptr(seconds), 0, 0) + remaining = uint(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go index 44f0678..995c852 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go @@ -1,4 +1,5 @@ // go run mksyscall.go -tags linux,mips64 syscall_linux.go syscall_linux_mips64x.go syscall_linux_alarm.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && mips64 @@ -15,633 +16,1051 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname *byte) (err error) { + _, _, e1 := Syscall6(SYS_FANOTIFY_MARK, uintptr(fd), uintptr(flags), uintptr(mask), uintptr(dirFd), uintptr(unsafe.Pointer(pathname)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { + _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { + r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, buf *Statfs_t) (err error) { + _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) + euid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(resource int, rlim *Rlimit) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { + _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { + r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) + off = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) + written = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsgid(gid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsuid(uid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { + r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, buf *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { + _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { + _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + nn = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fstat(fd int, st *stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(st)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fstatat(dirfd int, path string, st *stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_NEWFSTATAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(st)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func lstat(path string, st *stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(st)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func stat(path string, st *stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(st)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Alarm(seconds uint) (remaining uint, err error) { + r0, _, e1 := Syscall(SYS_ALARM, uintptr(seconds), 0, 0) + remaining = uint(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go index e7fa0ab..878ba47 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go @@ -1,4 +1,5 @@ // go run mksyscall.go -tags linux,mips64le syscall_linux.go syscall_linux_mips64x.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && mips64le @@ -15,622 +16,1033 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname *byte) (err error) { + _, _, e1 := Syscall6(SYS_FANOTIFY_MARK, uintptr(fd), uintptr(flags), uintptr(mask), uintptr(dirFd), uintptr(unsafe.Pointer(pathname)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { + _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { + r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, buf *Statfs_t) (err error) { + _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) + euid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(resource int, rlim *Rlimit) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { + _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { + r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) + off = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) + written = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsgid(gid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsuid(uid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { + r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, buf *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { + _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { + _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + nn = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fstat(fd int, st *stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(st)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fstatat(dirfd int, path string, st *stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_NEWFSTATAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(st)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func lstat(path string, st *stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(st)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func stat(path string, st *stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(st)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go index 8c51256..8c1c51d 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go @@ -1,4 +1,5 @@ // go run mksyscall.go -l32 -arm -tags linux,mipsle syscall_linux.go syscall_linux_mipsx.go syscall_linux_alarm.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && mipsle @@ -15,639 +16,1059 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname *byte) (err error) { + _, _, e1 := Syscall6(SYS_FANOTIFY_MARK, uintptr(fd), uintptr(flags), uintptr(mask), uintptr(mask>>32), uintptr(dirFd), uintptr(unsafe.Pointer(pathname))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { + _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(off>>32), uintptr(len), uintptr(len>>32)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { + r0, r1, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) + n = int64(int64(r1)<<32 | int64(r0)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall9(SYS_FADVISE64, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall6(SYS_FTRUNCATE64, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) + euid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS__NEWSELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + r0, _, e1 := Syscall6(SYS_SENDFILE64, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) + written = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsgid(gid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsuid(uid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { + r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { + _, _, e1 := Syscall9(SYS_SYNC_FILE_RANGE, uintptr(fd), 0, uintptr(off), uintptr(off>>32), uintptr(n), uintptr(n>>32), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_TRUNCATE64, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { + _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + nn = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ioperm(from int, num int, on int) (err error) { + _, _, e1 := Syscall(SYS_IOPERM, uintptr(from), uintptr(num), uintptr(on)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Iopl(level int) (err error) { + _, _, e1 := Syscall(SYS_IOPL, uintptr(level), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Time(t *Time_t) (tt Time_t, err error) { + r0, _, e1 := RawSyscall(SYS_TIME, uintptr(unsafe.Pointer(t)), 0, 0) + tt = Time_t(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT64, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { + _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MMAP2, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(pageOffset)) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getrlimit(resource int, rlim *rlimit32) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Alarm(seconds uint) (remaining uint, err error) { + r0, _, e1 := Syscall(SYS_ALARM, uintptr(seconds), 0, 0) + remaining = uint(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc.go index 7392fd4..aef8fcf 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc.go @@ -1,4 +1,5 @@ // go run mksyscall.go -b32 -tags linux,ppc syscall_linux.go syscall_linux_ppc.go syscall_linux_alarm.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && ppc @@ -15,644 +16,1069 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname *byte) (err error) { + _, _, e1 := Syscall6(SYS_FANOTIFY_MARK, uintptr(fd), uintptr(flags), uintptr(mask>>32), uintptr(mask), uintptr(dirFd), uintptr(unsafe.Pointer(pathname))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { + _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off>>32), uintptr(off), uintptr(len>>32), uintptr(len)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { + r0, r1, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) + n = int64(int64(r0)<<32 | int64(r1)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT64, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall(SYS_FTRUNCATE64, uintptr(fd), uintptr(length>>32), uintptr(length)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) + euid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ioperm(from int, num int, on int) (err error) { + _, _, e1 := Syscall(SYS_IOPERM, uintptr(from), uintptr(num), uintptr(on)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Iopl(level int) (err error) { + _, _, e1 := Syscall(SYS_IOPL, uintptr(level), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { + _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset>>32), uintptr(offset), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset>>32), uintptr(offset), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS__NEWSELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + r0, _, e1 := Syscall6(SYS_SENDFILE64, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) + written = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsgid(gid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsuid(uid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { + r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_TRUNCATE64, uintptr(unsafe.Pointer(_p0)), uintptr(length>>32), uintptr(length)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { + _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + nn = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Time(t *Time_t) (tt Time_t, err error) { + r0, _, e1 := RawSyscall(SYS_TIME, uintptr(unsafe.Pointer(t)), 0, 0) + tt = Time_t(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MMAP2, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(pageOffset)) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getrlimit(resource int, rlim *rlimit32) (err error) { + _, _, e1 := RawSyscall(SYS_UGETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func syncFileRange2(fd int, flags int, off int64, n int64) (err error) { + _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE2, uintptr(fd), uintptr(flags), uintptr(off>>32), uintptr(off), uintptr(n>>32), uintptr(n)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kexecFileLoad(kernelFd int, initrdFd int, cmdlineLen int, cmdline string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(cmdline) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_KEXEC_FILE_LOAD, uintptr(kernelFd), uintptr(initrdFd), uintptr(cmdlineLen), uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Alarm(seconds uint) (remaining uint, err error) { + r0, _, e1 := Syscall(SYS_ALARM, uintptr(seconds), 0, 0) + remaining = uint(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go index 4118043..a6c91d3 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go @@ -1,4 +1,5 @@ // go run mksyscall.go -tags linux,ppc64 syscall_linux.go syscall_linux_ppc64x.go syscall_linux_alarm.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && ppc64 @@ -15,690 +16,1145 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname *byte) (err error) { + _, _, e1 := Syscall6(SYS_FANOTIFY_MARK, uintptr(fd), uintptr(flags), uintptr(mask), uintptr(dirFd), uintptr(unsafe.Pointer(pathname)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { + _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { + r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_NEWFSTATAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, buf *Statfs_t) (err error) { + _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) + euid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(resource int, rlim *Rlimit) (err error) { + _, _, e1 := RawSyscall(SYS_UGETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ioperm(from int, num int, on int) (err error) { + _, _, e1 := Syscall(SYS_IOPERM, uintptr(from), uintptr(num), uintptr(on)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Iopl(level int) (err error) { + _, _, e1 := Syscall(SYS_IOPL, uintptr(level), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { + _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { + r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) + off = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS__NEWSELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) + written = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsgid(gid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsuid(uid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { + r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, buf *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { + _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + nn = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Time(t *Time_t) (tt Time_t, err error) { + r0, _, e1 := RawSyscall(SYS_TIME, uintptr(unsafe.Pointer(t)), 0, 0) + tt = Time_t(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func syncFileRange2(fd int, flags int, off int64, n int64) (err error) { + _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE2, uintptr(fd), uintptr(flags), uintptr(off), uintptr(n), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kexecFileLoad(kernelFd int, initrdFd int, cmdlineLen int, cmdline string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(cmdline) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_KEXEC_FILE_LOAD, uintptr(kernelFd), uintptr(initrdFd), uintptr(cmdlineLen), uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Alarm(seconds uint) (remaining uint, err error) { + r0, _, e1 := Syscall(SYS_ALARM, uintptr(seconds), 0, 0) + remaining = uint(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go index 40c6ce7..771fbef 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go @@ -1,4 +1,5 @@ // go run mksyscall.go -tags linux,ppc64le syscall_linux.go syscall_linux_ppc64x.go syscall_linux_alarm.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && ppc64le @@ -15,690 +16,1145 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname *byte) (err error) { + _, _, e1 := Syscall6(SYS_FANOTIFY_MARK, uintptr(fd), uintptr(flags), uintptr(mask), uintptr(dirFd), uintptr(unsafe.Pointer(pathname)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { + _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { + r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_NEWFSTATAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, buf *Statfs_t) (err error) { + _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) + euid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(resource int, rlim *Rlimit) (err error) { + _, _, e1 := RawSyscall(SYS_UGETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ioperm(from int, num int, on int) (err error) { + _, _, e1 := Syscall(SYS_IOPERM, uintptr(from), uintptr(num), uintptr(on)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Iopl(level int) (err error) { + _, _, e1 := Syscall(SYS_IOPL, uintptr(level), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { + _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { + r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) + off = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS__NEWSELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) + written = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsgid(gid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsuid(uid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { + r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, buf *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { + _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + nn = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Time(t *Time_t) (tt Time_t, err error) { + r0, _, e1 := RawSyscall(SYS_TIME, uintptr(unsafe.Pointer(t)), 0, 0) + tt = Time_t(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func syncFileRange2(fd int, flags int, off int64, n int64) (err error) { + _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE2, uintptr(fd), uintptr(flags), uintptr(off), uintptr(n), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kexecFileLoad(kernelFd int, initrdFd int, cmdlineLen int, cmdline string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(cmdline) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_KEXEC_FILE_LOAD, uintptr(kernelFd), uintptr(initrdFd), uintptr(cmdlineLen), uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Alarm(seconds uint) (remaining uint, err error) { + r0, _, e1 := Syscall(SYS_ALARM, uintptr(seconds), 0, 0) + remaining = uint(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go index 2cfe34a..7299255 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go @@ -1,4 +1,5 @@ // go run mksyscall.go -tags linux,riscv64 syscall_linux.go syscall_linux_riscv64.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && riscv64 @@ -15,534 +16,881 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname *byte) (err error) { + _, _, e1 := Syscall6(SYS_FANOTIFY_MARK, uintptr(fd), uintptr(flags), uintptr(mask), uintptr(dirFd), uintptr(unsafe.Pointer(pathname)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { + _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { + r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EPOLL_PWAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, buf *Statfs_t) (err error) { + _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) + euid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(resource int, rlim *Rlimit) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func MemfdSecret(flags int) (fd int, err error) { + r0, _, e1 := Syscall(SYS_MEMFD_SECRET, uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { + r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) + off = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) + written = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsgid(gid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsuid(uid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { + r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, buf *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { + _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + nn = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kexecFileLoad(kernelFd int, initrdFd int, cmdlineLen int, cmdline string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(cmdline) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_KEXEC_FILE_LOAD, uintptr(kernelFd), uintptr(initrdFd), uintptr(cmdlineLen), uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func riscvHWProbe(pairs []RISCVHWProbePairs, cpuCount uintptr, cpus *CPUSet, flags uint) (err error) { + var _p0 unsafe.Pointer + if len(pairs) > 0 { + _p0 = unsafe.Pointer(&pairs[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_RISCV_HWPROBE, uintptr(_p0), uintptr(len(pairs)), uintptr(cpuCount), uintptr(unsafe.Pointer(cpus)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go index 61e6f07..2c217a0 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go @@ -1,4 +1,5 @@ // go run mksyscall.go -tags linux,s390x syscall_linux.go syscall_linux_s390x.go syscall_linux_alarm.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && s390x @@ -15,481 +16,803 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname *byte) (err error) { + _, _, e1 := Syscall6(SYS_FANOTIFY_MARK, uintptr(fd), uintptr(flags), uintptr(mask), uintptr(dirFd), uintptr(unsafe.Pointer(pathname)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { + _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { + r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_NEWFSTATAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, buf *Statfs_t) (err error) { + _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) + euid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(resource int, rlim *Rlimit) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { + _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { + r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) + off = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) + written = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsgid(gid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsuid(uid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { + r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, buf *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { + _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { + _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + nn = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kexecFileLoad(kernelFd int, initrdFd int, cmdlineLen int, cmdline string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(cmdline) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_KEXEC_FILE_LOAD, uintptr(kernelFd), uintptr(initrdFd), uintptr(cmdlineLen), uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Alarm(seconds uint) (remaining uint, err error) { + r0, _, e1 := Syscall(SYS_ALARM, uintptr(seconds), 0, 0) + remaining = uint(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go index 834b842..f15307e 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go @@ -1,4 +1,5 @@ // go run mksyscall.go -tags linux,sparc64 syscall_linux.go syscall_linux_sparc64.go syscall_linux_alarm.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && sparc64 @@ -15,634 +16,1053 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname *byte) (err error) { + _, _, e1 := Syscall6(SYS_FANOTIFY_MARK, uintptr(fd), uintptr(flags), uintptr(mask), uintptr(dirFd), uintptr(unsafe.Pointer(pathname)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { + _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { + r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT64, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, buf *Statfs_t) (err error) { + _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) + euid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(resource int, rlim *Rlimit) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { + _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { + r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) + off = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) + written = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsgid(gid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setfsuid(uid int) (prev int, err error) { + r0, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) + prev = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { + r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, buf *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { + _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + nn = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Alarm(seconds uint) (remaining uint, err error) { + r0, _, e1 := Syscall(SYS_ALARM, uintptr(seconds), 0, 0) + remaining = uint(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go index e91ebc1..57d01ee 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go @@ -1,4 +1,5 @@ // go run mksyscall.go -l32 -netbsd -tags netbsd,386 syscall_bsd.go syscall_netbsd.go syscall_netbsd_386.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build netbsd && 386 @@ -15,1834 +16,3105 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { + r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { + _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { + _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { + _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { + r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { + _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(from int, to int, flags int) (err error) { + _, _, e1 := Syscall(SYS_DUP3, uintptr(from), uintptr(to), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + Syscall(SYS_EXIT, uintptr(code), 0, 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall9(SYS_POSIX_FADVISE, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), 0, uintptr(length), uintptr(length>>32), uintptr(advice), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { + _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { + r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatvfs1(fd int, buf *Statvfs_t, flags int) (err error) { + _, _, e1 := Syscall(SYS_FSTATVFS1, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall6(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { + r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) + pgrp = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + pid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + ppid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { + r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) + tainted = bool(r0 != 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { + _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { + r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifoat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKFIFOAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0) + newoffset = int64(int64(r1)<<32 | int64(r0)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statvfs1(path string, buf *Statvfs_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STATVFS1, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { + _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { + r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) + oldmask = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mremapNetBSD(oldp uintptr, oldsize uintptr, newp uintptr, newsize uintptr, flags int) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MREMAP, uintptr(oldp), uintptr(oldsize), uintptr(newp), uintptr(newsize), uintptr(flags), 0) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go index be28bab..889adda 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go @@ -1,4 +1,5 @@ // go run mksyscall.go -netbsd -tags netbsd,amd64 syscall_bsd.go syscall_netbsd.go syscall_netbsd_amd64.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build netbsd && amd64 @@ -15,1834 +16,3105 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { + r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { + _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { + _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { + _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { + r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { + _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(from int, to int, flags int) (err error) { + _, _, e1 := Syscall(SYS_DUP3, uintptr(from), uintptr(to), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + Syscall(SYS_EXIT, uintptr(code), 0, 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_POSIX_FADVISE, uintptr(fd), 0, uintptr(offset), 0, uintptr(length), uintptr(advice)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { + _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { + r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatvfs1(fd int, buf *Statvfs_t, flags int) (err error) { + _, _, e1 := Syscall(SYS_FSTATVFS1, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { + r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) + pgrp = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + pid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + ppid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { + r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) + tainted = bool(r0 != 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { + _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { + r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifoat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKFIFOAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, _, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(whence), 0, 0) + newoffset = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statvfs1(path string, buf *Statvfs_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STATVFS1, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { + _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { + r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) + oldmask = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), 0, 0) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mremapNetBSD(oldp uintptr, oldsize uintptr, newp uintptr, newsize uintptr, flags int) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MREMAP, uintptr(oldp), uintptr(oldsize), uintptr(newp), uintptr(newsize), uintptr(flags), 0) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go index fb587e8..97ad053 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go @@ -1,4 +1,5 @@ // go run mksyscall.go -l32 -netbsd -arm -tags netbsd,arm syscall_bsd.go syscall_netbsd.go syscall_netbsd_arm.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build netbsd && arm @@ -15,1834 +16,3105 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { + r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { + _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { + _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { + _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { + r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { + _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(from int, to int, flags int) (err error) { + _, _, e1 := Syscall(SYS_DUP3, uintptr(from), uintptr(to), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + Syscall(SYS_EXIT, uintptr(code), 0, 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall9(SYS_POSIX_FADVISE, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), 0, uintptr(length), uintptr(length>>32), uintptr(advice), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { + _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { + r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatvfs1(fd int, buf *Statvfs_t, flags int) (err error) { + _, _, e1 := Syscall(SYS_FSTATVFS1, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall6(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { + r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) + pgrp = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + pid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + ppid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { + r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) + tainted = bool(r0 != 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { + _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { + r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifoat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKFIFOAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0) + newoffset = int64(int64(r1)<<32 | int64(r0)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statvfs1(path string, buf *Statvfs_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STATVFS1, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { + _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { + r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) + oldmask = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mremapNetBSD(oldp uintptr, oldsize uintptr, newp uintptr, newsize uintptr, flags int) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MREMAP, uintptr(oldp), uintptr(oldsize), uintptr(newp), uintptr(newsize), uintptr(flags), 0) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go index d576438..6848bb9 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go @@ -1,4 +1,5 @@ // go run mksyscall.go -netbsd -tags netbsd,arm64 syscall_bsd.go syscall_netbsd.go syscall_netbsd_arm64.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build netbsd && arm64 @@ -15,1834 +16,3105 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { + r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { + _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { + _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { + r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { + _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { + _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { + _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { + r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { + _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(from int, to int, flags int) (err error) { + _, _, e1 := Syscall(SYS_DUP3, uintptr(from), uintptr(to), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + Syscall(SYS_EXIT, uintptr(code), 0, 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_EXTATTR_DELETE_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_POSIX_FADVISE, uintptr(fd), 0, uintptr(offset), 0, uintptr(length), uintptr(advice)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { + _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { + r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatvfs1(fd int, buf *Statvfs_t, flags int) (err error) { + _, _, e1 := Syscall(SYS_FSTATVFS1, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { + r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) + pgrp = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + pid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + ppid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { + _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { + r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) + tainted = bool(r0 != 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { + _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { + r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { + _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifoat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKFIFOAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, _, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(whence), 0, 0) + newoffset = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statvfs1(path string, buf *Statvfs_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_STATVFS1, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { + _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { + r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) + oldmask = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), 0, 0) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mremapNetBSD(oldp uintptr, oldsize uintptr, newp uintptr, newsize uintptr, flags int) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MREMAP, uintptr(oldp), uintptr(oldsize), uintptr(newp), uintptr(newsize), uintptr(flags), 0) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go index 9dc4241..af8b2f1 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go @@ -1,4 +1,5 @@ // go run mksyscall.go -l32 -openbsd -libc -tags openbsd,386 syscall_bsd.go syscall_openbsd.go syscall_openbsd_386.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build openbsd && 386 @@ -15,12 +16,19 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getgroups_trampoline_addr uintptr @@ -30,11 +38,17 @@ var libc_getgroups_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setgroups_trampoline_addr uintptr @@ -44,12 +58,19 @@ var libc_setgroups_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := syscall_syscall6(libc_wait4_trampoline_addr, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_wait4_trampoline_addr uintptr @@ -59,12 +80,19 @@ var libc_wait4_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := syscall_syscall(libc_accept_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_accept_trampoline_addr uintptr @@ -74,11 +102,17 @@ var libc_accept_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := syscall_syscall(libc_bind_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_bind_trampoline_addr uintptr @@ -88,11 +122,17 @@ var libc_bind_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := syscall_syscall(libc_connect_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_connect_trampoline_addr uintptr @@ -102,12 +142,19 @@ var libc_connect_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_socket_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_socket_trampoline_addr uintptr @@ -117,11 +164,17 @@ var libc_socket_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := syscall_syscall6(libc_getsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsockopt_trampoline_addr uintptr @@ -131,11 +184,17 @@ var libc_getsockopt_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := syscall_syscall6(libc_setsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setsockopt_trampoline_addr uintptr @@ -145,11 +204,17 @@ var libc_setsockopt_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getpeername_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpeername_trampoline_addr uintptr @@ -159,11 +224,17 @@ var libc_getpeername_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getsockname_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsockname_trampoline_addr uintptr @@ -173,11 +244,17 @@ var libc_getsockname_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { + _, _, e1 := syscall_syscall(libc_shutdown_trampoline_addr, uintptr(s), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_shutdown_trampoline_addr uintptr @@ -187,11 +264,17 @@ var libc_shutdown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := syscall_rawSyscall6(libc_socketpair_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_socketpair_trampoline_addr uintptr @@ -201,18 +284,31 @@ var libc_socketpair_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_recvfrom_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_recvfrom_trampoline_addr uintptr @@ -222,17 +318,29 @@ var libc_recvfrom_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall6(libc_sendto_trampoline_addr, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sendto_trampoline_addr uintptr @@ -242,12 +350,19 @@ var libc_sendto_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_recvmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_recvmsg_trampoline_addr uintptr @@ -257,12 +372,19 @@ var libc_recvmsg_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_sendmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sendmsg_trampoline_addr uintptr @@ -272,12 +394,19 @@ var libc_sendmsg_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_kevent_trampoline_addr, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kevent_trampoline_addr uintptr @@ -287,16 +416,27 @@ var libc_kevent_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_utimes_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_utimes_trampoline_addr uintptr @@ -306,11 +446,17 @@ var libc_utimes_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { + _, _, e1 := syscall_syscall(libc_futimes_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_futimes_trampoline_addr uintptr @@ -320,12 +466,19 @@ var libc_futimes_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_poll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_poll_trampoline_addr uintptr @@ -335,17 +488,29 @@ var libc_poll_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_madvise_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_madvise_trampoline_addr uintptr @@ -355,17 +520,29 @@ var libc_madvise_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_mlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mlock_trampoline_addr uintptr @@ -375,11 +552,17 @@ var libc_mlock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := syscall_syscall(libc_mlockall_trampoline_addr, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mlockall_trampoline_addr uintptr @@ -389,17 +572,29 @@ var libc_mlockall_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_mprotect_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mprotect_trampoline_addr uintptr @@ -409,17 +604,29 @@ var libc_mprotect_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_msync_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_msync_trampoline_addr uintptr @@ -429,17 +636,29 @@ var libc_msync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_munlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munlock_trampoline_addr uintptr @@ -449,11 +668,17 @@ var libc_munlock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := syscall_syscall(libc_munlockall_trampoline_addr, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munlockall_trampoline_addr uintptr @@ -463,11 +688,17 @@ var libc_munlockall_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_pipe2_trampoline_addr, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pipe2_trampoline_addr uintptr @@ -477,18 +708,31 @@ var libc_pipe2_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_getdents_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getdents_trampoline_addr uintptr @@ -498,18 +742,31 @@ var libc_getdents_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_getcwd_trampoline_addr, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getcwd_trampoline_addr uintptr @@ -519,8 +776,11 @@ var libc_getcwd_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getresuid(ruid *_C_int, euid *_C_int, suid *_C_int) { + syscall_rawSyscall(libc_getresuid_trampoline_addr, uintptr(unsafe.Pointer(ruid)), uintptr(unsafe.Pointer(euid)), uintptr(unsafe.Pointer(suid))) + return + } var libc_getresuid_trampoline_addr uintptr @@ -530,8 +790,11 @@ var libc_getresuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getresgid(rgid *_C_int, egid *_C_int, sgid *_C_int) { + syscall_rawSyscall(libc_getresgid_trampoline_addr, uintptr(unsafe.Pointer(rgid)), uintptr(unsafe.Pointer(egid)), uintptr(unsafe.Pointer(sgid))) + return + } var libc_getresgid_trampoline_addr uintptr @@ -541,11 +804,17 @@ var libc_getresgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ioctl_trampoline_addr uintptr @@ -555,27 +824,45 @@ var libc_ioctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall6(libc_sysctl_trampoline_addr, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sysctl_trampoline_addr uintptr @@ -585,12 +872,19 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fcntl_trampoline_addr uintptr @@ -600,23 +894,37 @@ var libc_fcntl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ppoll_trampoline_addr uintptr @@ -626,16 +934,27 @@ var libc_ppoll_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_access_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_access_trampoline_addr uintptr @@ -645,11 +964,17 @@ var libc_access_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { + _, _, e1 := syscall_syscall(libc_adjtime_trampoline_addr, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_adjtime_trampoline_addr uintptr @@ -659,16 +984,27 @@ var libc_adjtime_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chdir_trampoline_addr uintptr @@ -678,16 +1014,27 @@ var libc_chdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chflags_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chflags_trampoline_addr uintptr @@ -697,16 +1044,27 @@ var libc_chflags_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chmod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chmod_trampoline_addr uintptr @@ -716,16 +1074,27 @@ var libc_chmod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chown_trampoline_addr uintptr @@ -735,16 +1104,27 @@ var libc_chown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chroot_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chroot_trampoline_addr uintptr @@ -754,11 +1134,17 @@ var libc_chroot_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := syscall_syscall(libc_clock_gettime_trampoline_addr, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_clock_gettime_trampoline_addr uintptr @@ -768,11 +1154,17 @@ var libc_clock_gettime_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_close_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_close_trampoline_addr uintptr @@ -782,12 +1174,19 @@ var libc_close_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { + r0, _, e1 := syscall_syscall(libc_dup_trampoline_addr, uintptr(fd), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup_trampoline_addr uintptr @@ -797,11 +1196,17 @@ var libc_dup_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { + _, _, e1 := syscall_syscall(libc_dup2_trampoline_addr, uintptr(from), uintptr(to), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup2_trampoline_addr uintptr @@ -811,11 +1216,17 @@ var libc_dup2_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(from int, to int, flags int) (err error) { + _, _, e1 := syscall_syscall(libc_dup3_trampoline_addr, uintptr(from), uintptr(to), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup3_trampoline_addr uintptr @@ -825,8 +1236,11 @@ var libc_dup3_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + syscall_syscall(libc_exit_trampoline_addr, uintptr(code), 0, 0) + return + } var libc_exit_trampoline_addr uintptr @@ -836,16 +1250,27 @@ var libc_exit_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_faccessat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_faccessat_trampoline_addr uintptr @@ -855,11 +1280,17 @@ var libc_faccessat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_fchdir_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchdir_trampoline_addr uintptr @@ -869,11 +1300,17 @@ var libc_fchdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { + _, _, e1 := syscall_syscall(libc_fchflags_trampoline_addr, uintptr(fd), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchflags_trampoline_addr uintptr @@ -883,11 +1320,17 @@ var libc_fchflags_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := syscall_syscall(libc_fchmod_trampoline_addr, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchmod_trampoline_addr uintptr @@ -897,16 +1340,27 @@ var libc_fchmod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fchmodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchmodat_trampoline_addr uintptr @@ -916,11 +1370,17 @@ var libc_fchmodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := syscall_syscall(libc_fchown_trampoline_addr, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchown_trampoline_addr uintptr @@ -930,16 +1390,27 @@ var libc_fchown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fchownat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchownat_trampoline_addr uintptr @@ -949,11 +1420,17 @@ var libc_fchownat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := syscall_syscall(libc_flock_trampoline_addr, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_flock_trampoline_addr uintptr @@ -963,12 +1440,19 @@ var libc_flock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { + r0, _, e1 := syscall_syscall(libc_fpathconf_trampoline_addr, uintptr(fd), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fpathconf_trampoline_addr uintptr @@ -978,11 +1462,17 @@ var libc_fpathconf_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := syscall_syscall(libc_fstat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstat_trampoline_addr uintptr @@ -992,16 +1482,27 @@ var libc_fstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fstatat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstatat_trampoline_addr uintptr @@ -1011,11 +1512,17 @@ var libc_fstatat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { + _, _, e1 := syscall_syscall(libc_fstatfs_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstatfs_trampoline_addr uintptr @@ -1025,11 +1532,17 @@ var libc_fstatfs_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_fsync_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fsync_trampoline_addr uintptr @@ -1039,11 +1552,17 @@ var libc_fsync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := syscall_syscall(libc_ftruncate_trampoline_addr, uintptr(fd), uintptr(length), uintptr(length>>32)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ftruncate_trampoline_addr uintptr @@ -1053,9 +1572,13 @@ var libc_ftruncate_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _, _ := syscall_rawSyscall(libc_getegid_trampoline_addr, 0, 0, 0) + egid = int(r0) + return + } var libc_getegid_trampoline_addr uintptr @@ -1065,9 +1588,13 @@ var libc_getegid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { + r0, _, _ := syscall_rawSyscall(libc_geteuid_trampoline_addr, 0, 0, 0) + uid = int(r0) + return + } var libc_geteuid_trampoline_addr uintptr @@ -1077,9 +1604,13 @@ var libc_geteuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := syscall_rawSyscall(libc_getgid_trampoline_addr, 0, 0, 0) + gid = int(r0) + return + } var libc_getgid_trampoline_addr uintptr @@ -1089,12 +1620,19 @@ var libc_getgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getpgid_trampoline_addr, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpgid_trampoline_addr uintptr @@ -1104,9 +1642,13 @@ var libc_getpgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { + r0, _, _ := syscall_rawSyscall(libc_getpgrp_trampoline_addr, 0, 0, 0) + pgrp = int(r0) + return + } var libc_getpgrp_trampoline_addr uintptr @@ -1116,9 +1658,13 @@ var libc_getpgrp_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := syscall_rawSyscall(libc_getpid_trampoline_addr, 0, 0, 0) + pid = int(r0) + return + } var libc_getpid_trampoline_addr uintptr @@ -1128,9 +1674,13 @@ var libc_getpid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _, _ := syscall_rawSyscall(libc_getppid_trampoline_addr, 0, 0, 0) + ppid = int(r0) + return + } var libc_getppid_trampoline_addr uintptr @@ -1140,12 +1690,19 @@ var libc_getppid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := syscall_syscall(libc_getpriority_trampoline_addr, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpriority_trampoline_addr uintptr @@ -1155,11 +1712,17 @@ var libc_getpriority_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getrlimit_trampoline_addr, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrlimit_trampoline_addr uintptr @@ -1169,12 +1732,19 @@ var libc_getrlimit_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrtable() (rtable int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getrtable_trampoline_addr, 0, 0, 0) + rtable = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrtable_trampoline_addr uintptr @@ -1184,11 +1754,17 @@ var libc_getrtable_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getrusage_trampoline_addr, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrusage_trampoline_addr uintptr @@ -1198,12 +1774,19 @@ var libc_getrusage_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getsid_trampoline_addr, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsid_trampoline_addr uintptr @@ -1213,11 +1796,17 @@ var libc_getsid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(libc_gettimeofday_trampoline_addr, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_gettimeofday_trampoline_addr uintptr @@ -1227,9 +1816,13 @@ var libc_gettimeofday_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := syscall_rawSyscall(libc_getuid_trampoline_addr, 0, 0, 0) + uid = int(r0) + return + } var libc_getuid_trampoline_addr uintptr @@ -1239,9 +1832,13 @@ var libc_getuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { + r0, _, _ := syscall_syscall(libc_issetugid_trampoline_addr, 0, 0, 0) + tainted = bool(r0 != 0) + return + } var libc_issetugid_trampoline_addr uintptr @@ -1251,11 +1848,17 @@ var libc_issetugid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { + _, _, e1 := syscall_syscall(libc_kill_trampoline_addr, uintptr(pid), uintptr(signum), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kill_trampoline_addr uintptr @@ -1265,12 +1868,19 @@ var libc_kill_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { + r0, _, e1 := syscall_syscall(libc_kqueue_trampoline_addr, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kqueue_trampoline_addr uintptr @@ -1280,16 +1890,27 @@ var libc_kqueue_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_lchown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lchown_trampoline_addr uintptr @@ -1299,21 +1920,37 @@ var libc_lchown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_link_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_link_trampoline_addr uintptr @@ -1323,21 +1960,37 @@ var libc_link_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_linkat_trampoline_addr, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_linkat_trampoline_addr uintptr @@ -1347,11 +2000,17 @@ var libc_linkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { + _, _, e1 := syscall_syscall(libc_listen_trampoline_addr, uintptr(s), uintptr(backlog), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_listen_trampoline_addr uintptr @@ -1361,16 +2020,27 @@ var libc_listen_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_lstat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lstat_trampoline_addr uintptr @@ -1380,16 +2050,27 @@ var libc_lstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkdir_trampoline_addr uintptr @@ -1399,16 +2080,27 @@ var libc_mkdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkdirat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkdirat_trampoline_addr uintptr @@ -1418,16 +2110,27 @@ var libc_mkdirat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkfifo_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkfifo_trampoline_addr uintptr @@ -1437,16 +2140,27 @@ var libc_mkfifo_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifoat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkfifoat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkfifoat_trampoline_addr uintptr @@ -1456,16 +2170,27 @@ var libc_mkfifoat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mknod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mknod_trampoline_addr uintptr @@ -1475,16 +2200,27 @@ var libc_mknod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mknodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mknodat_trampoline_addr uintptr @@ -1494,11 +2230,17 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_nanosleep_trampoline_addr uintptr @@ -1508,17 +2250,29 @@ var libc_nanosleep_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall(libc_open_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_open_trampoline_addr uintptr @@ -1528,17 +2282,29 @@ var libc_open_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall6(libc_openat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_openat_trampoline_addr uintptr @@ -1548,17 +2314,29 @@ var libc_openat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall(libc_pathconf_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pathconf_trampoline_addr uintptr @@ -1568,18 +2346,31 @@ var libc_pathconf_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_pread_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pread_trampoline_addr uintptr @@ -1589,18 +2380,31 @@ var libc_pread_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_pwrite_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pwrite_trampoline_addr uintptr @@ -1610,18 +2414,31 @@ var libc_pwrite_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_read_trampoline_addr uintptr @@ -1631,23 +2448,41 @@ var libc_read_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_readlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_readlink_trampoline_addr uintptr @@ -1657,23 +2492,41 @@ var libc_readlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_readlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_readlinkat_trampoline_addr uintptr @@ -1683,21 +2536,37 @@ var libc_readlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_rename_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_rename_trampoline_addr uintptr @@ -1707,21 +2576,37 @@ var libc_rename_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_renameat_trampoline_addr, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_renameat_trampoline_addr uintptr @@ -1731,16 +2616,27 @@ var libc_renameat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_revoke_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_revoke_trampoline_addr uintptr @@ -1750,16 +2646,27 @@ var libc_revoke_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_rmdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_rmdir_trampoline_addr uintptr @@ -1769,12 +2676,19 @@ var libc_rmdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, r1, e1 := syscall_syscall6(libc_lseek_trampoline_addr, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(whence), 0, 0) + newoffset = int64(int64(r1)<<32 | int64(r0)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lseek_trampoline_addr uintptr @@ -1784,12 +2698,19 @@ var libc_lseek_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_select_trampoline_addr, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_select_trampoline_addr uintptr @@ -1799,11 +2720,17 @@ var libc_select_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setegid_trampoline_addr, uintptr(egid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setegid_trampoline_addr uintptr @@ -1813,11 +2740,17 @@ var libc_setegid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_seteuid_trampoline_addr, uintptr(euid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_seteuid_trampoline_addr uintptr @@ -1827,11 +2760,17 @@ var libc_seteuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setgid_trampoline_addr, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setgid_trampoline_addr uintptr @@ -1841,16 +2780,27 @@ var libc_setgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(name) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_setlogin_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setlogin_trampoline_addr uintptr @@ -1860,11 +2810,17 @@ var libc_setlogin_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setpgid_trampoline_addr, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setpgid_trampoline_addr uintptr @@ -1874,11 +2830,17 @@ var libc_setpgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := syscall_syscall(libc_setpriority_trampoline_addr, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setpriority_trampoline_addr uintptr @@ -1888,11 +2850,17 @@ var libc_setpriority_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setregid_trampoline_addr, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setregid_trampoline_addr uintptr @@ -1902,11 +2870,17 @@ var libc_setregid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setreuid_trampoline_addr, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setreuid_trampoline_addr uintptr @@ -1916,11 +2890,17 @@ var libc_setreuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setresgid_trampoline_addr, uintptr(rgid), uintptr(egid), uintptr(sgid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setresgid_trampoline_addr uintptr @@ -1930,11 +2910,17 @@ var libc_setresgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setresuid_trampoline_addr, uintptr(ruid), uintptr(euid), uintptr(suid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setresuid_trampoline_addr uintptr @@ -1944,11 +2930,17 @@ var libc_setresuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrtable(rtable int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setrtable_trampoline_addr, uintptr(rtable), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setrtable_trampoline_addr uintptr @@ -1958,12 +2950,19 @@ var libc_setrtable_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_setsid_trampoline_addr, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setsid_trampoline_addr uintptr @@ -1973,11 +2972,17 @@ var libc_setsid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(libc_settimeofday_trampoline_addr, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_settimeofday_trampoline_addr uintptr @@ -1987,11 +2992,17 @@ var libc_settimeofday_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setuid_trampoline_addr, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setuid_trampoline_addr uintptr @@ -2001,16 +3012,27 @@ var libc_setuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_stat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_stat_trampoline_addr uintptr @@ -2020,16 +3042,27 @@ var libc_stat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_statfs_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_statfs_trampoline_addr uintptr @@ -2039,21 +3072,37 @@ var libc_statfs_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_symlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_symlink_trampoline_addr uintptr @@ -2063,21 +3112,37 @@ var libc_symlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_symlinkat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_symlinkat_trampoline_addr uintptr @@ -2087,11 +3152,17 @@ var libc_symlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { + _, _, e1 := syscall_syscall(libc_sync_trampoline_addr, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sync_trampoline_addr uintptr @@ -2101,16 +3172,27 @@ var libc_sync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_truncate_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(length), uintptr(length>>32)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_truncate_trampoline_addr uintptr @@ -2120,9 +3202,13 @@ var libc_truncate_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { + r0, _, _ := syscall_syscall(libc_umask_trampoline_addr, uintptr(newmask), 0, 0) + oldmask = int(r0) + return + } var libc_umask_trampoline_addr uintptr @@ -2132,16 +3218,27 @@ var libc_umask_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unlink_trampoline_addr uintptr @@ -2151,16 +3248,27 @@ var libc_unlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unlinkat_trampoline_addr uintptr @@ -2170,16 +3278,27 @@ var libc_unlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unmount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unmount_trampoline_addr uintptr @@ -2189,18 +3308,31 @@ var libc_unmount_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_write_trampoline_addr uintptr @@ -2210,12 +3342,19 @@ var libc_write_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + r0, _, e1 := syscall_syscall9(libc_mmap_trampoline_addr, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos), uintptr(pos>>32), 0, 0) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mmap_trampoline_addr uintptr @@ -2225,11 +3364,17 @@ var libc_mmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_munmap_trampoline_addr, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munmap_trampoline_addr uintptr @@ -2239,12 +3384,19 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getfsstat(stat *Statfs_t, bufsize uintptr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_getfsstat_trampoline_addr, uintptr(unsafe.Pointer(stat)), uintptr(bufsize), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getfsstat_trampoline_addr uintptr @@ -2254,16 +3406,27 @@ var libc_getfsstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_utimensat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_utimensat_trampoline_addr uintptr @@ -2273,11 +3436,17 @@ var libc_utimensat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pledge(promises *byte, execpromises *byte) (err error) { + _, _, e1 := syscall_syscall(libc_pledge_trampoline_addr, uintptr(unsafe.Pointer(promises)), uintptr(unsafe.Pointer(execpromises)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pledge_trampoline_addr uintptr @@ -2287,11 +3456,17 @@ var libc_pledge_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func unveil(path *byte, flags *byte) (err error) { + _, _, e1 := syscall_syscall(libc_unveil_trampoline_addr, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(flags)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unveil_trampoline_addr uintptr diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go index 0d3a075..5f8786f 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go @@ -1,4 +1,5 @@ // go run mksyscall.go -openbsd -libc -tags openbsd,amd64 syscall_bsd.go syscall_openbsd.go syscall_openbsd_amd64.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build openbsd && amd64 @@ -15,12 +16,19 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getgroups_trampoline_addr uintptr @@ -30,11 +38,17 @@ var libc_getgroups_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setgroups_trampoline_addr uintptr @@ -44,12 +58,19 @@ var libc_setgroups_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := syscall_syscall6(libc_wait4_trampoline_addr, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_wait4_trampoline_addr uintptr @@ -59,12 +80,19 @@ var libc_wait4_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := syscall_syscall(libc_accept_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_accept_trampoline_addr uintptr @@ -74,11 +102,17 @@ var libc_accept_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := syscall_syscall(libc_bind_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_bind_trampoline_addr uintptr @@ -88,11 +122,17 @@ var libc_bind_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := syscall_syscall(libc_connect_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_connect_trampoline_addr uintptr @@ -102,12 +142,19 @@ var libc_connect_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_socket_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_socket_trampoline_addr uintptr @@ -117,11 +164,17 @@ var libc_socket_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := syscall_syscall6(libc_getsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsockopt_trampoline_addr uintptr @@ -131,11 +184,17 @@ var libc_getsockopt_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := syscall_syscall6(libc_setsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setsockopt_trampoline_addr uintptr @@ -145,11 +204,17 @@ var libc_setsockopt_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getpeername_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpeername_trampoline_addr uintptr @@ -159,11 +224,17 @@ var libc_getpeername_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getsockname_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsockname_trampoline_addr uintptr @@ -173,11 +244,17 @@ var libc_getsockname_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { + _, _, e1 := syscall_syscall(libc_shutdown_trampoline_addr, uintptr(s), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_shutdown_trampoline_addr uintptr @@ -187,11 +264,17 @@ var libc_shutdown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := syscall_rawSyscall6(libc_socketpair_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_socketpair_trampoline_addr uintptr @@ -201,18 +284,31 @@ var libc_socketpair_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_recvfrom_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_recvfrom_trampoline_addr uintptr @@ -222,17 +318,29 @@ var libc_recvfrom_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall6(libc_sendto_trampoline_addr, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sendto_trampoline_addr uintptr @@ -242,12 +350,19 @@ var libc_sendto_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_recvmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_recvmsg_trampoline_addr uintptr @@ -257,12 +372,19 @@ var libc_recvmsg_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_sendmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sendmsg_trampoline_addr uintptr @@ -272,12 +394,19 @@ var libc_sendmsg_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_kevent_trampoline_addr, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kevent_trampoline_addr uintptr @@ -287,16 +416,27 @@ var libc_kevent_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_utimes_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_utimes_trampoline_addr uintptr @@ -306,11 +446,17 @@ var libc_utimes_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { + _, _, e1 := syscall_syscall(libc_futimes_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_futimes_trampoline_addr uintptr @@ -320,12 +466,19 @@ var libc_futimes_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_poll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_poll_trampoline_addr uintptr @@ -335,17 +488,29 @@ var libc_poll_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_madvise_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_madvise_trampoline_addr uintptr @@ -355,17 +520,29 @@ var libc_madvise_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_mlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mlock_trampoline_addr uintptr @@ -375,11 +552,17 @@ var libc_mlock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := syscall_syscall(libc_mlockall_trampoline_addr, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mlockall_trampoline_addr uintptr @@ -389,17 +572,29 @@ var libc_mlockall_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_mprotect_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mprotect_trampoline_addr uintptr @@ -409,17 +604,29 @@ var libc_mprotect_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_msync_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_msync_trampoline_addr uintptr @@ -429,17 +636,29 @@ var libc_msync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_munlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munlock_trampoline_addr uintptr @@ -449,11 +668,17 @@ var libc_munlock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := syscall_syscall(libc_munlockall_trampoline_addr, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munlockall_trampoline_addr uintptr @@ -463,11 +688,17 @@ var libc_munlockall_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_pipe2_trampoline_addr, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pipe2_trampoline_addr uintptr @@ -477,18 +708,31 @@ var libc_pipe2_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_getdents_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getdents_trampoline_addr uintptr @@ -498,18 +742,31 @@ var libc_getdents_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_getcwd_trampoline_addr, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getcwd_trampoline_addr uintptr @@ -519,8 +776,11 @@ var libc_getcwd_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getresuid(ruid *_C_int, euid *_C_int, suid *_C_int) { + syscall_rawSyscall(libc_getresuid_trampoline_addr, uintptr(unsafe.Pointer(ruid)), uintptr(unsafe.Pointer(euid)), uintptr(unsafe.Pointer(suid))) + return + } var libc_getresuid_trampoline_addr uintptr @@ -530,8 +790,11 @@ var libc_getresuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getresgid(rgid *_C_int, egid *_C_int, sgid *_C_int) { + syscall_rawSyscall(libc_getresgid_trampoline_addr, uintptr(unsafe.Pointer(rgid)), uintptr(unsafe.Pointer(egid)), uintptr(unsafe.Pointer(sgid))) + return + } var libc_getresgid_trampoline_addr uintptr @@ -541,11 +804,17 @@ var libc_getresgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ioctl_trampoline_addr uintptr @@ -555,27 +824,45 @@ var libc_ioctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall6(libc_sysctl_trampoline_addr, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sysctl_trampoline_addr uintptr @@ -585,12 +872,19 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fcntl_trampoline_addr uintptr @@ -600,23 +894,37 @@ var libc_fcntl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ppoll_trampoline_addr uintptr @@ -626,16 +934,27 @@ var libc_ppoll_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_access_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_access_trampoline_addr uintptr @@ -645,11 +964,17 @@ var libc_access_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { + _, _, e1 := syscall_syscall(libc_adjtime_trampoline_addr, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_adjtime_trampoline_addr uintptr @@ -659,16 +984,27 @@ var libc_adjtime_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chdir_trampoline_addr uintptr @@ -678,16 +1014,27 @@ var libc_chdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chflags_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chflags_trampoline_addr uintptr @@ -697,16 +1044,27 @@ var libc_chflags_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chmod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chmod_trampoline_addr uintptr @@ -716,16 +1074,27 @@ var libc_chmod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chown_trampoline_addr uintptr @@ -735,16 +1104,27 @@ var libc_chown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chroot_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chroot_trampoline_addr uintptr @@ -754,11 +1134,17 @@ var libc_chroot_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := syscall_syscall(libc_clock_gettime_trampoline_addr, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_clock_gettime_trampoline_addr uintptr @@ -768,11 +1154,17 @@ var libc_clock_gettime_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_close_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_close_trampoline_addr uintptr @@ -782,12 +1174,19 @@ var libc_close_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { + r0, _, e1 := syscall_syscall(libc_dup_trampoline_addr, uintptr(fd), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup_trampoline_addr uintptr @@ -797,11 +1196,17 @@ var libc_dup_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { + _, _, e1 := syscall_syscall(libc_dup2_trampoline_addr, uintptr(from), uintptr(to), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup2_trampoline_addr uintptr @@ -811,11 +1216,17 @@ var libc_dup2_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(from int, to int, flags int) (err error) { + _, _, e1 := syscall_syscall(libc_dup3_trampoline_addr, uintptr(from), uintptr(to), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup3_trampoline_addr uintptr @@ -825,8 +1236,11 @@ var libc_dup3_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + syscall_syscall(libc_exit_trampoline_addr, uintptr(code), 0, 0) + return + } var libc_exit_trampoline_addr uintptr @@ -836,16 +1250,27 @@ var libc_exit_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_faccessat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_faccessat_trampoline_addr uintptr @@ -855,11 +1280,17 @@ var libc_faccessat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_fchdir_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchdir_trampoline_addr uintptr @@ -869,11 +1300,17 @@ var libc_fchdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { + _, _, e1 := syscall_syscall(libc_fchflags_trampoline_addr, uintptr(fd), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchflags_trampoline_addr uintptr @@ -883,11 +1320,17 @@ var libc_fchflags_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := syscall_syscall(libc_fchmod_trampoline_addr, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchmod_trampoline_addr uintptr @@ -897,16 +1340,27 @@ var libc_fchmod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fchmodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchmodat_trampoline_addr uintptr @@ -916,11 +1370,17 @@ var libc_fchmodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := syscall_syscall(libc_fchown_trampoline_addr, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchown_trampoline_addr uintptr @@ -930,16 +1390,27 @@ var libc_fchown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fchownat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchownat_trampoline_addr uintptr @@ -949,11 +1420,17 @@ var libc_fchownat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := syscall_syscall(libc_flock_trampoline_addr, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_flock_trampoline_addr uintptr @@ -963,12 +1440,19 @@ var libc_flock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { + r0, _, e1 := syscall_syscall(libc_fpathconf_trampoline_addr, uintptr(fd), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fpathconf_trampoline_addr uintptr @@ -978,11 +1462,17 @@ var libc_fpathconf_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := syscall_syscall(libc_fstat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstat_trampoline_addr uintptr @@ -992,16 +1482,27 @@ var libc_fstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fstatat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstatat_trampoline_addr uintptr @@ -1011,11 +1512,17 @@ var libc_fstatat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { + _, _, e1 := syscall_syscall(libc_fstatfs_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstatfs_trampoline_addr uintptr @@ -1025,11 +1532,17 @@ var libc_fstatfs_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_fsync_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fsync_trampoline_addr uintptr @@ -1039,11 +1552,17 @@ var libc_fsync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := syscall_syscall(libc_ftruncate_trampoline_addr, uintptr(fd), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ftruncate_trampoline_addr uintptr @@ -1053,9 +1572,13 @@ var libc_ftruncate_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _, _ := syscall_rawSyscall(libc_getegid_trampoline_addr, 0, 0, 0) + egid = int(r0) + return + } var libc_getegid_trampoline_addr uintptr @@ -1065,9 +1588,13 @@ var libc_getegid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { + r0, _, _ := syscall_rawSyscall(libc_geteuid_trampoline_addr, 0, 0, 0) + uid = int(r0) + return + } var libc_geteuid_trampoline_addr uintptr @@ -1077,9 +1604,13 @@ var libc_geteuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := syscall_rawSyscall(libc_getgid_trampoline_addr, 0, 0, 0) + gid = int(r0) + return + } var libc_getgid_trampoline_addr uintptr @@ -1089,12 +1620,19 @@ var libc_getgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getpgid_trampoline_addr, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpgid_trampoline_addr uintptr @@ -1104,9 +1642,13 @@ var libc_getpgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { + r0, _, _ := syscall_rawSyscall(libc_getpgrp_trampoline_addr, 0, 0, 0) + pgrp = int(r0) + return + } var libc_getpgrp_trampoline_addr uintptr @@ -1116,9 +1658,13 @@ var libc_getpgrp_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := syscall_rawSyscall(libc_getpid_trampoline_addr, 0, 0, 0) + pid = int(r0) + return + } var libc_getpid_trampoline_addr uintptr @@ -1128,9 +1674,13 @@ var libc_getpid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _, _ := syscall_rawSyscall(libc_getppid_trampoline_addr, 0, 0, 0) + ppid = int(r0) + return + } var libc_getppid_trampoline_addr uintptr @@ -1140,12 +1690,19 @@ var libc_getppid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := syscall_syscall(libc_getpriority_trampoline_addr, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpriority_trampoline_addr uintptr @@ -1155,11 +1712,17 @@ var libc_getpriority_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getrlimit_trampoline_addr, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrlimit_trampoline_addr uintptr @@ -1169,12 +1732,19 @@ var libc_getrlimit_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrtable() (rtable int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getrtable_trampoline_addr, 0, 0, 0) + rtable = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrtable_trampoline_addr uintptr @@ -1184,11 +1754,17 @@ var libc_getrtable_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getrusage_trampoline_addr, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrusage_trampoline_addr uintptr @@ -1198,12 +1774,19 @@ var libc_getrusage_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getsid_trampoline_addr, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsid_trampoline_addr uintptr @@ -1213,11 +1796,17 @@ var libc_getsid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(libc_gettimeofday_trampoline_addr, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_gettimeofday_trampoline_addr uintptr @@ -1227,9 +1816,13 @@ var libc_gettimeofday_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := syscall_rawSyscall(libc_getuid_trampoline_addr, 0, 0, 0) + uid = int(r0) + return + } var libc_getuid_trampoline_addr uintptr @@ -1239,9 +1832,13 @@ var libc_getuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { + r0, _, _ := syscall_syscall(libc_issetugid_trampoline_addr, 0, 0, 0) + tainted = bool(r0 != 0) + return + } var libc_issetugid_trampoline_addr uintptr @@ -1251,11 +1848,17 @@ var libc_issetugid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { + _, _, e1 := syscall_syscall(libc_kill_trampoline_addr, uintptr(pid), uintptr(signum), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kill_trampoline_addr uintptr @@ -1265,12 +1868,19 @@ var libc_kill_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { + r0, _, e1 := syscall_syscall(libc_kqueue_trampoline_addr, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kqueue_trampoline_addr uintptr @@ -1280,16 +1890,27 @@ var libc_kqueue_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_lchown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lchown_trampoline_addr uintptr @@ -1299,21 +1920,37 @@ var libc_lchown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_link_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_link_trampoline_addr uintptr @@ -1323,21 +1960,37 @@ var libc_link_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_linkat_trampoline_addr, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_linkat_trampoline_addr uintptr @@ -1347,11 +2000,17 @@ var libc_linkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { + _, _, e1 := syscall_syscall(libc_listen_trampoline_addr, uintptr(s), uintptr(backlog), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_listen_trampoline_addr uintptr @@ -1361,16 +2020,27 @@ var libc_listen_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_lstat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lstat_trampoline_addr uintptr @@ -1380,16 +2050,27 @@ var libc_lstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkdir_trampoline_addr uintptr @@ -1399,16 +2080,27 @@ var libc_mkdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkdirat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkdirat_trampoline_addr uintptr @@ -1418,16 +2110,27 @@ var libc_mkdirat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkfifo_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkfifo_trampoline_addr uintptr @@ -1437,16 +2140,27 @@ var libc_mkfifo_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifoat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkfifoat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkfifoat_trampoline_addr uintptr @@ -1456,16 +2170,27 @@ var libc_mkfifoat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mknod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mknod_trampoline_addr uintptr @@ -1475,16 +2200,27 @@ var libc_mknod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mknodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mknodat_trampoline_addr uintptr @@ -1494,11 +2230,17 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_nanosleep_trampoline_addr uintptr @@ -1508,17 +2250,29 @@ var libc_nanosleep_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall(libc_open_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_open_trampoline_addr uintptr @@ -1528,17 +2282,29 @@ var libc_open_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall6(libc_openat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_openat_trampoline_addr uintptr @@ -1548,17 +2314,29 @@ var libc_openat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall(libc_pathconf_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pathconf_trampoline_addr uintptr @@ -1568,18 +2346,31 @@ var libc_pathconf_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_pread_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pread_trampoline_addr uintptr @@ -1589,18 +2380,31 @@ var libc_pread_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_pwrite_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pwrite_trampoline_addr uintptr @@ -1610,18 +2414,31 @@ var libc_pwrite_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_read_trampoline_addr uintptr @@ -1631,23 +2448,41 @@ var libc_read_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_readlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_readlink_trampoline_addr uintptr @@ -1657,23 +2492,41 @@ var libc_readlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_readlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_readlinkat_trampoline_addr uintptr @@ -1683,21 +2536,37 @@ var libc_readlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_rename_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_rename_trampoline_addr uintptr @@ -1707,21 +2576,37 @@ var libc_rename_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_renameat_trampoline_addr, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_renameat_trampoline_addr uintptr @@ -1731,16 +2616,27 @@ var libc_renameat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_revoke_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_revoke_trampoline_addr uintptr @@ -1750,16 +2646,27 @@ var libc_revoke_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_rmdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_rmdir_trampoline_addr uintptr @@ -1769,12 +2676,19 @@ var libc_rmdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, _, e1 := syscall_syscall(libc_lseek_trampoline_addr, uintptr(fd), uintptr(offset), uintptr(whence)) + newoffset = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lseek_trampoline_addr uintptr @@ -1784,12 +2698,19 @@ var libc_lseek_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_select_trampoline_addr, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_select_trampoline_addr uintptr @@ -1799,11 +2720,17 @@ var libc_select_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setegid_trampoline_addr, uintptr(egid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setegid_trampoline_addr uintptr @@ -1813,11 +2740,17 @@ var libc_setegid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_seteuid_trampoline_addr, uintptr(euid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_seteuid_trampoline_addr uintptr @@ -1827,11 +2760,17 @@ var libc_seteuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setgid_trampoline_addr, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setgid_trampoline_addr uintptr @@ -1841,16 +2780,27 @@ var libc_setgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(name) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_setlogin_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setlogin_trampoline_addr uintptr @@ -1860,11 +2810,17 @@ var libc_setlogin_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setpgid_trampoline_addr, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setpgid_trampoline_addr uintptr @@ -1874,11 +2830,17 @@ var libc_setpgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := syscall_syscall(libc_setpriority_trampoline_addr, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setpriority_trampoline_addr uintptr @@ -1888,11 +2850,17 @@ var libc_setpriority_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setregid_trampoline_addr, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setregid_trampoline_addr uintptr @@ -1902,11 +2870,17 @@ var libc_setregid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setreuid_trampoline_addr, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setreuid_trampoline_addr uintptr @@ -1916,11 +2890,17 @@ var libc_setreuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setresgid_trampoline_addr, uintptr(rgid), uintptr(egid), uintptr(sgid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setresgid_trampoline_addr uintptr @@ -1930,11 +2910,17 @@ var libc_setresgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setresuid_trampoline_addr, uintptr(ruid), uintptr(euid), uintptr(suid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setresuid_trampoline_addr uintptr @@ -1944,11 +2930,17 @@ var libc_setresuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrtable(rtable int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setrtable_trampoline_addr, uintptr(rtable), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setrtable_trampoline_addr uintptr @@ -1958,12 +2950,19 @@ var libc_setrtable_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_setsid_trampoline_addr, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setsid_trampoline_addr uintptr @@ -1973,11 +2972,17 @@ var libc_setsid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(libc_settimeofday_trampoline_addr, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_settimeofday_trampoline_addr uintptr @@ -1987,11 +2992,17 @@ var libc_settimeofday_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setuid_trampoline_addr, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setuid_trampoline_addr uintptr @@ -2001,16 +3012,27 @@ var libc_setuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_stat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_stat_trampoline_addr uintptr @@ -2020,16 +3042,27 @@ var libc_stat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_statfs_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_statfs_trampoline_addr uintptr @@ -2039,21 +3072,37 @@ var libc_statfs_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_symlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_symlink_trampoline_addr uintptr @@ -2063,21 +3112,37 @@ var libc_symlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_symlinkat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_symlinkat_trampoline_addr uintptr @@ -2087,11 +3152,17 @@ var libc_symlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { + _, _, e1 := syscall_syscall(libc_sync_trampoline_addr, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sync_trampoline_addr uintptr @@ -2101,16 +3172,27 @@ var libc_sync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_truncate_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_truncate_trampoline_addr uintptr @@ -2120,9 +3202,13 @@ var libc_truncate_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { + r0, _, _ := syscall_syscall(libc_umask_trampoline_addr, uintptr(newmask), 0, 0) + oldmask = int(r0) + return + } var libc_umask_trampoline_addr uintptr @@ -2132,16 +3218,27 @@ var libc_umask_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unlink_trampoline_addr uintptr @@ -2151,16 +3248,27 @@ var libc_unlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unlinkat_trampoline_addr uintptr @@ -2170,16 +3278,27 @@ var libc_unlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unmount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unmount_trampoline_addr uintptr @@ -2189,18 +3308,31 @@ var libc_unmount_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_write_trampoline_addr uintptr @@ -2210,12 +3342,19 @@ var libc_write_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + r0, _, e1 := syscall_syscall6(libc_mmap_trampoline_addr, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mmap_trampoline_addr uintptr @@ -2225,11 +3364,17 @@ var libc_mmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_munmap_trampoline_addr, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munmap_trampoline_addr uintptr @@ -2239,12 +3384,19 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getfsstat(stat *Statfs_t, bufsize uintptr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_getfsstat_trampoline_addr, uintptr(unsafe.Pointer(stat)), uintptr(bufsize), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getfsstat_trampoline_addr uintptr @@ -2254,16 +3406,27 @@ var libc_getfsstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_utimensat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_utimensat_trampoline_addr uintptr @@ -2273,11 +3436,17 @@ var libc_utimensat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pledge(promises *byte, execpromises *byte) (err error) { + _, _, e1 := syscall_syscall(libc_pledge_trampoline_addr, uintptr(unsafe.Pointer(promises)), uintptr(unsafe.Pointer(execpromises)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pledge_trampoline_addr uintptr @@ -2287,11 +3456,17 @@ var libc_pledge_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func unveil(path *byte, flags *byte) (err error) { + _, _, e1 := syscall_syscall(libc_unveil_trampoline_addr, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(flags)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unveil_trampoline_addr uintptr diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go index c39f777..4e0df67 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go @@ -1,4 +1,5 @@ // go run mksyscall.go -l32 -openbsd -arm -libc -tags openbsd,arm syscall_bsd.go syscall_openbsd.go syscall_openbsd_arm.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build openbsd && arm @@ -15,12 +16,19 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getgroups_trampoline_addr uintptr @@ -30,11 +38,17 @@ var libc_getgroups_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setgroups_trampoline_addr uintptr @@ -44,12 +58,19 @@ var libc_setgroups_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := syscall_syscall6(libc_wait4_trampoline_addr, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_wait4_trampoline_addr uintptr @@ -59,12 +80,19 @@ var libc_wait4_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := syscall_syscall(libc_accept_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_accept_trampoline_addr uintptr @@ -74,11 +102,17 @@ var libc_accept_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := syscall_syscall(libc_bind_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_bind_trampoline_addr uintptr @@ -88,11 +122,17 @@ var libc_bind_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := syscall_syscall(libc_connect_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_connect_trampoline_addr uintptr @@ -102,12 +142,19 @@ var libc_connect_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_socket_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_socket_trampoline_addr uintptr @@ -117,11 +164,17 @@ var libc_socket_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := syscall_syscall6(libc_getsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsockopt_trampoline_addr uintptr @@ -131,11 +184,17 @@ var libc_getsockopt_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := syscall_syscall6(libc_setsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setsockopt_trampoline_addr uintptr @@ -145,11 +204,17 @@ var libc_setsockopt_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getpeername_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpeername_trampoline_addr uintptr @@ -159,11 +224,17 @@ var libc_getpeername_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getsockname_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsockname_trampoline_addr uintptr @@ -173,11 +244,17 @@ var libc_getsockname_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { + _, _, e1 := syscall_syscall(libc_shutdown_trampoline_addr, uintptr(s), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_shutdown_trampoline_addr uintptr @@ -187,11 +264,17 @@ var libc_shutdown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := syscall_rawSyscall6(libc_socketpair_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_socketpair_trampoline_addr uintptr @@ -201,18 +284,31 @@ var libc_socketpair_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_recvfrom_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_recvfrom_trampoline_addr uintptr @@ -222,17 +318,29 @@ var libc_recvfrom_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall6(libc_sendto_trampoline_addr, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sendto_trampoline_addr uintptr @@ -242,12 +350,19 @@ var libc_sendto_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_recvmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_recvmsg_trampoline_addr uintptr @@ -257,12 +372,19 @@ var libc_recvmsg_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_sendmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sendmsg_trampoline_addr uintptr @@ -272,12 +394,19 @@ var libc_sendmsg_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_kevent_trampoline_addr, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kevent_trampoline_addr uintptr @@ -287,16 +416,27 @@ var libc_kevent_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_utimes_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_utimes_trampoline_addr uintptr @@ -306,11 +446,17 @@ var libc_utimes_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { + _, _, e1 := syscall_syscall(libc_futimes_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_futimes_trampoline_addr uintptr @@ -320,12 +466,19 @@ var libc_futimes_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_poll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_poll_trampoline_addr uintptr @@ -335,17 +488,29 @@ var libc_poll_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_madvise_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_madvise_trampoline_addr uintptr @@ -355,17 +520,29 @@ var libc_madvise_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_mlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mlock_trampoline_addr uintptr @@ -375,11 +552,17 @@ var libc_mlock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := syscall_syscall(libc_mlockall_trampoline_addr, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mlockall_trampoline_addr uintptr @@ -389,17 +572,29 @@ var libc_mlockall_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_mprotect_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mprotect_trampoline_addr uintptr @@ -409,17 +604,29 @@ var libc_mprotect_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_msync_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_msync_trampoline_addr uintptr @@ -429,17 +636,29 @@ var libc_msync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_munlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munlock_trampoline_addr uintptr @@ -449,11 +668,17 @@ var libc_munlock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := syscall_syscall(libc_munlockall_trampoline_addr, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munlockall_trampoline_addr uintptr @@ -463,11 +688,17 @@ var libc_munlockall_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_pipe2_trampoline_addr, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pipe2_trampoline_addr uintptr @@ -477,18 +708,31 @@ var libc_pipe2_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_getdents_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getdents_trampoline_addr uintptr @@ -498,18 +742,31 @@ var libc_getdents_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_getcwd_trampoline_addr, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getcwd_trampoline_addr uintptr @@ -519,8 +776,11 @@ var libc_getcwd_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getresuid(ruid *_C_int, euid *_C_int, suid *_C_int) { + syscall_rawSyscall(libc_getresuid_trampoline_addr, uintptr(unsafe.Pointer(ruid)), uintptr(unsafe.Pointer(euid)), uintptr(unsafe.Pointer(suid))) + return + } var libc_getresuid_trampoline_addr uintptr @@ -530,8 +790,11 @@ var libc_getresuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getresgid(rgid *_C_int, egid *_C_int, sgid *_C_int) { + syscall_rawSyscall(libc_getresgid_trampoline_addr, uintptr(unsafe.Pointer(rgid)), uintptr(unsafe.Pointer(egid)), uintptr(unsafe.Pointer(sgid))) + return + } var libc_getresgid_trampoline_addr uintptr @@ -541,11 +804,17 @@ var libc_getresgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ioctl_trampoline_addr uintptr @@ -555,27 +824,45 @@ var libc_ioctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall6(libc_sysctl_trampoline_addr, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sysctl_trampoline_addr uintptr @@ -585,12 +872,19 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fcntl_trampoline_addr uintptr @@ -600,23 +894,37 @@ var libc_fcntl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ppoll_trampoline_addr uintptr @@ -626,16 +934,27 @@ var libc_ppoll_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_access_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_access_trampoline_addr uintptr @@ -645,11 +964,17 @@ var libc_access_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { + _, _, e1 := syscall_syscall(libc_adjtime_trampoline_addr, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_adjtime_trampoline_addr uintptr @@ -659,16 +984,27 @@ var libc_adjtime_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chdir_trampoline_addr uintptr @@ -678,16 +1014,27 @@ var libc_chdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chflags_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chflags_trampoline_addr uintptr @@ -697,16 +1044,27 @@ var libc_chflags_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chmod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chmod_trampoline_addr uintptr @@ -716,16 +1074,27 @@ var libc_chmod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chown_trampoline_addr uintptr @@ -735,16 +1104,27 @@ var libc_chown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chroot_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chroot_trampoline_addr uintptr @@ -754,11 +1134,17 @@ var libc_chroot_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := syscall_syscall(libc_clock_gettime_trampoline_addr, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_clock_gettime_trampoline_addr uintptr @@ -768,11 +1154,17 @@ var libc_clock_gettime_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_close_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_close_trampoline_addr uintptr @@ -782,12 +1174,19 @@ var libc_close_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { + r0, _, e1 := syscall_syscall(libc_dup_trampoline_addr, uintptr(fd), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup_trampoline_addr uintptr @@ -797,11 +1196,17 @@ var libc_dup_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { + _, _, e1 := syscall_syscall(libc_dup2_trampoline_addr, uintptr(from), uintptr(to), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup2_trampoline_addr uintptr @@ -811,11 +1216,17 @@ var libc_dup2_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(from int, to int, flags int) (err error) { + _, _, e1 := syscall_syscall(libc_dup3_trampoline_addr, uintptr(from), uintptr(to), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup3_trampoline_addr uintptr @@ -825,8 +1236,11 @@ var libc_dup3_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + syscall_syscall(libc_exit_trampoline_addr, uintptr(code), 0, 0) + return + } var libc_exit_trampoline_addr uintptr @@ -836,16 +1250,27 @@ var libc_exit_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_faccessat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_faccessat_trampoline_addr uintptr @@ -855,11 +1280,17 @@ var libc_faccessat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_fchdir_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchdir_trampoline_addr uintptr @@ -869,11 +1300,17 @@ var libc_fchdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { + _, _, e1 := syscall_syscall(libc_fchflags_trampoline_addr, uintptr(fd), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchflags_trampoline_addr uintptr @@ -883,11 +1320,17 @@ var libc_fchflags_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := syscall_syscall(libc_fchmod_trampoline_addr, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchmod_trampoline_addr uintptr @@ -897,16 +1340,27 @@ var libc_fchmod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fchmodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchmodat_trampoline_addr uintptr @@ -916,11 +1370,17 @@ var libc_fchmodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := syscall_syscall(libc_fchown_trampoline_addr, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchown_trampoline_addr uintptr @@ -930,16 +1390,27 @@ var libc_fchown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fchownat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchownat_trampoline_addr uintptr @@ -949,11 +1420,17 @@ var libc_fchownat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := syscall_syscall(libc_flock_trampoline_addr, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_flock_trampoline_addr uintptr @@ -963,12 +1440,19 @@ var libc_flock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { + r0, _, e1 := syscall_syscall(libc_fpathconf_trampoline_addr, uintptr(fd), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fpathconf_trampoline_addr uintptr @@ -978,11 +1462,17 @@ var libc_fpathconf_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := syscall_syscall(libc_fstat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstat_trampoline_addr uintptr @@ -992,16 +1482,27 @@ var libc_fstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fstatat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstatat_trampoline_addr uintptr @@ -1011,11 +1512,17 @@ var libc_fstatat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { + _, _, e1 := syscall_syscall(libc_fstatfs_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstatfs_trampoline_addr uintptr @@ -1025,11 +1532,17 @@ var libc_fstatfs_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_fsync_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fsync_trampoline_addr uintptr @@ -1039,11 +1552,17 @@ var libc_fsync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := syscall_syscall6(libc_ftruncate_trampoline_addr, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ftruncate_trampoline_addr uintptr @@ -1053,9 +1572,13 @@ var libc_ftruncate_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _, _ := syscall_rawSyscall(libc_getegid_trampoline_addr, 0, 0, 0) + egid = int(r0) + return + } var libc_getegid_trampoline_addr uintptr @@ -1065,9 +1588,13 @@ var libc_getegid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { + r0, _, _ := syscall_rawSyscall(libc_geteuid_trampoline_addr, 0, 0, 0) + uid = int(r0) + return + } var libc_geteuid_trampoline_addr uintptr @@ -1077,9 +1604,13 @@ var libc_geteuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := syscall_rawSyscall(libc_getgid_trampoline_addr, 0, 0, 0) + gid = int(r0) + return + } var libc_getgid_trampoline_addr uintptr @@ -1089,12 +1620,19 @@ var libc_getgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getpgid_trampoline_addr, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpgid_trampoline_addr uintptr @@ -1104,9 +1642,13 @@ var libc_getpgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { + r0, _, _ := syscall_rawSyscall(libc_getpgrp_trampoline_addr, 0, 0, 0) + pgrp = int(r0) + return + } var libc_getpgrp_trampoline_addr uintptr @@ -1116,9 +1658,13 @@ var libc_getpgrp_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := syscall_rawSyscall(libc_getpid_trampoline_addr, 0, 0, 0) + pid = int(r0) + return + } var libc_getpid_trampoline_addr uintptr @@ -1128,9 +1674,13 @@ var libc_getpid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _, _ := syscall_rawSyscall(libc_getppid_trampoline_addr, 0, 0, 0) + ppid = int(r0) + return + } var libc_getppid_trampoline_addr uintptr @@ -1140,12 +1690,19 @@ var libc_getppid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := syscall_syscall(libc_getpriority_trampoline_addr, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpriority_trampoline_addr uintptr @@ -1155,11 +1712,17 @@ var libc_getpriority_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getrlimit_trampoline_addr, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrlimit_trampoline_addr uintptr @@ -1169,12 +1732,19 @@ var libc_getrlimit_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrtable() (rtable int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getrtable_trampoline_addr, 0, 0, 0) + rtable = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrtable_trampoline_addr uintptr @@ -1184,11 +1754,17 @@ var libc_getrtable_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getrusage_trampoline_addr, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrusage_trampoline_addr uintptr @@ -1198,12 +1774,19 @@ var libc_getrusage_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getsid_trampoline_addr, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsid_trampoline_addr uintptr @@ -1213,11 +1796,17 @@ var libc_getsid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(libc_gettimeofday_trampoline_addr, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_gettimeofday_trampoline_addr uintptr @@ -1227,9 +1816,13 @@ var libc_gettimeofday_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := syscall_rawSyscall(libc_getuid_trampoline_addr, 0, 0, 0) + uid = int(r0) + return + } var libc_getuid_trampoline_addr uintptr @@ -1239,9 +1832,13 @@ var libc_getuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { + r0, _, _ := syscall_syscall(libc_issetugid_trampoline_addr, 0, 0, 0) + tainted = bool(r0 != 0) + return + } var libc_issetugid_trampoline_addr uintptr @@ -1251,11 +1848,17 @@ var libc_issetugid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { + _, _, e1 := syscall_syscall(libc_kill_trampoline_addr, uintptr(pid), uintptr(signum), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kill_trampoline_addr uintptr @@ -1265,12 +1868,19 @@ var libc_kill_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { + r0, _, e1 := syscall_syscall(libc_kqueue_trampoline_addr, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kqueue_trampoline_addr uintptr @@ -1280,16 +1890,27 @@ var libc_kqueue_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_lchown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lchown_trampoline_addr uintptr @@ -1299,21 +1920,37 @@ var libc_lchown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_link_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_link_trampoline_addr uintptr @@ -1323,21 +1960,37 @@ var libc_link_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_linkat_trampoline_addr, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_linkat_trampoline_addr uintptr @@ -1347,11 +2000,17 @@ var libc_linkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { + _, _, e1 := syscall_syscall(libc_listen_trampoline_addr, uintptr(s), uintptr(backlog), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_listen_trampoline_addr uintptr @@ -1361,16 +2020,27 @@ var libc_listen_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_lstat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lstat_trampoline_addr uintptr @@ -1380,16 +2050,27 @@ var libc_lstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkdir_trampoline_addr uintptr @@ -1399,16 +2080,27 @@ var libc_mkdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkdirat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkdirat_trampoline_addr uintptr @@ -1418,16 +2110,27 @@ var libc_mkdirat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkfifo_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkfifo_trampoline_addr uintptr @@ -1437,16 +2140,27 @@ var libc_mkfifo_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifoat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkfifoat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkfifoat_trampoline_addr uintptr @@ -1456,16 +2170,27 @@ var libc_mkfifoat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mknod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mknod_trampoline_addr uintptr @@ -1475,16 +2200,27 @@ var libc_mknod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mknodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mknodat_trampoline_addr uintptr @@ -1494,11 +2230,17 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_nanosleep_trampoline_addr uintptr @@ -1508,17 +2250,29 @@ var libc_nanosleep_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall(libc_open_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_open_trampoline_addr uintptr @@ -1528,17 +2282,29 @@ var libc_open_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall6(libc_openat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_openat_trampoline_addr uintptr @@ -1548,17 +2314,29 @@ var libc_openat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall(libc_pathconf_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pathconf_trampoline_addr uintptr @@ -1568,18 +2346,31 @@ var libc_pathconf_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_pread_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pread_trampoline_addr uintptr @@ -1589,18 +2380,31 @@ var libc_pread_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_pwrite_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pwrite_trampoline_addr uintptr @@ -1610,18 +2414,31 @@ var libc_pwrite_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_read_trampoline_addr uintptr @@ -1631,23 +2448,41 @@ var libc_read_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_readlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_readlink_trampoline_addr uintptr @@ -1657,23 +2492,41 @@ var libc_readlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_readlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_readlinkat_trampoline_addr uintptr @@ -1683,21 +2536,37 @@ var libc_readlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_rename_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_rename_trampoline_addr uintptr @@ -1707,21 +2576,37 @@ var libc_rename_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_renameat_trampoline_addr, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_renameat_trampoline_addr uintptr @@ -1731,16 +2616,27 @@ var libc_renameat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_revoke_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_revoke_trampoline_addr uintptr @@ -1750,16 +2646,27 @@ var libc_revoke_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_rmdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_rmdir_trampoline_addr uintptr @@ -1769,12 +2676,19 @@ var libc_rmdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, r1, e1 := syscall_syscall6(libc_lseek_trampoline_addr, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0) + newoffset = int64(int64(r1)<<32 | int64(r0)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lseek_trampoline_addr uintptr @@ -1784,12 +2698,19 @@ var libc_lseek_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_select_trampoline_addr, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_select_trampoline_addr uintptr @@ -1799,11 +2720,17 @@ var libc_select_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setegid_trampoline_addr, uintptr(egid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setegid_trampoline_addr uintptr @@ -1813,11 +2740,17 @@ var libc_setegid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_seteuid_trampoline_addr, uintptr(euid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_seteuid_trampoline_addr uintptr @@ -1827,11 +2760,17 @@ var libc_seteuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setgid_trampoline_addr, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setgid_trampoline_addr uintptr @@ -1841,16 +2780,27 @@ var libc_setgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(name) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_setlogin_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setlogin_trampoline_addr uintptr @@ -1860,11 +2810,17 @@ var libc_setlogin_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setpgid_trampoline_addr, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setpgid_trampoline_addr uintptr @@ -1874,11 +2830,17 @@ var libc_setpgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := syscall_syscall(libc_setpriority_trampoline_addr, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setpriority_trampoline_addr uintptr @@ -1888,11 +2850,17 @@ var libc_setpriority_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setregid_trampoline_addr, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setregid_trampoline_addr uintptr @@ -1902,11 +2870,17 @@ var libc_setregid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setreuid_trampoline_addr, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setreuid_trampoline_addr uintptr @@ -1916,11 +2890,17 @@ var libc_setreuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setresgid_trampoline_addr, uintptr(rgid), uintptr(egid), uintptr(sgid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setresgid_trampoline_addr uintptr @@ -1930,11 +2910,17 @@ var libc_setresgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setresuid_trampoline_addr, uintptr(ruid), uintptr(euid), uintptr(suid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setresuid_trampoline_addr uintptr @@ -1944,11 +2930,17 @@ var libc_setresuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrtable(rtable int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setrtable_trampoline_addr, uintptr(rtable), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setrtable_trampoline_addr uintptr @@ -1958,12 +2950,19 @@ var libc_setrtable_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_setsid_trampoline_addr, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setsid_trampoline_addr uintptr @@ -1973,11 +2972,17 @@ var libc_setsid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(libc_settimeofday_trampoline_addr, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_settimeofday_trampoline_addr uintptr @@ -1987,11 +2992,17 @@ var libc_settimeofday_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setuid_trampoline_addr, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setuid_trampoline_addr uintptr @@ -2001,16 +3012,27 @@ var libc_setuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_stat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_stat_trampoline_addr uintptr @@ -2020,16 +3042,27 @@ var libc_stat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_statfs_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_statfs_trampoline_addr uintptr @@ -2039,21 +3072,37 @@ var libc_statfs_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_symlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_symlink_trampoline_addr uintptr @@ -2063,21 +3112,37 @@ var libc_symlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_symlinkat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_symlinkat_trampoline_addr uintptr @@ -2087,11 +3152,17 @@ var libc_symlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { + _, _, e1 := syscall_syscall(libc_sync_trampoline_addr, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sync_trampoline_addr uintptr @@ -2101,16 +3172,27 @@ var libc_sync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_truncate_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_truncate_trampoline_addr uintptr @@ -2120,9 +3202,13 @@ var libc_truncate_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { + r0, _, _ := syscall_syscall(libc_umask_trampoline_addr, uintptr(newmask), 0, 0) + oldmask = int(r0) + return + } var libc_umask_trampoline_addr uintptr @@ -2132,16 +3218,27 @@ var libc_umask_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unlink_trampoline_addr uintptr @@ -2151,16 +3248,27 @@ var libc_unlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unlinkat_trampoline_addr uintptr @@ -2170,16 +3278,27 @@ var libc_unlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unmount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unmount_trampoline_addr uintptr @@ -2189,18 +3308,31 @@ var libc_unmount_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_write_trampoline_addr uintptr @@ -2210,12 +3342,19 @@ var libc_write_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + r0, _, e1 := syscall_syscall9(libc_mmap_trampoline_addr, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mmap_trampoline_addr uintptr @@ -2225,11 +3364,17 @@ var libc_mmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_munmap_trampoline_addr, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munmap_trampoline_addr uintptr @@ -2239,12 +3384,19 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getfsstat(stat *Statfs_t, bufsize uintptr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_getfsstat_trampoline_addr, uintptr(unsafe.Pointer(stat)), uintptr(bufsize), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getfsstat_trampoline_addr uintptr @@ -2254,16 +3406,27 @@ var libc_getfsstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_utimensat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_utimensat_trampoline_addr uintptr @@ -2273,11 +3436,17 @@ var libc_utimensat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pledge(promises *byte, execpromises *byte) (err error) { + _, _, e1 := syscall_syscall(libc_pledge_trampoline_addr, uintptr(unsafe.Pointer(promises)), uintptr(unsafe.Pointer(execpromises)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pledge_trampoline_addr uintptr @@ -2287,11 +3456,17 @@ var libc_pledge_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func unveil(path *byte, flags *byte) (err error) { + _, _, e1 := syscall_syscall(libc_unveil_trampoline_addr, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(flags)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unveil_trampoline_addr uintptr diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.go index 57571d0..017864a 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.go @@ -1,4 +1,5 @@ // go run mksyscall.go -openbsd -libc -tags openbsd,arm64 syscall_bsd.go syscall_openbsd.go syscall_openbsd_arm64.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build openbsd && arm64 @@ -15,12 +16,19 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getgroups_trampoline_addr uintptr @@ -30,11 +38,17 @@ var libc_getgroups_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setgroups_trampoline_addr uintptr @@ -44,12 +58,19 @@ var libc_setgroups_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := syscall_syscall6(libc_wait4_trampoline_addr, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_wait4_trampoline_addr uintptr @@ -59,12 +80,19 @@ var libc_wait4_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := syscall_syscall(libc_accept_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_accept_trampoline_addr uintptr @@ -74,11 +102,17 @@ var libc_accept_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := syscall_syscall(libc_bind_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_bind_trampoline_addr uintptr @@ -88,11 +122,17 @@ var libc_bind_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := syscall_syscall(libc_connect_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_connect_trampoline_addr uintptr @@ -102,12 +142,19 @@ var libc_connect_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_socket_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_socket_trampoline_addr uintptr @@ -117,11 +164,17 @@ var libc_socket_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := syscall_syscall6(libc_getsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsockopt_trampoline_addr uintptr @@ -131,11 +184,17 @@ var libc_getsockopt_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := syscall_syscall6(libc_setsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setsockopt_trampoline_addr uintptr @@ -145,11 +204,17 @@ var libc_setsockopt_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getpeername_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpeername_trampoline_addr uintptr @@ -159,11 +224,17 @@ var libc_getpeername_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getsockname_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsockname_trampoline_addr uintptr @@ -173,11 +244,17 @@ var libc_getsockname_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { + _, _, e1 := syscall_syscall(libc_shutdown_trampoline_addr, uintptr(s), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_shutdown_trampoline_addr uintptr @@ -187,11 +264,17 @@ var libc_shutdown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := syscall_rawSyscall6(libc_socketpair_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_socketpair_trampoline_addr uintptr @@ -201,18 +284,31 @@ var libc_socketpair_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_recvfrom_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_recvfrom_trampoline_addr uintptr @@ -222,17 +318,29 @@ var libc_recvfrom_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall6(libc_sendto_trampoline_addr, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sendto_trampoline_addr uintptr @@ -242,12 +350,19 @@ var libc_sendto_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_recvmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_recvmsg_trampoline_addr uintptr @@ -257,12 +372,19 @@ var libc_recvmsg_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_sendmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sendmsg_trampoline_addr uintptr @@ -272,12 +394,19 @@ var libc_sendmsg_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_kevent_trampoline_addr, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kevent_trampoline_addr uintptr @@ -287,16 +416,27 @@ var libc_kevent_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_utimes_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_utimes_trampoline_addr uintptr @@ -306,11 +446,17 @@ var libc_utimes_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { + _, _, e1 := syscall_syscall(libc_futimes_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_futimes_trampoline_addr uintptr @@ -320,12 +466,19 @@ var libc_futimes_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_poll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_poll_trampoline_addr uintptr @@ -335,17 +488,29 @@ var libc_poll_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_madvise_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_madvise_trampoline_addr uintptr @@ -355,17 +520,29 @@ var libc_madvise_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_mlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mlock_trampoline_addr uintptr @@ -375,11 +552,17 @@ var libc_mlock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := syscall_syscall(libc_mlockall_trampoline_addr, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mlockall_trampoline_addr uintptr @@ -389,17 +572,29 @@ var libc_mlockall_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_mprotect_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mprotect_trampoline_addr uintptr @@ -409,17 +604,29 @@ var libc_mprotect_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_msync_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_msync_trampoline_addr uintptr @@ -429,17 +636,29 @@ var libc_msync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_munlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munlock_trampoline_addr uintptr @@ -449,11 +668,17 @@ var libc_munlock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := syscall_syscall(libc_munlockall_trampoline_addr, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munlockall_trampoline_addr uintptr @@ -463,11 +688,17 @@ var libc_munlockall_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_pipe2_trampoline_addr, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pipe2_trampoline_addr uintptr @@ -477,18 +708,31 @@ var libc_pipe2_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_getdents_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getdents_trampoline_addr uintptr @@ -498,18 +742,31 @@ var libc_getdents_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_getcwd_trampoline_addr, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getcwd_trampoline_addr uintptr @@ -519,8 +776,11 @@ var libc_getcwd_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getresuid(ruid *_C_int, euid *_C_int, suid *_C_int) { + syscall_rawSyscall(libc_getresuid_trampoline_addr, uintptr(unsafe.Pointer(ruid)), uintptr(unsafe.Pointer(euid)), uintptr(unsafe.Pointer(suid))) + return + } var libc_getresuid_trampoline_addr uintptr @@ -530,8 +790,11 @@ var libc_getresuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getresgid(rgid *_C_int, egid *_C_int, sgid *_C_int) { + syscall_rawSyscall(libc_getresgid_trampoline_addr, uintptr(unsafe.Pointer(rgid)), uintptr(unsafe.Pointer(egid)), uintptr(unsafe.Pointer(sgid))) + return + } var libc_getresgid_trampoline_addr uintptr @@ -541,11 +804,17 @@ var libc_getresgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ioctl_trampoline_addr uintptr @@ -555,27 +824,45 @@ var libc_ioctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall6(libc_sysctl_trampoline_addr, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sysctl_trampoline_addr uintptr @@ -585,12 +872,19 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fcntl_trampoline_addr uintptr @@ -600,23 +894,37 @@ var libc_fcntl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ppoll_trampoline_addr uintptr @@ -626,16 +934,27 @@ var libc_ppoll_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_access_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_access_trampoline_addr uintptr @@ -645,11 +964,17 @@ var libc_access_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { + _, _, e1 := syscall_syscall(libc_adjtime_trampoline_addr, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_adjtime_trampoline_addr uintptr @@ -659,16 +984,27 @@ var libc_adjtime_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chdir_trampoline_addr uintptr @@ -678,16 +1014,27 @@ var libc_chdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chflags_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chflags_trampoline_addr uintptr @@ -697,16 +1044,27 @@ var libc_chflags_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chmod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chmod_trampoline_addr uintptr @@ -716,16 +1074,27 @@ var libc_chmod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chown_trampoline_addr uintptr @@ -735,16 +1104,27 @@ var libc_chown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chroot_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chroot_trampoline_addr uintptr @@ -754,11 +1134,17 @@ var libc_chroot_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := syscall_syscall(libc_clock_gettime_trampoline_addr, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_clock_gettime_trampoline_addr uintptr @@ -768,11 +1154,17 @@ var libc_clock_gettime_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_close_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_close_trampoline_addr uintptr @@ -782,12 +1174,19 @@ var libc_close_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { + r0, _, e1 := syscall_syscall(libc_dup_trampoline_addr, uintptr(fd), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup_trampoline_addr uintptr @@ -797,11 +1196,17 @@ var libc_dup_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { + _, _, e1 := syscall_syscall(libc_dup2_trampoline_addr, uintptr(from), uintptr(to), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup2_trampoline_addr uintptr @@ -811,11 +1216,17 @@ var libc_dup2_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(from int, to int, flags int) (err error) { + _, _, e1 := syscall_syscall(libc_dup3_trampoline_addr, uintptr(from), uintptr(to), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup3_trampoline_addr uintptr @@ -825,8 +1236,11 @@ var libc_dup3_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + syscall_syscall(libc_exit_trampoline_addr, uintptr(code), 0, 0) + return + } var libc_exit_trampoline_addr uintptr @@ -836,16 +1250,27 @@ var libc_exit_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_faccessat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_faccessat_trampoline_addr uintptr @@ -855,11 +1280,17 @@ var libc_faccessat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_fchdir_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchdir_trampoline_addr uintptr @@ -869,11 +1300,17 @@ var libc_fchdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { + _, _, e1 := syscall_syscall(libc_fchflags_trampoline_addr, uintptr(fd), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchflags_trampoline_addr uintptr @@ -883,11 +1320,17 @@ var libc_fchflags_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := syscall_syscall(libc_fchmod_trampoline_addr, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchmod_trampoline_addr uintptr @@ -897,16 +1340,27 @@ var libc_fchmod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fchmodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchmodat_trampoline_addr uintptr @@ -916,11 +1370,17 @@ var libc_fchmodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := syscall_syscall(libc_fchown_trampoline_addr, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchown_trampoline_addr uintptr @@ -930,16 +1390,27 @@ var libc_fchown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fchownat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchownat_trampoline_addr uintptr @@ -949,11 +1420,17 @@ var libc_fchownat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := syscall_syscall(libc_flock_trampoline_addr, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_flock_trampoline_addr uintptr @@ -963,12 +1440,19 @@ var libc_flock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { + r0, _, e1 := syscall_syscall(libc_fpathconf_trampoline_addr, uintptr(fd), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fpathconf_trampoline_addr uintptr @@ -978,11 +1462,17 @@ var libc_fpathconf_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := syscall_syscall(libc_fstat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstat_trampoline_addr uintptr @@ -992,16 +1482,27 @@ var libc_fstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fstatat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstatat_trampoline_addr uintptr @@ -1011,11 +1512,17 @@ var libc_fstatat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { + _, _, e1 := syscall_syscall(libc_fstatfs_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstatfs_trampoline_addr uintptr @@ -1025,11 +1532,17 @@ var libc_fstatfs_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_fsync_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fsync_trampoline_addr uintptr @@ -1039,11 +1552,17 @@ var libc_fsync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := syscall_syscall(libc_ftruncate_trampoline_addr, uintptr(fd), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ftruncate_trampoline_addr uintptr @@ -1053,9 +1572,13 @@ var libc_ftruncate_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _, _ := syscall_rawSyscall(libc_getegid_trampoline_addr, 0, 0, 0) + egid = int(r0) + return + } var libc_getegid_trampoline_addr uintptr @@ -1065,9 +1588,13 @@ var libc_getegid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { + r0, _, _ := syscall_rawSyscall(libc_geteuid_trampoline_addr, 0, 0, 0) + uid = int(r0) + return + } var libc_geteuid_trampoline_addr uintptr @@ -1077,9 +1604,13 @@ var libc_geteuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := syscall_rawSyscall(libc_getgid_trampoline_addr, 0, 0, 0) + gid = int(r0) + return + } var libc_getgid_trampoline_addr uintptr @@ -1089,12 +1620,19 @@ var libc_getgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getpgid_trampoline_addr, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpgid_trampoline_addr uintptr @@ -1104,9 +1642,13 @@ var libc_getpgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { + r0, _, _ := syscall_rawSyscall(libc_getpgrp_trampoline_addr, 0, 0, 0) + pgrp = int(r0) + return + } var libc_getpgrp_trampoline_addr uintptr @@ -1116,9 +1658,13 @@ var libc_getpgrp_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := syscall_rawSyscall(libc_getpid_trampoline_addr, 0, 0, 0) + pid = int(r0) + return + } var libc_getpid_trampoline_addr uintptr @@ -1128,9 +1674,13 @@ var libc_getpid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _, _ := syscall_rawSyscall(libc_getppid_trampoline_addr, 0, 0, 0) + ppid = int(r0) + return + } var libc_getppid_trampoline_addr uintptr @@ -1140,12 +1690,19 @@ var libc_getppid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := syscall_syscall(libc_getpriority_trampoline_addr, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpriority_trampoline_addr uintptr @@ -1155,11 +1712,17 @@ var libc_getpriority_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getrlimit_trampoline_addr, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrlimit_trampoline_addr uintptr @@ -1169,12 +1732,19 @@ var libc_getrlimit_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrtable() (rtable int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getrtable_trampoline_addr, 0, 0, 0) + rtable = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrtable_trampoline_addr uintptr @@ -1184,11 +1754,17 @@ var libc_getrtable_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getrusage_trampoline_addr, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrusage_trampoline_addr uintptr @@ -1198,12 +1774,19 @@ var libc_getrusage_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getsid_trampoline_addr, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsid_trampoline_addr uintptr @@ -1213,11 +1796,17 @@ var libc_getsid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(libc_gettimeofday_trampoline_addr, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_gettimeofday_trampoline_addr uintptr @@ -1227,9 +1816,13 @@ var libc_gettimeofday_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := syscall_rawSyscall(libc_getuid_trampoline_addr, 0, 0, 0) + uid = int(r0) + return + } var libc_getuid_trampoline_addr uintptr @@ -1239,9 +1832,13 @@ var libc_getuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { + r0, _, _ := syscall_syscall(libc_issetugid_trampoline_addr, 0, 0, 0) + tainted = bool(r0 != 0) + return + } var libc_issetugid_trampoline_addr uintptr @@ -1251,11 +1848,17 @@ var libc_issetugid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { + _, _, e1 := syscall_syscall(libc_kill_trampoline_addr, uintptr(pid), uintptr(signum), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kill_trampoline_addr uintptr @@ -1265,12 +1868,19 @@ var libc_kill_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { + r0, _, e1 := syscall_syscall(libc_kqueue_trampoline_addr, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kqueue_trampoline_addr uintptr @@ -1280,16 +1890,27 @@ var libc_kqueue_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_lchown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lchown_trampoline_addr uintptr @@ -1299,21 +1920,37 @@ var libc_lchown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_link_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_link_trampoline_addr uintptr @@ -1323,21 +1960,37 @@ var libc_link_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_linkat_trampoline_addr, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_linkat_trampoline_addr uintptr @@ -1347,11 +2000,17 @@ var libc_linkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { + _, _, e1 := syscall_syscall(libc_listen_trampoline_addr, uintptr(s), uintptr(backlog), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_listen_trampoline_addr uintptr @@ -1361,16 +2020,27 @@ var libc_listen_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_lstat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lstat_trampoline_addr uintptr @@ -1380,16 +2050,27 @@ var libc_lstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkdir_trampoline_addr uintptr @@ -1399,16 +2080,27 @@ var libc_mkdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkdirat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkdirat_trampoline_addr uintptr @@ -1418,16 +2110,27 @@ var libc_mkdirat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkfifo_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkfifo_trampoline_addr uintptr @@ -1437,16 +2140,27 @@ var libc_mkfifo_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifoat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkfifoat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkfifoat_trampoline_addr uintptr @@ -1456,16 +2170,27 @@ var libc_mkfifoat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mknod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mknod_trampoline_addr uintptr @@ -1475,16 +2200,27 @@ var libc_mknod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mknodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mknodat_trampoline_addr uintptr @@ -1494,11 +2230,17 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_nanosleep_trampoline_addr uintptr @@ -1508,17 +2250,29 @@ var libc_nanosleep_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall(libc_open_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_open_trampoline_addr uintptr @@ -1528,17 +2282,29 @@ var libc_open_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall6(libc_openat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_openat_trampoline_addr uintptr @@ -1548,17 +2314,29 @@ var libc_openat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall(libc_pathconf_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pathconf_trampoline_addr uintptr @@ -1568,18 +2346,31 @@ var libc_pathconf_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_pread_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pread_trampoline_addr uintptr @@ -1589,18 +2380,31 @@ var libc_pread_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_pwrite_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pwrite_trampoline_addr uintptr @@ -1610,18 +2414,31 @@ var libc_pwrite_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_read_trampoline_addr uintptr @@ -1631,23 +2448,41 @@ var libc_read_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_readlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_readlink_trampoline_addr uintptr @@ -1657,23 +2492,41 @@ var libc_readlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_readlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_readlinkat_trampoline_addr uintptr @@ -1683,21 +2536,37 @@ var libc_readlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_rename_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_rename_trampoline_addr uintptr @@ -1707,21 +2576,37 @@ var libc_rename_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_renameat_trampoline_addr, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_renameat_trampoline_addr uintptr @@ -1731,16 +2616,27 @@ var libc_renameat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_revoke_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_revoke_trampoline_addr uintptr @@ -1750,16 +2646,27 @@ var libc_revoke_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_rmdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_rmdir_trampoline_addr uintptr @@ -1769,12 +2676,19 @@ var libc_rmdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, _, e1 := syscall_syscall(libc_lseek_trampoline_addr, uintptr(fd), uintptr(offset), uintptr(whence)) + newoffset = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lseek_trampoline_addr uintptr @@ -1784,12 +2698,19 @@ var libc_lseek_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_select_trampoline_addr, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_select_trampoline_addr uintptr @@ -1799,11 +2720,17 @@ var libc_select_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setegid_trampoline_addr, uintptr(egid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setegid_trampoline_addr uintptr @@ -1813,11 +2740,17 @@ var libc_setegid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_seteuid_trampoline_addr, uintptr(euid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_seteuid_trampoline_addr uintptr @@ -1827,11 +2760,17 @@ var libc_seteuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setgid_trampoline_addr, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setgid_trampoline_addr uintptr @@ -1841,16 +2780,27 @@ var libc_setgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(name) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_setlogin_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setlogin_trampoline_addr uintptr @@ -1860,11 +2810,17 @@ var libc_setlogin_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setpgid_trampoline_addr, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setpgid_trampoline_addr uintptr @@ -1874,11 +2830,17 @@ var libc_setpgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := syscall_syscall(libc_setpriority_trampoline_addr, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setpriority_trampoline_addr uintptr @@ -1888,11 +2850,17 @@ var libc_setpriority_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setregid_trampoline_addr, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setregid_trampoline_addr uintptr @@ -1902,11 +2870,17 @@ var libc_setregid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setreuid_trampoline_addr, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setreuid_trampoline_addr uintptr @@ -1916,11 +2890,17 @@ var libc_setreuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setresgid_trampoline_addr, uintptr(rgid), uintptr(egid), uintptr(sgid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setresgid_trampoline_addr uintptr @@ -1930,11 +2910,17 @@ var libc_setresgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setresuid_trampoline_addr, uintptr(ruid), uintptr(euid), uintptr(suid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setresuid_trampoline_addr uintptr @@ -1944,11 +2930,17 @@ var libc_setresuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrtable(rtable int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setrtable_trampoline_addr, uintptr(rtable), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setrtable_trampoline_addr uintptr @@ -1958,12 +2950,19 @@ var libc_setrtable_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_setsid_trampoline_addr, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setsid_trampoline_addr uintptr @@ -1973,11 +2972,17 @@ var libc_setsid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(libc_settimeofday_trampoline_addr, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_settimeofday_trampoline_addr uintptr @@ -1987,11 +2992,17 @@ var libc_settimeofday_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setuid_trampoline_addr, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setuid_trampoline_addr uintptr @@ -2001,16 +3012,27 @@ var libc_setuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_stat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_stat_trampoline_addr uintptr @@ -2020,16 +3042,27 @@ var libc_stat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_statfs_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_statfs_trampoline_addr uintptr @@ -2039,21 +3072,37 @@ var libc_statfs_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_symlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_symlink_trampoline_addr uintptr @@ -2063,21 +3112,37 @@ var libc_symlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_symlinkat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_symlinkat_trampoline_addr uintptr @@ -2087,11 +3152,17 @@ var libc_symlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { + _, _, e1 := syscall_syscall(libc_sync_trampoline_addr, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sync_trampoline_addr uintptr @@ -2101,16 +3172,27 @@ var libc_sync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_truncate_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_truncate_trampoline_addr uintptr @@ -2120,9 +3202,13 @@ var libc_truncate_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { + r0, _, _ := syscall_syscall(libc_umask_trampoline_addr, uintptr(newmask), 0, 0) + oldmask = int(r0) + return + } var libc_umask_trampoline_addr uintptr @@ -2132,16 +3218,27 @@ var libc_umask_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unlink_trampoline_addr uintptr @@ -2151,16 +3248,27 @@ var libc_unlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unlinkat_trampoline_addr uintptr @@ -2170,16 +3278,27 @@ var libc_unlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unmount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unmount_trampoline_addr uintptr @@ -2189,18 +3308,31 @@ var libc_unmount_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_write_trampoline_addr uintptr @@ -2210,12 +3342,19 @@ var libc_write_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + r0, _, e1 := syscall_syscall6(libc_mmap_trampoline_addr, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mmap_trampoline_addr uintptr @@ -2225,11 +3364,17 @@ var libc_mmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_munmap_trampoline_addr, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munmap_trampoline_addr uintptr @@ -2239,12 +3384,19 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getfsstat(stat *Statfs_t, bufsize uintptr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_getfsstat_trampoline_addr, uintptr(unsafe.Pointer(stat)), uintptr(bufsize), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getfsstat_trampoline_addr uintptr @@ -2254,16 +3406,27 @@ var libc_getfsstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_utimensat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_utimensat_trampoline_addr uintptr @@ -2273,11 +3436,17 @@ var libc_utimensat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pledge(promises *byte, execpromises *byte) (err error) { + _, _, e1 := syscall_syscall(libc_pledge_trampoline_addr, uintptr(unsafe.Pointer(promises)), uintptr(unsafe.Pointer(execpromises)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pledge_trampoline_addr uintptr @@ -2287,11 +3456,17 @@ var libc_pledge_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func unveil(path *byte, flags *byte) (err error) { + _, _, e1 := syscall_syscall(libc_unveil_trampoline_addr, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(flags)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unveil_trampoline_addr uintptr diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.go index e62963e..8d23a13 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.go @@ -1,4 +1,5 @@ // go run mksyscall.go -openbsd -libc -tags openbsd,mips64 syscall_bsd.go syscall_openbsd.go syscall_openbsd_mips64.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build openbsd && mips64 @@ -15,12 +16,19 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getgroups_trampoline_addr uintptr @@ -30,11 +38,17 @@ var libc_getgroups_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setgroups_trampoline_addr uintptr @@ -44,12 +58,19 @@ var libc_setgroups_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := syscall_syscall6(libc_wait4_trampoline_addr, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_wait4_trampoline_addr uintptr @@ -59,12 +80,19 @@ var libc_wait4_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := syscall_syscall(libc_accept_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_accept_trampoline_addr uintptr @@ -74,11 +102,17 @@ var libc_accept_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := syscall_syscall(libc_bind_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_bind_trampoline_addr uintptr @@ -88,11 +122,17 @@ var libc_bind_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := syscall_syscall(libc_connect_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_connect_trampoline_addr uintptr @@ -102,12 +142,19 @@ var libc_connect_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_socket_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_socket_trampoline_addr uintptr @@ -117,11 +164,17 @@ var libc_socket_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := syscall_syscall6(libc_getsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsockopt_trampoline_addr uintptr @@ -131,11 +184,17 @@ var libc_getsockopt_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := syscall_syscall6(libc_setsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setsockopt_trampoline_addr uintptr @@ -145,11 +204,17 @@ var libc_setsockopt_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getpeername_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpeername_trampoline_addr uintptr @@ -159,11 +224,17 @@ var libc_getpeername_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getsockname_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsockname_trampoline_addr uintptr @@ -173,11 +244,17 @@ var libc_getsockname_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { + _, _, e1 := syscall_syscall(libc_shutdown_trampoline_addr, uintptr(s), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_shutdown_trampoline_addr uintptr @@ -187,11 +264,17 @@ var libc_shutdown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := syscall_rawSyscall6(libc_socketpair_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_socketpair_trampoline_addr uintptr @@ -201,18 +284,31 @@ var libc_socketpair_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_recvfrom_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_recvfrom_trampoline_addr uintptr @@ -222,17 +318,29 @@ var libc_recvfrom_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall6(libc_sendto_trampoline_addr, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sendto_trampoline_addr uintptr @@ -242,12 +350,19 @@ var libc_sendto_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_recvmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_recvmsg_trampoline_addr uintptr @@ -257,12 +372,19 @@ var libc_recvmsg_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_sendmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sendmsg_trampoline_addr uintptr @@ -272,12 +394,19 @@ var libc_sendmsg_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_kevent_trampoline_addr, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kevent_trampoline_addr uintptr @@ -287,16 +416,27 @@ var libc_kevent_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_utimes_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_utimes_trampoline_addr uintptr @@ -306,11 +446,17 @@ var libc_utimes_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { + _, _, e1 := syscall_syscall(libc_futimes_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_futimes_trampoline_addr uintptr @@ -320,12 +466,19 @@ var libc_futimes_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_poll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_poll_trampoline_addr uintptr @@ -335,17 +488,29 @@ var libc_poll_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_madvise_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_madvise_trampoline_addr uintptr @@ -355,17 +520,29 @@ var libc_madvise_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_mlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mlock_trampoline_addr uintptr @@ -375,11 +552,17 @@ var libc_mlock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := syscall_syscall(libc_mlockall_trampoline_addr, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mlockall_trampoline_addr uintptr @@ -389,17 +572,29 @@ var libc_mlockall_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_mprotect_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mprotect_trampoline_addr uintptr @@ -409,17 +604,29 @@ var libc_mprotect_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_msync_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_msync_trampoline_addr uintptr @@ -429,17 +636,29 @@ var libc_msync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_munlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munlock_trampoline_addr uintptr @@ -449,11 +668,17 @@ var libc_munlock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := syscall_syscall(libc_munlockall_trampoline_addr, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munlockall_trampoline_addr uintptr @@ -463,11 +688,17 @@ var libc_munlockall_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_pipe2_trampoline_addr, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pipe2_trampoline_addr uintptr @@ -477,18 +708,31 @@ var libc_pipe2_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_getdents_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getdents_trampoline_addr uintptr @@ -498,18 +742,31 @@ var libc_getdents_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_getcwd_trampoline_addr, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getcwd_trampoline_addr uintptr @@ -519,8 +776,11 @@ var libc_getcwd_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getresuid(ruid *_C_int, euid *_C_int, suid *_C_int) { + syscall_rawSyscall(libc_getresuid_trampoline_addr, uintptr(unsafe.Pointer(ruid)), uintptr(unsafe.Pointer(euid)), uintptr(unsafe.Pointer(suid))) + return + } var libc_getresuid_trampoline_addr uintptr @@ -530,8 +790,11 @@ var libc_getresuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getresgid(rgid *_C_int, egid *_C_int, sgid *_C_int) { + syscall_rawSyscall(libc_getresgid_trampoline_addr, uintptr(unsafe.Pointer(rgid)), uintptr(unsafe.Pointer(egid)), uintptr(unsafe.Pointer(sgid))) + return + } var libc_getresgid_trampoline_addr uintptr @@ -541,11 +804,17 @@ var libc_getresgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ioctl_trampoline_addr uintptr @@ -555,27 +824,45 @@ var libc_ioctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall6(libc_sysctl_trampoline_addr, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sysctl_trampoline_addr uintptr @@ -585,12 +872,19 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fcntl_trampoline_addr uintptr @@ -600,23 +894,37 @@ var libc_fcntl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ppoll_trampoline_addr uintptr @@ -626,16 +934,27 @@ var libc_ppoll_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_access_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_access_trampoline_addr uintptr @@ -645,11 +964,17 @@ var libc_access_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { + _, _, e1 := syscall_syscall(libc_adjtime_trampoline_addr, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_adjtime_trampoline_addr uintptr @@ -659,16 +984,27 @@ var libc_adjtime_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chdir_trampoline_addr uintptr @@ -678,16 +1014,27 @@ var libc_chdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chflags_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chflags_trampoline_addr uintptr @@ -697,16 +1044,27 @@ var libc_chflags_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chmod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chmod_trampoline_addr uintptr @@ -716,16 +1074,27 @@ var libc_chmod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chown_trampoline_addr uintptr @@ -735,16 +1104,27 @@ var libc_chown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chroot_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chroot_trampoline_addr uintptr @@ -754,11 +1134,17 @@ var libc_chroot_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := syscall_syscall(libc_clock_gettime_trampoline_addr, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_clock_gettime_trampoline_addr uintptr @@ -768,11 +1154,17 @@ var libc_clock_gettime_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_close_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_close_trampoline_addr uintptr @@ -782,12 +1174,19 @@ var libc_close_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { + r0, _, e1 := syscall_syscall(libc_dup_trampoline_addr, uintptr(fd), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup_trampoline_addr uintptr @@ -797,11 +1196,17 @@ var libc_dup_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { + _, _, e1 := syscall_syscall(libc_dup2_trampoline_addr, uintptr(from), uintptr(to), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup2_trampoline_addr uintptr @@ -811,11 +1216,17 @@ var libc_dup2_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(from int, to int, flags int) (err error) { + _, _, e1 := syscall_syscall(libc_dup3_trampoline_addr, uintptr(from), uintptr(to), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup3_trampoline_addr uintptr @@ -825,8 +1236,11 @@ var libc_dup3_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + syscall_syscall(libc_exit_trampoline_addr, uintptr(code), 0, 0) + return + } var libc_exit_trampoline_addr uintptr @@ -836,16 +1250,27 @@ var libc_exit_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_faccessat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_faccessat_trampoline_addr uintptr @@ -855,11 +1280,17 @@ var libc_faccessat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_fchdir_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchdir_trampoline_addr uintptr @@ -869,11 +1300,17 @@ var libc_fchdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { + _, _, e1 := syscall_syscall(libc_fchflags_trampoline_addr, uintptr(fd), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchflags_trampoline_addr uintptr @@ -883,11 +1320,17 @@ var libc_fchflags_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := syscall_syscall(libc_fchmod_trampoline_addr, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchmod_trampoline_addr uintptr @@ -897,16 +1340,27 @@ var libc_fchmod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fchmodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchmodat_trampoline_addr uintptr @@ -916,11 +1370,17 @@ var libc_fchmodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := syscall_syscall(libc_fchown_trampoline_addr, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchown_trampoline_addr uintptr @@ -930,16 +1390,27 @@ var libc_fchown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fchownat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchownat_trampoline_addr uintptr @@ -949,11 +1420,17 @@ var libc_fchownat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := syscall_syscall(libc_flock_trampoline_addr, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_flock_trampoline_addr uintptr @@ -963,12 +1440,19 @@ var libc_flock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { + r0, _, e1 := syscall_syscall(libc_fpathconf_trampoline_addr, uintptr(fd), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fpathconf_trampoline_addr uintptr @@ -978,11 +1462,17 @@ var libc_fpathconf_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := syscall_syscall(libc_fstat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstat_trampoline_addr uintptr @@ -992,16 +1482,27 @@ var libc_fstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fstatat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstatat_trampoline_addr uintptr @@ -1011,11 +1512,17 @@ var libc_fstatat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { + _, _, e1 := syscall_syscall(libc_fstatfs_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstatfs_trampoline_addr uintptr @@ -1025,11 +1532,17 @@ var libc_fstatfs_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_fsync_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fsync_trampoline_addr uintptr @@ -1039,11 +1552,17 @@ var libc_fsync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := syscall_syscall(libc_ftruncate_trampoline_addr, uintptr(fd), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ftruncate_trampoline_addr uintptr @@ -1053,9 +1572,13 @@ var libc_ftruncate_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _, _ := syscall_rawSyscall(libc_getegid_trampoline_addr, 0, 0, 0) + egid = int(r0) + return + } var libc_getegid_trampoline_addr uintptr @@ -1065,9 +1588,13 @@ var libc_getegid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { + r0, _, _ := syscall_rawSyscall(libc_geteuid_trampoline_addr, 0, 0, 0) + uid = int(r0) + return + } var libc_geteuid_trampoline_addr uintptr @@ -1077,9 +1604,13 @@ var libc_geteuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := syscall_rawSyscall(libc_getgid_trampoline_addr, 0, 0, 0) + gid = int(r0) + return + } var libc_getgid_trampoline_addr uintptr @@ -1089,12 +1620,19 @@ var libc_getgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getpgid_trampoline_addr, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpgid_trampoline_addr uintptr @@ -1104,9 +1642,13 @@ var libc_getpgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { + r0, _, _ := syscall_rawSyscall(libc_getpgrp_trampoline_addr, 0, 0, 0) + pgrp = int(r0) + return + } var libc_getpgrp_trampoline_addr uintptr @@ -1116,9 +1658,13 @@ var libc_getpgrp_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := syscall_rawSyscall(libc_getpid_trampoline_addr, 0, 0, 0) + pid = int(r0) + return + } var libc_getpid_trampoline_addr uintptr @@ -1128,9 +1674,13 @@ var libc_getpid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _, _ := syscall_rawSyscall(libc_getppid_trampoline_addr, 0, 0, 0) + ppid = int(r0) + return + } var libc_getppid_trampoline_addr uintptr @@ -1140,12 +1690,19 @@ var libc_getppid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := syscall_syscall(libc_getpriority_trampoline_addr, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpriority_trampoline_addr uintptr @@ -1155,11 +1712,17 @@ var libc_getpriority_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getrlimit_trampoline_addr, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrlimit_trampoline_addr uintptr @@ -1169,12 +1732,19 @@ var libc_getrlimit_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrtable() (rtable int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getrtable_trampoline_addr, 0, 0, 0) + rtable = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrtable_trampoline_addr uintptr @@ -1184,11 +1754,17 @@ var libc_getrtable_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getrusage_trampoline_addr, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrusage_trampoline_addr uintptr @@ -1198,12 +1774,19 @@ var libc_getrusage_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getsid_trampoline_addr, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsid_trampoline_addr uintptr @@ -1213,11 +1796,17 @@ var libc_getsid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(libc_gettimeofday_trampoline_addr, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_gettimeofday_trampoline_addr uintptr @@ -1227,9 +1816,13 @@ var libc_gettimeofday_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := syscall_rawSyscall(libc_getuid_trampoline_addr, 0, 0, 0) + uid = int(r0) + return + } var libc_getuid_trampoline_addr uintptr @@ -1239,9 +1832,13 @@ var libc_getuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { + r0, _, _ := syscall_syscall(libc_issetugid_trampoline_addr, 0, 0, 0) + tainted = bool(r0 != 0) + return + } var libc_issetugid_trampoline_addr uintptr @@ -1251,11 +1848,17 @@ var libc_issetugid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { + _, _, e1 := syscall_syscall(libc_kill_trampoline_addr, uintptr(pid), uintptr(signum), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kill_trampoline_addr uintptr @@ -1265,12 +1868,19 @@ var libc_kill_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { + r0, _, e1 := syscall_syscall(libc_kqueue_trampoline_addr, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kqueue_trampoline_addr uintptr @@ -1280,16 +1890,27 @@ var libc_kqueue_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_lchown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lchown_trampoline_addr uintptr @@ -1299,21 +1920,37 @@ var libc_lchown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_link_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_link_trampoline_addr uintptr @@ -1323,21 +1960,37 @@ var libc_link_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_linkat_trampoline_addr, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_linkat_trampoline_addr uintptr @@ -1347,11 +2000,17 @@ var libc_linkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { + _, _, e1 := syscall_syscall(libc_listen_trampoline_addr, uintptr(s), uintptr(backlog), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_listen_trampoline_addr uintptr @@ -1361,16 +2020,27 @@ var libc_listen_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_lstat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lstat_trampoline_addr uintptr @@ -1380,16 +2050,27 @@ var libc_lstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkdir_trampoline_addr uintptr @@ -1399,16 +2080,27 @@ var libc_mkdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkdirat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkdirat_trampoline_addr uintptr @@ -1418,16 +2110,27 @@ var libc_mkdirat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkfifo_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkfifo_trampoline_addr uintptr @@ -1437,16 +2140,27 @@ var libc_mkfifo_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifoat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkfifoat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkfifoat_trampoline_addr uintptr @@ -1456,16 +2170,27 @@ var libc_mkfifoat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mknod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mknod_trampoline_addr uintptr @@ -1475,16 +2200,27 @@ var libc_mknod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mknodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mknodat_trampoline_addr uintptr @@ -1494,11 +2230,17 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_nanosleep_trampoline_addr uintptr @@ -1508,17 +2250,29 @@ var libc_nanosleep_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall(libc_open_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_open_trampoline_addr uintptr @@ -1528,17 +2282,29 @@ var libc_open_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall6(libc_openat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_openat_trampoline_addr uintptr @@ -1548,17 +2314,29 @@ var libc_openat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall(libc_pathconf_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pathconf_trampoline_addr uintptr @@ -1568,18 +2346,31 @@ var libc_pathconf_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_pread_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pread_trampoline_addr uintptr @@ -1589,18 +2380,31 @@ var libc_pread_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_pwrite_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pwrite_trampoline_addr uintptr @@ -1610,18 +2414,31 @@ var libc_pwrite_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_read_trampoline_addr uintptr @@ -1631,23 +2448,41 @@ var libc_read_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_readlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_readlink_trampoline_addr uintptr @@ -1657,23 +2492,41 @@ var libc_readlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_readlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_readlinkat_trampoline_addr uintptr @@ -1683,21 +2536,37 @@ var libc_readlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_rename_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_rename_trampoline_addr uintptr @@ -1707,21 +2576,37 @@ var libc_rename_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_renameat_trampoline_addr, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_renameat_trampoline_addr uintptr @@ -1731,16 +2616,27 @@ var libc_renameat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_revoke_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_revoke_trampoline_addr uintptr @@ -1750,16 +2646,27 @@ var libc_revoke_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_rmdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_rmdir_trampoline_addr uintptr @@ -1769,12 +2676,19 @@ var libc_rmdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, _, e1 := syscall_syscall(libc_lseek_trampoline_addr, uintptr(fd), uintptr(offset), uintptr(whence)) + newoffset = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lseek_trampoline_addr uintptr @@ -1784,12 +2698,19 @@ var libc_lseek_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_select_trampoline_addr, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_select_trampoline_addr uintptr @@ -1799,11 +2720,17 @@ var libc_select_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setegid_trampoline_addr, uintptr(egid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setegid_trampoline_addr uintptr @@ -1813,11 +2740,17 @@ var libc_setegid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_seteuid_trampoline_addr, uintptr(euid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_seteuid_trampoline_addr uintptr @@ -1827,11 +2760,17 @@ var libc_seteuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setgid_trampoline_addr, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setgid_trampoline_addr uintptr @@ -1841,16 +2780,27 @@ var libc_setgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(name) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_setlogin_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setlogin_trampoline_addr uintptr @@ -1860,11 +2810,17 @@ var libc_setlogin_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setpgid_trampoline_addr, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setpgid_trampoline_addr uintptr @@ -1874,11 +2830,17 @@ var libc_setpgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := syscall_syscall(libc_setpriority_trampoline_addr, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setpriority_trampoline_addr uintptr @@ -1888,11 +2850,17 @@ var libc_setpriority_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setregid_trampoline_addr, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setregid_trampoline_addr uintptr @@ -1902,11 +2870,17 @@ var libc_setregid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setreuid_trampoline_addr, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setreuid_trampoline_addr uintptr @@ -1916,11 +2890,17 @@ var libc_setreuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setresgid_trampoline_addr, uintptr(rgid), uintptr(egid), uintptr(sgid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setresgid_trampoline_addr uintptr @@ -1930,11 +2910,17 @@ var libc_setresgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setresuid_trampoline_addr, uintptr(ruid), uintptr(euid), uintptr(suid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setresuid_trampoline_addr uintptr @@ -1944,11 +2930,17 @@ var libc_setresuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrtable(rtable int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setrtable_trampoline_addr, uintptr(rtable), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setrtable_trampoline_addr uintptr @@ -1958,12 +2950,19 @@ var libc_setrtable_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_setsid_trampoline_addr, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setsid_trampoline_addr uintptr @@ -1973,11 +2972,17 @@ var libc_setsid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(libc_settimeofday_trampoline_addr, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_settimeofday_trampoline_addr uintptr @@ -1987,11 +2992,17 @@ var libc_settimeofday_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setuid_trampoline_addr, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setuid_trampoline_addr uintptr @@ -2001,16 +3012,27 @@ var libc_setuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_stat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_stat_trampoline_addr uintptr @@ -2020,16 +3042,27 @@ var libc_stat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_statfs_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_statfs_trampoline_addr uintptr @@ -2039,21 +3072,37 @@ var libc_statfs_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_symlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_symlink_trampoline_addr uintptr @@ -2063,21 +3112,37 @@ var libc_symlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_symlinkat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_symlinkat_trampoline_addr uintptr @@ -2087,11 +3152,17 @@ var libc_symlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { + _, _, e1 := syscall_syscall(libc_sync_trampoline_addr, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sync_trampoline_addr uintptr @@ -2101,16 +3172,27 @@ var libc_sync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_truncate_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_truncate_trampoline_addr uintptr @@ -2120,9 +3202,13 @@ var libc_truncate_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { + r0, _, _ := syscall_syscall(libc_umask_trampoline_addr, uintptr(newmask), 0, 0) + oldmask = int(r0) + return + } var libc_umask_trampoline_addr uintptr @@ -2132,16 +3218,27 @@ var libc_umask_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unlink_trampoline_addr uintptr @@ -2151,16 +3248,27 @@ var libc_unlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unlinkat_trampoline_addr uintptr @@ -2170,16 +3278,27 @@ var libc_unlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unmount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unmount_trampoline_addr uintptr @@ -2189,18 +3308,31 @@ var libc_unmount_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_write_trampoline_addr uintptr @@ -2210,12 +3342,19 @@ var libc_write_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + r0, _, e1 := syscall_syscall6(libc_mmap_trampoline_addr, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mmap_trampoline_addr uintptr @@ -2225,11 +3364,17 @@ var libc_mmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_munmap_trampoline_addr, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munmap_trampoline_addr uintptr @@ -2239,12 +3384,19 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getfsstat(stat *Statfs_t, bufsize uintptr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_getfsstat_trampoline_addr, uintptr(unsafe.Pointer(stat)), uintptr(bufsize), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getfsstat_trampoline_addr uintptr @@ -2254,16 +3406,27 @@ var libc_getfsstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_utimensat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_utimensat_trampoline_addr uintptr @@ -2273,11 +3436,17 @@ var libc_utimensat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pledge(promises *byte, execpromises *byte) (err error) { + _, _, e1 := syscall_syscall(libc_pledge_trampoline_addr, uintptr(unsafe.Pointer(promises)), uintptr(unsafe.Pointer(execpromises)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pledge_trampoline_addr uintptr @@ -2287,11 +3456,17 @@ var libc_pledge_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func unveil(path *byte, flags *byte) (err error) { + _, _, e1 := syscall_syscall(libc_unveil_trampoline_addr, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(flags)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unveil_trampoline_addr uintptr diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.go index 0083135..218d973 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.go @@ -1,4 +1,5 @@ // go run mksyscall.go -openbsd -libc -tags openbsd,ppc64 syscall_bsd.go syscall_openbsd.go syscall_openbsd_ppc64.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build openbsd && ppc64 @@ -15,12 +16,19 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getgroups_trampoline_addr uintptr @@ -30,11 +38,17 @@ var libc_getgroups_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setgroups_trampoline_addr uintptr @@ -44,12 +58,19 @@ var libc_setgroups_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := syscall_syscall6(libc_wait4_trampoline_addr, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_wait4_trampoline_addr uintptr @@ -59,12 +80,19 @@ var libc_wait4_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := syscall_syscall(libc_accept_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_accept_trampoline_addr uintptr @@ -74,11 +102,17 @@ var libc_accept_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := syscall_syscall(libc_bind_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_bind_trampoline_addr uintptr @@ -88,11 +122,17 @@ var libc_bind_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := syscall_syscall(libc_connect_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_connect_trampoline_addr uintptr @@ -102,12 +142,19 @@ var libc_connect_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_socket_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_socket_trampoline_addr uintptr @@ -117,11 +164,17 @@ var libc_socket_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := syscall_syscall6(libc_getsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsockopt_trampoline_addr uintptr @@ -131,11 +184,17 @@ var libc_getsockopt_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := syscall_syscall6(libc_setsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setsockopt_trampoline_addr uintptr @@ -145,11 +204,17 @@ var libc_setsockopt_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getpeername_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpeername_trampoline_addr uintptr @@ -159,11 +224,17 @@ var libc_getpeername_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getsockname_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsockname_trampoline_addr uintptr @@ -173,11 +244,17 @@ var libc_getsockname_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { + _, _, e1 := syscall_syscall(libc_shutdown_trampoline_addr, uintptr(s), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_shutdown_trampoline_addr uintptr @@ -187,11 +264,17 @@ var libc_shutdown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := syscall_rawSyscall6(libc_socketpair_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_socketpair_trampoline_addr uintptr @@ -201,18 +284,31 @@ var libc_socketpair_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_recvfrom_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_recvfrom_trampoline_addr uintptr @@ -222,17 +318,29 @@ var libc_recvfrom_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall6(libc_sendto_trampoline_addr, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sendto_trampoline_addr uintptr @@ -242,12 +350,19 @@ var libc_sendto_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_recvmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_recvmsg_trampoline_addr uintptr @@ -257,12 +372,19 @@ var libc_recvmsg_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_sendmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sendmsg_trampoline_addr uintptr @@ -272,12 +394,19 @@ var libc_sendmsg_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_kevent_trampoline_addr, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kevent_trampoline_addr uintptr @@ -287,16 +416,27 @@ var libc_kevent_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_utimes_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_utimes_trampoline_addr uintptr @@ -306,11 +446,17 @@ var libc_utimes_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { + _, _, e1 := syscall_syscall(libc_futimes_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_futimes_trampoline_addr uintptr @@ -320,12 +466,19 @@ var libc_futimes_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_poll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_poll_trampoline_addr uintptr @@ -335,17 +488,29 @@ var libc_poll_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_madvise_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_madvise_trampoline_addr uintptr @@ -355,17 +520,29 @@ var libc_madvise_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_mlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mlock_trampoline_addr uintptr @@ -375,11 +552,17 @@ var libc_mlock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := syscall_syscall(libc_mlockall_trampoline_addr, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mlockall_trampoline_addr uintptr @@ -389,17 +572,29 @@ var libc_mlockall_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_mprotect_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mprotect_trampoline_addr uintptr @@ -409,17 +604,29 @@ var libc_mprotect_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_msync_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_msync_trampoline_addr uintptr @@ -429,17 +636,29 @@ var libc_msync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_munlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munlock_trampoline_addr uintptr @@ -449,11 +668,17 @@ var libc_munlock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := syscall_syscall(libc_munlockall_trampoline_addr, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munlockall_trampoline_addr uintptr @@ -463,11 +688,17 @@ var libc_munlockall_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_pipe2_trampoline_addr, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pipe2_trampoline_addr uintptr @@ -477,18 +708,31 @@ var libc_pipe2_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_getdents_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getdents_trampoline_addr uintptr @@ -498,18 +742,31 @@ var libc_getdents_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_getcwd_trampoline_addr, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getcwd_trampoline_addr uintptr @@ -519,8 +776,11 @@ var libc_getcwd_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getresuid(ruid *_C_int, euid *_C_int, suid *_C_int) { + syscall_rawSyscall(libc_getresuid_trampoline_addr, uintptr(unsafe.Pointer(ruid)), uintptr(unsafe.Pointer(euid)), uintptr(unsafe.Pointer(suid))) + return + } var libc_getresuid_trampoline_addr uintptr @@ -530,8 +790,11 @@ var libc_getresuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getresgid(rgid *_C_int, egid *_C_int, sgid *_C_int) { + syscall_rawSyscall(libc_getresgid_trampoline_addr, uintptr(unsafe.Pointer(rgid)), uintptr(unsafe.Pointer(egid)), uintptr(unsafe.Pointer(sgid))) + return + } var libc_getresgid_trampoline_addr uintptr @@ -541,11 +804,17 @@ var libc_getresgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ioctl_trampoline_addr uintptr @@ -555,27 +824,45 @@ var libc_ioctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall6(libc_sysctl_trampoline_addr, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sysctl_trampoline_addr uintptr @@ -585,12 +872,19 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fcntl_trampoline_addr uintptr @@ -600,23 +894,37 @@ var libc_fcntl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ppoll_trampoline_addr uintptr @@ -626,16 +934,27 @@ var libc_ppoll_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_access_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_access_trampoline_addr uintptr @@ -645,11 +964,17 @@ var libc_access_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { + _, _, e1 := syscall_syscall(libc_adjtime_trampoline_addr, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_adjtime_trampoline_addr uintptr @@ -659,16 +984,27 @@ var libc_adjtime_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chdir_trampoline_addr uintptr @@ -678,16 +1014,27 @@ var libc_chdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chflags_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chflags_trampoline_addr uintptr @@ -697,16 +1044,27 @@ var libc_chflags_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chmod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chmod_trampoline_addr uintptr @@ -716,16 +1074,27 @@ var libc_chmod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chown_trampoline_addr uintptr @@ -735,16 +1104,27 @@ var libc_chown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chroot_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chroot_trampoline_addr uintptr @@ -754,11 +1134,17 @@ var libc_chroot_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := syscall_syscall(libc_clock_gettime_trampoline_addr, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_clock_gettime_trampoline_addr uintptr @@ -768,11 +1154,17 @@ var libc_clock_gettime_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_close_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_close_trampoline_addr uintptr @@ -782,12 +1174,19 @@ var libc_close_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { + r0, _, e1 := syscall_syscall(libc_dup_trampoline_addr, uintptr(fd), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup_trampoline_addr uintptr @@ -797,11 +1196,17 @@ var libc_dup_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { + _, _, e1 := syscall_syscall(libc_dup2_trampoline_addr, uintptr(from), uintptr(to), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup2_trampoline_addr uintptr @@ -811,11 +1216,17 @@ var libc_dup2_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(from int, to int, flags int) (err error) { + _, _, e1 := syscall_syscall(libc_dup3_trampoline_addr, uintptr(from), uintptr(to), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup3_trampoline_addr uintptr @@ -825,8 +1236,11 @@ var libc_dup3_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + syscall_syscall(libc_exit_trampoline_addr, uintptr(code), 0, 0) + return + } var libc_exit_trampoline_addr uintptr @@ -836,16 +1250,27 @@ var libc_exit_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_faccessat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_faccessat_trampoline_addr uintptr @@ -855,11 +1280,17 @@ var libc_faccessat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_fchdir_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchdir_trampoline_addr uintptr @@ -869,11 +1300,17 @@ var libc_fchdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { + _, _, e1 := syscall_syscall(libc_fchflags_trampoline_addr, uintptr(fd), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchflags_trampoline_addr uintptr @@ -883,11 +1320,17 @@ var libc_fchflags_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := syscall_syscall(libc_fchmod_trampoline_addr, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchmod_trampoline_addr uintptr @@ -897,16 +1340,27 @@ var libc_fchmod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fchmodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchmodat_trampoline_addr uintptr @@ -916,11 +1370,17 @@ var libc_fchmodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := syscall_syscall(libc_fchown_trampoline_addr, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchown_trampoline_addr uintptr @@ -930,16 +1390,27 @@ var libc_fchown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fchownat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchownat_trampoline_addr uintptr @@ -949,11 +1420,17 @@ var libc_fchownat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := syscall_syscall(libc_flock_trampoline_addr, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_flock_trampoline_addr uintptr @@ -963,12 +1440,19 @@ var libc_flock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { + r0, _, e1 := syscall_syscall(libc_fpathconf_trampoline_addr, uintptr(fd), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fpathconf_trampoline_addr uintptr @@ -978,11 +1462,17 @@ var libc_fpathconf_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := syscall_syscall(libc_fstat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstat_trampoline_addr uintptr @@ -992,16 +1482,27 @@ var libc_fstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fstatat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstatat_trampoline_addr uintptr @@ -1011,11 +1512,17 @@ var libc_fstatat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { + _, _, e1 := syscall_syscall(libc_fstatfs_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstatfs_trampoline_addr uintptr @@ -1025,11 +1532,17 @@ var libc_fstatfs_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_fsync_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fsync_trampoline_addr uintptr @@ -1039,11 +1552,17 @@ var libc_fsync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := syscall_syscall(libc_ftruncate_trampoline_addr, uintptr(fd), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ftruncate_trampoline_addr uintptr @@ -1053,9 +1572,13 @@ var libc_ftruncate_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _, _ := syscall_rawSyscall(libc_getegid_trampoline_addr, 0, 0, 0) + egid = int(r0) + return + } var libc_getegid_trampoline_addr uintptr @@ -1065,9 +1588,13 @@ var libc_getegid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { + r0, _, _ := syscall_rawSyscall(libc_geteuid_trampoline_addr, 0, 0, 0) + uid = int(r0) + return + } var libc_geteuid_trampoline_addr uintptr @@ -1077,9 +1604,13 @@ var libc_geteuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := syscall_rawSyscall(libc_getgid_trampoline_addr, 0, 0, 0) + gid = int(r0) + return + } var libc_getgid_trampoline_addr uintptr @@ -1089,12 +1620,19 @@ var libc_getgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getpgid_trampoline_addr, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpgid_trampoline_addr uintptr @@ -1104,9 +1642,13 @@ var libc_getpgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { + r0, _, _ := syscall_rawSyscall(libc_getpgrp_trampoline_addr, 0, 0, 0) + pgrp = int(r0) + return + } var libc_getpgrp_trampoline_addr uintptr @@ -1116,9 +1658,13 @@ var libc_getpgrp_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := syscall_rawSyscall(libc_getpid_trampoline_addr, 0, 0, 0) + pid = int(r0) + return + } var libc_getpid_trampoline_addr uintptr @@ -1128,9 +1674,13 @@ var libc_getpid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _, _ := syscall_rawSyscall(libc_getppid_trampoline_addr, 0, 0, 0) + ppid = int(r0) + return + } var libc_getppid_trampoline_addr uintptr @@ -1140,12 +1690,19 @@ var libc_getppid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := syscall_syscall(libc_getpriority_trampoline_addr, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpriority_trampoline_addr uintptr @@ -1155,11 +1712,17 @@ var libc_getpriority_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getrlimit_trampoline_addr, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrlimit_trampoline_addr uintptr @@ -1169,12 +1732,19 @@ var libc_getrlimit_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrtable() (rtable int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getrtable_trampoline_addr, 0, 0, 0) + rtable = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrtable_trampoline_addr uintptr @@ -1184,11 +1754,17 @@ var libc_getrtable_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getrusage_trampoline_addr, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrusage_trampoline_addr uintptr @@ -1198,12 +1774,19 @@ var libc_getrusage_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getsid_trampoline_addr, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsid_trampoline_addr uintptr @@ -1213,11 +1796,17 @@ var libc_getsid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(libc_gettimeofday_trampoline_addr, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_gettimeofday_trampoline_addr uintptr @@ -1227,9 +1816,13 @@ var libc_gettimeofday_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := syscall_rawSyscall(libc_getuid_trampoline_addr, 0, 0, 0) + uid = int(r0) + return + } var libc_getuid_trampoline_addr uintptr @@ -1239,9 +1832,13 @@ var libc_getuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { + r0, _, _ := syscall_syscall(libc_issetugid_trampoline_addr, 0, 0, 0) + tainted = bool(r0 != 0) + return + } var libc_issetugid_trampoline_addr uintptr @@ -1251,11 +1848,17 @@ var libc_issetugid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { + _, _, e1 := syscall_syscall(libc_kill_trampoline_addr, uintptr(pid), uintptr(signum), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kill_trampoline_addr uintptr @@ -1265,12 +1868,19 @@ var libc_kill_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { + r0, _, e1 := syscall_syscall(libc_kqueue_trampoline_addr, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kqueue_trampoline_addr uintptr @@ -1280,16 +1890,27 @@ var libc_kqueue_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_lchown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lchown_trampoline_addr uintptr @@ -1299,21 +1920,37 @@ var libc_lchown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_link_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_link_trampoline_addr uintptr @@ -1323,21 +1960,37 @@ var libc_link_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_linkat_trampoline_addr, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_linkat_trampoline_addr uintptr @@ -1347,11 +2000,17 @@ var libc_linkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { + _, _, e1 := syscall_syscall(libc_listen_trampoline_addr, uintptr(s), uintptr(backlog), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_listen_trampoline_addr uintptr @@ -1361,16 +2020,27 @@ var libc_listen_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_lstat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lstat_trampoline_addr uintptr @@ -1380,16 +2050,27 @@ var libc_lstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkdir_trampoline_addr uintptr @@ -1399,16 +2080,27 @@ var libc_mkdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkdirat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkdirat_trampoline_addr uintptr @@ -1418,16 +2110,27 @@ var libc_mkdirat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkfifo_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkfifo_trampoline_addr uintptr @@ -1437,16 +2140,27 @@ var libc_mkfifo_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifoat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkfifoat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkfifoat_trampoline_addr uintptr @@ -1456,16 +2170,27 @@ var libc_mkfifoat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mknod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mknod_trampoline_addr uintptr @@ -1475,16 +2200,27 @@ var libc_mknod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mknodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mknodat_trampoline_addr uintptr @@ -1494,11 +2230,17 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_nanosleep_trampoline_addr uintptr @@ -1508,17 +2250,29 @@ var libc_nanosleep_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall(libc_open_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_open_trampoline_addr uintptr @@ -1528,17 +2282,29 @@ var libc_open_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall6(libc_openat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_openat_trampoline_addr uintptr @@ -1548,17 +2314,29 @@ var libc_openat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall(libc_pathconf_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pathconf_trampoline_addr uintptr @@ -1568,18 +2346,31 @@ var libc_pathconf_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_pread_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pread_trampoline_addr uintptr @@ -1589,18 +2380,31 @@ var libc_pread_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_pwrite_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pwrite_trampoline_addr uintptr @@ -1610,18 +2414,31 @@ var libc_pwrite_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_read_trampoline_addr uintptr @@ -1631,23 +2448,41 @@ var libc_read_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_readlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_readlink_trampoline_addr uintptr @@ -1657,23 +2492,41 @@ var libc_readlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_readlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_readlinkat_trampoline_addr uintptr @@ -1683,21 +2536,37 @@ var libc_readlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_rename_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_rename_trampoline_addr uintptr @@ -1707,21 +2576,37 @@ var libc_rename_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_renameat_trampoline_addr, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_renameat_trampoline_addr uintptr @@ -1731,16 +2616,27 @@ var libc_renameat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_revoke_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_revoke_trampoline_addr uintptr @@ -1750,16 +2646,27 @@ var libc_revoke_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_rmdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_rmdir_trampoline_addr uintptr @@ -1769,12 +2676,19 @@ var libc_rmdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, _, e1 := syscall_syscall(libc_lseek_trampoline_addr, uintptr(fd), uintptr(offset), uintptr(whence)) + newoffset = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lseek_trampoline_addr uintptr @@ -1784,12 +2698,19 @@ var libc_lseek_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_select_trampoline_addr, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_select_trampoline_addr uintptr @@ -1799,11 +2720,17 @@ var libc_select_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setegid_trampoline_addr, uintptr(egid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setegid_trampoline_addr uintptr @@ -1813,11 +2740,17 @@ var libc_setegid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_seteuid_trampoline_addr, uintptr(euid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_seteuid_trampoline_addr uintptr @@ -1827,11 +2760,17 @@ var libc_seteuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setgid_trampoline_addr, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setgid_trampoline_addr uintptr @@ -1841,16 +2780,27 @@ var libc_setgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(name) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_setlogin_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setlogin_trampoline_addr uintptr @@ -1860,11 +2810,17 @@ var libc_setlogin_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setpgid_trampoline_addr, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setpgid_trampoline_addr uintptr @@ -1874,11 +2830,17 @@ var libc_setpgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := syscall_syscall(libc_setpriority_trampoline_addr, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setpriority_trampoline_addr uintptr @@ -1888,11 +2850,17 @@ var libc_setpriority_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setregid_trampoline_addr, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setregid_trampoline_addr uintptr @@ -1902,11 +2870,17 @@ var libc_setregid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setreuid_trampoline_addr, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setreuid_trampoline_addr uintptr @@ -1916,11 +2890,17 @@ var libc_setreuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setresgid_trampoline_addr, uintptr(rgid), uintptr(egid), uintptr(sgid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setresgid_trampoline_addr uintptr @@ -1930,11 +2910,17 @@ var libc_setresgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setresuid_trampoline_addr, uintptr(ruid), uintptr(euid), uintptr(suid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setresuid_trampoline_addr uintptr @@ -1944,11 +2930,17 @@ var libc_setresuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrtable(rtable int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setrtable_trampoline_addr, uintptr(rtable), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setrtable_trampoline_addr uintptr @@ -1958,12 +2950,19 @@ var libc_setrtable_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_setsid_trampoline_addr, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setsid_trampoline_addr uintptr @@ -1973,11 +2972,17 @@ var libc_setsid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(libc_settimeofday_trampoline_addr, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_settimeofday_trampoline_addr uintptr @@ -1987,11 +2992,17 @@ var libc_settimeofday_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setuid_trampoline_addr, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setuid_trampoline_addr uintptr @@ -2001,16 +3012,27 @@ var libc_setuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_stat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_stat_trampoline_addr uintptr @@ -2020,16 +3042,27 @@ var libc_stat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_statfs_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_statfs_trampoline_addr uintptr @@ -2039,21 +3072,37 @@ var libc_statfs_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_symlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_symlink_trampoline_addr uintptr @@ -2063,21 +3112,37 @@ var libc_symlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_symlinkat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_symlinkat_trampoline_addr uintptr @@ -2087,11 +3152,17 @@ var libc_symlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { + _, _, e1 := syscall_syscall(libc_sync_trampoline_addr, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sync_trampoline_addr uintptr @@ -2101,16 +3172,27 @@ var libc_sync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_truncate_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_truncate_trampoline_addr uintptr @@ -2120,9 +3202,13 @@ var libc_truncate_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { + r0, _, _ := syscall_syscall(libc_umask_trampoline_addr, uintptr(newmask), 0, 0) + oldmask = int(r0) + return + } var libc_umask_trampoline_addr uintptr @@ -2132,16 +3218,27 @@ var libc_umask_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unlink_trampoline_addr uintptr @@ -2151,16 +3248,27 @@ var libc_unlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unlinkat_trampoline_addr uintptr @@ -2170,16 +3278,27 @@ var libc_unlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unmount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unmount_trampoline_addr uintptr @@ -2189,18 +3308,31 @@ var libc_unmount_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_write_trampoline_addr uintptr @@ -2210,12 +3342,19 @@ var libc_write_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + r0, _, e1 := syscall_syscall6(libc_mmap_trampoline_addr, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mmap_trampoline_addr uintptr @@ -2225,11 +3364,17 @@ var libc_mmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_munmap_trampoline_addr, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munmap_trampoline_addr uintptr @@ -2239,12 +3384,19 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getfsstat(stat *Statfs_t, bufsize uintptr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_getfsstat_trampoline_addr, uintptr(unsafe.Pointer(stat)), uintptr(bufsize), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getfsstat_trampoline_addr uintptr @@ -2254,16 +3406,27 @@ var libc_getfsstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_utimensat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_utimensat_trampoline_addr uintptr @@ -2273,11 +3436,17 @@ var libc_utimensat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pledge(promises *byte, execpromises *byte) (err error) { + _, _, e1 := syscall_syscall(libc_pledge_trampoline_addr, uintptr(unsafe.Pointer(promises)), uintptr(unsafe.Pointer(execpromises)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pledge_trampoline_addr uintptr @@ -2287,11 +3456,17 @@ var libc_pledge_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func unveil(path *byte, flags *byte) (err error) { + _, _, e1 := syscall_syscall(libc_unveil_trampoline_addr, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(flags)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unveil_trampoline_addr uintptr diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.go index 79029ed..b7f50d8 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.go @@ -1,4 +1,5 @@ // go run mksyscall.go -openbsd -libc -tags openbsd,riscv64 syscall_bsd.go syscall_openbsd.go syscall_openbsd_riscv64.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build openbsd && riscv64 @@ -15,12 +16,19 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getgroups_trampoline_addr uintptr @@ -30,11 +38,17 @@ var libc_getgroups_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setgroups_trampoline_addr uintptr @@ -44,12 +58,19 @@ var libc_setgroups_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { + r0, _, e1 := syscall_syscall6(libc_wait4_trampoline_addr, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_wait4_trampoline_addr uintptr @@ -59,12 +80,19 @@ var libc_wait4_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := syscall_syscall(libc_accept_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_accept_trampoline_addr uintptr @@ -74,11 +102,17 @@ var libc_accept_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := syscall_syscall(libc_bind_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_bind_trampoline_addr uintptr @@ -88,11 +122,17 @@ var libc_bind_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := syscall_syscall(libc_connect_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_connect_trampoline_addr uintptr @@ -102,12 +142,19 @@ var libc_connect_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_socket_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_socket_trampoline_addr uintptr @@ -117,11 +164,17 @@ var libc_socket_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := syscall_syscall6(libc_getsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsockopt_trampoline_addr uintptr @@ -131,11 +184,17 @@ var libc_getsockopt_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := syscall_syscall6(libc_setsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setsockopt_trampoline_addr uintptr @@ -145,11 +204,17 @@ var libc_setsockopt_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getpeername_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpeername_trampoline_addr uintptr @@ -159,11 +224,17 @@ var libc_getpeername_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getsockname_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsockname_trampoline_addr uintptr @@ -173,11 +244,17 @@ var libc_getsockname_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { + _, _, e1 := syscall_syscall(libc_shutdown_trampoline_addr, uintptr(s), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_shutdown_trampoline_addr uintptr @@ -187,11 +264,17 @@ var libc_shutdown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := syscall_rawSyscall6(libc_socketpair_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_socketpair_trampoline_addr uintptr @@ -201,18 +284,31 @@ var libc_socketpair_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_recvfrom_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_recvfrom_trampoline_addr uintptr @@ -222,17 +318,29 @@ var libc_recvfrom_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall6(libc_sendto_trampoline_addr, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sendto_trampoline_addr uintptr @@ -242,12 +350,19 @@ var libc_sendto_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_recvmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_recvmsg_trampoline_addr uintptr @@ -257,12 +372,19 @@ var libc_recvmsg_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_sendmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sendmsg_trampoline_addr uintptr @@ -272,12 +394,19 @@ var libc_sendmsg_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_kevent_trampoline_addr, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kevent_trampoline_addr uintptr @@ -287,16 +416,27 @@ var libc_kevent_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_utimes_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_utimes_trampoline_addr uintptr @@ -306,11 +446,17 @@ var libc_utimes_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { + _, _, e1 := syscall_syscall(libc_futimes_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_futimes_trampoline_addr uintptr @@ -320,12 +466,19 @@ var libc_futimes_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_poll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_poll_trampoline_addr uintptr @@ -335,17 +488,29 @@ var libc_poll_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_madvise_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_madvise_trampoline_addr uintptr @@ -355,17 +520,29 @@ var libc_madvise_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_mlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mlock_trampoline_addr uintptr @@ -375,11 +552,17 @@ var libc_mlock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := syscall_syscall(libc_mlockall_trampoline_addr, uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mlockall_trampoline_addr uintptr @@ -389,17 +572,29 @@ var libc_mlockall_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_mprotect_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mprotect_trampoline_addr uintptr @@ -409,17 +604,29 @@ var libc_mprotect_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_msync_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_msync_trampoline_addr uintptr @@ -429,17 +636,29 @@ var libc_msync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall(libc_munlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munlock_trampoline_addr uintptr @@ -449,11 +668,17 @@ var libc_munlock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := syscall_syscall(libc_munlockall_trampoline_addr, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munlockall_trampoline_addr uintptr @@ -463,11 +688,17 @@ var libc_munlockall_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_pipe2_trampoline_addr, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pipe2_trampoline_addr uintptr @@ -477,18 +708,31 @@ var libc_pipe2_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_getdents_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getdents_trampoline_addr uintptr @@ -498,18 +742,31 @@ var libc_getdents_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_getcwd_trampoline_addr, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getcwd_trampoline_addr uintptr @@ -519,8 +776,11 @@ var libc_getcwd_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getresuid(ruid *_C_int, euid *_C_int, suid *_C_int) { + syscall_rawSyscall(libc_getresuid_trampoline_addr, uintptr(unsafe.Pointer(ruid)), uintptr(unsafe.Pointer(euid)), uintptr(unsafe.Pointer(suid))) + return + } var libc_getresuid_trampoline_addr uintptr @@ -530,8 +790,11 @@ var libc_getresuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getresgid(rgid *_C_int, egid *_C_int, sgid *_C_int) { + syscall_rawSyscall(libc_getresgid_trampoline_addr, uintptr(unsafe.Pointer(rgid)), uintptr(unsafe.Pointer(egid)), uintptr(unsafe.Pointer(sgid))) + return + } var libc_getresgid_trampoline_addr uintptr @@ -541,11 +804,17 @@ var libc_getresgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ioctl_trampoline_addr uintptr @@ -555,27 +824,45 @@ var libc_ioctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall6(libc_sysctl_trampoline_addr, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sysctl_trampoline_addr uintptr @@ -585,12 +872,19 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fcntl_trampoline_addr uintptr @@ -600,23 +894,37 @@ var libc_fcntl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ppoll_trampoline_addr uintptr @@ -626,16 +934,27 @@ var libc_ppoll_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_access_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_access_trampoline_addr uintptr @@ -645,11 +964,17 @@ var libc_access_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { + _, _, e1 := syscall_syscall(libc_adjtime_trampoline_addr, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_adjtime_trampoline_addr uintptr @@ -659,16 +984,27 @@ var libc_adjtime_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chdir_trampoline_addr uintptr @@ -678,16 +1014,27 @@ var libc_chdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chflags_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chflags_trampoline_addr uintptr @@ -697,16 +1044,27 @@ var libc_chflags_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chmod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chmod_trampoline_addr uintptr @@ -716,16 +1074,27 @@ var libc_chmod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chown_trampoline_addr uintptr @@ -735,16 +1104,27 @@ var libc_chown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_chroot_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_chroot_trampoline_addr uintptr @@ -754,11 +1134,17 @@ var libc_chroot_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := syscall_syscall(libc_clock_gettime_trampoline_addr, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_clock_gettime_trampoline_addr uintptr @@ -768,11 +1154,17 @@ var libc_clock_gettime_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_close_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_close_trampoline_addr uintptr @@ -782,12 +1174,19 @@ var libc_close_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { + r0, _, e1 := syscall_syscall(libc_dup_trampoline_addr, uintptr(fd), 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup_trampoline_addr uintptr @@ -797,11 +1196,17 @@ var libc_dup_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { + _, _, e1 := syscall_syscall(libc_dup2_trampoline_addr, uintptr(from), uintptr(to), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup2_trampoline_addr uintptr @@ -811,11 +1216,17 @@ var libc_dup2_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(from int, to int, flags int) (err error) { + _, _, e1 := syscall_syscall(libc_dup3_trampoline_addr, uintptr(from), uintptr(to), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_dup3_trampoline_addr uintptr @@ -825,8 +1236,11 @@ var libc_dup3_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + syscall_syscall(libc_exit_trampoline_addr, uintptr(code), 0, 0) + return + } var libc_exit_trampoline_addr uintptr @@ -836,16 +1250,27 @@ var libc_exit_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_faccessat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_faccessat_trampoline_addr uintptr @@ -855,11 +1280,17 @@ var libc_faccessat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_fchdir_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchdir_trampoline_addr uintptr @@ -869,11 +1300,17 @@ var libc_fchdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { + _, _, e1 := syscall_syscall(libc_fchflags_trampoline_addr, uintptr(fd), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchflags_trampoline_addr uintptr @@ -883,11 +1320,17 @@ var libc_fchflags_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := syscall_syscall(libc_fchmod_trampoline_addr, uintptr(fd), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchmod_trampoline_addr uintptr @@ -897,16 +1340,27 @@ var libc_fchmod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fchmodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchmodat_trampoline_addr uintptr @@ -916,11 +1370,17 @@ var libc_fchmodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := syscall_syscall(libc_fchown_trampoline_addr, uintptr(fd), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchown_trampoline_addr uintptr @@ -930,16 +1390,27 @@ var libc_fchown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fchownat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fchownat_trampoline_addr uintptr @@ -949,11 +1420,17 @@ var libc_fchownat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := syscall_syscall(libc_flock_trampoline_addr, uintptr(fd), uintptr(how), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_flock_trampoline_addr uintptr @@ -963,12 +1440,19 @@ var libc_flock_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { + r0, _, e1 := syscall_syscall(libc_fpathconf_trampoline_addr, uintptr(fd), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fpathconf_trampoline_addr uintptr @@ -978,11 +1462,17 @@ var libc_fpathconf_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := syscall_syscall(libc_fstat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstat_trampoline_addr uintptr @@ -992,16 +1482,27 @@ var libc_fstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_fstatat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstatat_trampoline_addr uintptr @@ -1011,11 +1512,17 @@ var libc_fstatat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { + _, _, e1 := syscall_syscall(libc_fstatfs_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fstatfs_trampoline_addr uintptr @@ -1025,11 +1532,17 @@ var libc_fstatfs_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_fsync_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_fsync_trampoline_addr uintptr @@ -1039,11 +1552,17 @@ var libc_fsync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := syscall_syscall(libc_ftruncate_trampoline_addr, uintptr(fd), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_ftruncate_trampoline_addr uintptr @@ -1053,9 +1572,13 @@ var libc_ftruncate_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _, _ := syscall_rawSyscall(libc_getegid_trampoline_addr, 0, 0, 0) + egid = int(r0) + return + } var libc_getegid_trampoline_addr uintptr @@ -1065,9 +1588,13 @@ var libc_getegid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { + r0, _, _ := syscall_rawSyscall(libc_geteuid_trampoline_addr, 0, 0, 0) + uid = int(r0) + return + } var libc_geteuid_trampoline_addr uintptr @@ -1077,9 +1604,13 @@ var libc_geteuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := syscall_rawSyscall(libc_getgid_trampoline_addr, 0, 0, 0) + gid = int(r0) + return + } var libc_getgid_trampoline_addr uintptr @@ -1089,12 +1620,19 @@ var libc_getgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getpgid_trampoline_addr, uintptr(pid), 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpgid_trampoline_addr uintptr @@ -1104,9 +1642,13 @@ var libc_getpgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { + r0, _, _ := syscall_rawSyscall(libc_getpgrp_trampoline_addr, 0, 0, 0) + pgrp = int(r0) + return + } var libc_getpgrp_trampoline_addr uintptr @@ -1116,9 +1658,13 @@ var libc_getpgrp_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := syscall_rawSyscall(libc_getpid_trampoline_addr, 0, 0, 0) + pid = int(r0) + return + } var libc_getpid_trampoline_addr uintptr @@ -1128,9 +1674,13 @@ var libc_getpid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _, _ := syscall_rawSyscall(libc_getppid_trampoline_addr, 0, 0, 0) + ppid = int(r0) + return + } var libc_getppid_trampoline_addr uintptr @@ -1140,12 +1690,19 @@ var libc_getppid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + r0, _, e1 := syscall_syscall(libc_getpriority_trampoline_addr, uintptr(which), uintptr(who), 0) + prio = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getpriority_trampoline_addr uintptr @@ -1155,11 +1712,17 @@ var libc_getpriority_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getrlimit_trampoline_addr, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrlimit_trampoline_addr uintptr @@ -1169,12 +1732,19 @@ var libc_getrlimit_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrtable() (rtable int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getrtable_trampoline_addr, 0, 0, 0) + rtable = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrtable_trampoline_addr uintptr @@ -1184,11 +1754,17 @@ var libc_getrtable_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := syscall_rawSyscall(libc_getrusage_trampoline_addr, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getrusage_trampoline_addr uintptr @@ -1198,12 +1774,19 @@ var libc_getrusage_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_getsid_trampoline_addr, uintptr(pid), 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getsid_trampoline_addr uintptr @@ -1213,11 +1796,17 @@ var libc_getsid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(libc_gettimeofday_trampoline_addr, uintptr(unsafe.Pointer(tv)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_gettimeofday_trampoline_addr uintptr @@ -1227,9 +1816,13 @@ var libc_gettimeofday_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := syscall_rawSyscall(libc_getuid_trampoline_addr, 0, 0, 0) + uid = int(r0) + return + } var libc_getuid_trampoline_addr uintptr @@ -1239,9 +1832,13 @@ var libc_getuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { + r0, _, _ := syscall_syscall(libc_issetugid_trampoline_addr, 0, 0, 0) + tainted = bool(r0 != 0) + return + } var libc_issetugid_trampoline_addr uintptr @@ -1251,11 +1848,17 @@ var libc_issetugid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { + _, _, e1 := syscall_syscall(libc_kill_trampoline_addr, uintptr(pid), uintptr(signum), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kill_trampoline_addr uintptr @@ -1265,12 +1868,19 @@ var libc_kill_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { + r0, _, e1 := syscall_syscall(libc_kqueue_trampoline_addr, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_kqueue_trampoline_addr uintptr @@ -1280,16 +1890,27 @@ var libc_kqueue_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_lchown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lchown_trampoline_addr uintptr @@ -1299,21 +1920,37 @@ var libc_lchown_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_link_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_link_trampoline_addr uintptr @@ -1323,21 +1960,37 @@ var libc_link_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_linkat_trampoline_addr, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_linkat_trampoline_addr uintptr @@ -1347,11 +2000,17 @@ var libc_linkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { + _, _, e1 := syscall_syscall(libc_listen_trampoline_addr, uintptr(s), uintptr(backlog), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_listen_trampoline_addr uintptr @@ -1361,16 +2020,27 @@ var libc_listen_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_lstat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lstat_trampoline_addr uintptr @@ -1380,16 +2050,27 @@ var libc_lstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkdir_trampoline_addr uintptr @@ -1399,16 +2080,27 @@ var libc_mkdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkdirat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkdirat_trampoline_addr uintptr @@ -1418,16 +2110,27 @@ var libc_mkdirat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkfifo_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkfifo_trampoline_addr uintptr @@ -1437,16 +2140,27 @@ var libc_mkfifo_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifoat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mkfifoat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mkfifoat_trampoline_addr uintptr @@ -1456,16 +2170,27 @@ var libc_mkfifoat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_mknod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mknod_trampoline_addr uintptr @@ -1475,16 +2200,27 @@ var libc_mknod_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mknodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mknodat_trampoline_addr uintptr @@ -1494,11 +2230,17 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_nanosleep_trampoline_addr uintptr @@ -1508,17 +2250,29 @@ var libc_nanosleep_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall(libc_open_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_open_trampoline_addr uintptr @@ -1528,17 +2282,29 @@ var libc_open_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall6(libc_openat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_openat_trampoline_addr uintptr @@ -1548,17 +2314,29 @@ var libc_openat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall_syscall(libc_pathconf_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pathconf_trampoline_addr uintptr @@ -1568,18 +2346,31 @@ var libc_pathconf_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_pread_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pread_trampoline_addr uintptr @@ -1589,18 +2380,31 @@ var libc_pread_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_pwrite_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pwrite_trampoline_addr uintptr @@ -1610,18 +2414,31 @@ var libc_pwrite_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_read_trampoline_addr uintptr @@ -1631,23 +2448,41 @@ var libc_read_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_readlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_readlink_trampoline_addr uintptr @@ -1657,23 +2492,41 @@ var libc_readlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_readlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_readlinkat_trampoline_addr uintptr @@ -1683,21 +2536,37 @@ var libc_readlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_rename_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_rename_trampoline_addr uintptr @@ -1707,21 +2576,37 @@ var libc_rename_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_renameat_trampoline_addr, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_renameat_trampoline_addr uintptr @@ -1731,16 +2616,27 @@ var libc_renameat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_revoke_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_revoke_trampoline_addr uintptr @@ -1750,16 +2646,27 @@ var libc_revoke_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_rmdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_rmdir_trampoline_addr uintptr @@ -1769,12 +2676,19 @@ var libc_rmdir_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, _, e1 := syscall_syscall(libc_lseek_trampoline_addr, uintptr(fd), uintptr(offset), uintptr(whence)) + newoffset = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_lseek_trampoline_addr uintptr @@ -1784,12 +2698,19 @@ var libc_lseek_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := syscall_syscall6(libc_select_trampoline_addr, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_select_trampoline_addr uintptr @@ -1799,11 +2720,17 @@ var libc_select_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setegid_trampoline_addr, uintptr(egid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setegid_trampoline_addr uintptr @@ -1813,11 +2740,17 @@ var libc_setegid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_seteuid_trampoline_addr, uintptr(euid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_seteuid_trampoline_addr uintptr @@ -1827,11 +2760,17 @@ var libc_seteuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setgid_trampoline_addr, uintptr(gid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setgid_trampoline_addr uintptr @@ -1841,16 +2780,27 @@ var libc_setgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(name) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_setlogin_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setlogin_trampoline_addr uintptr @@ -1860,11 +2810,17 @@ var libc_setlogin_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setpgid_trampoline_addr, uintptr(pid), uintptr(pgid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setpgid_trampoline_addr uintptr @@ -1874,11 +2830,17 @@ var libc_setpgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := syscall_syscall(libc_setpriority_trampoline_addr, uintptr(which), uintptr(who), uintptr(prio)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setpriority_trampoline_addr uintptr @@ -1888,11 +2850,17 @@ var libc_setpriority_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setregid_trampoline_addr, uintptr(rgid), uintptr(egid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setregid_trampoline_addr uintptr @@ -1902,11 +2870,17 @@ var libc_setregid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setreuid_trampoline_addr, uintptr(ruid), uintptr(euid), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setreuid_trampoline_addr uintptr @@ -1916,11 +2890,17 @@ var libc_setreuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setresgid_trampoline_addr, uintptr(rgid), uintptr(egid), uintptr(sgid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setresgid_trampoline_addr uintptr @@ -1930,11 +2910,17 @@ var libc_setresgid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setresuid_trampoline_addr, uintptr(ruid), uintptr(euid), uintptr(suid)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setresuid_trampoline_addr uintptr @@ -1944,11 +2930,17 @@ var libc_setresuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrtable(rtable int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setrtable_trampoline_addr, uintptr(rtable), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setrtable_trampoline_addr uintptr @@ -1958,12 +2950,19 @@ var libc_setrtable_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := syscall_rawSyscall(libc_setsid_trampoline_addr, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setsid_trampoline_addr uintptr @@ -1973,11 +2972,17 @@ var libc_setsid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(libc_settimeofday_trampoline_addr, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_settimeofday_trampoline_addr uintptr @@ -1987,11 +2992,17 @@ var libc_settimeofday_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + _, _, e1 := syscall_rawSyscall(libc_setuid_trampoline_addr, uintptr(uid), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_setuid_trampoline_addr uintptr @@ -2001,16 +3012,27 @@ var libc_setuid_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_stat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_stat_trampoline_addr uintptr @@ -2020,16 +3042,27 @@ var libc_stat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_statfs_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_statfs_trampoline_addr uintptr @@ -2039,21 +3072,37 @@ var libc_statfs_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_symlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_symlink_trampoline_addr uintptr @@ -2063,21 +3112,37 @@ var libc_symlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_symlinkat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_symlinkat_trampoline_addr uintptr @@ -2087,11 +3152,17 @@ var libc_symlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { + _, _, e1 := syscall_syscall(libc_sync_trampoline_addr, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_sync_trampoline_addr uintptr @@ -2101,16 +3172,27 @@ var libc_sync_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_truncate_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_truncate_trampoline_addr uintptr @@ -2120,9 +3202,13 @@ var libc_truncate_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { + r0, _, _ := syscall_syscall(libc_umask_trampoline_addr, uintptr(newmask), 0, 0) + oldmask = int(r0) + return + } var libc_umask_trampoline_addr uintptr @@ -2132,16 +3218,27 @@ var libc_umask_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unlink_trampoline_addr uintptr @@ -2151,16 +3248,27 @@ var libc_unlink_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unlinkat_trampoline_addr uintptr @@ -2170,16 +3278,27 @@ var libc_unlinkat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_unmount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unmount_trampoline_addr uintptr @@ -2189,18 +3308,31 @@ var libc_unmount_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_write_trampoline_addr uintptr @@ -2210,12 +3342,19 @@ var libc_write_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + r0, _, e1 := syscall_syscall6(libc_mmap_trampoline_addr, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_mmap_trampoline_addr uintptr @@ -2225,11 +3364,17 @@ var libc_mmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := syscall_syscall(libc_munmap_trampoline_addr, uintptr(addr), uintptr(length), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_munmap_trampoline_addr uintptr @@ -2239,12 +3384,19 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getfsstat(stat *Statfs_t, bufsize uintptr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_getfsstat_trampoline_addr, uintptr(unsafe.Pointer(stat)), uintptr(bufsize), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_getfsstat_trampoline_addr uintptr @@ -2254,16 +3406,27 @@ var libc_getfsstat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_utimensat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_utimensat_trampoline_addr uintptr @@ -2273,11 +3436,17 @@ var libc_utimensat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pledge(promises *byte, execpromises *byte) (err error) { + _, _, e1 := syscall_syscall(libc_pledge_trampoline_addr, uintptr(unsafe.Pointer(promises)), uintptr(unsafe.Pointer(execpromises)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_pledge_trampoline_addr uintptr @@ -2287,11 +3456,17 @@ var libc_pledge_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func unveil(path *byte, flags *byte) (err error) { + _, _, e1 := syscall_syscall(libc_unveil_trampoline_addr, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(flags)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } var libc_unveil_trampoline_addr uintptr diff --git a/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go index 829b87f..447f9f1 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go @@ -1,4 +1,5 @@ // go run mksyscall_solaris.go -tags solaris,amd64 syscall_solaris.go syscall_solaris_amd64.go + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build solaris && amd64 @@ -11,2093 +12,3621 @@ import ( ) //go:cgo_import_dynamic libc_pipe pipe "libc.so" + //go:cgo_import_dynamic libc_pipe2 pipe2 "libc.so" + //go:cgo_import_dynamic libc_getsockname getsockname "libsocket.so" + //go:cgo_import_dynamic libc_getcwd getcwd "libc.so" + //go:cgo_import_dynamic libc_getgroups getgroups "libc.so" + //go:cgo_import_dynamic libc_setgroups setgroups "libc.so" + //go:cgo_import_dynamic libc_wait4 wait4 "libc.so" + //go:cgo_import_dynamic libc_gethostname gethostname "libc.so" + //go:cgo_import_dynamic libc_utimes utimes "libc.so" + //go:cgo_import_dynamic libc_utimensat utimensat "libc.so" + //go:cgo_import_dynamic libc_fcntl fcntl "libc.so" + //go:cgo_import_dynamic libc_futimesat futimesat "libc.so" + //go:cgo_import_dynamic libc_accept accept "libsocket.so" + //go:cgo_import_dynamic libc___xnet_recvmsg __xnet_recvmsg "libsocket.so" + //go:cgo_import_dynamic libc___xnet_sendmsg __xnet_sendmsg "libsocket.so" + //go:cgo_import_dynamic libc_acct acct "libc.so" + //go:cgo_import_dynamic libc___makedev __makedev "libc.so" + //go:cgo_import_dynamic libc___major __major "libc.so" + //go:cgo_import_dynamic libc___minor __minor "libc.so" + //go:cgo_import_dynamic libc_ioctl ioctl "libc.so" + //go:cgo_import_dynamic libc_poll poll "libc.so" + //go:cgo_import_dynamic libc_access access "libc.so" + //go:cgo_import_dynamic libc_adjtime adjtime "libc.so" + //go:cgo_import_dynamic libc_chdir chdir "libc.so" + //go:cgo_import_dynamic libc_chmod chmod "libc.so" + //go:cgo_import_dynamic libc_chown chown "libc.so" + //go:cgo_import_dynamic libc_chroot chroot "libc.so" + //go:cgo_import_dynamic libc_clockgettime clockgettime "libc.so" + //go:cgo_import_dynamic libc_close close "libc.so" + //go:cgo_import_dynamic libc_creat creat "libc.so" + //go:cgo_import_dynamic libc_dup dup "libc.so" + //go:cgo_import_dynamic libc_dup2 dup2 "libc.so" + //go:cgo_import_dynamic libc_exit exit "libc.so" + //go:cgo_import_dynamic libc_faccessat faccessat "libc.so" + //go:cgo_import_dynamic libc_fchdir fchdir "libc.so" + //go:cgo_import_dynamic libc_fchmod fchmod "libc.so" + //go:cgo_import_dynamic libc_fchmodat fchmodat "libc.so" + //go:cgo_import_dynamic libc_fchown fchown "libc.so" + //go:cgo_import_dynamic libc_fchownat fchownat "libc.so" + //go:cgo_import_dynamic libc_fdatasync fdatasync "libc.so" + //go:cgo_import_dynamic libc_flock flock "libc.so" + //go:cgo_import_dynamic libc_fpathconf fpathconf "libc.so" + //go:cgo_import_dynamic libc_fstat fstat "libc.so" + //go:cgo_import_dynamic libc_fstatat fstatat "libc.so" + //go:cgo_import_dynamic libc_fstatvfs fstatvfs "libc.so" + //go:cgo_import_dynamic libc_getdents getdents "libc.so" + //go:cgo_import_dynamic libc_getgid getgid "libc.so" + //go:cgo_import_dynamic libc_getpid getpid "libc.so" + //go:cgo_import_dynamic libc_getpgid getpgid "libc.so" + //go:cgo_import_dynamic libc_getpgrp getpgrp "libc.so" + //go:cgo_import_dynamic libc_geteuid geteuid "libc.so" + //go:cgo_import_dynamic libc_getegid getegid "libc.so" + //go:cgo_import_dynamic libc_getppid getppid "libc.so" + //go:cgo_import_dynamic libc_getpriority getpriority "libc.so" + //go:cgo_import_dynamic libc_getrlimit getrlimit "libc.so" + //go:cgo_import_dynamic libc_getrusage getrusage "libc.so" + //go:cgo_import_dynamic libc_getsid getsid "libc.so" + //go:cgo_import_dynamic libc_gettimeofday gettimeofday "libc.so" + //go:cgo_import_dynamic libc_getuid getuid "libc.so" + //go:cgo_import_dynamic libc_kill kill "libc.so" + //go:cgo_import_dynamic libc_lchown lchown "libc.so" + //go:cgo_import_dynamic libc_link link "libc.so" + //go:cgo_import_dynamic libc___xnet_llisten __xnet_llisten "libsocket.so" + //go:cgo_import_dynamic libc_lstat lstat "libc.so" + //go:cgo_import_dynamic libc_madvise madvise "libc.so" + //go:cgo_import_dynamic libc_mkdir mkdir "libc.so" + //go:cgo_import_dynamic libc_mkdirat mkdirat "libc.so" + //go:cgo_import_dynamic libc_mkfifo mkfifo "libc.so" + //go:cgo_import_dynamic libc_mkfifoat mkfifoat "libc.so" + //go:cgo_import_dynamic libc_mknod mknod "libc.so" + //go:cgo_import_dynamic libc_mknodat mknodat "libc.so" + //go:cgo_import_dynamic libc_mlock mlock "libc.so" + //go:cgo_import_dynamic libc_mlockall mlockall "libc.so" + //go:cgo_import_dynamic libc_mprotect mprotect "libc.so" + //go:cgo_import_dynamic libc_msync msync "libc.so" + //go:cgo_import_dynamic libc_munlock munlock "libc.so" + //go:cgo_import_dynamic libc_munlockall munlockall "libc.so" + //go:cgo_import_dynamic libc_nanosleep nanosleep "libc.so" + //go:cgo_import_dynamic libc_open open "libc.so" + //go:cgo_import_dynamic libc_openat openat "libc.so" + //go:cgo_import_dynamic libc_pathconf pathconf "libc.so" + //go:cgo_import_dynamic libc_pause pause "libc.so" + //go:cgo_import_dynamic libc_pread pread "libc.so" + //go:cgo_import_dynamic libc_pwrite pwrite "libc.so" + //go:cgo_import_dynamic libc_read read "libc.so" + //go:cgo_import_dynamic libc_readlink readlink "libc.so" + //go:cgo_import_dynamic libc_rename rename "libc.so" + //go:cgo_import_dynamic libc_renameat renameat "libc.so" + //go:cgo_import_dynamic libc_rmdir rmdir "libc.so" + //go:cgo_import_dynamic libc_lseek lseek "libc.so" + //go:cgo_import_dynamic libc_select select "libc.so" + //go:cgo_import_dynamic libc_setegid setegid "libc.so" + //go:cgo_import_dynamic libc_seteuid seteuid "libc.so" + //go:cgo_import_dynamic libc_setgid setgid "libc.so" + //go:cgo_import_dynamic libc_sethostname sethostname "libc.so" + //go:cgo_import_dynamic libc_setpgid setpgid "libc.so" + //go:cgo_import_dynamic libc_setpriority setpriority "libc.so" + //go:cgo_import_dynamic libc_setregid setregid "libc.so" + //go:cgo_import_dynamic libc_setreuid setreuid "libc.so" + //go:cgo_import_dynamic libc_setsid setsid "libc.so" + //go:cgo_import_dynamic libc_setuid setuid "libc.so" + //go:cgo_import_dynamic libc_shutdown shutdown "libsocket.so" + //go:cgo_import_dynamic libc_stat stat "libc.so" + //go:cgo_import_dynamic libc_statvfs statvfs "libc.so" + //go:cgo_import_dynamic libc_symlink symlink "libc.so" + //go:cgo_import_dynamic libc_sync sync "libc.so" + //go:cgo_import_dynamic libc_sysconf sysconf "libc.so" + //go:cgo_import_dynamic libc_times times "libc.so" + //go:cgo_import_dynamic libc_truncate truncate "libc.so" + //go:cgo_import_dynamic libc_fsync fsync "libc.so" + //go:cgo_import_dynamic libc_ftruncate ftruncate "libc.so" + //go:cgo_import_dynamic libc_umask umask "libc.so" + //go:cgo_import_dynamic libc_uname uname "libc.so" + //go:cgo_import_dynamic libc_umount umount "libc.so" + //go:cgo_import_dynamic libc_unlink unlink "libc.so" + //go:cgo_import_dynamic libc_unlinkat unlinkat "libc.so" + //go:cgo_import_dynamic libc_ustat ustat "libc.so" + //go:cgo_import_dynamic libc_utime utime "libc.so" + //go:cgo_import_dynamic libc___xnet_bind __xnet_bind "libsocket.so" + //go:cgo_import_dynamic libc___xnet_connect __xnet_connect "libsocket.so" + //go:cgo_import_dynamic libc_mmap mmap "libc.so" + //go:cgo_import_dynamic libc_munmap munmap "libc.so" + //go:cgo_import_dynamic libc_sendfile sendfile "libsendfile.so" + //go:cgo_import_dynamic libc___xnet_sendto __xnet_sendto "libsocket.so" + //go:cgo_import_dynamic libc___xnet_socket __xnet_socket "libsocket.so" + //go:cgo_import_dynamic libc___xnet_socketpair __xnet_socketpair "libsocket.so" + //go:cgo_import_dynamic libc_write write "libc.so" + //go:cgo_import_dynamic libc___xnet_getsockopt __xnet_getsockopt "libsocket.so" + //go:cgo_import_dynamic libc_getpeername getpeername "libsocket.so" + //go:cgo_import_dynamic libc_setsockopt setsockopt "libsocket.so" + //go:cgo_import_dynamic libc_recvfrom recvfrom "libsocket.so" + //go:cgo_import_dynamic libc_port_create port_create "libc.so" + //go:cgo_import_dynamic libc_port_associate port_associate "libc.so" + //go:cgo_import_dynamic libc_port_dissociate port_dissociate "libc.so" + //go:cgo_import_dynamic libc_port_get port_get "libc.so" + //go:cgo_import_dynamic libc_port_getn port_getn "libc.so" + //go:cgo_import_dynamic libc_putmsg putmsg "libc.so" + //go:cgo_import_dynamic libc_getmsg getmsg "libc.so" //go:linkname procpipe libc_pipe + //go:linkname procpipe2 libc_pipe2 + //go:linkname procgetsockname libc_getsockname + //go:linkname procGetcwd libc_getcwd + //go:linkname procgetgroups libc_getgroups + //go:linkname procsetgroups libc_setgroups + //go:linkname procwait4 libc_wait4 + //go:linkname procgethostname libc_gethostname + //go:linkname procutimes libc_utimes + //go:linkname procutimensat libc_utimensat + //go:linkname procfcntl libc_fcntl + //go:linkname procfutimesat libc_futimesat + //go:linkname procaccept libc_accept + //go:linkname proc__xnet_recvmsg libc___xnet_recvmsg + //go:linkname proc__xnet_sendmsg libc___xnet_sendmsg + //go:linkname procacct libc_acct + //go:linkname proc__makedev libc___makedev + //go:linkname proc__major libc___major + //go:linkname proc__minor libc___minor + //go:linkname procioctl libc_ioctl + //go:linkname procpoll libc_poll + //go:linkname procAccess libc_access + //go:linkname procAdjtime libc_adjtime + //go:linkname procChdir libc_chdir + //go:linkname procChmod libc_chmod + //go:linkname procChown libc_chown + //go:linkname procChroot libc_chroot + //go:linkname procClockGettime libc_clockgettime + //go:linkname procClose libc_close + //go:linkname procCreat libc_creat + //go:linkname procDup libc_dup + //go:linkname procDup2 libc_dup2 + //go:linkname procExit libc_exit + //go:linkname procFaccessat libc_faccessat + //go:linkname procFchdir libc_fchdir + //go:linkname procFchmod libc_fchmod + //go:linkname procFchmodat libc_fchmodat + //go:linkname procFchown libc_fchown + //go:linkname procFchownat libc_fchownat + //go:linkname procFdatasync libc_fdatasync + //go:linkname procFlock libc_flock + //go:linkname procFpathconf libc_fpathconf + //go:linkname procFstat libc_fstat + //go:linkname procFstatat libc_fstatat + //go:linkname procFstatvfs libc_fstatvfs + //go:linkname procGetdents libc_getdents + //go:linkname procGetgid libc_getgid + //go:linkname procGetpid libc_getpid + //go:linkname procGetpgid libc_getpgid + //go:linkname procGetpgrp libc_getpgrp + //go:linkname procGeteuid libc_geteuid + //go:linkname procGetegid libc_getegid + //go:linkname procGetppid libc_getppid + //go:linkname procGetpriority libc_getpriority + //go:linkname procGetrlimit libc_getrlimit + //go:linkname procGetrusage libc_getrusage + //go:linkname procGetsid libc_getsid + //go:linkname procGettimeofday libc_gettimeofday + //go:linkname procGetuid libc_getuid + //go:linkname procKill libc_kill + //go:linkname procLchown libc_lchown + //go:linkname procLink libc_link + //go:linkname proc__xnet_llisten libc___xnet_llisten + //go:linkname procLstat libc_lstat + //go:linkname procMadvise libc_madvise + //go:linkname procMkdir libc_mkdir + //go:linkname procMkdirat libc_mkdirat + //go:linkname procMkfifo libc_mkfifo + //go:linkname procMkfifoat libc_mkfifoat + //go:linkname procMknod libc_mknod + //go:linkname procMknodat libc_mknodat + //go:linkname procMlock libc_mlock + //go:linkname procMlockall libc_mlockall + //go:linkname procMprotect libc_mprotect + //go:linkname procMsync libc_msync + //go:linkname procMunlock libc_munlock + //go:linkname procMunlockall libc_munlockall + //go:linkname procNanosleep libc_nanosleep + //go:linkname procOpen libc_open + //go:linkname procOpenat libc_openat + //go:linkname procPathconf libc_pathconf + //go:linkname procPause libc_pause + //go:linkname procpread libc_pread + //go:linkname procpwrite libc_pwrite + //go:linkname procread libc_read + //go:linkname procReadlink libc_readlink + //go:linkname procRename libc_rename + //go:linkname procRenameat libc_renameat + //go:linkname procRmdir libc_rmdir + //go:linkname proclseek libc_lseek + //go:linkname procSelect libc_select + //go:linkname procSetegid libc_setegid + //go:linkname procSeteuid libc_seteuid + //go:linkname procSetgid libc_setgid + //go:linkname procSethostname libc_sethostname + //go:linkname procSetpgid libc_setpgid + //go:linkname procSetpriority libc_setpriority + //go:linkname procSetregid libc_setregid + //go:linkname procSetreuid libc_setreuid + //go:linkname procSetsid libc_setsid + //go:linkname procSetuid libc_setuid + //go:linkname procshutdown libc_shutdown + //go:linkname procStat libc_stat + //go:linkname procStatvfs libc_statvfs + //go:linkname procSymlink libc_symlink + //go:linkname procSync libc_sync + //go:linkname procSysconf libc_sysconf + //go:linkname procTimes libc_times + //go:linkname procTruncate libc_truncate + //go:linkname procFsync libc_fsync + //go:linkname procFtruncate libc_ftruncate + //go:linkname procUmask libc_umask + //go:linkname procUname libc_uname + //go:linkname procumount libc_umount + //go:linkname procUnlink libc_unlink + //go:linkname procUnlinkat libc_unlinkat + //go:linkname procUstat libc_ustat + //go:linkname procUtime libc_utime + //go:linkname proc__xnet_bind libc___xnet_bind + //go:linkname proc__xnet_connect libc___xnet_connect + //go:linkname procmmap libc_mmap + //go:linkname procmunmap libc_munmap + //go:linkname procsendfile libc_sendfile + //go:linkname proc__xnet_sendto libc___xnet_sendto + //go:linkname proc__xnet_socket libc___xnet_socket + //go:linkname proc__xnet_socketpair libc___xnet_socketpair + //go:linkname procwrite libc_write + //go:linkname proc__xnet_getsockopt libc___xnet_getsockopt + //go:linkname procgetpeername libc_getpeername + //go:linkname procsetsockopt libc_setsockopt + //go:linkname procrecvfrom libc_recvfrom + //go:linkname procport_create libc_port_create + //go:linkname procport_associate libc_port_associate + //go:linkname procport_dissociate libc_port_dissociate + //go:linkname procport_get libc_port_get + //go:linkname procport_getn libc_port_getn + //go:linkname procputmsg libc_putmsg + //go:linkname procgetmsg libc_getmsg var ( procpipe, + procpipe2, + procgetsockname, + procGetcwd, + procgetgroups, + procsetgroups, + procwait4, + procgethostname, + procutimes, + procutimensat, + procfcntl, + procfutimesat, + procaccept, + proc__xnet_recvmsg, + proc__xnet_sendmsg, + procacct, + proc__makedev, + proc__major, + proc__minor, + procioctl, + procpoll, + procAccess, + procAdjtime, + procChdir, + procChmod, + procChown, + procChroot, + procClockGettime, + procClose, + procCreat, + procDup, + procDup2, + procExit, + procFaccessat, + procFchdir, + procFchmod, + procFchmodat, + procFchown, + procFchownat, + procFdatasync, + procFlock, + procFpathconf, + procFstat, + procFstatat, + procFstatvfs, + procGetdents, + procGetgid, + procGetpid, + procGetpgid, + procGetpgrp, + procGeteuid, + procGetegid, + procGetppid, + procGetpriority, + procGetrlimit, + procGetrusage, + procGetsid, + procGettimeofday, + procGetuid, + procKill, + procLchown, + procLink, + proc__xnet_llisten, + procLstat, + procMadvise, + procMkdir, + procMkdirat, + procMkfifo, + procMkfifoat, + procMknod, + procMknodat, + procMlock, + procMlockall, + procMprotect, + procMsync, + procMunlock, + procMunlockall, + procNanosleep, + procOpen, + procOpenat, + procPathconf, + procPause, + procpread, + procpwrite, + procread, + procReadlink, + procRename, + procRenameat, + procRmdir, + proclseek, + procSelect, + procSetegid, + procSeteuid, + procSetgid, + procSethostname, + procSetpgid, + procSetpriority, + procSetregid, + procSetreuid, + procSetsid, + procSetuid, + procshutdown, + procStat, + procStatvfs, + procSymlink, + procSync, + procSysconf, + procTimes, + procTruncate, + procFsync, + procFtruncate, + procUmask, + procUname, + procumount, + procUnlink, + procUnlinkat, + procUstat, + procUtime, + proc__xnet_bind, + proc__xnet_connect, + procmmap, + procmunmap, + procsendfile, + proc__xnet_sendto, + proc__xnet_socket, + proc__xnet_socketpair, + procwrite, + proc__xnet_getsockopt, + procgetpeername, + procsetsockopt, + procrecvfrom, + procport_create, + procport_associate, + procport_dissociate, + procport_get, + procport_getn, + procputmsg, + procgetmsg syscallFunc ) // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]_C_int) (n int, err error) { + r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procpipe)), 1, uintptr(unsafe.Pointer(p)), 0, 0, 0, 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { + _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procpipe2)), 2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procgetsockname)), 3, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { + var _p0 *byte + if len(buf) > 0 { + _p0 = &buf[0] + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procGetcwd)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0, 0, 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { + r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procgetgroups)), 2, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0, 0, 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { + _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procsetgroups)), 2, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int32, statusp *_C_int, options int, rusage *Rusage) (wpid int32, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procwait4)), 4, uintptr(pid), uintptr(unsafe.Pointer(statusp)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + wpid = int32(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func gethostname(buf []byte) (n int, err error) { + var _p0 *byte + if len(buf) > 0 { + _p0 = &buf[0] + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procgethostname)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0, 0, 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procutimes)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(fd int, path string, times *[2]Timespec, flag int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procutimensat)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flag), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(arg), 0, 0, 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(fildes int, path *byte, times *[2]Timeval) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procfutimesat)), 3, uintptr(fildes), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times)), 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procaccept)), 3, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_recvmsg)), 3, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags), 0, 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_sendmsg)), 3, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags), 0, 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func acct(path *byte) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procacct)), 1, uintptr(unsafe.Pointer(path)), 0, 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func __makedev(version int, major uint, minor uint) (val uint64) { + r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&proc__makedev)), 3, uintptr(version), uintptr(major), uintptr(minor), 0, 0, 0) + val = uint64(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func __major(version int, dev uint64) (val uint) { + r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&proc__major)), 2, uintptr(version), uintptr(dev), 0, 0, 0, 0) + val = uint(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func __minor(version int, dev uint64) (val uint) { + r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&proc__minor)), 2, uintptr(version), uintptr(dev), 0, 0, 0, 0) + val = uint(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlRet(fd int, req int, arg uintptr) (ret int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procioctl)), 3, uintptr(fd), uintptr(req), uintptr(arg), 0, 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtrRet(fd int, req int, arg unsafe.Pointer) (ret int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procioctl)), 3, uintptr(fd), uintptr(req), uintptr(arg), 0, 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procpoll)), 3, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout), 0, 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procAccess)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procAdjtime)), 2, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procChdir)), 1, uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procChmod)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procChown)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procChroot)), 1, uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procClockGettime)), 2, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procClose)), 1, uintptr(fd), 0, 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Creat(path string, mode uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procCreat)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procDup)), 1, uintptr(fd), 0, 0, 0, 0, 0) + nfd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(oldfd int, newfd int) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procDup2)), 2, uintptr(oldfd), uintptr(newfd), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + sysvicall6(uintptr(unsafe.Pointer(&procExit)), 1, uintptr(code), 0, 0, 0, 0, 0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFaccessat)), 4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchdir)), 1, uintptr(fd), 0, 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchmod)), 2, uintptr(fd), uintptr(mode), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchmodat)), 4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchown)), 3, uintptr(fd), uintptr(uid), uintptr(gid), 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchownat)), 5, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFdatasync)), 1, uintptr(fd), 0, 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFlock)), 2, uintptr(fd), uintptr(how), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFpathconf)), 2, uintptr(fd), uintptr(name), 0, 0, 0, 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFstat)), 2, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFstatat)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatvfs(fd int, vfsstat *Statvfs_t) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFstatvfs)), 2, uintptr(fd), uintptr(unsafe.Pointer(vfsstat)), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte, basep *uintptr) (n int, err error) { + var _p0 *byte + if len(buf) > 0 { + _p0 = &buf[0] + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procGetdents)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := rawSysvicall6(uintptr(unsafe.Pointer(&procGetgid)), 0, 0, 0, 0, 0, 0, 0) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := rawSysvicall6(uintptr(unsafe.Pointer(&procGetpid)), 0, 0, 0, 0, 0, 0, 0) + pid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetpgid)), 1, uintptr(pid), 0, 0, 0, 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgid int, err error) { + r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetpgrp)), 0, 0, 0, 0, 0, 0, 0) + pgid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { + r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procGeteuid)), 0, 0, 0, 0, 0, 0, 0) + euid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procGetegid)), 0, 0, 0, 0, 0, 0, 0) + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { + r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procGetppid)), 0, 0, 0, 0, 0, 0, 0) + ppid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (n int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procGetpriority)), 2, uintptr(which), uintptr(who), 0, 0, 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { + _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetrlimit)), 2, uintptr(which), uintptr(unsafe.Pointer(lim)), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { + _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetrusage)), 2, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetsid)), 1, uintptr(pid), 0, 0, 0, 0, 0) + sid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { + _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGettimeofday)), 1, uintptr(unsafe.Pointer(tv)), 0, 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := rawSysvicall6(uintptr(unsafe.Pointer(&procGetuid)), 0, 0, 0, 0, 0, 0, 0) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procKill)), 2, uintptr(pid), uintptr(signum), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procLchown)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procLink)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_llisten)), 2, uintptr(s), uintptr(backlog), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procLstat)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, advice int) (err error) { + var _p0 *byte + if len(b) > 0 { + _p0 = &b[0] + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMadvise)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(advice), 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMkdir)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMkdirat)), 3, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMkfifo)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifoat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMkfifoat)), 3, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMknod)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMknodat)), 4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { + var _p0 *byte + if len(b) > 0 { + _p0 = &b[0] + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMlock)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMlockall)), 1, uintptr(flags), 0, 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 *byte + if len(b) > 0 { + _p0 = &b[0] + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMprotect)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(prot), 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 *byte + if len(b) > 0 { + _p0 = &b[0] + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMsync)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(flags), 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { + var _p0 *byte + if len(b) > 0 { + _p0 = &b[0] + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMunlock)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMunlockall)), 0, 0, 0, 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procNanosleep)), 2, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procOpen)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procOpenat)), 4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procPathconf)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0, 0, 0, 0) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procPause)), 0, 0, 0, 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 *byte + if len(p) > 0 { + _p0 = &p[0] + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procpread)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 *byte + if len(p) > 0 { + _p0 = &p[0] + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procpwrite)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 *byte + if len(p) > 0 { + _p0 = &p[0] + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procread)), 3, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), 0, 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + if len(buf) > 0 { + _p1 = &buf[0] + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procReadlink)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(len(buf)), 0, 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procRename)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procRenameat)), 4, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procRmdir)), 1, uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proclseek)), 3, uintptr(fd), uintptr(offset), uintptr(whence), 0, 0, 0) + newoffset = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSelect)), 5, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetegid)), 1, uintptr(egid), 0, 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSeteuid)), 1, uintptr(euid), 0, 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { + _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetgid)), 1, uintptr(gid), 0, 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { + var _p0 *byte + if len(p) > 0 { + _p0 = &p[0] + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSethostname)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetpgid)), 2, uintptr(pid), uintptr(pgid), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSetpriority)), 3, uintptr(which), uintptr(who), uintptr(prio), 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetregid)), 2, uintptr(rgid), uintptr(egid), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetreuid)), 2, uintptr(ruid), uintptr(euid), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetsid)), 0, 0, 0, 0, 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetuid)), 1, uintptr(uid), 0, 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procshutdown)), 2, uintptr(s), uintptr(how), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procStat)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statvfs(path string, vfsstat *Statvfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procStatvfs)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(vfsstat)), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSymlink)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSync)), 0, 0, 0, 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysconf(which int) (n int64, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSysconf)), 1, uintptr(which), 0, 0, 0, 0, 0) + n = int64(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { + r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procTimes)), 1, uintptr(unsafe.Pointer(tms)), 0, 0, 0, 0, 0) + ticks = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procTruncate)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFsync)), 1, uintptr(fd), 0, 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFtruncate)), 2, uintptr(fd), uintptr(length), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { + r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procUmask)), 1, uintptr(mask), 0, 0, 0, 0, 0) + oldmask = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { + _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procUname)), 1, uintptr(unsafe.Pointer(buf)), 0, 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(target string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(target) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procumount)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUnlink)), 1, uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUnlinkat)), 3, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUstat)), 2, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUtime)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_bind)), 3, uintptr(s), uintptr(addr), uintptr(addrlen), 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_connect)), 3, uintptr(s), uintptr(addr), uintptr(addrlen), 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procmmap)), 6, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) + ret = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procmunmap)), 2, uintptr(addr), uintptr(length), 0, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procsendfile)), 4, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) + written = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 *byte + if len(buf) > 0 { + _p0 = &buf[0] + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_sendto)), 6, uintptr(s), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_socket)), 3, uintptr(domain), uintptr(typ), uintptr(proto), 0, 0, 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&proc__xnet_socketpair)), 4, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 *byte + if len(p) > 0 { + _p0 = &p[0] + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procwrite)), 3, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), 0, 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_getsockopt)), 5, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procgetpeername)), 3, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procsetsockopt)), 5, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 *byte + if len(p) > 0 { + _p0 = &p[0] + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procrecvfrom)), 6, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func port_create() (n int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procport_create)), 0, 0, 0, 0, 0, 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func port_associate(port int, source int, object uintptr, events int, user *byte) (n int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procport_associate)), 5, uintptr(port), uintptr(source), uintptr(object), uintptr(events), uintptr(unsafe.Pointer(user)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func port_dissociate(port int, source int, object uintptr) (n int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procport_dissociate)), 3, uintptr(port), uintptr(source), uintptr(object), 0, 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func port_get(port int, pe *portEvent, timeout *Timespec) (n int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procport_get)), 3, uintptr(port), uintptr(unsafe.Pointer(pe)), uintptr(unsafe.Pointer(timeout)), 0, 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func port_getn(port int, pe *portEvent, max uint32, nget *uint32, timeout *Timespec) (n int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procport_getn)), 5, uintptr(port), uintptr(unsafe.Pointer(pe)), uintptr(max), uintptr(unsafe.Pointer(nget)), uintptr(unsafe.Pointer(timeout)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func putmsg(fd int, clptr *strbuf, dataptr *strbuf, flags int) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procputmsg)), 4, uintptr(fd), uintptr(unsafe.Pointer(clptr)), uintptr(unsafe.Pointer(dataptr)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getmsg(fd int, clptr *strbuf, dataptr *strbuf, flags *int) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procgetmsg)), 4, uintptr(fd), uintptr(unsafe.Pointer(clptr)), uintptr(unsafe.Pointer(dataptr)), uintptr(unsafe.Pointer(flags)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_zos_s390x.go b/vendor/golang.org/x/sys/unix/zsyscall_zos_s390x.go index 7ccf66b..accfb46 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_zos_s390x.go @@ -1,4 +1,5 @@ // go run mksyscall_zos_s390x.go -o_sysnum zsysnum_zos_s390x.go -o_syscall zsyscall_zos_s390x.go -i_syscall syscall_zos_s390x.go -o_asm zsymaddr_zos_s390x.s + // Code generated by the command above; see README.md. DO NOT EDIT. //go:build zos && s390x @@ -16,3443 +17,5831 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCNTL<<4, uintptr(fd), uintptr(cmd), uintptr(arg)) + runtime.ExitSyscall() + val = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Flistxattr(fd int, dest []byte) (sz int, err error) { + var _p0 unsafe.Pointer + if len(dest) > 0 { + _p0 = unsafe.Pointer(&dest[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FLISTXATTR_A<<4, uintptr(fd), uintptr(_p0), uintptr(len(dest))) + runtime.ExitSyscall() + sz = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_FlistxattrAddr() *(func(fd int, dest []byte) (sz int, err error)) var Flistxattr = enter_Flistxattr func enter_Flistxattr(fd int, dest []byte) (sz int, err error) { + funcref := get_FlistxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___FLISTXATTR_A<<4, "") == 0 { + *funcref = impl_Flistxattr + } else { + *funcref = error_Flistxattr + } + return (*funcref)(fd, dest) + } func error_Flistxattr(fd int, dest []byte) (sz int, err error) { + sz = -1 + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Fremovexattr(fd int, attr string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attr) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FREMOVEXATTR_A<<4, uintptr(fd), uintptr(unsafe.Pointer(_p0))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_FremovexattrAddr() *(func(fd int, attr string) (err error)) var Fremovexattr = enter_Fremovexattr func enter_Fremovexattr(fd int, attr string) (err error) { + funcref := get_FremovexattrAddr() + if funcptrtest(GetZosLibVec()+SYS___FREMOVEXATTR_A<<4, "") == 0 { + *funcref = impl_Fremovexattr + } else { + *funcref = error_Fremovexattr + } + return (*funcref)(fd, attr) + } func error_Fremovexattr(fd int, attr string) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_READ<<4, uintptr(fd), uintptr(_p0), uintptr(len(p))) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_WRITE<<4, uintptr(fd), uintptr(_p0), uintptr(len(p))) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(dest) > 0 { + _p1 = unsafe.Pointer(&dest[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FGETXATTR_A<<4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) + runtime.ExitSyscall() + sz = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_FgetxattrAddr() *(func(fd int, attr string, dest []byte) (sz int, err error)) var Fgetxattr = enter_Fgetxattr func enter_Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) { + funcref := get_FgetxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___FGETXATTR_A<<4, "") == 0 { + *funcref = impl_Fgetxattr + } else { + *funcref = error_Fgetxattr + } + return (*funcref)(fd, attr, dest) + } func error_Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) { + sz = -1 + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Fsetxattr(fd int, attr string, data []byte, flag int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(data) > 0 { + _p1 = unsafe.Pointer(&data[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FSETXATTR_A<<4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(data)), uintptr(flag)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_FsetxattrAddr() *(func(fd int, attr string, data []byte, flag int) (err error)) var Fsetxattr = enter_Fsetxattr func enter_Fsetxattr(fd int, attr string, data []byte, flag int) (err error) { + funcref := get_FsetxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___FSETXATTR_A<<4, "") == 0 { + *funcref = impl_Fsetxattr + } else { + *funcref = error_Fsetxattr + } + return (*funcref)(fd, attr, data, flag) + } func error_Fsetxattr(fd int, attr string, data []byte, flag int) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___ACCEPT_A<<4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___ACCEPT4_A<<4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_accept4Addr() *(func(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error)) var accept4 = enter_accept4 func enter_accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + funcref := get_accept4Addr() + if funcptrtest(GetZosLibVec()+SYS___ACCEPT4_A<<4, "") == 0 { + *funcref = impl_accept4 + } else { + *funcref = error_accept4 + } + return (*funcref)(s, rsa, addrlen, flags) + } func error_accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + fd = -1 + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___BIND_A<<4, uintptr(s), uintptr(addr), uintptr(addrlen)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CONNECT_A<<4, uintptr(s), uintptr(addr), uintptr(addrlen)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETGROUPS<<4, uintptr(n), uintptr(unsafe.Pointer(list))) + nn = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETGROUPS<<4, uintptr(n), uintptr(unsafe.Pointer(list))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETSOCKOPT<<4, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETSOCKOPT<<4, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SOCKET<<4, uintptr(domain), uintptr(typ), uintptr(proto)) + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SOCKETPAIR<<4, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___GETPEERNAME_A<<4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___GETSOCKNAME_A<<4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Removexattr(path string, attr string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___REMOVEXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_RemovexattrAddr() *(func(path string, attr string) (err error)) var Removexattr = enter_Removexattr func enter_Removexattr(path string, attr string) (err error) { + funcref := get_RemovexattrAddr() + if funcptrtest(GetZosLibVec()+SYS___REMOVEXATTR_A<<4, "") == 0 { + *funcref = impl_Removexattr + } else { + *funcref = error_Removexattr + } + return (*funcref)(path, attr) + } func error_Removexattr(path string, attr string) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___RECVFROM_A<<4, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___SENDTO_A<<4, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___RECVMSG_A<<4, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___SENDMSG_A<<4, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_MMAP<<4, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) + runtime.ExitSyscall() + ret = uintptr(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_MUNMAP<<4, uintptr(addr), uintptr(length)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req int, arg uintptr) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_IOCTL<<4, uintptr(fd), uintptr(req), uintptr(arg)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req int, arg unsafe.Pointer) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_IOCTL<<4, uintptr(fd), uintptr(req), uintptr(arg)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func shmat(id int, addr uintptr, flag int) (ret uintptr, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SHMAT<<4, uintptr(id), uintptr(addr), uintptr(flag)) + runtime.ExitSyscall() + ret = uintptr(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func shmctl(id int, cmd int, buf *SysvShmDesc) (result int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SHMCTL64<<4, uintptr(id), uintptr(cmd), uintptr(unsafe.Pointer(buf))) + runtime.ExitSyscall() + result = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func shmdt(addr uintptr) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SHMDT<<4, uintptr(addr)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func shmget(key int, size int, flag int) (id int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SHMGET<<4, uintptr(key), uintptr(size), uintptr(flag)) + runtime.ExitSyscall() + id = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___ACCESS_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CHDIR_A<<4, uintptr(unsafe.Pointer(_p0))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CHOWN_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CHMOD_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Creat(path string, mode uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CREAT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_DUP<<4, uintptr(oldfd)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(oldfd int, newfd int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_DUP2<<4, uintptr(oldfd), uintptr(newfd)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Dup3(oldfd int, newfd int, flags int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_DUP3<<4, uintptr(oldfd), uintptr(newfd), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_Dup3Addr() *(func(oldfd int, newfd int, flags int) (err error)) var Dup3 = enter_Dup3 func enter_Dup3(oldfd int, newfd int, flags int) (err error) { + funcref := get_Dup3Addr() + if funcptrtest(GetZosLibVec()+SYS_DUP3<<4, "") == 0 { + *funcref = impl_Dup3 + } else { + *funcref = error_Dup3 + } + return (*funcref)(oldfd, newfd, flags) + } func error_Dup3(oldfd int, newfd int, flags int) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Dirfd(dirp uintptr) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_DIRFD<<4, uintptr(dirp)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_DirfdAddr() *(func(dirp uintptr) (fd int, err error)) var Dirfd = enter_Dirfd func enter_Dirfd(dirp uintptr) (fd int, err error) { + funcref := get_DirfdAddr() + if funcptrtest(GetZosLibVec()+SYS_DIRFD<<4, "") == 0 { + *funcref = impl_Dirfd + } else { + *funcref = error_Dirfd + } + return (*funcref)(dirp) + } func error_Dirfd(dirp uintptr) (fd int, err error) { + fd = -1 + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_EpollCreate(size int) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_EPOLL_CREATE<<4, uintptr(size)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_EpollCreateAddr() *(func(size int) (fd int, err error)) var EpollCreate = enter_EpollCreate func enter_EpollCreate(size int) (fd int, err error) { + funcref := get_EpollCreateAddr() + if funcptrtest(GetZosLibVec()+SYS_EPOLL_CREATE<<4, "") == 0 { + *funcref = impl_EpollCreate + } else { + *funcref = error_EpollCreate + } + return (*funcref)(size) + } func error_EpollCreate(size int) (fd int, err error) { + fd = -1 + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_EpollCreate1(flags int) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_EPOLL_CREATE1<<4, uintptr(flags)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_EpollCreate1Addr() *(func(flags int) (fd int, err error)) var EpollCreate1 = enter_EpollCreate1 func enter_EpollCreate1(flags int) (fd int, err error) { + funcref := get_EpollCreate1Addr() + if funcptrtest(GetZosLibVec()+SYS_EPOLL_CREATE1<<4, "") == 0 { + *funcref = impl_EpollCreate1 + } else { + *funcref = error_EpollCreate1 + } + return (*funcref)(flags) + } func error_EpollCreate1(flags int) (fd int, err error) { + fd = -1 + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_EPOLL_CTL<<4, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_EpollCtlAddr() *(func(epfd int, op int, fd int, event *EpollEvent) (err error)) var EpollCtl = enter_EpollCtl func enter_EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { + funcref := get_EpollCtlAddr() + if funcptrtest(GetZosLibVec()+SYS_EPOLL_CTL<<4, "") == 0 { + *funcref = impl_EpollCtl + } else { + *funcref = error_EpollCtl + } + return (*funcref)(epfd, op, fd, event) + } func error_EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_EpollPwait(epfd int, events []EpollEvent, msec int, sigmask *int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_EPOLL_PWAIT<<4, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), uintptr(unsafe.Pointer(sigmask))) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_EpollPwaitAddr() *(func(epfd int, events []EpollEvent, msec int, sigmask *int) (n int, err error)) var EpollPwait = enter_EpollPwait func enter_EpollPwait(epfd int, events []EpollEvent, msec int, sigmask *int) (n int, err error) { + funcref := get_EpollPwaitAddr() + if funcptrtest(GetZosLibVec()+SYS_EPOLL_PWAIT<<4, "") == 0 { + *funcref = impl_EpollPwait + } else { + *funcref = error_EpollPwait + } + return (*funcref)(epfd, events, msec, sigmask) + } func error_EpollPwait(epfd int, events []EpollEvent, msec int, sigmask *int) (n int, err error) { + n = -1 + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_EPOLL_WAIT<<4, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec)) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_EpollWaitAddr() *(func(epfd int, events []EpollEvent, msec int) (n int, err error)) var EpollWait = enter_EpollWait func enter_EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + funcref := get_EpollWaitAddr() + if funcptrtest(GetZosLibVec()+SYS_EPOLL_WAIT<<4, "") == 0 { + *funcref = impl_EpollWait + } else { + *funcref = error_EpollWait + } + return (*funcref)(epfd, events, msec) + } func error_EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + n = -1 + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Errno2() (er2 int) { + runtime.EnterSyscall() + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS___ERRNO2<<4) + runtime.ExitSyscall() + er2 = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Eventfd(initval uint, flags int) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_EVENTFD<<4, uintptr(initval), uintptr(flags)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_EventfdAddr() *(func(initval uint, flags int) (fd int, err error)) var Eventfd = enter_Eventfd func enter_Eventfd(initval uint, flags int) (fd int, err error) { + funcref := get_EventfdAddr() + if funcptrtest(GetZosLibVec()+SYS_EVENTFD<<4, "") == 0 { + *funcref = impl_Eventfd + } else { + *funcref = error_Eventfd + } + return (*funcref)(initval, flags) + } func error_Eventfd(initval uint, flags int) (fd int, err error) { + fd = -1 + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { + runtime.EnterSyscall() + CallLeFuncWithErr(GetZosLibVec()+SYS_EXIT<<4, uintptr(code)) + runtime.ExitSyscall() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FACCESSAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_FaccessatAddr() *(func(dirfd int, path string, mode uint32, flags int) (err error)) var Faccessat = enter_Faccessat func enter_Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + funcref := get_FaccessatAddr() + if funcptrtest(GetZosLibVec()+SYS___FACCESSAT_A<<4, "") == 0 { + *funcref = impl_Faccessat + } else { + *funcref = error_Faccessat + } + return (*funcref)(dirfd, path, mode, flags) + } func error_Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCHDIR<<4, uintptr(fd)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCHMOD<<4, uintptr(fd), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FCHMODAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_FchmodatAddr() *(func(dirfd int, path string, mode uint32, flags int) (err error)) var Fchmodat = enter_Fchmodat func enter_Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + funcref := get_FchmodatAddr() + if funcptrtest(GetZosLibVec()+SYS___FCHMODAT_A<<4, "") == 0 { + *funcref = impl_Fchmodat + } else { + *funcref = error_Fchmodat + } + return (*funcref)(dirfd, path, mode, flags) + } func error_Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCHOWN<<4, uintptr(fd), uintptr(uid), uintptr(gid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Fchownat(fd int, path string, uid int, gid int, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FCHOWNAT_A<<4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_FchownatAddr() *(func(fd int, path string, uid int, gid int, flags int) (err error)) var Fchownat = enter_Fchownat func enter_Fchownat(fd int, path string, uid int, gid int, flags int) (err error) { + funcref := get_FchownatAddr() + if funcptrtest(GetZosLibVec()+SYS___FCHOWNAT_A<<4, "") == 0 { + *funcref = impl_Fchownat + } else { + *funcref = error_Fchownat + } + return (*funcref)(fd, path, uid, gid, flags) + } func error_Fchownat(fd int, path string, uid int, gid int, flags int) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func FcntlInt(fd uintptr, cmd int, arg int) (retval int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCNTL<<4, uintptr(fd), uintptr(cmd), uintptr(arg)) + runtime.ExitSyscall() + retval = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Fdatasync(fd int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FDATASYNC<<4, uintptr(fd)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_FdatasyncAddr() *(func(fd int) (err error)) var Fdatasync = enter_Fdatasync func enter_Fdatasync(fd int) (err error) { + funcref := get_FdatasyncAddr() + if funcptrtest(GetZosLibVec()+SYS_FDATASYNC<<4, "") == 0 { + *funcref = impl_Fdatasync + } else { + *funcref = error_Fdatasync + } + return (*funcref)(fd) + } func error_Fdatasync(fd int) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fstat(fd int, stat *Stat_LE_t) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FSTAT<<4, uintptr(fd), uintptr(unsafe.Pointer(stat))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_fstatat(dirfd int, path string, stat *Stat_LE_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FSTATAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_fstatatAddr() *(func(dirfd int, path string, stat *Stat_LE_t, flags int) (err error)) var fstatat = enter_fstatat func enter_fstatat(dirfd int, path string, stat *Stat_LE_t, flags int) (err error) { + funcref := get_fstatatAddr() + if funcptrtest(GetZosLibVec()+SYS___FSTATAT_A<<4, "") == 0 { + *funcref = impl_fstatat + } else { + *funcref = error_fstatat + } + return (*funcref)(dirfd, path, stat, flags) + } func error_fstatat(dirfd int, path string, stat *Stat_LE_t, flags int) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Lgetxattr(link string, attr string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(dest) > 0 { + _p2 = unsafe.Pointer(&dest[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LGETXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest))) + runtime.ExitSyscall() + sz = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_LgetxattrAddr() *(func(link string, attr string, dest []byte) (sz int, err error)) var Lgetxattr = enter_Lgetxattr func enter_Lgetxattr(link string, attr string, dest []byte) (sz int, err error) { + funcref := get_LgetxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___LGETXATTR_A<<4, "") == 0 { + *funcref = impl_Lgetxattr + } else { + *funcref = error_Lgetxattr + } + return (*funcref)(link, attr, dest) + } func error_Lgetxattr(link string, attr string, dest []byte) (sz int, err error) { + sz = -1 + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Lsetxattr(path string, attr string, data []byte, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(data) > 0 { + _p2 = unsafe.Pointer(&data[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LSETXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_LsetxattrAddr() *(func(path string, attr string, data []byte, flags int) (err error)) var Lsetxattr = enter_Lsetxattr func enter_Lsetxattr(path string, attr string, data []byte, flags int) (err error) { + funcref := get_LsetxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___LSETXATTR_A<<4, "") == 0 { + *funcref = impl_Lsetxattr + } else { + *funcref = error_Lsetxattr + } + return (*funcref)(path, attr, data, flags) + } func error_Lsetxattr(path string, attr string, data []byte, flags int) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Fstatfs(fd int, buf *Statfs_t) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FSTATFS<<4, uintptr(fd), uintptr(unsafe.Pointer(buf))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_FstatfsAddr() *(func(fd int, buf *Statfs_t) (err error)) var Fstatfs = enter_Fstatfs func enter_Fstatfs(fd int, buf *Statfs_t) (err error) { + funcref := get_FstatfsAddr() + if funcptrtest(GetZosLibVec()+SYS_FSTATFS<<4, "") == 0 { + *funcref = impl_Fstatfs + } else { + *funcref = error_Fstatfs + } + return (*funcref)(fd, buf) + } func error_Fstatfs(fd int, buf *Statfs_t) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatvfs(fd int, stat *Statvfs_t) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FSTATVFS<<4, uintptr(fd), uintptr(unsafe.Pointer(stat))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FSYNC<<4, uintptr(fd)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Futimes(fd int, tv []Timeval) (err error) { + var _p0 unsafe.Pointer + if len(tv) > 0 { + _p0 = unsafe.Pointer(&tv[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FUTIMES<<4, uintptr(fd), uintptr(_p0), uintptr(len(tv))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_FutimesAddr() *(func(fd int, tv []Timeval) (err error)) var Futimes = enter_Futimes func enter_Futimes(fd int, tv []Timeval) (err error) { + funcref := get_FutimesAddr() + if funcptrtest(GetZosLibVec()+SYS_FUTIMES<<4, "") == 0 { + *funcref = impl_Futimes + } else { + *funcref = error_Futimes + } + return (*funcref)(fd, tv) + } func error_Futimes(fd int, tv []Timeval) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Futimesat(dirfd int, path string, tv []Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(tv) > 0 { + _p1 = unsafe.Pointer(&tv[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FUTIMESAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(tv))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_FutimesatAddr() *(func(dirfd int, path string, tv []Timeval) (err error)) var Futimesat = enter_Futimesat func enter_Futimesat(dirfd int, path string, tv []Timeval) (err error) { + funcref := get_FutimesatAddr() + if funcptrtest(GetZosLibVec()+SYS___FUTIMESAT_A<<4, "") == 0 { + *funcref = impl_Futimesat + } else { + *funcref = error_Futimesat + } + return (*funcref)(dirfd, path, tv) + } func error_Futimesat(dirfd int, path string, tv []Timeval) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FTRUNCATE<<4, uintptr(fd), uintptr(length)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Getrandom(buf []byte, flags int) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETRANDOM<<4, uintptr(_p0), uintptr(len(buf)), uintptr(flags)) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_GetrandomAddr() *(func(buf []byte, flags int) (n int, err error)) var Getrandom = enter_Getrandom func enter_Getrandom(buf []byte, flags int) (n int, err error) { + funcref := get_GetrandomAddr() + if funcptrtest(GetZosLibVec()+SYS_GETRANDOM<<4, "") == 0 { + *funcref = impl_Getrandom + } else { + *funcref = error_Getrandom + } + return (*funcref)(buf, flags) + } func error_Getrandom(buf []byte, flags int) (n int, err error) { + n = -1 + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_InotifyInit() (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec() + SYS_INOTIFY_INIT<<4) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_InotifyInitAddr() *(func() (fd int, err error)) var InotifyInit = enter_InotifyInit func enter_InotifyInit() (fd int, err error) { + funcref := get_InotifyInitAddr() + if funcptrtest(GetZosLibVec()+SYS_INOTIFY_INIT<<4, "") == 0 { + *funcref = impl_InotifyInit + } else { + *funcref = error_InotifyInit + } + return (*funcref)() + } func error_InotifyInit() (fd int, err error) { + fd = -1 + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_InotifyInit1(flags int) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_INOTIFY_INIT1<<4, uintptr(flags)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_InotifyInit1Addr() *(func(flags int) (fd int, err error)) var InotifyInit1 = enter_InotifyInit1 func enter_InotifyInit1(flags int) (fd int, err error) { + funcref := get_InotifyInit1Addr() + if funcptrtest(GetZosLibVec()+SYS_INOTIFY_INIT1<<4, "") == 0 { + *funcref = impl_InotifyInit1 + } else { + *funcref = error_InotifyInit1 + } + return (*funcref)(flags) + } func error_InotifyInit1(flags int) (fd int, err error) { + fd = -1 + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(pathname) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___INOTIFY_ADD_WATCH_A<<4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) + runtime.ExitSyscall() + watchdesc = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_InotifyAddWatchAddr() *(func(fd int, pathname string, mask uint32) (watchdesc int, err error)) var InotifyAddWatch = enter_InotifyAddWatch func enter_InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { + funcref := get_InotifyAddWatchAddr() + if funcptrtest(GetZosLibVec()+SYS___INOTIFY_ADD_WATCH_A<<4, "") == 0 { + *funcref = impl_InotifyAddWatch + } else { + *funcref = error_InotifyAddWatch + } + return (*funcref)(fd, pathname, mask) + } func error_InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { + watchdesc = -1 + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_INOTIFY_RM_WATCH<<4, uintptr(fd), uintptr(watchdesc)) + runtime.ExitSyscall() + success = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_InotifyRmWatchAddr() *(func(fd int, watchdesc uint32) (success int, err error)) var InotifyRmWatch = enter_InotifyRmWatch func enter_InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { + funcref := get_InotifyRmWatchAddr() + if funcptrtest(GetZosLibVec()+SYS_INOTIFY_RM_WATCH<<4, "") == 0 { + *funcref = impl_InotifyRmWatch + } else { + *funcref = error_InotifyRmWatch + } + return (*funcref)(fd, watchdesc) + } func error_InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { + success = -1 + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Listxattr(path string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(dest) > 0 { + _p1 = unsafe.Pointer(&dest[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LISTXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) + runtime.ExitSyscall() + sz = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_ListxattrAddr() *(func(path string, dest []byte) (sz int, err error)) var Listxattr = enter_Listxattr func enter_Listxattr(path string, dest []byte) (sz int, err error) { + funcref := get_ListxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___LISTXATTR_A<<4, "") == 0 { + *funcref = impl_Listxattr + } else { + *funcref = error_Listxattr + } + return (*funcref)(path, dest) + } func error_Listxattr(path string, dest []byte) (sz int, err error) { + sz = -1 + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Llistxattr(path string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(dest) > 0 { + _p1 = unsafe.Pointer(&dest[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LLISTXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) + runtime.ExitSyscall() + sz = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_LlistxattrAddr() *(func(path string, dest []byte) (sz int, err error)) var Llistxattr = enter_Llistxattr func enter_Llistxattr(path string, dest []byte) (sz int, err error) { + funcref := get_LlistxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___LLISTXATTR_A<<4, "") == 0 { + *funcref = impl_Llistxattr + } else { + *funcref = error_Llistxattr + } + return (*funcref)(path, dest) + } func error_Llistxattr(path string, dest []byte) (sz int, err error) { + sz = -1 + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Lremovexattr(path string, attr string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LREMOVEXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_LremovexattrAddr() *(func(path string, attr string) (err error)) var Lremovexattr = enter_Lremovexattr func enter_Lremovexattr(path string, attr string) (err error) { + funcref := get_LremovexattrAddr() + if funcptrtest(GetZosLibVec()+SYS___LREMOVEXATTR_A<<4, "") == 0 { + *funcref = impl_Lremovexattr + } else { + *funcref = error_Lremovexattr + } + return (*funcref)(path, attr) + } func error_Lremovexattr(path string, attr string) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Lutimes(path string, tv []Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(tv) > 0 { + _p1 = unsafe.Pointer(&tv[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LUTIMES_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(tv))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_LutimesAddr() *(func(path string, tv []Timeval) (err error)) var Lutimes = enter_Lutimes func enter_Lutimes(path string, tv []Timeval) (err error) { + funcref := get_LutimesAddr() + if funcptrtest(GetZosLibVec()+SYS___LUTIMES_A<<4, "") == 0 { + *funcref = impl_Lutimes + } else { + *funcref = error_Lutimes + } + return (*funcref)(path, tv) + } func error_Lutimes(path string, tv []Timeval) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_MPROTECT<<4, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_MSYNC<<4, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Console2(cmsg *ConsMsg2, modstr *byte, concmd *uint32) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CONSOLE2<<4, uintptr(unsafe.Pointer(cmsg)), uintptr(unsafe.Pointer(modstr)), uintptr(unsafe.Pointer(concmd))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Poll(fds []PollFd, timeout int) (n int, err error) { + var _p0 unsafe.Pointer + if len(fds) > 0 { + _p0 = unsafe.Pointer(&fds[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_POLL<<4, uintptr(_p0), uintptr(len(fds)), uintptr(timeout)) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readdir_r(dirp uintptr, entry *direntLE, result **direntLE) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___READDIR_R_A<<4, uintptr(dirp), uintptr(unsafe.Pointer(entry)), uintptr(unsafe.Pointer(result))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Statfs(path string, buf *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___STATFS_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_StatfsAddr() *(func(path string, buf *Statfs_t) (err error)) var Statfs = enter_Statfs func enter_Statfs(path string, buf *Statfs_t) (err error) { + funcref := get_StatfsAddr() + if funcptrtest(GetZosLibVec()+SYS___STATFS_A<<4, "") == 0 { + *funcref = impl_Statfs + } else { + *funcref = error_Statfs + } + return (*funcref)(path, buf) + } func error_Statfs(path string, buf *Statfs_t) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Syncfs(fd int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SYNCFS<<4, uintptr(fd)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_SyncfsAddr() *(func(fd int) (err error)) var Syncfs = enter_Syncfs func enter_Syncfs(fd int) (err error) { + funcref := get_SyncfsAddr() + if funcptrtest(GetZosLibVec()+SYS_SYNCFS<<4, "") == 0 { + *funcref = impl_Syncfs + } else { + *funcref = error_Syncfs + } + return (*funcref)(fd) + } func error_Syncfs(fd int) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_TIMES<<4, uintptr(unsafe.Pointer(tms))) + runtime.ExitSyscall() + ticks = uintptr(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func W_Getmntent(buff *byte, size int) (lastsys int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_W_GETMNTENT<<4, uintptr(unsafe.Pointer(buff)), uintptr(size)) + runtime.ExitSyscall() + lastsys = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func W_Getmntent_A(buff *byte, size int) (lastsys int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___W_GETMNTENT_A<<4, uintptr(unsafe.Pointer(buff)), uintptr(size)) + runtime.ExitSyscall() + lastsys = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount_LE(path string, filesystem string, fstype string, mtm uint32, parmlen int32, parm string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(filesystem) + if err != nil { + return + } + var _p2 *byte + _p2, err = BytePtrFromString(fstype) + if err != nil { + return + } + var _p3 *byte + _p3, err = BytePtrFromString(parm) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MOUNT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(mtm), uintptr(parmlen), uintptr(unsafe.Pointer(_p3))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func unmount_LE(filesystem string, mtm int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(filesystem) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UMOUNT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mtm)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CHROOT_A<<4, uintptr(unsafe.Pointer(_p0))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nmsgsfds int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (ret int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SELECT<<4, uintptr(nmsgsfds), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout))) + runtime.ExitSyscall() + ret = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_____OSNAME_A<<4, uintptr(unsafe.Pointer(buf))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Unshare(flags int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_UNSHARE<<4, uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_UnshareAddr() *(func(flags int) (err error)) var Unshare = enter_Unshare func enter_Unshare(flags int) (err error) { + funcref := get_UnshareAddr() + if funcptrtest(GetZosLibVec()+SYS_UNSHARE<<4, "") == 0 { + *funcref = impl_Unshare + } else { + *funcref = error_Unshare + } + return (*funcref)(flags) + } func error_Unshare(flags int) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gethostname(buf []byte) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___GETHOSTNAME_A<<4, uintptr(_p0), uintptr(len(buf))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS_GETGID<<4) + gid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS_GETPID<<4) + pid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETPGID<<4, uintptr(pid)) + pgid = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (pid int) { + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS_GETPPID<<4) + pid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETPRIORITY<<4, uintptr(which), uintptr(who)) + runtime.ExitSyscall() + prio = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(resource int, rlim *Rlimit) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETRLIMIT<<4, uintptr(resource), uintptr(unsafe.Pointer(rlim))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getrusage(who int, rusage *rusage_zos) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETRUSAGE<<4, uintptr(who), uintptr(unsafe.Pointer(rusage))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { + runtime.EnterSyscall() + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS_GETEGID<<4) + runtime.ExitSyscall() + egid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { + runtime.EnterSyscall() + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS_GETEUID<<4) + runtime.ExitSyscall() + euid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETSID<<4, uintptr(pid)) + sid = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS_GETUID<<4) + uid = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig Signal) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_KILL<<4, uintptr(pid), uintptr(sig)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LCHOWN_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LINK_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Linkat(oldDirFd int, oldPath string, newDirFd int, newPath string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldPath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newPath) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LINKAT_A<<4, uintptr(oldDirFd), uintptr(unsafe.Pointer(_p0)), uintptr(newDirFd), uintptr(unsafe.Pointer(_p1)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_LinkatAddr() *(func(oldDirFd int, oldPath string, newDirFd int, newPath string, flags int) (err error)) var Linkat = enter_Linkat func enter_Linkat(oldDirFd int, oldPath string, newDirFd int, newPath string, flags int) (err error) { + funcref := get_LinkatAddr() + if funcptrtest(GetZosLibVec()+SYS___LINKAT_A<<4, "") == 0 { + *funcref = impl_Linkat + } else { + *funcref = error_Linkat + } + return (*funcref)(oldDirFd, oldPath, newDirFd, newPath, flags) + } func error_Linkat(oldDirFd int, oldPath string, newDirFd int, newPath string, flags int) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_LISTEN<<4, uintptr(s), uintptr(n)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func lstat(path string, stat *Stat_LE_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LSTAT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MKDIR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MKDIRAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_MkdiratAddr() *(func(dirfd int, path string, mode uint32) (err error)) var Mkdirat = enter_Mkdirat func enter_Mkdirat(dirfd int, path string, mode uint32) (err error) { + funcref := get_MkdiratAddr() + if funcptrtest(GetZosLibVec()+SYS___MKDIRAT_A<<4, "") == 0 { + *funcref = impl_Mkdirat + } else { + *funcref = error_Mkdirat + } + return (*funcref)(dirfd, path, mode) + } func error_Mkdirat(dirfd int, path string, mode uint32) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MKFIFO_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MKNOD_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MKNODAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_MknodatAddr() *(func(dirfd int, path string, mode uint32, dev int) (err error)) var Mknodat = enter_Mknodat func enter_Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + funcref := get_MknodatAddr() + if funcptrtest(GetZosLibVec()+SYS___MKNODAT_A<<4, "") == 0 { + *funcref = impl_Mknodat + } else { + *funcref = error_Mknodat + } + return (*funcref)(dirfd, path, mode, dev) + } func error_Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_PivotRoot(newroot string, oldroot string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(newroot) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(oldroot) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___PIVOT_ROOT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_PivotRootAddr() *(func(newroot string, oldroot string) (err error)) var PivotRoot = enter_PivotRoot func enter_PivotRoot(newroot string, oldroot string) (err error) { + funcref := get_PivotRootAddr() + if funcptrtest(GetZosLibVec()+SYS___PIVOT_ROOT_A<<4, "") == 0 { + *funcref = impl_PivotRoot + } else { + *funcref = error_PivotRoot + } + return (*funcref)(newroot, oldroot) + } func error_PivotRoot(newroot string, oldroot string) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_PREAD<<4, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset)) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_PWRITE<<4, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset)) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___PRCTL_A<<4, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_PrctlAddr() *(func(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error)) var Prctl = enter_Prctl func enter_Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { + funcref := get_PrctlAddr() + if funcptrtest(GetZosLibVec()+SYS___PRCTL_A<<4, "") == 0 { + *funcref = impl_Prctl + } else { + *funcref = error_Prctl + } + return (*funcref)(option, arg2, arg3, arg4, arg5) + } func error_Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_PRLIMIT<<4, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_PrlimitAddr() *(func(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error)) var Prlimit = enter_Prlimit func enter_Prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + funcref := get_PrlimitAddr() + if funcptrtest(GetZosLibVec()+SYS_PRLIMIT<<4, "") == 0 { + *funcref = impl_Prlimit + } else { + *funcref = error_Prlimit + } + return (*funcref)(pid, resource, newlimit, old) + } func error_Prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___RENAME_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___RENAMEAT_A<<4, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_RenameatAddr() *(func(olddirfd int, oldpath string, newdirfd int, newpath string) (err error)) var Renameat = enter_Renameat func enter_Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + funcref := get_RenameatAddr() + if funcptrtest(GetZosLibVec()+SYS___RENAMEAT_A<<4, "") == 0 { + *funcref = impl_Renameat + } else { + *funcref = error_Renameat + } + return (*funcref)(olddirfd, oldpath, newdirfd, newpath) + } func error_Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Renameat2(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___RENAMEAT2_A<<4, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_Renameat2Addr() *(func(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error)) var Renameat2 = enter_Renameat2 func enter_Renameat2(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error) { + funcref := get_Renameat2Addr() + if funcptrtest(GetZosLibVec()+SYS___RENAMEAT2_A<<4, "") == 0 { + *funcref = impl_Renameat2 + } else { + *funcref = error_Renameat2 + } + return (*funcref)(olddirfd, oldpath, newdirfd, newpath, flags) + } func error_Renameat2(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___RMDIR_A<<4, uintptr(unsafe.Pointer(_p0))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_LSEEK<<4, uintptr(fd), uintptr(offset), uintptr(whence)) + runtime.ExitSyscall() + off = int64(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETEGID<<4, uintptr(egid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETEUID<<4, uintptr(euid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Sethostname(p []byte) (err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___SETHOSTNAME_A<<4, uintptr(_p0), uintptr(len(p))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_SethostnameAddr() *(func(p []byte) (err error)) var Sethostname = enter_Sethostname func enter_Sethostname(p []byte) (err error) { + funcref := get_SethostnameAddr() + if funcptrtest(GetZosLibVec()+SYS___SETHOSTNAME_A<<4, "") == 0 { + *funcref = impl_Sethostname + } else { + *funcref = error_Sethostname + } + return (*funcref)(p) + } func error_Sethostname(p []byte) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Setns(fd int, nstype int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETNS<<4, uintptr(fd), uintptr(nstype)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_SetnsAddr() *(func(fd int, nstype int) (err error)) var Setns = enter_Setns func enter_Setns(fd int, nstype int) (err error) { + funcref := get_SetnsAddr() + if funcptrtest(GetZosLibVec()+SYS_SETNS<<4, "") == 0 { + *funcref = impl_Setns + } else { + *funcref = error_Setns + } + return (*funcref)(fd, nstype) + } func error_Setns(fd int, nstype int) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETPRIORITY<<4, uintptr(which), uintptr(who), uintptr(prio)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETPGID<<4, uintptr(pid), uintptr(pgid)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(resource int, lim *Rlimit) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETRLIMIT<<4, uintptr(resource), uintptr(unsafe.Pointer(lim))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETREGID<<4, uintptr(rgid), uintptr(egid)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETREUID<<4, uintptr(ruid), uintptr(euid)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec() + SYS_SETSID<<4) + pid = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETUID<<4, uintptr(uid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(uid int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETGID<<4, uintptr(uid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SHUTDOWN<<4, uintptr(fd), uintptr(how)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func stat(path string, statLE *Stat_LE_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___STAT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(statLE))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___SYMLINK_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Symlinkat(oldPath string, dirfd int, newPath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldPath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newPath) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___SYMLINKAT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(dirfd), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_SymlinkatAddr() *(func(oldPath string, dirfd int, newPath string) (err error)) var Symlinkat = enter_Symlinkat func enter_Symlinkat(oldPath string, dirfd int, newPath string) (err error) { + funcref := get_SymlinkatAddr() + if funcptrtest(GetZosLibVec()+SYS___SYMLINKAT_A<<4, "") == 0 { + *funcref = impl_Symlinkat + } else { + *funcref = error_Symlinkat + } + return (*funcref)(oldPath, dirfd, newPath) + } func error_Symlinkat(oldPath string, dirfd int, newPath string) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { + runtime.EnterSyscall() + CallLeFuncWithErr(GetZosLibVec() + SYS_SYNC<<4) + runtime.ExitSyscall() + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___TRUNCATE_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(length)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tcgetattr(fildes int, termptr *Termios) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_TCGETATTR<<4, uintptr(fildes), uintptr(unsafe.Pointer(termptr))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tcsetattr(fildes int, when int, termptr *Termios) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_TCSETATTR<<4, uintptr(fildes), uintptr(when), uintptr(unsafe.Pointer(termptr))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { + runtime.EnterSyscall() + r0, _, _ := CallLeFuncWithErr(GetZosLibVec()+SYS_UMASK<<4, uintptr(mask)) + runtime.ExitSyscall() + oldmask = int(r0) + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UNLINK_A<<4, uintptr(unsafe.Pointer(_p0))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UNLINKAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_UnlinkatAddr() *(func(dirfd int, path string, flags int) (err error)) var Unlinkat = enter_Unlinkat func enter_Unlinkat(dirfd int, path string, flags int) (err error) { + funcref := get_UnlinkatAddr() + if funcptrtest(GetZosLibVec()+SYS___UNLINKAT_A<<4, "") == 0 { + *funcref = impl_Unlinkat + } else { + *funcref = error_Unlinkat + } + return (*funcref)(dirfd, path, flags) + } func error_Unlinkat(dirfd int, path string, flags int) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, utim *Utimbuf) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UTIME_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(utim))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func open(path string, mode int, perm uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___OPEN_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___OPENAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_openatAddr() *(func(dirfd int, path string, flags int, mode uint32) (fd int, err error)) var openat = enter_openat func enter_openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { + funcref := get_openatAddr() + if funcptrtest(GetZosLibVec()+SYS___OPENAT_A<<4, "") == 0 { + *funcref = impl_openat + } else { + *funcref = error_openat + } + return (*funcref)(dirfd, path, flags, mode) + } func error_openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { + fd = -1 + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_openat2(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___OPENAT2_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(open_how)), uintptr(size)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_openat2Addr() *(func(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error)) var openat2 = enter_openat2 func enter_openat2(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error) { + funcref := get_openat2Addr() + if funcptrtest(GetZosLibVec()+SYS___OPENAT2_A<<4, "") == 0 { + *funcref = impl_openat2 + } else { + *funcref = error_openat2 + } + return (*funcref)(dirfd, path, open_how, size) + } func error_openat2(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error) { + fd = -1 + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func remove(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_REMOVE<<4, uintptr(unsafe.Pointer(_p0))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func waitid(idType int, id int, info *Siginfo, options int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_WAITID<<4, uintptr(idType), uintptr(id), uintptr(unsafe.Pointer(info)), uintptr(options)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func waitpid(pid int, wstatus *_C_int, options int) (wpid int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_WAITPID<<4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options)) + runtime.ExitSyscall() + wpid = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func gettimeofday(tv *timeval_zos) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETTIMEOFDAY<<4, uintptr(unsafe.Pointer(tv))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]_C_int) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_PIPE<<4, uintptr(unsafe.Pointer(p))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UTIMES_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func impl_utimensat(dirfd int, path string, ts *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UTIMENSAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(ts)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } //go:nosplit + func get_utimensatAddr() *(func(dirfd int, path string, ts *[2]Timespec, flags int) (err error)) var utimensat = enter_utimensat func enter_utimensat(dirfd int, path string, ts *[2]Timespec, flags int) (err error) { + funcref := get_utimensatAddr() + if funcptrtest(GetZosLibVec()+SYS___UTIMENSAT_A<<4, "") == 0 { + *funcref = impl_utimensat + } else { + *funcref = error_utimensat + } + return (*funcref)(dirfd, path, ts, flags) + } func error_utimensat(dirfd int, path string, ts *[2]Timespec, flags int) (err error) { + err = ENOSYS + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Posix_openpt(oflag int) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_POSIX_OPENPT<<4, uintptr(oflag)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Grantpt(fildes int) (rc int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GRANTPT<<4, uintptr(fildes)) + runtime.ExitSyscall() + rc = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlockpt(fildes int) (rc int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_UNLOCKPT<<4, uintptr(fildes)) + runtime.ExitSyscall() + rc = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return + } diff --git a/vendor/golang.org/x/sys/windows/dll_windows.go b/vendor/golang.org/x/sys/windows/dll_windows.go index 115341f..824d629 100644 --- a/vendor/golang.org/x/sys/windows/dll_windows.go +++ b/vendor/golang.org/x/sys/windows/dll_windows.go @@ -1,5 +1,7 @@ // Copyright 2011 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package windows @@ -12,22 +14,31 @@ import ( ) // We need to use LoadLibrary and GetProcAddress from the Go runtime, because + // the these symbols are loaded by the system linker and are required to + // dynamically load additional symbols. Note that in the Go runtime, these + // return syscall.Handle and syscall.Errno, but these are the same, in fact, + // as windows.Handle and windows.Errno, and we intend to keep these the same. //go:linkname syscall_loadlibrary syscall.loadlibrary + func syscall_loadlibrary(filename *uint16) (handle Handle, err Errno) //go:linkname syscall_getprocaddress syscall.getprocaddress + func syscall_getprocaddress(handle Handle, procname *uint8) (proc uintptr, err Errno) // DLLError describes reasons for DLL load failures. + type DLLError struct { - Err error + Err error + ObjName string - Msg string + + Msg string } func (e *DLLError) Error() string { return e.Msg } @@ -35,380 +46,672 @@ func (e *DLLError) Error() string { return e.Msg } func (e *DLLError) Unwrap() error { return e.Err } // A DLL implements access to a single DLL. + type DLL struct { - Name string + Name string + Handle Handle } // LoadDLL loads DLL file into memory. + // + // Warning: using LoadDLL without an absolute path name is subject to + // DLL preloading attacks. To safely load a system DLL, use LazyDLL + // with System set to true, or use LoadLibraryEx directly. + func LoadDLL(name string) (dll *DLL, err error) { + namep, err := UTF16PtrFromString(name) + if err != nil { + return nil, err + } + h, e := syscall_loadlibrary(namep) + if e != 0 { + return nil, &DLLError{ - Err: e, + + Err: e, + ObjName: name, - Msg: "Failed to load " + name + ": " + e.Error(), + + Msg: "Failed to load " + name + ": " + e.Error(), } + } + d := &DLL{ - Name: name, + + Name: name, + Handle: h, } + return d, nil + } // MustLoadDLL is like LoadDLL but panics if load operation failes. + func MustLoadDLL(name string) *DLL { + d, e := LoadDLL(name) + if e != nil { + panic(e) + } + return d + } // FindProc searches DLL d for procedure named name and returns *Proc + // if found. It returns an error if search fails. + func (d *DLL) FindProc(name string) (proc *Proc, err error) { + namep, err := BytePtrFromString(name) + if err != nil { + return nil, err + } + a, e := syscall_getprocaddress(d.Handle, namep) + if e != 0 { + return nil, &DLLError{ - Err: e, + + Err: e, + ObjName: name, - Msg: "Failed to find " + name + " procedure in " + d.Name + ": " + e.Error(), + + Msg: "Failed to find " + name + " procedure in " + d.Name + ": " + e.Error(), } + } + p := &Proc{ - Dll: d, + + Dll: d, + Name: name, + addr: a, } + return p, nil + } // MustFindProc is like FindProc but panics if search fails. + func (d *DLL) MustFindProc(name string) *Proc { + p, e := d.FindProc(name) + if e != nil { + panic(e) + } + return p + } // FindProcByOrdinal searches DLL d for procedure by ordinal and returns *Proc + // if found. It returns an error if search fails. + func (d *DLL) FindProcByOrdinal(ordinal uintptr) (proc *Proc, err error) { + a, e := GetProcAddressByOrdinal(d.Handle, ordinal) + name := "#" + itoa(int(ordinal)) + if e != nil { + return nil, &DLLError{ - Err: e, + + Err: e, + ObjName: name, - Msg: "Failed to find " + name + " procedure in " + d.Name + ": " + e.Error(), + + Msg: "Failed to find " + name + " procedure in " + d.Name + ": " + e.Error(), } + } + p := &Proc{ - Dll: d, + + Dll: d, + Name: name, + addr: a, } + return p, nil + } // MustFindProcByOrdinal is like FindProcByOrdinal but panics if search fails. + func (d *DLL) MustFindProcByOrdinal(ordinal uintptr) *Proc { + p, e := d.FindProcByOrdinal(ordinal) + if e != nil { + panic(e) + } + return p + } // Release unloads DLL d from memory. + func (d *DLL) Release() (err error) { + return FreeLibrary(d.Handle) + } // A Proc implements access to a procedure inside a DLL. + type Proc struct { - Dll *DLL + Dll *DLL + Name string + addr uintptr } // Addr returns the address of the procedure represented by p. + // The return value can be passed to Syscall to run the procedure. + func (p *Proc) Addr() uintptr { + return p.addr + } //go:uintptrescapes // Call executes procedure p with arguments a. It will panic, if more than 15 arguments + // are supplied. + // + // The returned error is always non-nil, constructed from the result of GetLastError. + // Callers must inspect the primary return value to decide whether an error occurred + // (according to the semantics of the specific function being called) before consulting + // the error. The error will be guaranteed to contain windows.Errno. + func (p *Proc) Call(a ...uintptr) (r1, r2 uintptr, lastErr error) { + switch len(a) { + case 0: + return syscall.Syscall(p.Addr(), uintptr(len(a)), 0, 0, 0) + case 1: + return syscall.Syscall(p.Addr(), uintptr(len(a)), a[0], 0, 0) + case 2: + return syscall.Syscall(p.Addr(), uintptr(len(a)), a[0], a[1], 0) + case 3: + return syscall.Syscall(p.Addr(), uintptr(len(a)), a[0], a[1], a[2]) + case 4: + return syscall.Syscall6(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], 0, 0) + case 5: + return syscall.Syscall6(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], 0) + case 6: + return syscall.Syscall6(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5]) + case 7: + return syscall.Syscall9(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], 0, 0) + case 8: + return syscall.Syscall9(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], 0) + case 9: + return syscall.Syscall9(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]) + case 10: + return syscall.Syscall12(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], 0, 0) + case 11: + return syscall.Syscall12(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], 0) + case 12: + return syscall.Syscall12(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11]) + case 13: + return syscall.Syscall15(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], 0, 0) + case 14: + return syscall.Syscall15(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], 0) + case 15: + return syscall.Syscall15(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14]) + default: + panic("Call " + p.Name + " with too many arguments " + itoa(len(a)) + ".") + } + } // A LazyDLL implements access to a single DLL. + // It will delay the load of the DLL until the first + // call to its Handle method or to one of its + // LazyProc's Addr method. + type LazyDLL struct { Name string // System determines whether the DLL must be loaded from the + // Windows System directory, bypassing the normal DLL search + // path. + System bool - mu sync.Mutex + mu sync.Mutex + dll *DLL // non nil once DLL is loaded + } // Load loads DLL file d.Name into memory. It returns an error if fails. + // Load will not try to load DLL, if it is already loaded into memory. + func (d *LazyDLL) Load() error { + // Non-racy version of: + // if d.dll != nil { + if atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&d.dll))) != nil { + return nil + } + d.mu.Lock() + defer d.mu.Unlock() + if d.dll != nil { + return nil + } // kernel32.dll is special, since it's where LoadLibraryEx comes from. + // The kernel already special-cases its name, so it's always + // loaded from system32. + var dll *DLL + var err error + if d.Name == "kernel32.dll" { + dll, err = LoadDLL(d.Name) + } else { + dll, err = loadLibraryEx(d.Name, d.System) + } + if err != nil { + return err + } // Non-racy version of: + // d.dll = dll + atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&d.dll)), unsafe.Pointer(dll)) + return nil + } // mustLoad is like Load but panics if search fails. + func (d *LazyDLL) mustLoad() { + e := d.Load() + if e != nil { + panic(e) + } + } // Handle returns d's module handle. + func (d *LazyDLL) Handle() uintptr { + d.mustLoad() + return uintptr(d.dll.Handle) + } // NewProc returns a LazyProc for accessing the named procedure in the DLL d. + func (d *LazyDLL) NewProc(name string) *LazyProc { + return &LazyProc{l: d, Name: name} + } // NewLazyDLL creates new LazyDLL associated with DLL file. + func NewLazyDLL(name string) *LazyDLL { + return &LazyDLL{Name: name} + } // NewLazySystemDLL is like NewLazyDLL, but will only + // search Windows System directory for the DLL if name is + // a base name (like "advapi32.dll"). + func NewLazySystemDLL(name string) *LazyDLL { + return &LazyDLL{Name: name, System: true} + } // A LazyProc implements access to a procedure inside a LazyDLL. + // It delays the lookup until the Addr method is called. + type LazyProc struct { Name string - mu sync.Mutex - l *LazyDLL + mu sync.Mutex + + l *LazyDLL + proc *Proc } // Find searches DLL for procedure named p.Name. It returns + // an error if search fails. Find will not search procedure, + // if it is already found and loaded into memory. + func (p *LazyProc) Find() error { + // Non-racy version of: + // if p.proc == nil { + if atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&p.proc))) == nil { + p.mu.Lock() + defer p.mu.Unlock() + if p.proc == nil { + e := p.l.Load() + if e != nil { + return e + } + proc, e := p.l.dll.FindProc(p.Name) + if e != nil { + return e + } + // Non-racy version of: + // p.proc = proc + atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&p.proc)), unsafe.Pointer(proc)) + } + } + return nil + } // mustFind is like Find but panics if search fails. + func (p *LazyProc) mustFind() { + e := p.Find() + if e != nil { + panic(e) + } + } // Addr returns the address of the procedure represented by p. + // The return value can be passed to Syscall to run the procedure. + // It will panic if the procedure cannot be found. + func (p *LazyProc) Addr() uintptr { + p.mustFind() + return p.proc.Addr() + } //go:uintptrescapes // Call executes procedure p with arguments a. It will panic, if more than 15 arguments + // are supplied. It will also panic if the procedure cannot be found. + // + // The returned error is always non-nil, constructed from the result of GetLastError. + // Callers must inspect the primary return value to decide whether an error occurred + // (according to the semantics of the specific function being called) before consulting + // the error. The error will be guaranteed to contain windows.Errno. + func (p *LazyProc) Call(a ...uintptr) (r1, r2 uintptr, lastErr error) { + p.mustFind() + return p.proc.Call(a...) + } var canDoSearchSystem32Once struct { sync.Once + v bool } func initCanDoSearchSystem32() { + // https://msdn.microsoft.com/en-us/library/ms684179(v=vs.85).aspx says: + // "Windows 7, Windows Server 2008 R2, Windows Vista, and Windows + // Server 2008: The LOAD_LIBRARY_SEARCH_* flags are available on + // systems that have KB2533623 installed. To determine whether the + // flags are available, use GetProcAddress to get the address of the + // AddDllDirectory, RemoveDllDirectory, or SetDefaultDllDirectories + // function. If GetProcAddress succeeds, the LOAD_LIBRARY_SEARCH_* + // flags can be used with LoadLibraryEx." + canDoSearchSystem32Once.v = (modkernel32.NewProc("AddDllDirectory").Find() == nil) + } func canDoSearchSystem32() bool { + canDoSearchSystem32Once.Do(initCanDoSearchSystem32) + return canDoSearchSystem32Once.v + } func isBaseName(name string) bool { + for _, c := range name { + if c == ':' || c == '/' || c == '\\' { + return false + } + } + return true + } // loadLibraryEx wraps the Windows LoadLibraryEx function. + // + // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms684179(v=vs.85).aspx + // + // If name is not an absolute path, LoadLibraryEx searches for the DLL + // in a variety of automatic locations unless constrained by flags. + // See: https://msdn.microsoft.com/en-us/library/ff919712%28VS.85%29.aspx + func loadLibraryEx(name string, system bool) (*DLL, error) { + loadDLL := name + var flags uintptr + if system { + if canDoSearchSystem32() { + flags = LOAD_LIBRARY_SEARCH_SYSTEM32 + } else if isBaseName(name) { + // WindowsXP or unpatched Windows machine + // trying to load "foo.dll" out of the system + // folder, but LoadLibraryEx doesn't support + // that yet on their system, so emulate it. + systemdir, err := GetSystemDirectory() + if err != nil { + return nil, err + } + loadDLL = systemdir + "\\" + name + } + } + h, err := LoadLibraryEx(loadDLL, 0, flags) + if err != nil { + return nil, err + } + return &DLL{Name: name, Handle: h}, nil + } type errString string diff --git a/vendor/golang.org/x/sys/windows/env_windows.go b/vendor/golang.org/x/sys/windows/env_windows.go index d4577a4..0b07429 100644 --- a/vendor/golang.org/x/sys/windows/env_windows.go +++ b/vendor/golang.org/x/sys/windows/env_windows.go @@ -1,5 +1,7 @@ // Copyright 2010 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Windows environment variables. @@ -12,46 +14,77 @@ import ( ) func Getenv(key string) (value string, found bool) { + return syscall.Getenv(key) + } func Setenv(key, value string) error { + return syscall.Setenv(key, value) + } func Clearenv() { + syscall.Clearenv() + } func Environ() []string { + return syscall.Environ() + } // Returns a default environment associated with the token, rather than the current + // process. If inheritExisting is true, then this environment also inherits the + // environment of the current process. + func (token Token) Environ(inheritExisting bool) (env []string, err error) { + var block *uint16 + err = CreateEnvironmentBlock(&block, token, inheritExisting) + if err != nil { + return nil, err + } + defer DestroyEnvironmentBlock(block) + size := unsafe.Sizeof(*block) + for *block != 0 { + // find NUL terminator + end := unsafe.Pointer(block) + for *(*uint16)(end) != 0 { + end = unsafe.Add(end, size) + } entry := unsafe.Slice(block, (uintptr(end)-uintptr(unsafe.Pointer(block)))/size) + env = append(env, UTF16ToString(entry)) + block = (*uint16)(unsafe.Add(end, size)) + } + return env, nil + } func Unsetenv(key string) error { + return syscall.Unsetenv(key) + } diff --git a/vendor/golang.org/x/sys/windows/exec_windows.go b/vendor/golang.org/x/sys/windows/exec_windows.go index 9cabbb6..5c114f0 100644 --- a/vendor/golang.org/x/sys/windows/exec_windows.go +++ b/vendor/golang.org/x/sys/windows/exec_windows.go @@ -1,5 +1,7 @@ // Copyright 2009 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Fork, exec, wait, etc. @@ -12,237 +14,445 @@ import ( ) // EscapeArg rewrites command line argument s as prescribed + // in http://msdn.microsoft.com/en-us/library/ms880421. + // This function returns "" (2 double quotes) if s is empty. + // Alternatively, these transformations are done: + // - every back slash (\) is doubled, but only if immediately + // followed by double quote ("); + // - every double quote (") is escaped by back slash (\); + // - finally, s is wrapped with double quotes (arg -> "arg"), + // but only if there is space or tab inside s. + func EscapeArg(s string) string { + if len(s) == 0 { + return `""` + } + n := len(s) + hasSpace := false + for i := 0; i < len(s); i++ { + switch s[i] { + case '"', '\\': + n++ + case ' ', '\t': + hasSpace = true + } + } + if hasSpace { + n += 2 // Reserve space for quotes. + } + if n == len(s) { + return s + } qs := make([]byte, n) + j := 0 + if hasSpace { + qs[j] = '"' + j++ + } + slashes := 0 + for i := 0; i < len(s); i++ { + switch s[i] { + default: + slashes = 0 + qs[j] = s[i] + case '\\': + slashes++ + qs[j] = s[i] + case '"': + for ; slashes > 0; slashes-- { + qs[j] = '\\' + j++ + } + qs[j] = '\\' + j++ + qs[j] = s[i] + } + j++ + } + if hasSpace { + for ; slashes > 0; slashes-- { + qs[j] = '\\' + j++ + } + qs[j] = '"' + j++ + } + return string(qs[:j]) + } // ComposeCommandLine escapes and joins the given arguments suitable for use as a Windows command line, + // in CreateProcess's CommandLine argument, CreateService/ChangeServiceConfig's BinaryPathName argument, + // or any program that uses CommandLineToArgv. + func ComposeCommandLine(args []string) string { + if len(args) == 0 { + return "" + } // Per https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-commandlinetoargvw: + // “This function accepts command lines that contain a program name; the + // program name can be enclosed in quotation marks or not.” + // + // Unfortunately, it provides no means of escaping interior quotation marks + // within that program name, and we have no way to report them here. + prog := args[0] + mustQuote := len(prog) == 0 + for i := 0; i < len(prog); i++ { + c := prog[i] + if c <= ' ' || (c == '"' && i == 0) { + // Force quotes for not only the ASCII space and tab as described in the + // MSDN article, but also ASCII control characters. + // The documentation for CommandLineToArgvW doesn't say what happens when + // the first argument is not a valid program name, but it empirically + // seems to drop unquoted control characters. + mustQuote = true + break + } + } + var commandLine []byte + if mustQuote { + commandLine = make([]byte, 0, len(prog)+2) + commandLine = append(commandLine, '"') + for i := 0; i < len(prog); i++ { + c := prog[i] + if c == '"' { + // This quote would interfere with our surrounding quotes. + // We have no way to report an error, so just strip out + // the offending character instead. + continue + } + commandLine = append(commandLine, c) + } + commandLine = append(commandLine, '"') + } else { + if len(args) == 1 { + // args[0] is a valid command line representing itself. + // No need to allocate a new slice or string for it. + return prog + } + commandLine = []byte(prog) + } for _, arg := range args[1:] { + commandLine = append(commandLine, ' ') + // TODO(bcmills): since we're already appending to a slice, it would be nice + // to avoid the intermediate allocations of EscapeArg. + // Perhaps we can factor out an appendEscapedArg function. + commandLine = append(commandLine, EscapeArg(arg)...) + } + return string(commandLine) + } // DecomposeCommandLine breaks apart its argument command line into unescaped parts using CommandLineToArgv, + // as gathered from GetCommandLine, QUERY_SERVICE_CONFIG's BinaryPathName argument, or elsewhere that + // command lines are passed around. + // DecomposeCommandLine returns an error if commandLine contains NUL. + func DecomposeCommandLine(commandLine string) ([]string, error) { + if len(commandLine) == 0 { + return []string{}, nil + } + utf16CommandLine, err := UTF16FromString(commandLine) + if err != nil { + return nil, errorspkg.New("string with NUL passed to DecomposeCommandLine") + } + var argc int32 + argv, err := commandLineToArgv(&utf16CommandLine[0], &argc) + if err != nil { + return nil, err + } + defer LocalFree(Handle(unsafe.Pointer(argv))) var args []string + for _, p := range unsafe.Slice(argv, argc) { + args = append(args, UTF16PtrToString(p)) + } + return args, nil + } // CommandLineToArgv parses a Unicode command line string and sets + // argc to the number of parsed arguments. + // + // The returned memory should be freed using a single call to LocalFree. + // + // Note that although the return type of CommandLineToArgv indicates 8192 + // entries of up to 8192 characters each, the actual count of parsed arguments + // may exceed 8192, and the documentation for CommandLineToArgvW does not mention + // any bound on the lengths of the individual argument strings. + // (See https://go.dev/issue/63236.) + func CommandLineToArgv(cmd *uint16, argc *int32) (argv *[8192]*[8192]uint16, err error) { + argp, err := commandLineToArgv(cmd, argc) + argv = (*[8192]*[8192]uint16)(unsafe.Pointer(argp)) + return argv, err + } func CloseOnExec(fd Handle) { + SetHandleInformation(Handle(fd), HANDLE_FLAG_INHERIT, 0) + } // FullPath retrieves the full path of the specified file. + func FullPath(name string) (path string, err error) { + p, err := UTF16PtrFromString(name) + if err != nil { + return "", err + } + n := uint32(100) + for { + buf := make([]uint16, n) + n, err = GetFullPathName(p, uint32(len(buf)), &buf[0], nil) + if err != nil { + return "", err + } + if n <= uint32(len(buf)) { + return UTF16ToString(buf[:n]), nil + } + } + } // NewProcThreadAttributeList allocates a new ProcThreadAttributeListContainer, with the requested maximum number of attributes. + func NewProcThreadAttributeList(maxAttrCount uint32) (*ProcThreadAttributeListContainer, error) { + var size uintptr + err := initializeProcThreadAttributeList(nil, maxAttrCount, 0, &size) + if err != ERROR_INSUFFICIENT_BUFFER { + if err == nil { + return nil, errorspkg.New("unable to query buffer size from InitializeProcThreadAttributeList") + } + return nil, err + } + alloc, err := LocalAlloc(LMEM_FIXED, uint32(size)) + if err != nil { + return nil, err + } + // size is guaranteed to be ≥1 by InitializeProcThreadAttributeList. + al := &ProcThreadAttributeListContainer{data: (*ProcThreadAttributeList)(unsafe.Pointer(alloc))} + err = initializeProcThreadAttributeList(al.data, maxAttrCount, 0, &size) + if err != nil { + return nil, err + } + return al, err + } // Update modifies the ProcThreadAttributeList using UpdateProcThreadAttribute. + func (al *ProcThreadAttributeListContainer) Update(attribute uintptr, value unsafe.Pointer, size uintptr) error { + al.pointers = append(al.pointers, value) + return updateProcThreadAttribute(al.data, 0, attribute, value, size, nil, nil) + } // Delete frees ProcThreadAttributeList's resources. + func (al *ProcThreadAttributeListContainer) Delete() { + deleteProcThreadAttributeList(al.data) + LocalFree(Handle(unsafe.Pointer(al.data))) + al.data = nil + al.pointers = nil + } // List returns the actual ProcThreadAttributeList to be passed to StartupInfoEx. + func (al *ProcThreadAttributeListContainer) List() *ProcThreadAttributeList { + return al.data + } diff --git a/vendor/golang.org/x/sys/windows/race.go b/vendor/golang.org/x/sys/windows/race.go index 0f1bdc3..736f9ff 100644 --- a/vendor/golang.org/x/sys/windows/race.go +++ b/vendor/golang.org/x/sys/windows/race.go @@ -1,5 +1,7 @@ // Copyright 2012 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build windows && race @@ -14,17 +16,25 @@ import ( const raceenabled = true func raceAcquire(addr unsafe.Pointer) { + runtime.RaceAcquire(addr) + } func raceReleaseMerge(addr unsafe.Pointer) { + runtime.RaceReleaseMerge(addr) + } func raceReadRange(addr unsafe.Pointer, len int) { + runtime.RaceReadRange(addr, len) + } func raceWriteRange(addr unsafe.Pointer, len int) { + runtime.RaceWriteRange(addr, len) + } diff --git a/vendor/golang.org/x/sys/windows/security_windows.go b/vendor/golang.org/x/sys/windows/security_windows.go index 26be94a..27033aa 100644 --- a/vendor/golang.org/x/sys/windows/security_windows.go +++ b/vendor/golang.org/x/sys/windows/security_windows.go @@ -1,5 +1,7 @@ // Copyright 2012 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package windows @@ -10,76 +12,130 @@ import ( ) const ( - NameUnknown = 0 + NameUnknown = 0 + NameFullyQualifiedDN = 1 - NameSamCompatible = 2 - NameDisplay = 3 - NameUniqueId = 6 - NameCanonical = 7 - NameUserPrincipal = 8 - NameCanonicalEx = 9 + + NameSamCompatible = 2 + + NameDisplay = 3 + + NameUniqueId = 6 + + NameCanonical = 7 + + NameUserPrincipal = 8 + + NameCanonicalEx = 9 + NameServicePrincipal = 10 - NameDnsDomain = 12 + + NameDnsDomain = 12 ) // This function returns 1 byte BOOLEAN rather than the 4 byte BOOL. + // http://blogs.msdn.com/b/drnick/archive/2007/12/19/windows-and-upn-format-credentials.aspx + //sys TranslateName(accName *uint16, accNameFormat uint32, desiredNameFormat uint32, translatedName *uint16, nSize *uint32) (err error) [failretval&0xff==0] = secur32.TranslateNameW + //sys GetUserNameEx(nameFormat uint32, nameBuffre *uint16, nSize *uint32) (err error) [failretval&0xff==0] = secur32.GetUserNameExW // TranslateAccountName converts a directory service + // object name from one format to another. + func TranslateAccountName(username string, from, to uint32, initSize int) (string, error) { + u, e := UTF16PtrFromString(username) + if e != nil { + return "", e + } + n := uint32(50) + for { + b := make([]uint16, n) + e = TranslateName(u, from, to, &b[0], &n) + if e == nil { + return UTF16ToString(b[:n]), nil + } + if e != ERROR_INSUFFICIENT_BUFFER { + return "", e + } + if n <= uint32(len(b)) { + return "", e + } + } + } const ( + // do not reorder + NetSetupUnknownStatus = iota + NetSetupUnjoined + NetSetupWorkgroupName + NetSetupDomainName ) type UserInfo10 struct { - Name *uint16 - Comment *uint16 + Name *uint16 + + Comment *uint16 + UsrComment *uint16 - FullName *uint16 + + FullName *uint16 } //sys NetUserGetInfo(serverName *uint16, userName *uint16, level uint32, buf **byte) (neterr error) = netapi32.NetUserGetInfo + //sys NetGetJoinInformation(server *uint16, name **uint16, bufType *uint32) (neterr error) = netapi32.NetGetJoinInformation + //sys NetApiBufferFree(buf *byte) (neterr error) = netapi32.NetApiBufferFree const ( + // do not reorder + SidTypeUser = 1 + iota + SidTypeGroup + SidTypeDomain + SidTypeAlias + SidTypeWellKnownGroup + SidTypeDeletedAccount + SidTypeInvalid + SidTypeUnknown + SidTypeComputer + SidTypeLabel ) @@ -88,499 +144,910 @@ type SidIdentifierAuthority struct { } var ( - SECURITY_NULL_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 0}} - SECURITY_WORLD_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 1}} - SECURITY_LOCAL_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 2}} - SECURITY_CREATOR_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 3}} - SECURITY_NON_UNIQUE_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 4}} - SECURITY_NT_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 5}} + SECURITY_NULL_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 0}} + + SECURITY_WORLD_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 1}} + + SECURITY_LOCAL_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 2}} + + SECURITY_CREATOR_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 3}} + + SECURITY_NON_UNIQUE_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 4}} + + SECURITY_NT_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 5}} + SECURITY_MANDATORY_LABEL_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 16}} ) const ( - SECURITY_NULL_RID = 0 - SECURITY_WORLD_RID = 0 - SECURITY_LOCAL_RID = 0 - SECURITY_CREATOR_OWNER_RID = 0 - SECURITY_CREATOR_GROUP_RID = 1 - SECURITY_DIALUP_RID = 1 - SECURITY_NETWORK_RID = 2 - SECURITY_BATCH_RID = 3 - SECURITY_INTERACTIVE_RID = 4 - SECURITY_LOGON_IDS_RID = 5 - SECURITY_SERVICE_RID = 6 - SECURITY_LOCAL_SYSTEM_RID = 18 - SECURITY_BUILTIN_DOMAIN_RID = 32 - SECURITY_PRINCIPAL_SELF_RID = 10 - SECURITY_CREATOR_OWNER_SERVER_RID = 0x2 - SECURITY_CREATOR_GROUP_SERVER_RID = 0x3 - SECURITY_LOGON_IDS_RID_COUNT = 0x3 - SECURITY_ANONYMOUS_LOGON_RID = 0x7 - SECURITY_PROXY_RID = 0x8 + SECURITY_NULL_RID = 0 + + SECURITY_WORLD_RID = 0 + + SECURITY_LOCAL_RID = 0 + + SECURITY_CREATOR_OWNER_RID = 0 + + SECURITY_CREATOR_GROUP_RID = 1 + + SECURITY_DIALUP_RID = 1 + + SECURITY_NETWORK_RID = 2 + + SECURITY_BATCH_RID = 3 + + SECURITY_INTERACTIVE_RID = 4 + + SECURITY_LOGON_IDS_RID = 5 + + SECURITY_SERVICE_RID = 6 + + SECURITY_LOCAL_SYSTEM_RID = 18 + + SECURITY_BUILTIN_DOMAIN_RID = 32 + + SECURITY_PRINCIPAL_SELF_RID = 10 + + SECURITY_CREATOR_OWNER_SERVER_RID = 0x2 + + SECURITY_CREATOR_GROUP_SERVER_RID = 0x3 + + SECURITY_LOGON_IDS_RID_COUNT = 0x3 + + SECURITY_ANONYMOUS_LOGON_RID = 0x7 + + SECURITY_PROXY_RID = 0x8 + SECURITY_ENTERPRISE_CONTROLLERS_RID = 0x9 - SECURITY_SERVER_LOGON_RID = SECURITY_ENTERPRISE_CONTROLLERS_RID - SECURITY_AUTHENTICATED_USER_RID = 0xb - SECURITY_RESTRICTED_CODE_RID = 0xc - SECURITY_NT_NON_UNIQUE_RID = 0x15 + + SECURITY_SERVER_LOGON_RID = SECURITY_ENTERPRISE_CONTROLLERS_RID + + SECURITY_AUTHENTICATED_USER_RID = 0xb + + SECURITY_RESTRICTED_CODE_RID = 0xc + + SECURITY_NT_NON_UNIQUE_RID = 0x15 ) // Predefined domain-relative RIDs for local groups. + // See https://msdn.microsoft.com/en-us/library/windows/desktop/aa379649(v=vs.85).aspx + const ( - DOMAIN_ALIAS_RID_ADMINS = 0x220 - DOMAIN_ALIAS_RID_USERS = 0x221 - DOMAIN_ALIAS_RID_GUESTS = 0x222 - DOMAIN_ALIAS_RID_POWER_USERS = 0x223 - DOMAIN_ALIAS_RID_ACCOUNT_OPS = 0x224 - DOMAIN_ALIAS_RID_SYSTEM_OPS = 0x225 - DOMAIN_ALIAS_RID_PRINT_OPS = 0x226 - DOMAIN_ALIAS_RID_BACKUP_OPS = 0x227 - DOMAIN_ALIAS_RID_REPLICATOR = 0x228 - DOMAIN_ALIAS_RID_RAS_SERVERS = 0x229 - DOMAIN_ALIAS_RID_PREW2KCOMPACCESS = 0x22a - DOMAIN_ALIAS_RID_REMOTE_DESKTOP_USERS = 0x22b - DOMAIN_ALIAS_RID_NETWORK_CONFIGURATION_OPS = 0x22c + DOMAIN_ALIAS_RID_ADMINS = 0x220 + + DOMAIN_ALIAS_RID_USERS = 0x221 + + DOMAIN_ALIAS_RID_GUESTS = 0x222 + + DOMAIN_ALIAS_RID_POWER_USERS = 0x223 + + DOMAIN_ALIAS_RID_ACCOUNT_OPS = 0x224 + + DOMAIN_ALIAS_RID_SYSTEM_OPS = 0x225 + + DOMAIN_ALIAS_RID_PRINT_OPS = 0x226 + + DOMAIN_ALIAS_RID_BACKUP_OPS = 0x227 + + DOMAIN_ALIAS_RID_REPLICATOR = 0x228 + + DOMAIN_ALIAS_RID_RAS_SERVERS = 0x229 + + DOMAIN_ALIAS_RID_PREW2KCOMPACCESS = 0x22a + + DOMAIN_ALIAS_RID_REMOTE_DESKTOP_USERS = 0x22b + + DOMAIN_ALIAS_RID_NETWORK_CONFIGURATION_OPS = 0x22c + DOMAIN_ALIAS_RID_INCOMING_FOREST_TRUST_BUILDERS = 0x22d - DOMAIN_ALIAS_RID_MONITORING_USERS = 0x22e - DOMAIN_ALIAS_RID_LOGGING_USERS = 0x22f - DOMAIN_ALIAS_RID_AUTHORIZATIONACCESS = 0x230 - DOMAIN_ALIAS_RID_TS_LICENSE_SERVERS = 0x231 - DOMAIN_ALIAS_RID_DCOM_USERS = 0x232 - DOMAIN_ALIAS_RID_IUSERS = 0x238 - DOMAIN_ALIAS_RID_CRYPTO_OPERATORS = 0x239 - DOMAIN_ALIAS_RID_CACHEABLE_PRINCIPALS_GROUP = 0x23b + + DOMAIN_ALIAS_RID_MONITORING_USERS = 0x22e + + DOMAIN_ALIAS_RID_LOGGING_USERS = 0x22f + + DOMAIN_ALIAS_RID_AUTHORIZATIONACCESS = 0x230 + + DOMAIN_ALIAS_RID_TS_LICENSE_SERVERS = 0x231 + + DOMAIN_ALIAS_RID_DCOM_USERS = 0x232 + + DOMAIN_ALIAS_RID_IUSERS = 0x238 + + DOMAIN_ALIAS_RID_CRYPTO_OPERATORS = 0x239 + + DOMAIN_ALIAS_RID_CACHEABLE_PRINCIPALS_GROUP = 0x23b + DOMAIN_ALIAS_RID_NON_CACHEABLE_PRINCIPALS_GROUP = 0x23c - DOMAIN_ALIAS_RID_EVENT_LOG_READERS_GROUP = 0x23d - DOMAIN_ALIAS_RID_CERTSVC_DCOM_ACCESS_GROUP = 0x23e + + DOMAIN_ALIAS_RID_EVENT_LOG_READERS_GROUP = 0x23d + + DOMAIN_ALIAS_RID_CERTSVC_DCOM_ACCESS_GROUP = 0x23e ) //sys LookupAccountSid(systemName *uint16, sid *SID, name *uint16, nameLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) = advapi32.LookupAccountSidW + //sys LookupAccountName(systemName *uint16, accountName *uint16, sid *SID, sidLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) = advapi32.LookupAccountNameW + //sys ConvertSidToStringSid(sid *SID, stringSid **uint16) (err error) = advapi32.ConvertSidToStringSidW + //sys ConvertStringSidToSid(stringSid *uint16, sid **SID) (err error) = advapi32.ConvertStringSidToSidW + //sys GetLengthSid(sid *SID) (len uint32) = advapi32.GetLengthSid + //sys CopySid(destSidLen uint32, destSid *SID, srcSid *SID) (err error) = advapi32.CopySid + //sys AllocateAndInitializeSid(identAuth *SidIdentifierAuthority, subAuth byte, subAuth0 uint32, subAuth1 uint32, subAuth2 uint32, subAuth3 uint32, subAuth4 uint32, subAuth5 uint32, subAuth6 uint32, subAuth7 uint32, sid **SID) (err error) = advapi32.AllocateAndInitializeSid + //sys createWellKnownSid(sidType WELL_KNOWN_SID_TYPE, domainSid *SID, sid *SID, sizeSid *uint32) (err error) = advapi32.CreateWellKnownSid + //sys isWellKnownSid(sid *SID, sidType WELL_KNOWN_SID_TYPE) (isWellKnown bool) = advapi32.IsWellKnownSid + //sys FreeSid(sid *SID) (err error) [failretval!=0] = advapi32.FreeSid + //sys EqualSid(sid1 *SID, sid2 *SID) (isEqual bool) = advapi32.EqualSid + //sys getSidIdentifierAuthority(sid *SID) (authority *SidIdentifierAuthority) = advapi32.GetSidIdentifierAuthority + //sys getSidSubAuthorityCount(sid *SID) (count *uint8) = advapi32.GetSidSubAuthorityCount + //sys getSidSubAuthority(sid *SID, index uint32) (subAuthority *uint32) = advapi32.GetSidSubAuthority + //sys isValidSid(sid *SID) (isValid bool) = advapi32.IsValidSid // The security identifier (SID) structure is a variable-length + // structure used to uniquely identify users or groups. + type SID struct{} // StringToSid converts a string-format security identifier + // SID into a valid, functional SID. + func StringToSid(s string) (*SID, error) { + var sid *SID + p, e := UTF16PtrFromString(s) + if e != nil { + return nil, e + } + e = ConvertStringSidToSid(p, &sid) + if e != nil { + return nil, e + } + defer LocalFree((Handle)(unsafe.Pointer(sid))) + return sid.Copy() + } // LookupSID retrieves a security identifier SID for the account + // and the name of the domain on which the account was found. + // System specify target computer to search. + func LookupSID(system, account string) (sid *SID, domain string, accType uint32, err error) { + if len(account) == 0 { + return nil, "", 0, syscall.EINVAL + } + acc, e := UTF16PtrFromString(account) + if e != nil { + return nil, "", 0, e + } + var sys *uint16 + if len(system) > 0 { + sys, e = UTF16PtrFromString(system) + if e != nil { + return nil, "", 0, e + } + } + n := uint32(50) + dn := uint32(50) + for { + b := make([]byte, n) + db := make([]uint16, dn) + sid = (*SID)(unsafe.Pointer(&b[0])) + e = LookupAccountName(sys, acc, sid, &n, &db[0], &dn, &accType) + if e == nil { + return sid, UTF16ToString(db), accType, nil + } + if e != ERROR_INSUFFICIENT_BUFFER { + return nil, "", 0, e + } + if n <= uint32(len(b)) { + return nil, "", 0, e + } + } + } // String converts SID to a string format suitable for display, storage, or transmission. + func (sid *SID) String() string { + var s *uint16 + e := ConvertSidToStringSid(sid, &s) + if e != nil { + return "" + } + defer LocalFree((Handle)(unsafe.Pointer(s))) + return UTF16ToString((*[256]uint16)(unsafe.Pointer(s))[:]) + } // Len returns the length, in bytes, of a valid security identifier SID. + func (sid *SID) Len() int { + return int(GetLengthSid(sid)) + } // Copy creates a duplicate of security identifier SID. + func (sid *SID) Copy() (*SID, error) { + b := make([]byte, sid.Len()) + sid2 := (*SID)(unsafe.Pointer(&b[0])) + e := CopySid(uint32(len(b)), sid2, sid) + if e != nil { + return nil, e + } + return sid2, nil + } // IdentifierAuthority returns the identifier authority of the SID. + func (sid *SID) IdentifierAuthority() SidIdentifierAuthority { + return *getSidIdentifierAuthority(sid) + } // SubAuthorityCount returns the number of sub-authorities in the SID. + func (sid *SID) SubAuthorityCount() uint8 { + return *getSidSubAuthorityCount(sid) + } // SubAuthority returns the sub-authority of the SID as specified by + // the index, which must be less than sid.SubAuthorityCount(). + func (sid *SID) SubAuthority(idx uint32) uint32 { + if idx >= uint32(sid.SubAuthorityCount()) { + panic("sub-authority index out of range") + } + return *getSidSubAuthority(sid, idx) + } // IsValid returns whether the SID has a valid revision and length. + func (sid *SID) IsValid() bool { + return isValidSid(sid) + } // Equals compares two SIDs for equality. + func (sid *SID) Equals(sid2 *SID) bool { + return EqualSid(sid, sid2) + } // IsWellKnown determines whether the SID matches the well-known sidType. + func (sid *SID) IsWellKnown(sidType WELL_KNOWN_SID_TYPE) bool { + return isWellKnownSid(sid, sidType) + } // LookupAccount retrieves the name of the account for this SID + // and the name of the first domain on which this SID is found. + // System specify target computer to search for. + func (sid *SID) LookupAccount(system string) (account, domain string, accType uint32, err error) { + var sys *uint16 + if len(system) > 0 { + sys, err = UTF16PtrFromString(system) + if err != nil { + return "", "", 0, err + } + } + n := uint32(50) + dn := uint32(50) + for { + b := make([]uint16, n) + db := make([]uint16, dn) + e := LookupAccountSid(sys, sid, &b[0], &n, &db[0], &dn, &accType) + if e == nil { + return UTF16ToString(b), UTF16ToString(db), accType, nil + } + if e != ERROR_INSUFFICIENT_BUFFER { + return "", "", 0, e + } + if n <= uint32(len(b)) { + return "", "", 0, e + } + } + } // Various types of pre-specified SIDs that can be synthesized and compared at runtime. + type WELL_KNOWN_SID_TYPE uint32 const ( - WinNullSid = 0 - WinWorldSid = 1 - WinLocalSid = 2 - WinCreatorOwnerSid = 3 - WinCreatorGroupSid = 4 - WinCreatorOwnerServerSid = 5 - WinCreatorGroupServerSid = 6 - WinNtAuthoritySid = 7 - WinDialupSid = 8 - WinNetworkSid = 9 - WinBatchSid = 10 - WinInteractiveSid = 11 - WinServiceSid = 12 - WinAnonymousSid = 13 - WinProxySid = 14 - WinEnterpriseControllersSid = 15 - WinSelfSid = 16 - WinAuthenticatedUserSid = 17 - WinRestrictedCodeSid = 18 - WinTerminalServerSid = 19 - WinRemoteLogonIdSid = 20 - WinLogonIdsSid = 21 - WinLocalSystemSid = 22 - WinLocalServiceSid = 23 - WinNetworkServiceSid = 24 - WinBuiltinDomainSid = 25 - WinBuiltinAdministratorsSid = 26 - WinBuiltinUsersSid = 27 - WinBuiltinGuestsSid = 28 - WinBuiltinPowerUsersSid = 29 - WinBuiltinAccountOperatorsSid = 30 - WinBuiltinSystemOperatorsSid = 31 - WinBuiltinPrintOperatorsSid = 32 - WinBuiltinBackupOperatorsSid = 33 - WinBuiltinReplicatorSid = 34 - WinBuiltinPreWindows2000CompatibleAccessSid = 35 - WinBuiltinRemoteDesktopUsersSid = 36 - WinBuiltinNetworkConfigurationOperatorsSid = 37 - WinAccountAdministratorSid = 38 - WinAccountGuestSid = 39 - WinAccountKrbtgtSid = 40 - WinAccountDomainAdminsSid = 41 - WinAccountDomainUsersSid = 42 - WinAccountDomainGuestsSid = 43 - WinAccountComputersSid = 44 - WinAccountControllersSid = 45 - WinAccountCertAdminsSid = 46 - WinAccountSchemaAdminsSid = 47 - WinAccountEnterpriseAdminsSid = 48 - WinAccountPolicyAdminsSid = 49 - WinAccountRasAndIasServersSid = 50 - WinNTLMAuthenticationSid = 51 - WinDigestAuthenticationSid = 52 - WinSChannelAuthenticationSid = 53 - WinThisOrganizationSid = 54 - WinOtherOrganizationSid = 55 - WinBuiltinIncomingForestTrustBuildersSid = 56 - WinBuiltinPerfMonitoringUsersSid = 57 - WinBuiltinPerfLoggingUsersSid = 58 - WinBuiltinAuthorizationAccessSid = 59 - WinBuiltinTerminalServerLicenseServersSid = 60 - WinBuiltinDCOMUsersSid = 61 - WinBuiltinIUsersSid = 62 - WinIUserSid = 63 - WinBuiltinCryptoOperatorsSid = 64 - WinUntrustedLabelSid = 65 - WinLowLabelSid = 66 - WinMediumLabelSid = 67 - WinHighLabelSid = 68 - WinSystemLabelSid = 69 - WinWriteRestrictedCodeSid = 70 - WinCreatorOwnerRightsSid = 71 - WinCacheablePrincipalsGroupSid = 72 - WinNonCacheablePrincipalsGroupSid = 73 - WinEnterpriseReadonlyControllersSid = 74 - WinAccountReadonlyControllersSid = 75 - WinBuiltinEventLogReadersGroup = 76 - WinNewEnterpriseReadonlyControllersSid = 77 - WinBuiltinCertSvcDComAccessGroup = 78 - WinMediumPlusLabelSid = 79 - WinLocalLogonSid = 80 - WinConsoleLogonSid = 81 - WinThisOrganizationCertificateSid = 82 - WinApplicationPackageAuthoritySid = 83 - WinBuiltinAnyPackageSid = 84 - WinCapabilityInternetClientSid = 85 - WinCapabilityInternetClientServerSid = 86 - WinCapabilityPrivateNetworkClientServerSid = 87 - WinCapabilityPicturesLibrarySid = 88 - WinCapabilityVideosLibrarySid = 89 - WinCapabilityMusicLibrarySid = 90 - WinCapabilityDocumentsLibrarySid = 91 - WinCapabilitySharedUserCertificatesSid = 92 - WinCapabilityEnterpriseAuthenticationSid = 93 - WinCapabilityRemovableStorageSid = 94 - WinBuiltinRDSRemoteAccessServersSid = 95 - WinBuiltinRDSEndpointServersSid = 96 - WinBuiltinRDSManagementServersSid = 97 - WinUserModeDriversSid = 98 - WinBuiltinHyperVAdminsSid = 99 - WinAccountCloneableControllersSid = 100 + WinNullSid = 0 + + WinWorldSid = 1 + + WinLocalSid = 2 + + WinCreatorOwnerSid = 3 + + WinCreatorGroupSid = 4 + + WinCreatorOwnerServerSid = 5 + + WinCreatorGroupServerSid = 6 + + WinNtAuthoritySid = 7 + + WinDialupSid = 8 + + WinNetworkSid = 9 + + WinBatchSid = 10 + + WinInteractiveSid = 11 + + WinServiceSid = 12 + + WinAnonymousSid = 13 + + WinProxySid = 14 + + WinEnterpriseControllersSid = 15 + + WinSelfSid = 16 + + WinAuthenticatedUserSid = 17 + + WinRestrictedCodeSid = 18 + + WinTerminalServerSid = 19 + + WinRemoteLogonIdSid = 20 + + WinLogonIdsSid = 21 + + WinLocalSystemSid = 22 + + WinLocalServiceSid = 23 + + WinNetworkServiceSid = 24 + + WinBuiltinDomainSid = 25 + + WinBuiltinAdministratorsSid = 26 + + WinBuiltinUsersSid = 27 + + WinBuiltinGuestsSid = 28 + + WinBuiltinPowerUsersSid = 29 + + WinBuiltinAccountOperatorsSid = 30 + + WinBuiltinSystemOperatorsSid = 31 + + WinBuiltinPrintOperatorsSid = 32 + + WinBuiltinBackupOperatorsSid = 33 + + WinBuiltinReplicatorSid = 34 + + WinBuiltinPreWindows2000CompatibleAccessSid = 35 + + WinBuiltinRemoteDesktopUsersSid = 36 + + WinBuiltinNetworkConfigurationOperatorsSid = 37 + + WinAccountAdministratorSid = 38 + + WinAccountGuestSid = 39 + + WinAccountKrbtgtSid = 40 + + WinAccountDomainAdminsSid = 41 + + WinAccountDomainUsersSid = 42 + + WinAccountDomainGuestsSid = 43 + + WinAccountComputersSid = 44 + + WinAccountControllersSid = 45 + + WinAccountCertAdminsSid = 46 + + WinAccountSchemaAdminsSid = 47 + + WinAccountEnterpriseAdminsSid = 48 + + WinAccountPolicyAdminsSid = 49 + + WinAccountRasAndIasServersSid = 50 + + WinNTLMAuthenticationSid = 51 + + WinDigestAuthenticationSid = 52 + + WinSChannelAuthenticationSid = 53 + + WinThisOrganizationSid = 54 + + WinOtherOrganizationSid = 55 + + WinBuiltinIncomingForestTrustBuildersSid = 56 + + WinBuiltinPerfMonitoringUsersSid = 57 + + WinBuiltinPerfLoggingUsersSid = 58 + + WinBuiltinAuthorizationAccessSid = 59 + + WinBuiltinTerminalServerLicenseServersSid = 60 + + WinBuiltinDCOMUsersSid = 61 + + WinBuiltinIUsersSid = 62 + + WinIUserSid = 63 + + WinBuiltinCryptoOperatorsSid = 64 + + WinUntrustedLabelSid = 65 + + WinLowLabelSid = 66 + + WinMediumLabelSid = 67 + + WinHighLabelSid = 68 + + WinSystemLabelSid = 69 + + WinWriteRestrictedCodeSid = 70 + + WinCreatorOwnerRightsSid = 71 + + WinCacheablePrincipalsGroupSid = 72 + + WinNonCacheablePrincipalsGroupSid = 73 + + WinEnterpriseReadonlyControllersSid = 74 + + WinAccountReadonlyControllersSid = 75 + + WinBuiltinEventLogReadersGroup = 76 + + WinNewEnterpriseReadonlyControllersSid = 77 + + WinBuiltinCertSvcDComAccessGroup = 78 + + WinMediumPlusLabelSid = 79 + + WinLocalLogonSid = 80 + + WinConsoleLogonSid = 81 + + WinThisOrganizationCertificateSid = 82 + + WinApplicationPackageAuthoritySid = 83 + + WinBuiltinAnyPackageSid = 84 + + WinCapabilityInternetClientSid = 85 + + WinCapabilityInternetClientServerSid = 86 + + WinCapabilityPrivateNetworkClientServerSid = 87 + + WinCapabilityPicturesLibrarySid = 88 + + WinCapabilityVideosLibrarySid = 89 + + WinCapabilityMusicLibrarySid = 90 + + WinCapabilityDocumentsLibrarySid = 91 + + WinCapabilitySharedUserCertificatesSid = 92 + + WinCapabilityEnterpriseAuthenticationSid = 93 + + WinCapabilityRemovableStorageSid = 94 + + WinBuiltinRDSRemoteAccessServersSid = 95 + + WinBuiltinRDSEndpointServersSid = 96 + + WinBuiltinRDSManagementServersSid = 97 + + WinUserModeDriversSid = 98 + + WinBuiltinHyperVAdminsSid = 99 + + WinAccountCloneableControllersSid = 100 + WinBuiltinAccessControlAssistanceOperatorsSid = 101 - WinBuiltinRemoteManagementUsersSid = 102 - WinAuthenticationAuthorityAssertedSid = 103 - WinAuthenticationServiceAssertedSid = 104 - WinLocalAccountSid = 105 - WinLocalAccountAndAdministratorSid = 106 - WinAccountProtectedUsersSid = 107 - WinCapabilityAppointmentsSid = 108 - WinCapabilityContactsSid = 109 - WinAccountDefaultSystemManagedSid = 110 - WinBuiltinDefaultSystemManagedGroupSid = 111 - WinBuiltinStorageReplicaAdminsSid = 112 - WinAccountKeyAdminsSid = 113 - WinAccountEnterpriseKeyAdminsSid = 114 - WinAuthenticationKeyTrustSid = 115 - WinAuthenticationKeyPropertyMFASid = 116 - WinAuthenticationKeyPropertyAttestationSid = 117 - WinAuthenticationFreshKeyAuthSid = 118 - WinBuiltinDeviceOwnersSid = 119 + + WinBuiltinRemoteManagementUsersSid = 102 + + WinAuthenticationAuthorityAssertedSid = 103 + + WinAuthenticationServiceAssertedSid = 104 + + WinLocalAccountSid = 105 + + WinLocalAccountAndAdministratorSid = 106 + + WinAccountProtectedUsersSid = 107 + + WinCapabilityAppointmentsSid = 108 + + WinCapabilityContactsSid = 109 + + WinAccountDefaultSystemManagedSid = 110 + + WinBuiltinDefaultSystemManagedGroupSid = 111 + + WinBuiltinStorageReplicaAdminsSid = 112 + + WinAccountKeyAdminsSid = 113 + + WinAccountEnterpriseKeyAdminsSid = 114 + + WinAuthenticationKeyTrustSid = 115 + + WinAuthenticationKeyPropertyMFASid = 116 + + WinAuthenticationKeyPropertyAttestationSid = 117 + + WinAuthenticationFreshKeyAuthSid = 118 + + WinBuiltinDeviceOwnersSid = 119 ) // Creates a SID for a well-known predefined alias, generally using the constants of the form + // Win*Sid, for the local machine. + func CreateWellKnownSid(sidType WELL_KNOWN_SID_TYPE) (*SID, error) { + return CreateWellKnownDomainSid(sidType, nil) + } // Creates a SID for a well-known predefined alias, generally using the constants of the form + // Win*Sid, for the domain specified by the domainSid parameter. + func CreateWellKnownDomainSid(sidType WELL_KNOWN_SID_TYPE, domainSid *SID) (*SID, error) { + n := uint32(50) + for { + b := make([]byte, n) + sid := (*SID)(unsafe.Pointer(&b[0])) + err := createWellKnownSid(sidType, domainSid, sid, &n) + if err == nil { + return sid, nil + } + if err != ERROR_INSUFFICIENT_BUFFER { + return nil, err + } + if n <= uint32(len(b)) { + return nil, err + } + } + } const ( + // do not reorder + TOKEN_ASSIGN_PRIMARY = 1 << iota + TOKEN_DUPLICATE + TOKEN_IMPERSONATE + TOKEN_QUERY + TOKEN_QUERY_SOURCE + TOKEN_ADJUST_PRIVILEGES + TOKEN_ADJUST_GROUPS + TOKEN_ADJUST_DEFAULT + TOKEN_ADJUST_SESSIONID TOKEN_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | + TOKEN_ASSIGN_PRIMARY | + TOKEN_DUPLICATE | + TOKEN_IMPERSONATE | + TOKEN_QUERY | + TOKEN_QUERY_SOURCE | + TOKEN_ADJUST_PRIVILEGES | + TOKEN_ADJUST_GROUPS | + TOKEN_ADJUST_DEFAULT | + TOKEN_ADJUST_SESSIONID - TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY + + TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY + TOKEN_WRITE = STANDARD_RIGHTS_WRITE | + TOKEN_ADJUST_PRIVILEGES | + TOKEN_ADJUST_GROUPS | + TOKEN_ADJUST_DEFAULT + TOKEN_EXECUTE = STANDARD_RIGHTS_EXECUTE ) const ( + // do not reorder + TokenUser = 1 + iota + TokenGroups + TokenPrivileges + TokenOwner + TokenPrimaryGroup + TokenDefaultDacl + TokenSource + TokenType + TokenImpersonationLevel + TokenStatistics + TokenRestrictedSids + TokenSessionId + TokenGroupsAndPrivileges + TokenSessionReference + TokenSandBoxInert + TokenAuditPolicy + TokenOrigin + TokenElevationType + TokenLinkedToken + TokenElevation + TokenHasRestrictions + TokenAccessInformation + TokenVirtualizationAllowed + TokenVirtualizationEnabled + TokenIntegrityLevel + TokenUIAccess + TokenMandatoryPolicy + TokenLogonSid + MaxTokenInfoClass ) // Group attributes inside of Tokengroups.Groups[i].Attributes + const ( - SE_GROUP_MANDATORY = 0x00000001 + SE_GROUP_MANDATORY = 0x00000001 + SE_GROUP_ENABLED_BY_DEFAULT = 0x00000002 - SE_GROUP_ENABLED = 0x00000004 - SE_GROUP_OWNER = 0x00000008 - SE_GROUP_USE_FOR_DENY_ONLY = 0x00000010 - SE_GROUP_INTEGRITY = 0x00000020 - SE_GROUP_INTEGRITY_ENABLED = 0x00000040 - SE_GROUP_LOGON_ID = 0xC0000000 - SE_GROUP_RESOURCE = 0x20000000 - SE_GROUP_VALID_ATTRIBUTES = SE_GROUP_MANDATORY | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_ENABLED | SE_GROUP_OWNER | SE_GROUP_USE_FOR_DENY_ONLY | SE_GROUP_LOGON_ID | SE_GROUP_RESOURCE | SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED + + SE_GROUP_ENABLED = 0x00000004 + + SE_GROUP_OWNER = 0x00000008 + + SE_GROUP_USE_FOR_DENY_ONLY = 0x00000010 + + SE_GROUP_INTEGRITY = 0x00000020 + + SE_GROUP_INTEGRITY_ENABLED = 0x00000040 + + SE_GROUP_LOGON_ID = 0xC0000000 + + SE_GROUP_RESOURCE = 0x20000000 + + SE_GROUP_VALID_ATTRIBUTES = SE_GROUP_MANDATORY | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_ENABLED | SE_GROUP_OWNER | SE_GROUP_USE_FOR_DENY_ONLY | SE_GROUP_LOGON_ID | SE_GROUP_RESOURCE | SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED ) // Privilege attributes + const ( SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001 - SE_PRIVILEGE_ENABLED = 0x00000002 - SE_PRIVILEGE_REMOVED = 0x00000004 - SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000 - SE_PRIVILEGE_VALID_ATTRIBUTES = SE_PRIVILEGE_ENABLED_BY_DEFAULT | SE_PRIVILEGE_ENABLED | SE_PRIVILEGE_REMOVED | SE_PRIVILEGE_USED_FOR_ACCESS + + SE_PRIVILEGE_ENABLED = 0x00000002 + + SE_PRIVILEGE_REMOVED = 0x00000004 + + SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000 + + SE_PRIVILEGE_VALID_ATTRIBUTES = SE_PRIVILEGE_ENABLED_BY_DEFAULT | SE_PRIVILEGE_ENABLED | SE_PRIVILEGE_REMOVED | SE_PRIVILEGE_USED_FOR_ACCESS ) // Token types + const ( - TokenPrimary = 1 + TokenPrimary = 1 + TokenImpersonation = 2 ) // Impersonation levels + const ( - SecurityAnonymous = 0 + SecurityAnonymous = 0 + SecurityIdentification = 1 - SecurityImpersonation = 2 - SecurityDelegation = 3 + + SecurityImpersonation = 2 + + SecurityDelegation = 3 ) type LUID struct { - LowPart uint32 + LowPart uint32 + HighPart int32 } type LUIDAndAttributes struct { - Luid LUID + Luid LUID + Attributes uint32 } type SIDAndAttributes struct { - Sid *SID + Sid *SID + Attributes uint32 } @@ -594,22 +1061,32 @@ type Tokenprimarygroup struct { type Tokengroups struct { GroupCount uint32 - Groups [1]SIDAndAttributes // Use AllGroups() for iterating. + + Groups [1]SIDAndAttributes // Use AllGroups() for iterating. + } // AllGroups returns a slice that can be used to iterate over the groups in g. + func (g *Tokengroups) AllGroups() []SIDAndAttributes { + return (*[(1 << 28) - 1]SIDAndAttributes)(unsafe.Pointer(&g.Groups[0]))[:g.GroupCount:g.GroupCount] + } type Tokenprivileges struct { PrivilegeCount uint32 - Privileges [1]LUIDAndAttributes // Use AllPrivileges() for iterating. + + Privileges [1]LUIDAndAttributes // Use AllPrivileges() for iterating. + } // AllPrivileges returns a slice that can be used to iterate over the privileges in p. + func (p *Tokenprivileges) AllPrivileges() []LUIDAndAttributes { + return (*[(1 << 27) - 1]LUIDAndAttributes)(unsafe.Pointer(&p.Privileges[0]))[:p.PrivilegeCount:p.PrivilegeCount] + } type Tokenmandatorylabel struct { @@ -617,819 +1094,1417 @@ type Tokenmandatorylabel struct { } func (tml *Tokenmandatorylabel) Size() uint32 { + return uint32(unsafe.Sizeof(Tokenmandatorylabel{})) + GetLengthSid(tml.Label.Sid) + } // Authorization Functions + //sys checkTokenMembership(tokenHandle Token, sidToCheck *SID, isMember *int32) (err error) = advapi32.CheckTokenMembership + //sys isTokenRestricted(tokenHandle Token) (ret bool, err error) [!failretval] = advapi32.IsTokenRestricted + //sys OpenProcessToken(process Handle, access uint32, token *Token) (err error) = advapi32.OpenProcessToken + //sys OpenThreadToken(thread Handle, access uint32, openAsSelf bool, token *Token) (err error) = advapi32.OpenThreadToken + //sys ImpersonateSelf(impersonationlevel uint32) (err error) = advapi32.ImpersonateSelf + //sys RevertToSelf() (err error) = advapi32.RevertToSelf + //sys SetThreadToken(thread *Handle, token Token) (err error) = advapi32.SetThreadToken + //sys LookupPrivilegeValue(systemname *uint16, name *uint16, luid *LUID) (err error) = advapi32.LookupPrivilegeValueW + //sys AdjustTokenPrivileges(token Token, disableAllPrivileges bool, newstate *Tokenprivileges, buflen uint32, prevstate *Tokenprivileges, returnlen *uint32) (err error) = advapi32.AdjustTokenPrivileges + //sys AdjustTokenGroups(token Token, resetToDefault bool, newstate *Tokengroups, buflen uint32, prevstate *Tokengroups, returnlen *uint32) (err error) = advapi32.AdjustTokenGroups + //sys GetTokenInformation(token Token, infoClass uint32, info *byte, infoLen uint32, returnedLen *uint32) (err error) = advapi32.GetTokenInformation + //sys SetTokenInformation(token Token, infoClass uint32, info *byte, infoLen uint32) (err error) = advapi32.SetTokenInformation + //sys DuplicateTokenEx(existingToken Token, desiredAccess uint32, tokenAttributes *SecurityAttributes, impersonationLevel uint32, tokenType uint32, newToken *Token) (err error) = advapi32.DuplicateTokenEx + //sys GetUserProfileDirectory(t Token, dir *uint16, dirLen *uint32) (err error) = userenv.GetUserProfileDirectoryW + //sys getSystemDirectory(dir *uint16, dirLen uint32) (len uint32, err error) = kernel32.GetSystemDirectoryW + //sys getWindowsDirectory(dir *uint16, dirLen uint32) (len uint32, err error) = kernel32.GetWindowsDirectoryW + //sys getSystemWindowsDirectory(dir *uint16, dirLen uint32) (len uint32, err error) = kernel32.GetSystemWindowsDirectoryW // An access token contains the security information for a logon session. + // The system creates an access token when a user logs on, and every + // process executed on behalf of the user has a copy of the token. + // The token identifies the user, the user's groups, and the user's + // privileges. The system uses the token to control access to securable + // objects and to control the ability of the user to perform various + // system-related operations on the local computer. + type Token Handle // OpenCurrentProcessToken opens an access token associated with current + // process with TOKEN_QUERY access. It is a real token that needs to be closed. + // + // Deprecated: Explicitly call OpenProcessToken(CurrentProcess(), ...) + // with the desired access instead, or use GetCurrentProcessToken for a + // TOKEN_QUERY token. + func OpenCurrentProcessToken() (Token, error) { + var token Token + err := OpenProcessToken(CurrentProcess(), TOKEN_QUERY, &token) + return token, err + } // GetCurrentProcessToken returns the access token associated with + // the current process. It is a pseudo token that does not need + // to be closed. + func GetCurrentProcessToken() Token { + return Token(^uintptr(4 - 1)) + } // GetCurrentThreadToken return the access token associated with + // the current thread. It is a pseudo token that does not need + // to be closed. + func GetCurrentThreadToken() Token { + return Token(^uintptr(5 - 1)) + } // GetCurrentThreadEffectiveToken returns the effective access token + // associated with the current thread. It is a pseudo token that does + // not need to be closed. + func GetCurrentThreadEffectiveToken() Token { + return Token(^uintptr(6 - 1)) + } // Close releases access to access token. + func (t Token) Close() error { + return CloseHandle(Handle(t)) + } // getInfo retrieves a specified type of information about an access token. + func (t Token) getInfo(class uint32, initSize int) (unsafe.Pointer, error) { + n := uint32(initSize) + for { + b := make([]byte, n) + e := GetTokenInformation(t, class, &b[0], uint32(len(b)), &n) + if e == nil { + return unsafe.Pointer(&b[0]), nil + } + if e != ERROR_INSUFFICIENT_BUFFER { + return nil, e + } + if n <= uint32(len(b)) { + return nil, e + } + } + } // GetTokenUser retrieves access token t user account information. + func (t Token) GetTokenUser() (*Tokenuser, error) { + i, e := t.getInfo(TokenUser, 50) + if e != nil { + return nil, e + } + return (*Tokenuser)(i), nil + } // GetTokenGroups retrieves group accounts associated with access token t. + func (t Token) GetTokenGroups() (*Tokengroups, error) { + i, e := t.getInfo(TokenGroups, 50) + if e != nil { + return nil, e + } + return (*Tokengroups)(i), nil + } // GetTokenPrimaryGroup retrieves access token t primary group information. + // A pointer to a SID structure representing a group that will become + // the primary group of any objects created by a process using this access token. + func (t Token) GetTokenPrimaryGroup() (*Tokenprimarygroup, error) { + i, e := t.getInfo(TokenPrimaryGroup, 50) + if e != nil { + return nil, e + } + return (*Tokenprimarygroup)(i), nil + } // GetUserProfileDirectory retrieves path to the + // root directory of the access token t user's profile. + func (t Token) GetUserProfileDirectory() (string, error) { + n := uint32(100) + for { + b := make([]uint16, n) + e := GetUserProfileDirectory(t, &b[0], &n) + if e == nil { + return UTF16ToString(b), nil + } + if e != ERROR_INSUFFICIENT_BUFFER { + return "", e + } + if n <= uint32(len(b)) { + return "", e + } + } + } // IsElevated returns whether the current token is elevated from a UAC perspective. + func (token Token) IsElevated() bool { + var isElevated uint32 + var outLen uint32 + err := GetTokenInformation(token, TokenElevation, (*byte)(unsafe.Pointer(&isElevated)), uint32(unsafe.Sizeof(isElevated)), &outLen) + if err != nil { + return false + } + return outLen == uint32(unsafe.Sizeof(isElevated)) && isElevated != 0 + } // GetLinkedToken returns the linked token, which may be an elevated UAC token. + func (token Token) GetLinkedToken() (Token, error) { + var linkedToken Token + var outLen uint32 + err := GetTokenInformation(token, TokenLinkedToken, (*byte)(unsafe.Pointer(&linkedToken)), uint32(unsafe.Sizeof(linkedToken)), &outLen) + if err != nil { + return Token(0), err + } + return linkedToken, nil + } // GetSystemDirectory retrieves the path to current location of the system + // directory, which is typically, though not always, `C:\Windows\System32`. + func GetSystemDirectory() (string, error) { + n := uint32(MAX_PATH) + for { + b := make([]uint16, n) + l, e := getSystemDirectory(&b[0], n) + if e != nil { + return "", e + } + if l <= n { + return UTF16ToString(b[:l]), nil + } + n = l + } + } // GetWindowsDirectory retrieves the path to current location of the Windows + // directory, which is typically, though not always, `C:\Windows`. This may + // be a private user directory in the case that the application is running + // under a terminal server. + func GetWindowsDirectory() (string, error) { + n := uint32(MAX_PATH) + for { + b := make([]uint16, n) + l, e := getWindowsDirectory(&b[0], n) + if e != nil { + return "", e + } + if l <= n { + return UTF16ToString(b[:l]), nil + } + n = l + } + } // GetSystemWindowsDirectory retrieves the path to current location of the + // Windows directory, which is typically, though not always, `C:\Windows`. + func GetSystemWindowsDirectory() (string, error) { + n := uint32(MAX_PATH) + for { + b := make([]uint16, n) + l, e := getSystemWindowsDirectory(&b[0], n) + if e != nil { + return "", e + } + if l <= n { + return UTF16ToString(b[:l]), nil + } + n = l + } + } // IsMember reports whether the access token t is a member of the provided SID. + func (t Token) IsMember(sid *SID) (bool, error) { + var b int32 + if e := checkTokenMembership(t, sid, &b); e != nil { + return false, e + } + return b != 0, nil + } // IsRestricted reports whether the access token t is a restricted token. + func (t Token) IsRestricted() (isRestricted bool, err error) { + isRestricted, err = isTokenRestricted(t) + if !isRestricted && err == syscall.EINVAL { + // If err is EINVAL, this returned ERROR_SUCCESS indicating a non-restricted token. + err = nil + } + return + } const ( - WTS_CONSOLE_CONNECT = 0x1 - WTS_CONSOLE_DISCONNECT = 0x2 - WTS_REMOTE_CONNECT = 0x3 - WTS_REMOTE_DISCONNECT = 0x4 - WTS_SESSION_LOGON = 0x5 - WTS_SESSION_LOGOFF = 0x6 - WTS_SESSION_LOCK = 0x7 - WTS_SESSION_UNLOCK = 0x8 + WTS_CONSOLE_CONNECT = 0x1 + + WTS_CONSOLE_DISCONNECT = 0x2 + + WTS_REMOTE_CONNECT = 0x3 + + WTS_REMOTE_DISCONNECT = 0x4 + + WTS_SESSION_LOGON = 0x5 + + WTS_SESSION_LOGOFF = 0x6 + + WTS_SESSION_LOCK = 0x7 + + WTS_SESSION_UNLOCK = 0x8 + WTS_SESSION_REMOTE_CONTROL = 0x9 - WTS_SESSION_CREATE = 0xa - WTS_SESSION_TERMINATE = 0xb + + WTS_SESSION_CREATE = 0xa + + WTS_SESSION_TERMINATE = 0xb ) const ( - WTSActive = 0 - WTSConnected = 1 + WTSActive = 0 + + WTSConnected = 1 + WTSConnectQuery = 2 - WTSShadow = 3 + + WTSShadow = 3 + WTSDisconnected = 4 - WTSIdle = 5 - WTSListen = 6 - WTSReset = 7 - WTSDown = 8 - WTSInit = 9 + + WTSIdle = 5 + + WTSListen = 6 + + WTSReset = 7 + + WTSDown = 8 + + WTSInit = 9 ) type WTSSESSION_NOTIFICATION struct { - Size uint32 + Size uint32 + SessionID uint32 } type WTS_SESSION_INFO struct { - SessionID uint32 + SessionID uint32 + WindowStationName *uint16 - State uint32 + + State uint32 } //sys WTSQueryUserToken(session uint32, token *Token) (err error) = wtsapi32.WTSQueryUserToken + //sys WTSEnumerateSessions(handle Handle, reserved uint32, version uint32, sessions **WTS_SESSION_INFO, count *uint32) (err error) = wtsapi32.WTSEnumerateSessionsW + //sys WTSFreeMemory(ptr uintptr) = wtsapi32.WTSFreeMemory + //sys WTSGetActiveConsoleSessionId() (sessionID uint32) type ACL struct { aclRevision byte - sbz1 byte - aclSize uint16 - aceCount uint16 - sbz2 uint16 + + sbz1 byte + + aclSize uint16 + + aceCount uint16 + + sbz2 uint16 } type SECURITY_DESCRIPTOR struct { revision byte - sbz1 byte - control SECURITY_DESCRIPTOR_CONTROL - owner *SID - group *SID - sacl *ACL - dacl *ACL + + sbz1 byte + + control SECURITY_DESCRIPTOR_CONTROL + + owner *SID + + group *SID + + sacl *ACL + + dacl *ACL } type SECURITY_QUALITY_OF_SERVICE struct { - Length uint32 - ImpersonationLevel uint32 + Length uint32 + + ImpersonationLevel uint32 + ContextTrackingMode byte - EffectiveOnly byte + + EffectiveOnly byte } // Constants for the ContextTrackingMode field of SECURITY_QUALITY_OF_SERVICE. + const ( - SECURITY_STATIC_TRACKING = 0 + SECURITY_STATIC_TRACKING = 0 + SECURITY_DYNAMIC_TRACKING = 1 ) type SecurityAttributes struct { - Length uint32 + Length uint32 + SecurityDescriptor *SECURITY_DESCRIPTOR - InheritHandle uint32 + + InheritHandle uint32 } type SE_OBJECT_TYPE uint32 // Constants for type SE_OBJECT_TYPE + const ( - SE_UNKNOWN_OBJECT_TYPE = 0 - SE_FILE_OBJECT = 1 - SE_SERVICE = 2 - SE_PRINTER = 3 - SE_REGISTRY_KEY = 4 - SE_LMSHARE = 5 - SE_KERNEL_OBJECT = 6 - SE_WINDOW_OBJECT = 7 - SE_DS_OBJECT = 8 - SE_DS_OBJECT_ALL = 9 + SE_UNKNOWN_OBJECT_TYPE = 0 + + SE_FILE_OBJECT = 1 + + SE_SERVICE = 2 + + SE_PRINTER = 3 + + SE_REGISTRY_KEY = 4 + + SE_LMSHARE = 5 + + SE_KERNEL_OBJECT = 6 + + SE_WINDOW_OBJECT = 7 + + SE_DS_OBJECT = 8 + + SE_DS_OBJECT_ALL = 9 + SE_PROVIDER_DEFINED_OBJECT = 10 - SE_WMIGUID_OBJECT = 11 - SE_REGISTRY_WOW64_32KEY = 12 - SE_REGISTRY_WOW64_64KEY = 13 + + SE_WMIGUID_OBJECT = 11 + + SE_REGISTRY_WOW64_32KEY = 12 + + SE_REGISTRY_WOW64_64KEY = 13 ) type SECURITY_INFORMATION uint32 // Constants for type SECURITY_INFORMATION + const ( - OWNER_SECURITY_INFORMATION = 0x00000001 - GROUP_SECURITY_INFORMATION = 0x00000002 - DACL_SECURITY_INFORMATION = 0x00000004 - SACL_SECURITY_INFORMATION = 0x00000008 - LABEL_SECURITY_INFORMATION = 0x00000010 - ATTRIBUTE_SECURITY_INFORMATION = 0x00000020 - SCOPE_SECURITY_INFORMATION = 0x00000040 - BACKUP_SECURITY_INFORMATION = 0x00010000 - PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000 - PROTECTED_SACL_SECURITY_INFORMATION = 0x40000000 + OWNER_SECURITY_INFORMATION = 0x00000001 + + GROUP_SECURITY_INFORMATION = 0x00000002 + + DACL_SECURITY_INFORMATION = 0x00000004 + + SACL_SECURITY_INFORMATION = 0x00000008 + + LABEL_SECURITY_INFORMATION = 0x00000010 + + ATTRIBUTE_SECURITY_INFORMATION = 0x00000020 + + SCOPE_SECURITY_INFORMATION = 0x00000040 + + BACKUP_SECURITY_INFORMATION = 0x00010000 + + PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000 + + PROTECTED_SACL_SECURITY_INFORMATION = 0x40000000 + UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000 + UNPROTECTED_SACL_SECURITY_INFORMATION = 0x10000000 ) type SECURITY_DESCRIPTOR_CONTROL uint16 // Constants for type SECURITY_DESCRIPTOR_CONTROL + const ( - SE_OWNER_DEFAULTED = 0x0001 - SE_GROUP_DEFAULTED = 0x0002 - SE_DACL_PRESENT = 0x0004 - SE_DACL_DEFAULTED = 0x0008 - SE_SACL_PRESENT = 0x0010 - SE_SACL_DEFAULTED = 0x0020 + SE_OWNER_DEFAULTED = 0x0001 + + SE_GROUP_DEFAULTED = 0x0002 + + SE_DACL_PRESENT = 0x0004 + + SE_DACL_DEFAULTED = 0x0008 + + SE_SACL_PRESENT = 0x0010 + + SE_SACL_DEFAULTED = 0x0020 + SE_DACL_AUTO_INHERIT_REQ = 0x0100 + SE_SACL_AUTO_INHERIT_REQ = 0x0200 - SE_DACL_AUTO_INHERITED = 0x0400 - SE_SACL_AUTO_INHERITED = 0x0800 - SE_DACL_PROTECTED = 0x1000 - SE_SACL_PROTECTED = 0x2000 - SE_RM_CONTROL_VALID = 0x4000 - SE_SELF_RELATIVE = 0x8000 + + SE_DACL_AUTO_INHERITED = 0x0400 + + SE_SACL_AUTO_INHERITED = 0x0800 + + SE_DACL_PROTECTED = 0x1000 + + SE_SACL_PROTECTED = 0x2000 + + SE_RM_CONTROL_VALID = 0x4000 + + SE_SELF_RELATIVE = 0x8000 ) type ACCESS_MASK uint32 // Constants for type ACCESS_MASK + const ( - DELETE = 0x00010000 - READ_CONTROL = 0x00020000 - WRITE_DAC = 0x00040000 - WRITE_OWNER = 0x00080000 - SYNCHRONIZE = 0x00100000 + DELETE = 0x00010000 + + READ_CONTROL = 0x00020000 + + WRITE_DAC = 0x00040000 + + WRITE_OWNER = 0x00080000 + + SYNCHRONIZE = 0x00100000 + STANDARD_RIGHTS_REQUIRED = 0x000F0000 - STANDARD_RIGHTS_READ = READ_CONTROL - STANDARD_RIGHTS_WRITE = READ_CONTROL - STANDARD_RIGHTS_EXECUTE = READ_CONTROL - STANDARD_RIGHTS_ALL = 0x001F0000 - SPECIFIC_RIGHTS_ALL = 0x0000FFFF - ACCESS_SYSTEM_SECURITY = 0x01000000 - MAXIMUM_ALLOWED = 0x02000000 - GENERIC_READ = 0x80000000 - GENERIC_WRITE = 0x40000000 - GENERIC_EXECUTE = 0x20000000 - GENERIC_ALL = 0x10000000 + + STANDARD_RIGHTS_READ = READ_CONTROL + + STANDARD_RIGHTS_WRITE = READ_CONTROL + + STANDARD_RIGHTS_EXECUTE = READ_CONTROL + + STANDARD_RIGHTS_ALL = 0x001F0000 + + SPECIFIC_RIGHTS_ALL = 0x0000FFFF + + ACCESS_SYSTEM_SECURITY = 0x01000000 + + MAXIMUM_ALLOWED = 0x02000000 + + GENERIC_READ = 0x80000000 + + GENERIC_WRITE = 0x40000000 + + GENERIC_EXECUTE = 0x20000000 + + GENERIC_ALL = 0x10000000 ) type ACCESS_MODE uint32 // Constants for type ACCESS_MODE + const ( - NOT_USED_ACCESS = 0 - GRANT_ACCESS = 1 - SET_ACCESS = 2 - DENY_ACCESS = 3 - REVOKE_ACCESS = 4 + NOT_USED_ACCESS = 0 + + GRANT_ACCESS = 1 + + SET_ACCESS = 2 + + DENY_ACCESS = 3 + + REVOKE_ACCESS = 4 + SET_AUDIT_SUCCESS = 5 + SET_AUDIT_FAILURE = 6 ) // Constants for AceFlags and Inheritance fields + const ( - NO_INHERITANCE = 0x0 - SUB_OBJECTS_ONLY_INHERIT = 0x1 - SUB_CONTAINERS_ONLY_INHERIT = 0x2 + NO_INHERITANCE = 0x0 + + SUB_OBJECTS_ONLY_INHERIT = 0x1 + + SUB_CONTAINERS_ONLY_INHERIT = 0x2 + SUB_CONTAINERS_AND_OBJECTS_INHERIT = 0x3 - INHERIT_NO_PROPAGATE = 0x4 - INHERIT_ONLY = 0x8 - INHERITED_ACCESS_ENTRY = 0x10 - INHERITED_PARENT = 0x10000000 - INHERITED_GRANDPARENT = 0x20000000 - OBJECT_INHERIT_ACE = 0x1 - CONTAINER_INHERIT_ACE = 0x2 - NO_PROPAGATE_INHERIT_ACE = 0x4 - INHERIT_ONLY_ACE = 0x8 - INHERITED_ACE = 0x10 - VALID_INHERIT_FLAGS = 0x1F + + INHERIT_NO_PROPAGATE = 0x4 + + INHERIT_ONLY = 0x8 + + INHERITED_ACCESS_ENTRY = 0x10 + + INHERITED_PARENT = 0x10000000 + + INHERITED_GRANDPARENT = 0x20000000 + + OBJECT_INHERIT_ACE = 0x1 + + CONTAINER_INHERIT_ACE = 0x2 + + NO_PROPAGATE_INHERIT_ACE = 0x4 + + INHERIT_ONLY_ACE = 0x8 + + INHERITED_ACE = 0x10 + + VALID_INHERIT_FLAGS = 0x1F ) type MULTIPLE_TRUSTEE_OPERATION uint32 // Constants for MULTIPLE_TRUSTEE_OPERATION + const ( - NO_MULTIPLE_TRUSTEE = 0 + NO_MULTIPLE_TRUSTEE = 0 + TRUSTEE_IS_IMPERSONATE = 1 ) type TRUSTEE_FORM uint32 // Constants for TRUSTEE_FORM + const ( - TRUSTEE_IS_SID = 0 - TRUSTEE_IS_NAME = 1 - TRUSTEE_BAD_FORM = 2 - TRUSTEE_IS_OBJECTS_AND_SID = 3 + TRUSTEE_IS_SID = 0 + + TRUSTEE_IS_NAME = 1 + + TRUSTEE_BAD_FORM = 2 + + TRUSTEE_IS_OBJECTS_AND_SID = 3 + TRUSTEE_IS_OBJECTS_AND_NAME = 4 ) type TRUSTEE_TYPE uint32 // Constants for TRUSTEE_TYPE + const ( - TRUSTEE_IS_UNKNOWN = 0 - TRUSTEE_IS_USER = 1 - TRUSTEE_IS_GROUP = 2 - TRUSTEE_IS_DOMAIN = 3 - TRUSTEE_IS_ALIAS = 4 + TRUSTEE_IS_UNKNOWN = 0 + + TRUSTEE_IS_USER = 1 + + TRUSTEE_IS_GROUP = 2 + + TRUSTEE_IS_DOMAIN = 3 + + TRUSTEE_IS_ALIAS = 4 + TRUSTEE_IS_WELL_KNOWN_GROUP = 5 - TRUSTEE_IS_DELETED = 6 - TRUSTEE_IS_INVALID = 7 - TRUSTEE_IS_COMPUTER = 8 + + TRUSTEE_IS_DELETED = 6 + + TRUSTEE_IS_INVALID = 7 + + TRUSTEE_IS_COMPUTER = 8 ) // Constants for ObjectsPresent field + const ( - ACE_OBJECT_TYPE_PRESENT = 0x1 + ACE_OBJECT_TYPE_PRESENT = 0x1 + ACE_INHERITED_OBJECT_TYPE_PRESENT = 0x2 ) type EXPLICIT_ACCESS struct { AccessPermissions ACCESS_MASK - AccessMode ACCESS_MODE - Inheritance uint32 - Trustee TRUSTEE + + AccessMode ACCESS_MODE + + Inheritance uint32 + + Trustee TRUSTEE } // This type is the union inside of TRUSTEE and must be created using one of the TrusteeValueFrom* functions. + type TrusteeValue uintptr func TrusteeValueFromString(str string) TrusteeValue { + return TrusteeValue(unsafe.Pointer(StringToUTF16Ptr(str))) + } + func TrusteeValueFromSID(sid *SID) TrusteeValue { + return TrusteeValue(unsafe.Pointer(sid)) + } + func TrusteeValueFromObjectsAndSid(objectsAndSid *OBJECTS_AND_SID) TrusteeValue { + return TrusteeValue(unsafe.Pointer(objectsAndSid)) + } + func TrusteeValueFromObjectsAndName(objectsAndName *OBJECTS_AND_NAME) TrusteeValue { + return TrusteeValue(unsafe.Pointer(objectsAndName)) + } type TRUSTEE struct { - MultipleTrustee *TRUSTEE + MultipleTrustee *TRUSTEE + MultipleTrusteeOperation MULTIPLE_TRUSTEE_OPERATION - TrusteeForm TRUSTEE_FORM - TrusteeType TRUSTEE_TYPE - TrusteeValue TrusteeValue + + TrusteeForm TRUSTEE_FORM + + TrusteeType TRUSTEE_TYPE + + TrusteeValue TrusteeValue } type OBJECTS_AND_SID struct { - ObjectsPresent uint32 - ObjectTypeGuid GUID + ObjectsPresent uint32 + + ObjectTypeGuid GUID + InheritedObjectTypeGuid GUID - Sid *SID + + Sid *SID } type OBJECTS_AND_NAME struct { - ObjectsPresent uint32 - ObjectType SE_OBJECT_TYPE - ObjectTypeName *uint16 + ObjectsPresent uint32 + + ObjectType SE_OBJECT_TYPE + + ObjectTypeName *uint16 + InheritedObjectTypeName *uint16 - Name *uint16 + + Name *uint16 } //sys getSecurityInfo(handle Handle, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner **SID, group **SID, dacl **ACL, sacl **ACL, sd **SECURITY_DESCRIPTOR) (ret error) = advapi32.GetSecurityInfo + //sys SetSecurityInfo(handle Handle, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner *SID, group *SID, dacl *ACL, sacl *ACL) (ret error) = advapi32.SetSecurityInfo + //sys getNamedSecurityInfo(objectName string, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner **SID, group **SID, dacl **ACL, sacl **ACL, sd **SECURITY_DESCRIPTOR) (ret error) = advapi32.GetNamedSecurityInfoW + //sys SetNamedSecurityInfo(objectName string, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner *SID, group *SID, dacl *ACL, sacl *ACL) (ret error) = advapi32.SetNamedSecurityInfoW + //sys SetKernelObjectSecurity(handle Handle, securityInformation SECURITY_INFORMATION, securityDescriptor *SECURITY_DESCRIPTOR) (err error) = advapi32.SetKernelObjectSecurity //sys buildSecurityDescriptor(owner *TRUSTEE, group *TRUSTEE, countAccessEntries uint32, accessEntries *EXPLICIT_ACCESS, countAuditEntries uint32, auditEntries *EXPLICIT_ACCESS, oldSecurityDescriptor *SECURITY_DESCRIPTOR, sizeNewSecurityDescriptor *uint32, newSecurityDescriptor **SECURITY_DESCRIPTOR) (ret error) = advapi32.BuildSecurityDescriptorW + //sys initializeSecurityDescriptor(absoluteSD *SECURITY_DESCRIPTOR, revision uint32) (err error) = advapi32.InitializeSecurityDescriptor //sys getSecurityDescriptorControl(sd *SECURITY_DESCRIPTOR, control *SECURITY_DESCRIPTOR_CONTROL, revision *uint32) (err error) = advapi32.GetSecurityDescriptorControl + //sys getSecurityDescriptorDacl(sd *SECURITY_DESCRIPTOR, daclPresent *bool, dacl **ACL, daclDefaulted *bool) (err error) = advapi32.GetSecurityDescriptorDacl + //sys getSecurityDescriptorSacl(sd *SECURITY_DESCRIPTOR, saclPresent *bool, sacl **ACL, saclDefaulted *bool) (err error) = advapi32.GetSecurityDescriptorSacl + //sys getSecurityDescriptorOwner(sd *SECURITY_DESCRIPTOR, owner **SID, ownerDefaulted *bool) (err error) = advapi32.GetSecurityDescriptorOwner + //sys getSecurityDescriptorGroup(sd *SECURITY_DESCRIPTOR, group **SID, groupDefaulted *bool) (err error) = advapi32.GetSecurityDescriptorGroup + //sys getSecurityDescriptorLength(sd *SECURITY_DESCRIPTOR) (len uint32) = advapi32.GetSecurityDescriptorLength + //sys getSecurityDescriptorRMControl(sd *SECURITY_DESCRIPTOR, rmControl *uint8) (ret error) [failretval!=0] = advapi32.GetSecurityDescriptorRMControl + //sys isValidSecurityDescriptor(sd *SECURITY_DESCRIPTOR) (isValid bool) = advapi32.IsValidSecurityDescriptor //sys setSecurityDescriptorControl(sd *SECURITY_DESCRIPTOR, controlBitsOfInterest SECURITY_DESCRIPTOR_CONTROL, controlBitsToSet SECURITY_DESCRIPTOR_CONTROL) (err error) = advapi32.SetSecurityDescriptorControl + //sys setSecurityDescriptorDacl(sd *SECURITY_DESCRIPTOR, daclPresent bool, dacl *ACL, daclDefaulted bool) (err error) = advapi32.SetSecurityDescriptorDacl + //sys setSecurityDescriptorSacl(sd *SECURITY_DESCRIPTOR, saclPresent bool, sacl *ACL, saclDefaulted bool) (err error) = advapi32.SetSecurityDescriptorSacl + //sys setSecurityDescriptorOwner(sd *SECURITY_DESCRIPTOR, owner *SID, ownerDefaulted bool) (err error) = advapi32.SetSecurityDescriptorOwner + //sys setSecurityDescriptorGroup(sd *SECURITY_DESCRIPTOR, group *SID, groupDefaulted bool) (err error) = advapi32.SetSecurityDescriptorGroup + //sys setSecurityDescriptorRMControl(sd *SECURITY_DESCRIPTOR, rmControl *uint8) = advapi32.SetSecurityDescriptorRMControl //sys convertStringSecurityDescriptorToSecurityDescriptor(str string, revision uint32, sd **SECURITY_DESCRIPTOR, size *uint32) (err error) = advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW + //sys convertSecurityDescriptorToStringSecurityDescriptor(sd *SECURITY_DESCRIPTOR, revision uint32, securityInformation SECURITY_INFORMATION, str **uint16, strLen *uint32) (err error) = advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW //sys makeAbsoluteSD(selfRelativeSD *SECURITY_DESCRIPTOR, absoluteSD *SECURITY_DESCRIPTOR, absoluteSDSize *uint32, dacl *ACL, daclSize *uint32, sacl *ACL, saclSize *uint32, owner *SID, ownerSize *uint32, group *SID, groupSize *uint32) (err error) = advapi32.MakeAbsoluteSD + //sys makeSelfRelativeSD(absoluteSD *SECURITY_DESCRIPTOR, selfRelativeSD *SECURITY_DESCRIPTOR, selfRelativeSDSize *uint32) (err error) = advapi32.MakeSelfRelativeSD //sys setEntriesInAcl(countExplicitEntries uint32, explicitEntries *EXPLICIT_ACCESS, oldACL *ACL, newACL **ACL) (ret error) = advapi32.SetEntriesInAclW // Control returns the security descriptor control bits. + func (sd *SECURITY_DESCRIPTOR) Control() (control SECURITY_DESCRIPTOR_CONTROL, revision uint32, err error) { + err = getSecurityDescriptorControl(sd, &control, &revision) + return + } // SetControl sets the security descriptor control bits. + func (sd *SECURITY_DESCRIPTOR) SetControl(controlBitsOfInterest SECURITY_DESCRIPTOR_CONTROL, controlBitsToSet SECURITY_DESCRIPTOR_CONTROL) error { + return setSecurityDescriptorControl(sd, controlBitsOfInterest, controlBitsToSet) + } // RMControl returns the security descriptor resource manager control bits. + func (sd *SECURITY_DESCRIPTOR) RMControl() (control uint8, err error) { + err = getSecurityDescriptorRMControl(sd, &control) + return + } // SetRMControl sets the security descriptor resource manager control bits. + func (sd *SECURITY_DESCRIPTOR) SetRMControl(rmControl uint8) { + setSecurityDescriptorRMControl(sd, &rmControl) + } // DACL returns the security descriptor DACL and whether it was defaulted. The dacl return value may be nil + // if a DACL exists but is an "empty DACL", meaning fully permissive. If the DACL does not exist, err returns + // ERROR_OBJECT_NOT_FOUND. + func (sd *SECURITY_DESCRIPTOR) DACL() (dacl *ACL, defaulted bool, err error) { + var present bool + err = getSecurityDescriptorDacl(sd, &present, &dacl, &defaulted) + if !present { + err = ERROR_OBJECT_NOT_FOUND + } + return + } // SetDACL sets the absolute security descriptor DACL. + func (absoluteSD *SECURITY_DESCRIPTOR) SetDACL(dacl *ACL, present, defaulted bool) error { + return setSecurityDescriptorDacl(absoluteSD, present, dacl, defaulted) + } // SACL returns the security descriptor SACL and whether it was defaulted. The sacl return value may be nil + // if a SACL exists but is an "empty SACL", meaning fully permissive. If the SACL does not exist, err returns + // ERROR_OBJECT_NOT_FOUND. + func (sd *SECURITY_DESCRIPTOR) SACL() (sacl *ACL, defaulted bool, err error) { + var present bool + err = getSecurityDescriptorSacl(sd, &present, &sacl, &defaulted) + if !present { + err = ERROR_OBJECT_NOT_FOUND + } + return + } // SetSACL sets the absolute security descriptor SACL. + func (absoluteSD *SECURITY_DESCRIPTOR) SetSACL(sacl *ACL, present, defaulted bool) error { + return setSecurityDescriptorSacl(absoluteSD, present, sacl, defaulted) + } // Owner returns the security descriptor owner and whether it was defaulted. + func (sd *SECURITY_DESCRIPTOR) Owner() (owner *SID, defaulted bool, err error) { + err = getSecurityDescriptorOwner(sd, &owner, &defaulted) + return + } // SetOwner sets the absolute security descriptor owner. + func (absoluteSD *SECURITY_DESCRIPTOR) SetOwner(owner *SID, defaulted bool) error { + return setSecurityDescriptorOwner(absoluteSD, owner, defaulted) + } // Group returns the security descriptor group and whether it was defaulted. + func (sd *SECURITY_DESCRIPTOR) Group() (group *SID, defaulted bool, err error) { + err = getSecurityDescriptorGroup(sd, &group, &defaulted) + return + } // SetGroup sets the absolute security descriptor owner. + func (absoluteSD *SECURITY_DESCRIPTOR) SetGroup(group *SID, defaulted bool) error { + return setSecurityDescriptorGroup(absoluteSD, group, defaulted) + } // Length returns the length of the security descriptor. + func (sd *SECURITY_DESCRIPTOR) Length() uint32 { + return getSecurityDescriptorLength(sd) + } // IsValid returns whether the security descriptor is valid. + func (sd *SECURITY_DESCRIPTOR) IsValid() bool { + return isValidSecurityDescriptor(sd) + } // String returns the SDDL form of the security descriptor, with a function signature that can be + // used with %v formatting directives. + func (sd *SECURITY_DESCRIPTOR) String() string { + var sddl *uint16 + err := convertSecurityDescriptorToStringSecurityDescriptor(sd, 1, 0xff, &sddl, nil) + if err != nil { + return "" + } + defer LocalFree(Handle(unsafe.Pointer(sddl))) + return UTF16PtrToString(sddl) + } // ToAbsolute converts a self-relative security descriptor into an absolute one. + func (selfRelativeSD *SECURITY_DESCRIPTOR) ToAbsolute() (absoluteSD *SECURITY_DESCRIPTOR, err error) { + control, _, err := selfRelativeSD.Control() + if err != nil { + return + } + if control&SE_SELF_RELATIVE == 0 { + err = ERROR_INVALID_PARAMETER + return + } + var absoluteSDSize, daclSize, saclSize, ownerSize, groupSize uint32 + err = makeAbsoluteSD(selfRelativeSD, nil, &absoluteSDSize, + nil, &daclSize, nil, &saclSize, nil, &ownerSize, nil, &groupSize) + switch err { + case ERROR_INSUFFICIENT_BUFFER: + case nil: + // makeAbsoluteSD is expected to fail, but it succeeds. + return nil, ERROR_INTERNAL_ERROR + default: + return nil, err + } + if absoluteSDSize > 0 { + absoluteSD = (*SECURITY_DESCRIPTOR)(unsafe.Pointer(&make([]byte, absoluteSDSize)[0])) + } + var ( - dacl *ACL - sacl *ACL + dacl *ACL + + sacl *ACL + owner *SID + group *SID ) + if daclSize > 0 { + dacl = (*ACL)(unsafe.Pointer(&make([]byte, daclSize)[0])) + } + if saclSize > 0 { + sacl = (*ACL)(unsafe.Pointer(&make([]byte, saclSize)[0])) + } + if ownerSize > 0 { + owner = (*SID)(unsafe.Pointer(&make([]byte, ownerSize)[0])) + } + if groupSize > 0 { + group = (*SID)(unsafe.Pointer(&make([]byte, groupSize)[0])) + } + err = makeAbsoluteSD(selfRelativeSD, absoluteSD, &absoluteSDSize, + dacl, &daclSize, sacl, &saclSize, owner, &ownerSize, group, &groupSize) + return + } // ToSelfRelative converts an absolute security descriptor into a self-relative one. + func (absoluteSD *SECURITY_DESCRIPTOR) ToSelfRelative() (selfRelativeSD *SECURITY_DESCRIPTOR, err error) { + control, _, err := absoluteSD.Control() + if err != nil { + return + } + if control&SE_SELF_RELATIVE != 0 { + err = ERROR_INVALID_PARAMETER + return + } + var selfRelativeSDSize uint32 + err = makeSelfRelativeSD(absoluteSD, nil, &selfRelativeSDSize) + switch err { + case ERROR_INSUFFICIENT_BUFFER: + case nil: + // makeSelfRelativeSD is expected to fail, but it succeeds. + return nil, ERROR_INTERNAL_ERROR + default: + return nil, err + } + if selfRelativeSDSize > 0 { + selfRelativeSD = (*SECURITY_DESCRIPTOR)(unsafe.Pointer(&make([]byte, selfRelativeSDSize)[0])) + } + err = makeSelfRelativeSD(absoluteSD, selfRelativeSD, &selfRelativeSDSize) + return + } func (selfRelativeSD *SECURITY_DESCRIPTOR) copySelfRelativeSecurityDescriptor() *SECURITY_DESCRIPTOR { + sdLen := int(selfRelativeSD.Length()) + const min = int(unsafe.Sizeof(SECURITY_DESCRIPTOR{})) + if sdLen < min { + sdLen = min + } src := unsafe.Slice((*byte)(unsafe.Pointer(selfRelativeSD)), sdLen) + // SECURITY_DESCRIPTOR has pointers in it, which means checkptr expects for it to + // be aligned properly. When we're copying a Windows-allocated struct to a + // Go-allocated one, make sure that the Go allocation is aligned to the + // pointer size. + const psize = int(unsafe.Sizeof(uintptr(0))) + alloc := make([]uintptr, (sdLen+psize-1)/psize) + dst := unsafe.Slice((*byte)(unsafe.Pointer(&alloc[0])), sdLen) + copy(dst, src) + return (*SECURITY_DESCRIPTOR)(unsafe.Pointer(&dst[0])) + } // SecurityDescriptorFromString converts an SDDL string describing a security descriptor into a + // self-relative security descriptor object allocated on the Go heap. + func SecurityDescriptorFromString(sddl string) (sd *SECURITY_DESCRIPTOR, err error) { + var winHeapSD *SECURITY_DESCRIPTOR + err = convertStringSecurityDescriptorToSecurityDescriptor(sddl, 1, &winHeapSD, nil) + if err != nil { + return + } + defer LocalFree(Handle(unsafe.Pointer(winHeapSD))) + return winHeapSD.copySelfRelativeSecurityDescriptor(), nil + } // GetSecurityInfo queries the security information for a given handle and returns the self-relative security + // descriptor result on the Go heap. + func GetSecurityInfo(handle Handle, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION) (sd *SECURITY_DESCRIPTOR, err error) { + var winHeapSD *SECURITY_DESCRIPTOR + err = getSecurityInfo(handle, objectType, securityInformation, nil, nil, nil, nil, &winHeapSD) + if err != nil { + return + } + defer LocalFree(Handle(unsafe.Pointer(winHeapSD))) + return winHeapSD.copySelfRelativeSecurityDescriptor(), nil + } // GetNamedSecurityInfo queries the security information for a given named object and returns the self-relative security + // descriptor result on the Go heap. + func GetNamedSecurityInfo(objectName string, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION) (sd *SECURITY_DESCRIPTOR, err error) { + var winHeapSD *SECURITY_DESCRIPTOR + err = getNamedSecurityInfo(objectName, objectType, securityInformation, nil, nil, nil, nil, &winHeapSD) + if err != nil { + return + } + defer LocalFree(Handle(unsafe.Pointer(winHeapSD))) + return winHeapSD.copySelfRelativeSecurityDescriptor(), nil + } // BuildSecurityDescriptor makes a new security descriptor using the input trustees, explicit access lists, and + // prior security descriptor to be merged, any of which can be nil, returning the self-relative security descriptor + // result on the Go heap. + func BuildSecurityDescriptor(owner *TRUSTEE, group *TRUSTEE, accessEntries []EXPLICIT_ACCESS, auditEntries []EXPLICIT_ACCESS, mergedSecurityDescriptor *SECURITY_DESCRIPTOR) (sd *SECURITY_DESCRIPTOR, err error) { + var winHeapSD *SECURITY_DESCRIPTOR + var winHeapSDSize uint32 + var firstAccessEntry *EXPLICIT_ACCESS + if len(accessEntries) > 0 { + firstAccessEntry = &accessEntries[0] + } + var firstAuditEntry *EXPLICIT_ACCESS + if len(auditEntries) > 0 { + firstAuditEntry = &auditEntries[0] + } + err = buildSecurityDescriptor(owner, group, uint32(len(accessEntries)), firstAccessEntry, uint32(len(auditEntries)), firstAuditEntry, mergedSecurityDescriptor, &winHeapSDSize, &winHeapSD) + if err != nil { + return + } + defer LocalFree(Handle(unsafe.Pointer(winHeapSD))) + return winHeapSD.copySelfRelativeSecurityDescriptor(), nil + } // NewSecurityDescriptor creates and initializes a new absolute security descriptor. + func NewSecurityDescriptor() (absoluteSD *SECURITY_DESCRIPTOR, err error) { + absoluteSD = &SECURITY_DESCRIPTOR{} + err = initializeSecurityDescriptor(absoluteSD, 1) + return + } // ACLFromEntries returns a new ACL on the Go heap containing a list of explicit entries as well as those of another ACL. + // Both explicitEntries and mergedACL are optional and can be nil. + func ACLFromEntries(explicitEntries []EXPLICIT_ACCESS, mergedACL *ACL) (acl *ACL, err error) { + var firstExplicitEntry *EXPLICIT_ACCESS + if len(explicitEntries) > 0 { + firstExplicitEntry = &explicitEntries[0] + } + var winHeapACL *ACL + err = setEntriesInAcl(uint32(len(explicitEntries)), firstExplicitEntry, mergedACL, &winHeapACL) + if err != nil { + return + } + defer LocalFree(Handle(unsafe.Pointer(winHeapACL))) + aclBytes := make([]byte, winHeapACL.aclSize) + copy(aclBytes, (*[(1 << 31) - 1]byte)(unsafe.Pointer(winHeapACL))[:len(aclBytes):len(aclBytes)]) + return (*ACL)(unsafe.Pointer(&aclBytes[0])), nil + } diff --git a/vendor/golang.org/x/sys/windows/setupapi_windows.go b/vendor/golang.org/x/sys/windows/setupapi_windows.go index f812648..b8f23e6 100644 --- a/vendor/golang.org/x/sys/windows/setupapi_windows.go +++ b/vendor/golang.org/x/sys/windows/setupapi_windows.go @@ -1,5 +1,7 @@ // Copyright 2021 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package windows @@ -15,582 +17,978 @@ import ( ) // This file contains functions that wrap SetupAPI.dll and CfgMgr32.dll, + // core system functions for managing hardware devices, drivers, and the PnP tree. + // Information about these APIs can be found at: + // https://docs.microsoft.com/en-us/windows-hardware/drivers/install/setupapi + // https://docs.microsoft.com/en-us/windows/win32/devinst/cfgmgr32- const ( - ERROR_EXPECTED_SECTION_NAME Errno = 0x20000000 | 0xC0000000 | 0 - ERROR_BAD_SECTION_NAME_LINE Errno = 0x20000000 | 0xC0000000 | 1 - ERROR_SECTION_NAME_TOO_LONG Errno = 0x20000000 | 0xC0000000 | 2 - ERROR_GENERAL_SYNTAX Errno = 0x20000000 | 0xC0000000 | 3 - ERROR_WRONG_INF_STYLE Errno = 0x20000000 | 0xC0000000 | 0x100 - ERROR_SECTION_NOT_FOUND Errno = 0x20000000 | 0xC0000000 | 0x101 - ERROR_LINE_NOT_FOUND Errno = 0x20000000 | 0xC0000000 | 0x102 - ERROR_NO_BACKUP Errno = 0x20000000 | 0xC0000000 | 0x103 - ERROR_NO_ASSOCIATED_CLASS Errno = 0x20000000 | 0xC0000000 | 0x200 - ERROR_CLASS_MISMATCH Errno = 0x20000000 | 0xC0000000 | 0x201 - ERROR_DUPLICATE_FOUND Errno = 0x20000000 | 0xC0000000 | 0x202 - ERROR_NO_DRIVER_SELECTED Errno = 0x20000000 | 0xC0000000 | 0x203 - ERROR_KEY_DOES_NOT_EXIST Errno = 0x20000000 | 0xC0000000 | 0x204 - ERROR_INVALID_DEVINST_NAME Errno = 0x20000000 | 0xC0000000 | 0x205 - ERROR_INVALID_CLASS Errno = 0x20000000 | 0xC0000000 | 0x206 - ERROR_DEVINST_ALREADY_EXISTS Errno = 0x20000000 | 0xC0000000 | 0x207 - ERROR_DEVINFO_NOT_REGISTERED Errno = 0x20000000 | 0xC0000000 | 0x208 - ERROR_INVALID_REG_PROPERTY Errno = 0x20000000 | 0xC0000000 | 0x209 - ERROR_NO_INF Errno = 0x20000000 | 0xC0000000 | 0x20A - ERROR_NO_SUCH_DEVINST Errno = 0x20000000 | 0xC0000000 | 0x20B - ERROR_CANT_LOAD_CLASS_ICON Errno = 0x20000000 | 0xC0000000 | 0x20C - ERROR_INVALID_CLASS_INSTALLER Errno = 0x20000000 | 0xC0000000 | 0x20D - ERROR_DI_DO_DEFAULT Errno = 0x20000000 | 0xC0000000 | 0x20E - ERROR_DI_NOFILECOPY Errno = 0x20000000 | 0xC0000000 | 0x20F - ERROR_INVALID_HWPROFILE Errno = 0x20000000 | 0xC0000000 | 0x210 - ERROR_NO_DEVICE_SELECTED Errno = 0x20000000 | 0xC0000000 | 0x211 - ERROR_DEVINFO_LIST_LOCKED Errno = 0x20000000 | 0xC0000000 | 0x212 - ERROR_DEVINFO_DATA_LOCKED Errno = 0x20000000 | 0xC0000000 | 0x213 - ERROR_DI_BAD_PATH Errno = 0x20000000 | 0xC0000000 | 0x214 - ERROR_NO_CLASSINSTALL_PARAMS Errno = 0x20000000 | 0xC0000000 | 0x215 - ERROR_FILEQUEUE_LOCKED Errno = 0x20000000 | 0xC0000000 | 0x216 - ERROR_BAD_SERVICE_INSTALLSECT Errno = 0x20000000 | 0xC0000000 | 0x217 - ERROR_NO_CLASS_DRIVER_LIST Errno = 0x20000000 | 0xC0000000 | 0x218 - ERROR_NO_ASSOCIATED_SERVICE Errno = 0x20000000 | 0xC0000000 | 0x219 - ERROR_NO_DEFAULT_DEVICE_INTERFACE Errno = 0x20000000 | 0xC0000000 | 0x21A - ERROR_DEVICE_INTERFACE_ACTIVE Errno = 0x20000000 | 0xC0000000 | 0x21B - ERROR_DEVICE_INTERFACE_REMOVED Errno = 0x20000000 | 0xC0000000 | 0x21C - ERROR_BAD_INTERFACE_INSTALLSECT Errno = 0x20000000 | 0xC0000000 | 0x21D - ERROR_NO_SUCH_INTERFACE_CLASS Errno = 0x20000000 | 0xC0000000 | 0x21E - ERROR_INVALID_REFERENCE_STRING Errno = 0x20000000 | 0xC0000000 | 0x21F - ERROR_INVALID_MACHINENAME Errno = 0x20000000 | 0xC0000000 | 0x220 - ERROR_REMOTE_COMM_FAILURE Errno = 0x20000000 | 0xC0000000 | 0x221 - ERROR_MACHINE_UNAVAILABLE Errno = 0x20000000 | 0xC0000000 | 0x222 - ERROR_NO_CONFIGMGR_SERVICES Errno = 0x20000000 | 0xC0000000 | 0x223 - ERROR_INVALID_PROPPAGE_PROVIDER Errno = 0x20000000 | 0xC0000000 | 0x224 - ERROR_NO_SUCH_DEVICE_INTERFACE Errno = 0x20000000 | 0xC0000000 | 0x225 - ERROR_DI_POSTPROCESSING_REQUIRED Errno = 0x20000000 | 0xC0000000 | 0x226 - ERROR_INVALID_COINSTALLER Errno = 0x20000000 | 0xC0000000 | 0x227 - ERROR_NO_COMPAT_DRIVERS Errno = 0x20000000 | 0xC0000000 | 0x228 - ERROR_NO_DEVICE_ICON Errno = 0x20000000 | 0xC0000000 | 0x229 - ERROR_INVALID_INF_LOGCONFIG Errno = 0x20000000 | 0xC0000000 | 0x22A - ERROR_DI_DONT_INSTALL Errno = 0x20000000 | 0xC0000000 | 0x22B - ERROR_INVALID_FILTER_DRIVER Errno = 0x20000000 | 0xC0000000 | 0x22C - ERROR_NON_WINDOWS_NT_DRIVER Errno = 0x20000000 | 0xC0000000 | 0x22D - ERROR_NON_WINDOWS_DRIVER Errno = 0x20000000 | 0xC0000000 | 0x22E - ERROR_NO_CATALOG_FOR_OEM_INF Errno = 0x20000000 | 0xC0000000 | 0x22F - ERROR_DEVINSTALL_QUEUE_NONNATIVE Errno = 0x20000000 | 0xC0000000 | 0x230 - ERROR_NOT_DISABLEABLE Errno = 0x20000000 | 0xC0000000 | 0x231 - ERROR_CANT_REMOVE_DEVINST Errno = 0x20000000 | 0xC0000000 | 0x232 - ERROR_INVALID_TARGET Errno = 0x20000000 | 0xC0000000 | 0x233 - ERROR_DRIVER_NONNATIVE Errno = 0x20000000 | 0xC0000000 | 0x234 - ERROR_IN_WOW64 Errno = 0x20000000 | 0xC0000000 | 0x235 - ERROR_SET_SYSTEM_RESTORE_POINT Errno = 0x20000000 | 0xC0000000 | 0x236 - ERROR_SCE_DISABLED Errno = 0x20000000 | 0xC0000000 | 0x238 - ERROR_UNKNOWN_EXCEPTION Errno = 0x20000000 | 0xC0000000 | 0x239 - ERROR_PNP_REGISTRY_ERROR Errno = 0x20000000 | 0xC0000000 | 0x23A - ERROR_REMOTE_REQUEST_UNSUPPORTED Errno = 0x20000000 | 0xC0000000 | 0x23B - ERROR_NOT_AN_INSTALLED_OEM_INF Errno = 0x20000000 | 0xC0000000 | 0x23C - ERROR_INF_IN_USE_BY_DEVICES Errno = 0x20000000 | 0xC0000000 | 0x23D - ERROR_DI_FUNCTION_OBSOLETE Errno = 0x20000000 | 0xC0000000 | 0x23E - ERROR_NO_AUTHENTICODE_CATALOG Errno = 0x20000000 | 0xC0000000 | 0x23F - ERROR_AUTHENTICODE_DISALLOWED Errno = 0x20000000 | 0xC0000000 | 0x240 - ERROR_AUTHENTICODE_TRUSTED_PUBLISHER Errno = 0x20000000 | 0xC0000000 | 0x241 - ERROR_AUTHENTICODE_TRUST_NOT_ESTABLISHED Errno = 0x20000000 | 0xC0000000 | 0x242 - ERROR_AUTHENTICODE_PUBLISHER_NOT_TRUSTED Errno = 0x20000000 | 0xC0000000 | 0x243 - ERROR_SIGNATURE_OSATTRIBUTE_MISMATCH Errno = 0x20000000 | 0xC0000000 | 0x244 - ERROR_ONLY_VALIDATE_VIA_AUTHENTICODE Errno = 0x20000000 | 0xC0000000 | 0x245 - ERROR_DEVICE_INSTALLER_NOT_READY Errno = 0x20000000 | 0xC0000000 | 0x246 - ERROR_DRIVER_STORE_ADD_FAILED Errno = 0x20000000 | 0xC0000000 | 0x247 - ERROR_DEVICE_INSTALL_BLOCKED Errno = 0x20000000 | 0xC0000000 | 0x248 - ERROR_DRIVER_INSTALL_BLOCKED Errno = 0x20000000 | 0xC0000000 | 0x249 - ERROR_WRONG_INF_TYPE Errno = 0x20000000 | 0xC0000000 | 0x24A - ERROR_FILE_HASH_NOT_IN_CATALOG Errno = 0x20000000 | 0xC0000000 | 0x24B - ERROR_DRIVER_STORE_DELETE_FAILED Errno = 0x20000000 | 0xC0000000 | 0x24C - ERROR_UNRECOVERABLE_STACK_OVERFLOW Errno = 0x20000000 | 0xC0000000 | 0x300 + ERROR_EXPECTED_SECTION_NAME Errno = 0x20000000 | 0xC0000000 | 0 + + ERROR_BAD_SECTION_NAME_LINE Errno = 0x20000000 | 0xC0000000 | 1 + + ERROR_SECTION_NAME_TOO_LONG Errno = 0x20000000 | 0xC0000000 | 2 + + ERROR_GENERAL_SYNTAX Errno = 0x20000000 | 0xC0000000 | 3 + + ERROR_WRONG_INF_STYLE Errno = 0x20000000 | 0xC0000000 | 0x100 + + ERROR_SECTION_NOT_FOUND Errno = 0x20000000 | 0xC0000000 | 0x101 + + ERROR_LINE_NOT_FOUND Errno = 0x20000000 | 0xC0000000 | 0x102 + + ERROR_NO_BACKUP Errno = 0x20000000 | 0xC0000000 | 0x103 + + ERROR_NO_ASSOCIATED_CLASS Errno = 0x20000000 | 0xC0000000 | 0x200 + + ERROR_CLASS_MISMATCH Errno = 0x20000000 | 0xC0000000 | 0x201 + + ERROR_DUPLICATE_FOUND Errno = 0x20000000 | 0xC0000000 | 0x202 + + ERROR_NO_DRIVER_SELECTED Errno = 0x20000000 | 0xC0000000 | 0x203 + + ERROR_KEY_DOES_NOT_EXIST Errno = 0x20000000 | 0xC0000000 | 0x204 + + ERROR_INVALID_DEVINST_NAME Errno = 0x20000000 | 0xC0000000 | 0x205 + + ERROR_INVALID_CLASS Errno = 0x20000000 | 0xC0000000 | 0x206 + + ERROR_DEVINST_ALREADY_EXISTS Errno = 0x20000000 | 0xC0000000 | 0x207 + + ERROR_DEVINFO_NOT_REGISTERED Errno = 0x20000000 | 0xC0000000 | 0x208 + + ERROR_INVALID_REG_PROPERTY Errno = 0x20000000 | 0xC0000000 | 0x209 + + ERROR_NO_INF Errno = 0x20000000 | 0xC0000000 | 0x20A + + ERROR_NO_SUCH_DEVINST Errno = 0x20000000 | 0xC0000000 | 0x20B + + ERROR_CANT_LOAD_CLASS_ICON Errno = 0x20000000 | 0xC0000000 | 0x20C + + ERROR_INVALID_CLASS_INSTALLER Errno = 0x20000000 | 0xC0000000 | 0x20D + + ERROR_DI_DO_DEFAULT Errno = 0x20000000 | 0xC0000000 | 0x20E + + ERROR_DI_NOFILECOPY Errno = 0x20000000 | 0xC0000000 | 0x20F + + ERROR_INVALID_HWPROFILE Errno = 0x20000000 | 0xC0000000 | 0x210 + + ERROR_NO_DEVICE_SELECTED Errno = 0x20000000 | 0xC0000000 | 0x211 + + ERROR_DEVINFO_LIST_LOCKED Errno = 0x20000000 | 0xC0000000 | 0x212 + + ERROR_DEVINFO_DATA_LOCKED Errno = 0x20000000 | 0xC0000000 | 0x213 + + ERROR_DI_BAD_PATH Errno = 0x20000000 | 0xC0000000 | 0x214 + + ERROR_NO_CLASSINSTALL_PARAMS Errno = 0x20000000 | 0xC0000000 | 0x215 + + ERROR_FILEQUEUE_LOCKED Errno = 0x20000000 | 0xC0000000 | 0x216 + + ERROR_BAD_SERVICE_INSTALLSECT Errno = 0x20000000 | 0xC0000000 | 0x217 + + ERROR_NO_CLASS_DRIVER_LIST Errno = 0x20000000 | 0xC0000000 | 0x218 + + ERROR_NO_ASSOCIATED_SERVICE Errno = 0x20000000 | 0xC0000000 | 0x219 + + ERROR_NO_DEFAULT_DEVICE_INTERFACE Errno = 0x20000000 | 0xC0000000 | 0x21A + + ERROR_DEVICE_INTERFACE_ACTIVE Errno = 0x20000000 | 0xC0000000 | 0x21B + + ERROR_DEVICE_INTERFACE_REMOVED Errno = 0x20000000 | 0xC0000000 | 0x21C + + ERROR_BAD_INTERFACE_INSTALLSECT Errno = 0x20000000 | 0xC0000000 | 0x21D + + ERROR_NO_SUCH_INTERFACE_CLASS Errno = 0x20000000 | 0xC0000000 | 0x21E + + ERROR_INVALID_REFERENCE_STRING Errno = 0x20000000 | 0xC0000000 | 0x21F + + ERROR_INVALID_MACHINENAME Errno = 0x20000000 | 0xC0000000 | 0x220 + + ERROR_REMOTE_COMM_FAILURE Errno = 0x20000000 | 0xC0000000 | 0x221 + + ERROR_MACHINE_UNAVAILABLE Errno = 0x20000000 | 0xC0000000 | 0x222 + + ERROR_NO_CONFIGMGR_SERVICES Errno = 0x20000000 | 0xC0000000 | 0x223 + + ERROR_INVALID_PROPPAGE_PROVIDER Errno = 0x20000000 | 0xC0000000 | 0x224 + + ERROR_NO_SUCH_DEVICE_INTERFACE Errno = 0x20000000 | 0xC0000000 | 0x225 + + ERROR_DI_POSTPROCESSING_REQUIRED Errno = 0x20000000 | 0xC0000000 | 0x226 + + ERROR_INVALID_COINSTALLER Errno = 0x20000000 | 0xC0000000 | 0x227 + + ERROR_NO_COMPAT_DRIVERS Errno = 0x20000000 | 0xC0000000 | 0x228 + + ERROR_NO_DEVICE_ICON Errno = 0x20000000 | 0xC0000000 | 0x229 + + ERROR_INVALID_INF_LOGCONFIG Errno = 0x20000000 | 0xC0000000 | 0x22A + + ERROR_DI_DONT_INSTALL Errno = 0x20000000 | 0xC0000000 | 0x22B + + ERROR_INVALID_FILTER_DRIVER Errno = 0x20000000 | 0xC0000000 | 0x22C + + ERROR_NON_WINDOWS_NT_DRIVER Errno = 0x20000000 | 0xC0000000 | 0x22D + + ERROR_NON_WINDOWS_DRIVER Errno = 0x20000000 | 0xC0000000 | 0x22E + + ERROR_NO_CATALOG_FOR_OEM_INF Errno = 0x20000000 | 0xC0000000 | 0x22F + + ERROR_DEVINSTALL_QUEUE_NONNATIVE Errno = 0x20000000 | 0xC0000000 | 0x230 + + ERROR_NOT_DISABLEABLE Errno = 0x20000000 | 0xC0000000 | 0x231 + + ERROR_CANT_REMOVE_DEVINST Errno = 0x20000000 | 0xC0000000 | 0x232 + + ERROR_INVALID_TARGET Errno = 0x20000000 | 0xC0000000 | 0x233 + + ERROR_DRIVER_NONNATIVE Errno = 0x20000000 | 0xC0000000 | 0x234 + + ERROR_IN_WOW64 Errno = 0x20000000 | 0xC0000000 | 0x235 + + ERROR_SET_SYSTEM_RESTORE_POINT Errno = 0x20000000 | 0xC0000000 | 0x236 + + ERROR_SCE_DISABLED Errno = 0x20000000 | 0xC0000000 | 0x238 + + ERROR_UNKNOWN_EXCEPTION Errno = 0x20000000 | 0xC0000000 | 0x239 + + ERROR_PNP_REGISTRY_ERROR Errno = 0x20000000 | 0xC0000000 | 0x23A + + ERROR_REMOTE_REQUEST_UNSUPPORTED Errno = 0x20000000 | 0xC0000000 | 0x23B + + ERROR_NOT_AN_INSTALLED_OEM_INF Errno = 0x20000000 | 0xC0000000 | 0x23C + + ERROR_INF_IN_USE_BY_DEVICES Errno = 0x20000000 | 0xC0000000 | 0x23D + + ERROR_DI_FUNCTION_OBSOLETE Errno = 0x20000000 | 0xC0000000 | 0x23E + + ERROR_NO_AUTHENTICODE_CATALOG Errno = 0x20000000 | 0xC0000000 | 0x23F + + ERROR_AUTHENTICODE_DISALLOWED Errno = 0x20000000 | 0xC0000000 | 0x240 + + ERROR_AUTHENTICODE_TRUSTED_PUBLISHER Errno = 0x20000000 | 0xC0000000 | 0x241 + + ERROR_AUTHENTICODE_TRUST_NOT_ESTABLISHED Errno = 0x20000000 | 0xC0000000 | 0x242 + + ERROR_AUTHENTICODE_PUBLISHER_NOT_TRUSTED Errno = 0x20000000 | 0xC0000000 | 0x243 + + ERROR_SIGNATURE_OSATTRIBUTE_MISMATCH Errno = 0x20000000 | 0xC0000000 | 0x244 + + ERROR_ONLY_VALIDATE_VIA_AUTHENTICODE Errno = 0x20000000 | 0xC0000000 | 0x245 + + ERROR_DEVICE_INSTALLER_NOT_READY Errno = 0x20000000 | 0xC0000000 | 0x246 + + ERROR_DRIVER_STORE_ADD_FAILED Errno = 0x20000000 | 0xC0000000 | 0x247 + + ERROR_DEVICE_INSTALL_BLOCKED Errno = 0x20000000 | 0xC0000000 | 0x248 + + ERROR_DRIVER_INSTALL_BLOCKED Errno = 0x20000000 | 0xC0000000 | 0x249 + + ERROR_WRONG_INF_TYPE Errno = 0x20000000 | 0xC0000000 | 0x24A + + ERROR_FILE_HASH_NOT_IN_CATALOG Errno = 0x20000000 | 0xC0000000 | 0x24B + + ERROR_DRIVER_STORE_DELETE_FAILED Errno = 0x20000000 | 0xC0000000 | 0x24C + + ERROR_UNRECOVERABLE_STACK_OVERFLOW Errno = 0x20000000 | 0xC0000000 | 0x300 + EXCEPTION_SPAPI_UNRECOVERABLE_STACK_OVERFLOW Errno = ERROR_UNRECOVERABLE_STACK_OVERFLOW - ERROR_NO_DEFAULT_INTERFACE_DEVICE Errno = ERROR_NO_DEFAULT_DEVICE_INTERFACE - ERROR_INTERFACE_DEVICE_ACTIVE Errno = ERROR_DEVICE_INTERFACE_ACTIVE - ERROR_INTERFACE_DEVICE_REMOVED Errno = ERROR_DEVICE_INTERFACE_REMOVED - ERROR_NO_SUCH_INTERFACE_DEVICE Errno = ERROR_NO_SUCH_DEVICE_INTERFACE + + ERROR_NO_DEFAULT_INTERFACE_DEVICE Errno = ERROR_NO_DEFAULT_DEVICE_INTERFACE + + ERROR_INTERFACE_DEVICE_ACTIVE Errno = ERROR_DEVICE_INTERFACE_ACTIVE + + ERROR_INTERFACE_DEVICE_REMOVED Errno = ERROR_DEVICE_INTERFACE_REMOVED + + ERROR_NO_SUCH_INTERFACE_DEVICE Errno = ERROR_NO_SUCH_DEVICE_INTERFACE ) const ( - MAX_DEVICE_ID_LEN = 200 - MAX_DEVNODE_ID_LEN = MAX_DEVICE_ID_LEN + MAX_DEVICE_ID_LEN = 200 + + MAX_DEVNODE_ID_LEN = MAX_DEVICE_ID_LEN + MAX_GUID_STRING_LEN = 39 // 38 chars + terminator null - MAX_CLASS_NAME_LEN = 32 - MAX_PROFILE_LEN = 80 - MAX_CONFIG_VALUE = 9999 - MAX_INSTANCE_VALUE = 9999 - CONFIGMG_VERSION = 0x0400 + + MAX_CLASS_NAME_LEN = 32 + + MAX_PROFILE_LEN = 80 + + MAX_CONFIG_VALUE = 9999 + + MAX_INSTANCE_VALUE = 9999 + + CONFIGMG_VERSION = 0x0400 ) // Maximum string length constants + const ( - LINE_LEN = 256 // Windows 9x-compatible maximum for displayable strings coming from a device INF. - MAX_INF_STRING_LENGTH = 4096 // Actual maximum size of an INF string (including string substitutions). - MAX_INF_SECTION_NAME_LENGTH = 255 // For Windows 9x compatibility, INF section names should be constrained to 32 characters. - MAX_TITLE_LEN = 60 - MAX_INSTRUCTION_LEN = 256 - MAX_LABEL_LEN = 30 - MAX_SERVICE_NAME_LEN = 256 - MAX_SUBTITLE_LEN = 256 + LINE_LEN = 256 // Windows 9x-compatible maximum for displayable strings coming from a device INF. + + MAX_INF_STRING_LENGTH = 4096 // Actual maximum size of an INF string (including string substitutions). + + MAX_INF_SECTION_NAME_LENGTH = 255 // For Windows 9x compatibility, INF section names should be constrained to 32 characters. + + MAX_TITLE_LEN = 60 + + MAX_INSTRUCTION_LEN = 256 + + MAX_LABEL_LEN = 30 + + MAX_SERVICE_NAME_LEN = 256 + + MAX_SUBTITLE_LEN = 256 ) const ( + // SP_MAX_MACHINENAME_LENGTH defines maximum length of a machine name in the format expected by ConfigMgr32 CM_Connect_Machine (i.e., "\\\\MachineName\0"). + SP_MAX_MACHINENAME_LENGTH = MAX_PATH + 3 ) // HSPFILEQ is type for setup file queue + type HSPFILEQ uintptr // DevInfo holds reference to device information set + type DevInfo Handle // DEVINST is a handle usually recognized by cfgmgr32 APIs + type DEVINST uint32 // DevInfoData is a device information structure (references a device instance that is a member of a device information set) + type DevInfoData struct { - size uint32 + size uint32 + ClassGUID GUID - DevInst DEVINST - _ uintptr + + DevInst DEVINST + + _ uintptr } // DevInfoListDetailData is a structure for detailed information on a device information set (used for SetupDiGetDeviceInfoListDetail which supersedes the functionality of SetupDiGetDeviceInfoListClass). + type DevInfoListDetailData struct { - size uint32 // Use unsafeSizeOf method - ClassGUID GUID + size uint32 // Use unsafeSizeOf method + + ClassGUID GUID + RemoteMachineHandle Handle - remoteMachineName [SP_MAX_MACHINENAME_LENGTH]uint16 + + remoteMachineName [SP_MAX_MACHINENAME_LENGTH]uint16 } func (*DevInfoListDetailData) unsafeSizeOf() uint32 { + if unsafe.Sizeof(uintptr(0)) == 4 { + // Windows declares this with pshpack1.h + return uint32(unsafe.Offsetof(DevInfoListDetailData{}.remoteMachineName) + unsafe.Sizeof(DevInfoListDetailData{}.remoteMachineName)) + } + return uint32(unsafe.Sizeof(DevInfoListDetailData{})) + } func (data *DevInfoListDetailData) RemoteMachineName() string { + return UTF16ToString(data.remoteMachineName[:]) + } func (data *DevInfoListDetailData) SetRemoteMachineName(remoteMachineName string) error { + str, err := UTF16FromString(remoteMachineName) + if err != nil { + return err + } + copy(data.remoteMachineName[:], str) + return nil + } // DI_FUNCTION is function type for device installer + type DI_FUNCTION uint32 const ( - DIF_SELECTDEVICE DI_FUNCTION = 0x00000001 - DIF_INSTALLDEVICE DI_FUNCTION = 0x00000002 - DIF_ASSIGNRESOURCES DI_FUNCTION = 0x00000003 - DIF_PROPERTIES DI_FUNCTION = 0x00000004 - DIF_REMOVE DI_FUNCTION = 0x00000005 - DIF_FIRSTTIMESETUP DI_FUNCTION = 0x00000006 - DIF_FOUNDDEVICE DI_FUNCTION = 0x00000007 - DIF_SELECTCLASSDRIVERS DI_FUNCTION = 0x00000008 - DIF_VALIDATECLASSDRIVERS DI_FUNCTION = 0x00000009 - DIF_INSTALLCLASSDRIVERS DI_FUNCTION = 0x0000000A - DIF_CALCDISKSPACE DI_FUNCTION = 0x0000000B - DIF_DESTROYPRIVATEDATA DI_FUNCTION = 0x0000000C - DIF_VALIDATEDRIVER DI_FUNCTION = 0x0000000D - DIF_DETECT DI_FUNCTION = 0x0000000F - DIF_INSTALLWIZARD DI_FUNCTION = 0x00000010 - DIF_DESTROYWIZARDDATA DI_FUNCTION = 0x00000011 - DIF_PROPERTYCHANGE DI_FUNCTION = 0x00000012 - DIF_ENABLECLASS DI_FUNCTION = 0x00000013 - DIF_DETECTVERIFY DI_FUNCTION = 0x00000014 - DIF_INSTALLDEVICEFILES DI_FUNCTION = 0x00000015 - DIF_UNREMOVE DI_FUNCTION = 0x00000016 - DIF_SELECTBESTCOMPATDRV DI_FUNCTION = 0x00000017 - DIF_ALLOW_INSTALL DI_FUNCTION = 0x00000018 - DIF_REGISTERDEVICE DI_FUNCTION = 0x00000019 - DIF_NEWDEVICEWIZARD_PRESELECT DI_FUNCTION = 0x0000001A - DIF_NEWDEVICEWIZARD_SELECT DI_FUNCTION = 0x0000001B - DIF_NEWDEVICEWIZARD_PREANALYZE DI_FUNCTION = 0x0000001C - DIF_NEWDEVICEWIZARD_POSTANALYZE DI_FUNCTION = 0x0000001D - DIF_NEWDEVICEWIZARD_FINISHINSTALL DI_FUNCTION = 0x0000001E - DIF_INSTALLINTERFACES DI_FUNCTION = 0x00000020 - DIF_DETECTCANCEL DI_FUNCTION = 0x00000021 - DIF_REGISTER_COINSTALLERS DI_FUNCTION = 0x00000022 - DIF_ADDPROPERTYPAGE_ADVANCED DI_FUNCTION = 0x00000023 - DIF_ADDPROPERTYPAGE_BASIC DI_FUNCTION = 0x00000024 - DIF_TROUBLESHOOTER DI_FUNCTION = 0x00000026 - DIF_POWERMESSAGEWAKE DI_FUNCTION = 0x00000027 + DIF_SELECTDEVICE DI_FUNCTION = 0x00000001 + + DIF_INSTALLDEVICE DI_FUNCTION = 0x00000002 + + DIF_ASSIGNRESOURCES DI_FUNCTION = 0x00000003 + + DIF_PROPERTIES DI_FUNCTION = 0x00000004 + + DIF_REMOVE DI_FUNCTION = 0x00000005 + + DIF_FIRSTTIMESETUP DI_FUNCTION = 0x00000006 + + DIF_FOUNDDEVICE DI_FUNCTION = 0x00000007 + + DIF_SELECTCLASSDRIVERS DI_FUNCTION = 0x00000008 + + DIF_VALIDATECLASSDRIVERS DI_FUNCTION = 0x00000009 + + DIF_INSTALLCLASSDRIVERS DI_FUNCTION = 0x0000000A + + DIF_CALCDISKSPACE DI_FUNCTION = 0x0000000B + + DIF_DESTROYPRIVATEDATA DI_FUNCTION = 0x0000000C + + DIF_VALIDATEDRIVER DI_FUNCTION = 0x0000000D + + DIF_DETECT DI_FUNCTION = 0x0000000F + + DIF_INSTALLWIZARD DI_FUNCTION = 0x00000010 + + DIF_DESTROYWIZARDDATA DI_FUNCTION = 0x00000011 + + DIF_PROPERTYCHANGE DI_FUNCTION = 0x00000012 + + DIF_ENABLECLASS DI_FUNCTION = 0x00000013 + + DIF_DETECTVERIFY DI_FUNCTION = 0x00000014 + + DIF_INSTALLDEVICEFILES DI_FUNCTION = 0x00000015 + + DIF_UNREMOVE DI_FUNCTION = 0x00000016 + + DIF_SELECTBESTCOMPATDRV DI_FUNCTION = 0x00000017 + + DIF_ALLOW_INSTALL DI_FUNCTION = 0x00000018 + + DIF_REGISTERDEVICE DI_FUNCTION = 0x00000019 + + DIF_NEWDEVICEWIZARD_PRESELECT DI_FUNCTION = 0x0000001A + + DIF_NEWDEVICEWIZARD_SELECT DI_FUNCTION = 0x0000001B + + DIF_NEWDEVICEWIZARD_PREANALYZE DI_FUNCTION = 0x0000001C + + DIF_NEWDEVICEWIZARD_POSTANALYZE DI_FUNCTION = 0x0000001D + + DIF_NEWDEVICEWIZARD_FINISHINSTALL DI_FUNCTION = 0x0000001E + + DIF_INSTALLINTERFACES DI_FUNCTION = 0x00000020 + + DIF_DETECTCANCEL DI_FUNCTION = 0x00000021 + + DIF_REGISTER_COINSTALLERS DI_FUNCTION = 0x00000022 + + DIF_ADDPROPERTYPAGE_ADVANCED DI_FUNCTION = 0x00000023 + + DIF_ADDPROPERTYPAGE_BASIC DI_FUNCTION = 0x00000024 + + DIF_TROUBLESHOOTER DI_FUNCTION = 0x00000026 + + DIF_POWERMESSAGEWAKE DI_FUNCTION = 0x00000027 + DIF_ADDREMOTEPROPERTYPAGE_ADVANCED DI_FUNCTION = 0x00000028 - DIF_UPDATEDRIVER_UI DI_FUNCTION = 0x00000029 - DIF_FINISHINSTALL_ACTION DI_FUNCTION = 0x0000002A + + DIF_UPDATEDRIVER_UI DI_FUNCTION = 0x00000029 + + DIF_FINISHINSTALL_ACTION DI_FUNCTION = 0x0000002A ) // DevInstallParams is device installation parameters structure (associated with a particular device information element, or globally with a device information set) + type DevInstallParams struct { - size uint32 - Flags DI_FLAGS - FlagsEx DI_FLAGSEX - hwndParent uintptr - InstallMsgHandler uintptr + size uint32 + + Flags DI_FLAGS + + FlagsEx DI_FLAGSEX + + hwndParent uintptr + + InstallMsgHandler uintptr + InstallMsgHandlerContext uintptr - FileQueue HSPFILEQ - _ uintptr - _ uint32 - driverPath [MAX_PATH]uint16 + + FileQueue HSPFILEQ + + _ uintptr + + _ uint32 + + driverPath [MAX_PATH]uint16 } func (params *DevInstallParams) DriverPath() string { + return UTF16ToString(params.driverPath[:]) + } func (params *DevInstallParams) SetDriverPath(driverPath string) error { + str, err := UTF16FromString(driverPath) + if err != nil { + return err + } + copy(params.driverPath[:], str) + return nil + } // DI_FLAGS is SP_DEVINSTALL_PARAMS.Flags values + type DI_FLAGS uint32 const ( + // Flags for choosing a device - DI_SHOWOEM DI_FLAGS = 0x00000001 // support Other... button - DI_SHOWCOMPAT DI_FLAGS = 0x00000002 // show compatibility list - DI_SHOWCLASS DI_FLAGS = 0x00000004 // show class list - DI_SHOWALL DI_FLAGS = 0x00000007 // both class & compat list shown - DI_NOVCP DI_FLAGS = 0x00000008 // don't create a new copy queue--use caller-supplied FileQueue - DI_DIDCOMPAT DI_FLAGS = 0x00000010 // Searched for compatible devices - DI_DIDCLASS DI_FLAGS = 0x00000020 // Searched for class devices + + DI_SHOWOEM DI_FLAGS = 0x00000001 // support Other... button + + DI_SHOWCOMPAT DI_FLAGS = 0x00000002 // show compatibility list + + DI_SHOWCLASS DI_FLAGS = 0x00000004 // show class list + + DI_SHOWALL DI_FLAGS = 0x00000007 // both class & compat list shown + + DI_NOVCP DI_FLAGS = 0x00000008 // don't create a new copy queue--use caller-supplied FileQueue + + DI_DIDCOMPAT DI_FLAGS = 0x00000010 // Searched for compatible devices + + DI_DIDCLASS DI_FLAGS = 0x00000020 // Searched for class devices + DI_AUTOASSIGNRES DI_FLAGS = 0x00000040 // No UI for resources if possible // Flags returned by DiInstallDevice to indicate need to reboot/restart + DI_NEEDRESTART DI_FLAGS = 0x00000080 // Reboot required to take effect - DI_NEEDREBOOT DI_FLAGS = 0x00000100 // "" + + DI_NEEDREBOOT DI_FLAGS = 0x00000100 // "" // Flags for device installation + DI_NOBROWSE DI_FLAGS = 0x00000200 // no Browse... in InsertDisk // Flags set by DiBuildDriverInfoList + DI_MULTMFGS DI_FLAGS = 0x00000400 // Set if multiple manufacturers in class driver list // Flag indicates that device is disabled + DI_DISABLED DI_FLAGS = 0x00000800 // Set if device disabled // Flags for Device/Class Properties - DI_GENERALPAGE_ADDED DI_FLAGS = 0x00001000 + + DI_GENERALPAGE_ADDED DI_FLAGS = 0x00001000 + DI_RESOURCEPAGE_ADDED DI_FLAGS = 0x00002000 // Flag to indicate the setting properties for this Device (or class) caused a change so the Dev Mgr UI probably needs to be updated. + DI_PROPERTIES_CHANGE DI_FLAGS = 0x00004000 // Flag to indicate that the sorting from the INF file should be used. + DI_INF_IS_SORTED DI_FLAGS = 0x00008000 // Flag to indicate that only the INF specified by SP_DEVINSTALL_PARAMS.DriverPath should be searched. + DI_ENUMSINGLEINF DI_FLAGS = 0x00010000 // Flag that prevents ConfigMgr from removing/re-enumerating devices during device + // registration, installation, and deletion. + DI_DONOTCALLCONFIGMG DI_FLAGS = 0x00020000 // The following flag can be used to install a device disabled + DI_INSTALLDISABLED DI_FLAGS = 0x00040000 // Flag that causes SetupDiBuildDriverInfoList to build a device's compatible driver + // list from its existing class driver list, instead of the normal INF search. + DI_COMPAT_FROM_CLASS DI_FLAGS = 0x00080000 // This flag is set if the Class Install params should be used. + DI_CLASSINSTALLPARAMS DI_FLAGS = 0x00100000 // This flag is set if the caller of DiCallClassInstaller does NOT want the internal default action performed if the Class installer returns ERROR_DI_DO_DEFAULT. + DI_NODI_DEFAULTACTION DI_FLAGS = 0x00200000 // Flags for device installation - DI_QUIETINSTALL DI_FLAGS = 0x00800000 // don't confuse the user with questions or excess info - DI_NOFILECOPY DI_FLAGS = 0x01000000 // No file Copy necessary - DI_FORCECOPY DI_FLAGS = 0x02000000 // Force files to be copied from install path - DI_DRIVERPAGE_ADDED DI_FLAGS = 0x04000000 // Prop provider added Driver page. + + DI_QUIETINSTALL DI_FLAGS = 0x00800000 // don't confuse the user with questions or excess info + + DI_NOFILECOPY DI_FLAGS = 0x01000000 // No file Copy necessary + + DI_FORCECOPY DI_FLAGS = 0x02000000 // Force files to be copied from install path + + DI_DRIVERPAGE_ADDED DI_FLAGS = 0x04000000 // Prop provider added Driver page. + DI_USECI_SELECTSTRINGS DI_FLAGS = 0x08000000 // Use Class Installer Provided strings in the Select Device Dlg - DI_OVERRIDE_INFFLAGS DI_FLAGS = 0x10000000 // Override INF flags + + DI_OVERRIDE_INFFLAGS DI_FLAGS = 0x10000000 // Override INF flags + DI_PROPS_NOCHANGEUSAGE DI_FLAGS = 0x20000000 // No Enable/Disable in General Props DI_NOSELECTICONS DI_FLAGS = 0x40000000 // No small icons in select device dialogs DI_NOWRITE_IDS DI_FLAGS = 0x80000000 // Don't write HW & Compat IDs on install + ) // DI_FLAGSEX is SP_DEVINSTALL_PARAMS.FlagsEx values + type DI_FLAGSEX uint32 const ( - DI_FLAGSEX_CI_FAILED DI_FLAGSEX = 0x00000004 // Failed to Load/Call class installer - DI_FLAGSEX_FINISHINSTALL_ACTION DI_FLAGSEX = 0x00000008 // Class/co-installer wants to get a DIF_FINISH_INSTALL action in client context. - DI_FLAGSEX_DIDINFOLIST DI_FLAGSEX = 0x00000010 // Did the Class Info List - DI_FLAGSEX_DIDCOMPATINFO DI_FLAGSEX = 0x00000020 // Did the Compat Info List - DI_FLAGSEX_FILTERCLASSES DI_FLAGSEX = 0x00000040 - DI_FLAGSEX_SETFAILEDINSTALL DI_FLAGSEX = 0x00000080 - DI_FLAGSEX_DEVICECHANGE DI_FLAGSEX = 0x00000100 - DI_FLAGSEX_ALWAYSWRITEIDS DI_FLAGSEX = 0x00000200 - DI_FLAGSEX_PROPCHANGE_PENDING DI_FLAGSEX = 0x00000400 // One or more device property sheets have had changes made to them, and need to have a DIF_PROPERTYCHANGE occur. - DI_FLAGSEX_ALLOWEXCLUDEDDRVS DI_FLAGSEX = 0x00000800 - DI_FLAGSEX_NOUIONQUERYREMOVE DI_FLAGSEX = 0x00001000 - DI_FLAGSEX_USECLASSFORCOMPAT DI_FLAGSEX = 0x00002000 // Use the device's class when building compat drv list. (Ignored if DI_COMPAT_FROM_CLASS flag is specified.) - DI_FLAGSEX_NO_DRVREG_MODIFY DI_FLAGSEX = 0x00008000 // Don't run AddReg and DelReg for device's software (driver) key. - DI_FLAGSEX_IN_SYSTEM_SETUP DI_FLAGSEX = 0x00010000 // Installation is occurring during initial system setup. - DI_FLAGSEX_INET_DRIVER DI_FLAGSEX = 0x00020000 // Driver came from Windows Update - DI_FLAGSEX_APPENDDRIVERLIST DI_FLAGSEX = 0x00040000 // Cause SetupDiBuildDriverInfoList to append a new driver list to an existing list. - DI_FLAGSEX_PREINSTALLBACKUP DI_FLAGSEX = 0x00080000 // not used - DI_FLAGSEX_BACKUPONREPLACE DI_FLAGSEX = 0x00100000 // not used - DI_FLAGSEX_DRIVERLIST_FROM_URL DI_FLAGSEX = 0x00200000 // build driver list from INF(s) retrieved from URL specified in SP_DEVINSTALL_PARAMS.DriverPath (empty string means Windows Update website) + DI_FLAGSEX_CI_FAILED DI_FLAGSEX = 0x00000004 // Failed to Load/Call class installer + + DI_FLAGSEX_FINISHINSTALL_ACTION DI_FLAGSEX = 0x00000008 // Class/co-installer wants to get a DIF_FINISH_INSTALL action in client context. + + DI_FLAGSEX_DIDINFOLIST DI_FLAGSEX = 0x00000010 // Did the Class Info List + + DI_FLAGSEX_DIDCOMPATINFO DI_FLAGSEX = 0x00000020 // Did the Compat Info List + + DI_FLAGSEX_FILTERCLASSES DI_FLAGSEX = 0x00000040 + + DI_FLAGSEX_SETFAILEDINSTALL DI_FLAGSEX = 0x00000080 + + DI_FLAGSEX_DEVICECHANGE DI_FLAGSEX = 0x00000100 + + DI_FLAGSEX_ALWAYSWRITEIDS DI_FLAGSEX = 0x00000200 + + DI_FLAGSEX_PROPCHANGE_PENDING DI_FLAGSEX = 0x00000400 // One or more device property sheets have had changes made to them, and need to have a DIF_PROPERTYCHANGE occur. + + DI_FLAGSEX_ALLOWEXCLUDEDDRVS DI_FLAGSEX = 0x00000800 + + DI_FLAGSEX_NOUIONQUERYREMOVE DI_FLAGSEX = 0x00001000 + + DI_FLAGSEX_USECLASSFORCOMPAT DI_FLAGSEX = 0x00002000 // Use the device's class when building compat drv list. (Ignored if DI_COMPAT_FROM_CLASS flag is specified.) + + DI_FLAGSEX_NO_DRVREG_MODIFY DI_FLAGSEX = 0x00008000 // Don't run AddReg and DelReg for device's software (driver) key. + + DI_FLAGSEX_IN_SYSTEM_SETUP DI_FLAGSEX = 0x00010000 // Installation is occurring during initial system setup. + + DI_FLAGSEX_INET_DRIVER DI_FLAGSEX = 0x00020000 // Driver came from Windows Update + + DI_FLAGSEX_APPENDDRIVERLIST DI_FLAGSEX = 0x00040000 // Cause SetupDiBuildDriverInfoList to append a new driver list to an existing list. + + DI_FLAGSEX_PREINSTALLBACKUP DI_FLAGSEX = 0x00080000 // not used + + DI_FLAGSEX_BACKUPONREPLACE DI_FLAGSEX = 0x00100000 // not used + + DI_FLAGSEX_DRIVERLIST_FROM_URL DI_FLAGSEX = 0x00200000 // build driver list from INF(s) retrieved from URL specified in SP_DEVINSTALL_PARAMS.DriverPath (empty string means Windows Update website) + DI_FLAGSEX_EXCLUDE_OLD_INET_DRIVERS DI_FLAGSEX = 0x00800000 // Don't include old Internet drivers when building a driver list. Ignored on Windows Vista and later. - DI_FLAGSEX_POWERPAGE_ADDED DI_FLAGSEX = 0x01000000 // class installer added their own power page - DI_FLAGSEX_FILTERSIMILARDRIVERS DI_FLAGSEX = 0x02000000 // only include similar drivers in class list - DI_FLAGSEX_INSTALLEDDRIVER DI_FLAGSEX = 0x04000000 // only add the installed driver to the class or compat driver list. Used in calls to SetupDiBuildDriverInfoList - DI_FLAGSEX_NO_CLASSLIST_NODE_MERGE DI_FLAGSEX = 0x08000000 // Don't remove identical driver nodes from the class list - DI_FLAGSEX_ALTPLATFORM_DRVSEARCH DI_FLAGSEX = 0x10000000 // Build driver list based on alternate platform information specified in associated file queue - DI_FLAGSEX_RESTART_DEVICE_ONLY DI_FLAGSEX = 0x20000000 // only restart the device drivers are being installed on as opposed to restarting all devices using those drivers. - DI_FLAGSEX_RECURSIVESEARCH DI_FLAGSEX = 0x40000000 // Tell SetupDiBuildDriverInfoList to do a recursive search - DI_FLAGSEX_SEARCH_PUBLISHED_INFS DI_FLAGSEX = 0x80000000 // Tell SetupDiBuildDriverInfoList to do a "published INF" search + + DI_FLAGSEX_POWERPAGE_ADDED DI_FLAGSEX = 0x01000000 // class installer added their own power page + + DI_FLAGSEX_FILTERSIMILARDRIVERS DI_FLAGSEX = 0x02000000 // only include similar drivers in class list + + DI_FLAGSEX_INSTALLEDDRIVER DI_FLAGSEX = 0x04000000 // only add the installed driver to the class or compat driver list. Used in calls to SetupDiBuildDriverInfoList + + DI_FLAGSEX_NO_CLASSLIST_NODE_MERGE DI_FLAGSEX = 0x08000000 // Don't remove identical driver nodes from the class list + + DI_FLAGSEX_ALTPLATFORM_DRVSEARCH DI_FLAGSEX = 0x10000000 // Build driver list based on alternate platform information specified in associated file queue + + DI_FLAGSEX_RESTART_DEVICE_ONLY DI_FLAGSEX = 0x20000000 // only restart the device drivers are being installed on as opposed to restarting all devices using those drivers. + + DI_FLAGSEX_RECURSIVESEARCH DI_FLAGSEX = 0x40000000 // Tell SetupDiBuildDriverInfoList to do a recursive search + + DI_FLAGSEX_SEARCH_PUBLISHED_INFS DI_FLAGSEX = 0x80000000 // Tell SetupDiBuildDriverInfoList to do a "published INF" search + ) // ClassInstallHeader is the first member of any class install parameters structure. It contains the device installation request code that defines the format of the rest of the install parameters structure. + type ClassInstallHeader struct { - size uint32 + size uint32 + InstallFunction DI_FUNCTION } func MakeClassInstallHeader(installFunction DI_FUNCTION) *ClassInstallHeader { + hdr := &ClassInstallHeader{InstallFunction: installFunction} + hdr.size = uint32(unsafe.Sizeof(*hdr)) + return hdr + } // DICS_STATE specifies values indicating a change in a device's state + type DICS_STATE uint32 const ( - DICS_ENABLE DICS_STATE = 0x00000001 // The device is being enabled. - DICS_DISABLE DICS_STATE = 0x00000002 // The device is being disabled. + DICS_ENABLE DICS_STATE = 0x00000001 // The device is being enabled. + + DICS_DISABLE DICS_STATE = 0x00000002 // The device is being disabled. + DICS_PROPCHANGE DICS_STATE = 0x00000003 // The properties of the device have changed. - DICS_START DICS_STATE = 0x00000004 // The device is being started (if the request is for the currently active hardware profile). - DICS_STOP DICS_STATE = 0x00000005 // The device is being stopped. The driver stack will be unloaded and the CSCONFIGFLAG_DO_NOT_START flag will be set for the device. + + DICS_START DICS_STATE = 0x00000004 // The device is being started (if the request is for the currently active hardware profile). + + DICS_STOP DICS_STATE = 0x00000005 // The device is being stopped. The driver stack will be unloaded and the CSCONFIGFLAG_DO_NOT_START flag will be set for the device. + ) // DICS_FLAG specifies the scope of a device property change + type DICS_FLAG uint32 const ( - DICS_FLAG_GLOBAL DICS_FLAG = 0x00000001 // make change in all hardware profiles + DICS_FLAG_GLOBAL DICS_FLAG = 0x00000001 // make change in all hardware profiles + DICS_FLAG_CONFIGSPECIFIC DICS_FLAG = 0x00000002 // make change in specified profile only - DICS_FLAG_CONFIGGENERAL DICS_FLAG = 0x00000004 // 1 or more hardware profile-specific changes to follow (obsolete) + + DICS_FLAG_CONFIGGENERAL DICS_FLAG = 0x00000004 // 1 or more hardware profile-specific changes to follow (obsolete) + ) // PropChangeParams is a structure corresponding to a DIF_PROPERTYCHANGE install function. + type PropChangeParams struct { ClassInstallHeader ClassInstallHeader - StateChange DICS_STATE - Scope DICS_FLAG - HwProfile uint32 + + StateChange DICS_STATE + + Scope DICS_FLAG + + HwProfile uint32 } // DI_REMOVEDEVICE specifies the scope of the device removal + type DI_REMOVEDEVICE uint32 const ( - DI_REMOVEDEVICE_GLOBAL DI_REMOVEDEVICE = 0x00000001 // Make this change in all hardware profiles. Remove information about the device from the registry. + DI_REMOVEDEVICE_GLOBAL DI_REMOVEDEVICE = 0x00000001 // Make this change in all hardware profiles. Remove information about the device from the registry. + DI_REMOVEDEVICE_CONFIGSPECIFIC DI_REMOVEDEVICE = 0x00000002 // Make this change to only the hardware profile specified by HwProfile. this flag only applies to root-enumerated devices. When Windows removes the device from the last hardware profile in which it was configured, Windows performs a global removal. + ) // RemoveDeviceParams is a structure corresponding to a DIF_REMOVE install function. + type RemoveDeviceParams struct { ClassInstallHeader ClassInstallHeader - Scope DI_REMOVEDEVICE - HwProfile uint32 + + Scope DI_REMOVEDEVICE + + HwProfile uint32 } // DrvInfoData is driver information structure (member of a driver info list that may be associated with a particular device instance, or (globally) with a device information set) + type DrvInfoData struct { - size uint32 - DriverType uint32 - _ uintptr - description [LINE_LEN]uint16 - mfgName [LINE_LEN]uint16 - providerName [LINE_LEN]uint16 - DriverDate Filetime + size uint32 + + DriverType uint32 + + _ uintptr + + description [LINE_LEN]uint16 + + mfgName [LINE_LEN]uint16 + + providerName [LINE_LEN]uint16 + + DriverDate Filetime + DriverVersion uint64 } func (data *DrvInfoData) Description() string { + return UTF16ToString(data.description[:]) + } func (data *DrvInfoData) SetDescription(description string) error { + str, err := UTF16FromString(description) + if err != nil { + return err + } + copy(data.description[:], str) + return nil + } func (data *DrvInfoData) MfgName() string { + return UTF16ToString(data.mfgName[:]) + } func (data *DrvInfoData) SetMfgName(mfgName string) error { + str, err := UTF16FromString(mfgName) + if err != nil { + return err + } + copy(data.mfgName[:], str) + return nil + } func (data *DrvInfoData) ProviderName() string { + return UTF16ToString(data.providerName[:]) + } func (data *DrvInfoData) SetProviderName(providerName string) error { + str, err := UTF16FromString(providerName) + if err != nil { + return err + } + copy(data.providerName[:], str) + return nil + } // IsNewer method returns true if DrvInfoData date and version is newer than supplied parameters. + func (data *DrvInfoData) IsNewer(driverDate Filetime, driverVersion uint64) bool { + if data.DriverDate.HighDateTime > driverDate.HighDateTime { + return true + } + if data.DriverDate.HighDateTime < driverDate.HighDateTime { + return false + } if data.DriverDate.LowDateTime > driverDate.LowDateTime { + return true + } + if data.DriverDate.LowDateTime < driverDate.LowDateTime { + return false + } if data.DriverVersion > driverVersion { + return true + } + if data.DriverVersion < driverVersion { + return false + } return false + } // DrvInfoDetailData is driver information details structure (provides detailed information about a particular driver information structure) + type DrvInfoDetailData struct { - size uint32 // Use unsafeSizeOf method - InfDate Filetime + size uint32 // Use unsafeSizeOf method + + InfDate Filetime + compatIDsOffset uint32 + compatIDsLength uint32 - _ uintptr - sectionName [LINE_LEN]uint16 - infFileName [MAX_PATH]uint16 - drvDescription [LINE_LEN]uint16 - hardwareID [1]uint16 + + _ uintptr + + sectionName [LINE_LEN]uint16 + + infFileName [MAX_PATH]uint16 + + drvDescription [LINE_LEN]uint16 + + hardwareID [1]uint16 } func (*DrvInfoDetailData) unsafeSizeOf() uint32 { + if unsafe.Sizeof(uintptr(0)) == 4 { + // Windows declares this with pshpack1.h + return uint32(unsafe.Offsetof(DrvInfoDetailData{}.hardwareID) + unsafe.Sizeof(DrvInfoDetailData{}.hardwareID)) + } + return uint32(unsafe.Sizeof(DrvInfoDetailData{})) + } func (data *DrvInfoDetailData) SectionName() string { + return UTF16ToString(data.sectionName[:]) + } func (data *DrvInfoDetailData) InfFileName() string { + return UTF16ToString(data.infFileName[:]) + } func (data *DrvInfoDetailData) DrvDescription() string { + return UTF16ToString(data.drvDescription[:]) + } func (data *DrvInfoDetailData) HardwareID() string { + if data.compatIDsOffset > 1 { + bufW := data.getBuf() + return UTF16ToString(bufW[:wcslen(bufW)]) + } return "" + } func (data *DrvInfoDetailData) CompatIDs() []string { + a := make([]string, 0) if data.compatIDsLength > 0 { + bufW := data.getBuf() + bufW = bufW[data.compatIDsOffset : data.compatIDsOffset+data.compatIDsLength] + for i := 0; i < len(bufW); { + j := i + wcslen(bufW[i:]) + if i < j { + a = append(a, UTF16ToString(bufW[i:j])) + } + i = j + 1 + } + } return a + } func (data *DrvInfoDetailData) getBuf() []uint16 { + len := (data.size - uint32(unsafe.Offsetof(data.hardwareID))) / 2 + sl := struct { addr *uint16 - len int - cap int + + len int + + cap int }{&data.hardwareID[0], int(len), int(len)} + return *(*[]uint16)(unsafe.Pointer(&sl)) + } // IsCompatible method tests if given hardware ID matches the driver or is listed on the compatible ID list. + func (data *DrvInfoDetailData) IsCompatible(hwid string) bool { + hwidLC := strings.ToLower(hwid) + if strings.ToLower(data.HardwareID()) == hwidLC { + return true + } + a := data.CompatIDs() + for i := range a { + if strings.ToLower(a[i]) == hwidLC { + return true + } + } return false + } // DICD flags control SetupDiCreateDeviceInfo + type DICD uint32 const ( - DICD_GENERATE_ID DICD = 0x00000001 + DICD_GENERATE_ID DICD = 0x00000001 + DICD_INHERIT_CLASSDRVS DICD = 0x00000002 ) // SUOI flags control SetupUninstallOEMInf + type SUOI uint32 const ( @@ -598,828 +996,1404 @@ const ( ) // SPDIT flags to distinguish between class drivers and + // device drivers. (Passed in 'DriverType' parameter of + // driver information list APIs) + type SPDIT uint32 const ( - SPDIT_NODRIVER SPDIT = 0x00000000 - SPDIT_CLASSDRIVER SPDIT = 0x00000001 + SPDIT_NODRIVER SPDIT = 0x00000000 + + SPDIT_CLASSDRIVER SPDIT = 0x00000001 + SPDIT_COMPATDRIVER SPDIT = 0x00000002 ) // DIGCF flags control what is included in the device information set built by SetupDiGetClassDevs + type DIGCF uint32 const ( - DIGCF_DEFAULT DIGCF = 0x00000001 // only valid with DIGCF_DEVICEINTERFACE - DIGCF_PRESENT DIGCF = 0x00000002 - DIGCF_ALLCLASSES DIGCF = 0x00000004 - DIGCF_PROFILE DIGCF = 0x00000008 + DIGCF_DEFAULT DIGCF = 0x00000001 // only valid with DIGCF_DEVICEINTERFACE + + DIGCF_PRESENT DIGCF = 0x00000002 + + DIGCF_ALLCLASSES DIGCF = 0x00000004 + + DIGCF_PROFILE DIGCF = 0x00000008 + DIGCF_DEVICEINTERFACE DIGCF = 0x00000010 ) // DIREG specifies values for SetupDiCreateDevRegKey, SetupDiOpenDevRegKey, and SetupDiDeleteDevRegKey. + type DIREG uint32 const ( - DIREG_DEV DIREG = 0x00000001 // Open/Create/Delete device key - DIREG_DRV DIREG = 0x00000002 // Open/Create/Delete driver key + DIREG_DEV DIREG = 0x00000001 // Open/Create/Delete device key + + DIREG_DRV DIREG = 0x00000002 // Open/Create/Delete driver key + DIREG_BOTH DIREG = 0x00000004 // Delete both driver and Device key + ) // SPDRP specifies device registry property codes + // (Codes marked as read-only (R) may only be used for + // SetupDiGetDeviceRegistryProperty) + // + // These values should cover the same set of registry properties + // as defined by the CM_DRP codes in cfgmgr32.h. + // + // Note that SPDRP codes are zero based while CM_DRP codes are one based! + type SPDRP uint32 const ( - SPDRP_DEVICEDESC SPDRP = 0x00000000 // DeviceDesc (R/W) - SPDRP_HARDWAREID SPDRP = 0x00000001 // HardwareID (R/W) - SPDRP_COMPATIBLEIDS SPDRP = 0x00000002 // CompatibleIDs (R/W) - SPDRP_SERVICE SPDRP = 0x00000004 // Service (R/W) - SPDRP_CLASS SPDRP = 0x00000007 // Class (R--tied to ClassGUID) - SPDRP_CLASSGUID SPDRP = 0x00000008 // ClassGUID (R/W) - SPDRP_DRIVER SPDRP = 0x00000009 // Driver (R/W) - SPDRP_CONFIGFLAGS SPDRP = 0x0000000A // ConfigFlags (R/W) - SPDRP_MFG SPDRP = 0x0000000B // Mfg (R/W) - SPDRP_FRIENDLYNAME SPDRP = 0x0000000C // FriendlyName (R/W) - SPDRP_LOCATION_INFORMATION SPDRP = 0x0000000D // LocationInformation (R/W) + SPDRP_DEVICEDESC SPDRP = 0x00000000 // DeviceDesc (R/W) + + SPDRP_HARDWAREID SPDRP = 0x00000001 // HardwareID (R/W) + + SPDRP_COMPATIBLEIDS SPDRP = 0x00000002 // CompatibleIDs (R/W) + + SPDRP_SERVICE SPDRP = 0x00000004 // Service (R/W) + + SPDRP_CLASS SPDRP = 0x00000007 // Class (R--tied to ClassGUID) + + SPDRP_CLASSGUID SPDRP = 0x00000008 // ClassGUID (R/W) + + SPDRP_DRIVER SPDRP = 0x00000009 // Driver (R/W) + + SPDRP_CONFIGFLAGS SPDRP = 0x0000000A // ConfigFlags (R/W) + + SPDRP_MFG SPDRP = 0x0000000B // Mfg (R/W) + + SPDRP_FRIENDLYNAME SPDRP = 0x0000000C // FriendlyName (R/W) + + SPDRP_LOCATION_INFORMATION SPDRP = 0x0000000D // LocationInformation (R/W) + SPDRP_PHYSICAL_DEVICE_OBJECT_NAME SPDRP = 0x0000000E // PhysicalDeviceObjectName (R) - SPDRP_CAPABILITIES SPDRP = 0x0000000F // Capabilities (R) - SPDRP_UI_NUMBER SPDRP = 0x00000010 // UiNumber (R) - SPDRP_UPPERFILTERS SPDRP = 0x00000011 // UpperFilters (R/W) - SPDRP_LOWERFILTERS SPDRP = 0x00000012 // LowerFilters (R/W) - SPDRP_BUSTYPEGUID SPDRP = 0x00000013 // BusTypeGUID (R) - SPDRP_LEGACYBUSTYPE SPDRP = 0x00000014 // LegacyBusType (R) - SPDRP_BUSNUMBER SPDRP = 0x00000015 // BusNumber (R) - SPDRP_ENUMERATOR_NAME SPDRP = 0x00000016 // Enumerator Name (R) - SPDRP_SECURITY SPDRP = 0x00000017 // Security (R/W, binary form) - SPDRP_SECURITY_SDS SPDRP = 0x00000018 // Security (W, SDS form) - SPDRP_DEVTYPE SPDRP = 0x00000019 // Device Type (R/W) - SPDRP_EXCLUSIVE SPDRP = 0x0000001A // Device is exclusive-access (R/W) - SPDRP_CHARACTERISTICS SPDRP = 0x0000001B // Device Characteristics (R/W) - SPDRP_ADDRESS SPDRP = 0x0000001C // Device Address (R) - SPDRP_UI_NUMBER_DESC_FORMAT SPDRP = 0x0000001D // UiNumberDescFormat (R/W) - SPDRP_DEVICE_POWER_DATA SPDRP = 0x0000001E // Device Power Data (R) - SPDRP_REMOVAL_POLICY SPDRP = 0x0000001F // Removal Policy (R) - SPDRP_REMOVAL_POLICY_HW_DEFAULT SPDRP = 0x00000020 // Hardware Removal Policy (R) - SPDRP_REMOVAL_POLICY_OVERRIDE SPDRP = 0x00000021 // Removal Policy Override (RW) - SPDRP_INSTALL_STATE SPDRP = 0x00000022 // Device Install State (R) - SPDRP_LOCATION_PATHS SPDRP = 0x00000023 // Device Location Paths (R) - SPDRP_BASE_CONTAINERID SPDRP = 0x00000024 // Base ContainerID (R) + + SPDRP_CAPABILITIES SPDRP = 0x0000000F // Capabilities (R) + + SPDRP_UI_NUMBER SPDRP = 0x00000010 // UiNumber (R) + + SPDRP_UPPERFILTERS SPDRP = 0x00000011 // UpperFilters (R/W) + + SPDRP_LOWERFILTERS SPDRP = 0x00000012 // LowerFilters (R/W) + + SPDRP_BUSTYPEGUID SPDRP = 0x00000013 // BusTypeGUID (R) + + SPDRP_LEGACYBUSTYPE SPDRP = 0x00000014 // LegacyBusType (R) + + SPDRP_BUSNUMBER SPDRP = 0x00000015 // BusNumber (R) + + SPDRP_ENUMERATOR_NAME SPDRP = 0x00000016 // Enumerator Name (R) + + SPDRP_SECURITY SPDRP = 0x00000017 // Security (R/W, binary form) + + SPDRP_SECURITY_SDS SPDRP = 0x00000018 // Security (W, SDS form) + + SPDRP_DEVTYPE SPDRP = 0x00000019 // Device Type (R/W) + + SPDRP_EXCLUSIVE SPDRP = 0x0000001A // Device is exclusive-access (R/W) + + SPDRP_CHARACTERISTICS SPDRP = 0x0000001B // Device Characteristics (R/W) + + SPDRP_ADDRESS SPDRP = 0x0000001C // Device Address (R) + + SPDRP_UI_NUMBER_DESC_FORMAT SPDRP = 0x0000001D // UiNumberDescFormat (R/W) + + SPDRP_DEVICE_POWER_DATA SPDRP = 0x0000001E // Device Power Data (R) + + SPDRP_REMOVAL_POLICY SPDRP = 0x0000001F // Removal Policy (R) + + SPDRP_REMOVAL_POLICY_HW_DEFAULT SPDRP = 0x00000020 // Hardware Removal Policy (R) + + SPDRP_REMOVAL_POLICY_OVERRIDE SPDRP = 0x00000021 // Removal Policy Override (RW) + + SPDRP_INSTALL_STATE SPDRP = 0x00000022 // Device Install State (R) + + SPDRP_LOCATION_PATHS SPDRP = 0x00000023 // Device Location Paths (R) + + SPDRP_BASE_CONTAINERID SPDRP = 0x00000024 // Base ContainerID (R) SPDRP_MAXIMUM_PROPERTY SPDRP = 0x00000025 // Upper bound on ordinals + ) // DEVPROPTYPE represents the property-data-type identifier that specifies the + // data type of a device property value in the unified device property model. + type DEVPROPTYPE uint32 const ( DEVPROP_TYPEMOD_ARRAY DEVPROPTYPE = 0x00001000 - DEVPROP_TYPEMOD_LIST DEVPROPTYPE = 0x00002000 - DEVPROP_TYPE_EMPTY DEVPROPTYPE = 0x00000000 - DEVPROP_TYPE_NULL DEVPROPTYPE = 0x00000001 - DEVPROP_TYPE_SBYTE DEVPROPTYPE = 0x00000002 - DEVPROP_TYPE_BYTE DEVPROPTYPE = 0x00000003 - DEVPROP_TYPE_INT16 DEVPROPTYPE = 0x00000004 - DEVPROP_TYPE_UINT16 DEVPROPTYPE = 0x00000005 - DEVPROP_TYPE_INT32 DEVPROPTYPE = 0x00000006 - DEVPROP_TYPE_UINT32 DEVPROPTYPE = 0x00000007 - DEVPROP_TYPE_INT64 DEVPROPTYPE = 0x00000008 - DEVPROP_TYPE_UINT64 DEVPROPTYPE = 0x00000009 - DEVPROP_TYPE_FLOAT DEVPROPTYPE = 0x0000000A - DEVPROP_TYPE_DOUBLE DEVPROPTYPE = 0x0000000B - DEVPROP_TYPE_DECIMAL DEVPROPTYPE = 0x0000000C - DEVPROP_TYPE_GUID DEVPROPTYPE = 0x0000000D - DEVPROP_TYPE_CURRENCY DEVPROPTYPE = 0x0000000E - DEVPROP_TYPE_DATE DEVPROPTYPE = 0x0000000F - DEVPROP_TYPE_FILETIME DEVPROPTYPE = 0x00000010 - DEVPROP_TYPE_BOOLEAN DEVPROPTYPE = 0x00000011 - DEVPROP_TYPE_STRING DEVPROPTYPE = 0x00000012 - DEVPROP_TYPE_STRING_LIST DEVPROPTYPE = DEVPROP_TYPE_STRING | DEVPROP_TYPEMOD_LIST - DEVPROP_TYPE_SECURITY_DESCRIPTOR DEVPROPTYPE = 0x00000013 + DEVPROP_TYPEMOD_LIST DEVPROPTYPE = 0x00002000 + + DEVPROP_TYPE_EMPTY DEVPROPTYPE = 0x00000000 + + DEVPROP_TYPE_NULL DEVPROPTYPE = 0x00000001 + + DEVPROP_TYPE_SBYTE DEVPROPTYPE = 0x00000002 + + DEVPROP_TYPE_BYTE DEVPROPTYPE = 0x00000003 + + DEVPROP_TYPE_INT16 DEVPROPTYPE = 0x00000004 + + DEVPROP_TYPE_UINT16 DEVPROPTYPE = 0x00000005 + + DEVPROP_TYPE_INT32 DEVPROPTYPE = 0x00000006 + + DEVPROP_TYPE_UINT32 DEVPROPTYPE = 0x00000007 + + DEVPROP_TYPE_INT64 DEVPROPTYPE = 0x00000008 + + DEVPROP_TYPE_UINT64 DEVPROPTYPE = 0x00000009 + + DEVPROP_TYPE_FLOAT DEVPROPTYPE = 0x0000000A + + DEVPROP_TYPE_DOUBLE DEVPROPTYPE = 0x0000000B + + DEVPROP_TYPE_DECIMAL DEVPROPTYPE = 0x0000000C + + DEVPROP_TYPE_GUID DEVPROPTYPE = 0x0000000D + + DEVPROP_TYPE_CURRENCY DEVPROPTYPE = 0x0000000E + + DEVPROP_TYPE_DATE DEVPROPTYPE = 0x0000000F + + DEVPROP_TYPE_FILETIME DEVPROPTYPE = 0x00000010 + + DEVPROP_TYPE_BOOLEAN DEVPROPTYPE = 0x00000011 + + DEVPROP_TYPE_STRING DEVPROPTYPE = 0x00000012 + + DEVPROP_TYPE_STRING_LIST DEVPROPTYPE = DEVPROP_TYPE_STRING | DEVPROP_TYPEMOD_LIST + + DEVPROP_TYPE_SECURITY_DESCRIPTOR DEVPROPTYPE = 0x00000013 + DEVPROP_TYPE_SECURITY_DESCRIPTOR_STRING DEVPROPTYPE = 0x00000014 - DEVPROP_TYPE_DEVPROPKEY DEVPROPTYPE = 0x00000015 - DEVPROP_TYPE_DEVPROPTYPE DEVPROPTYPE = 0x00000016 - DEVPROP_TYPE_BINARY DEVPROPTYPE = DEVPROP_TYPE_BYTE | DEVPROP_TYPEMOD_ARRAY - DEVPROP_TYPE_ERROR DEVPROPTYPE = 0x00000017 - DEVPROP_TYPE_NTSTATUS DEVPROPTYPE = 0x00000018 - DEVPROP_TYPE_STRING_INDIRECT DEVPROPTYPE = 0x00000019 - MAX_DEVPROP_TYPE DEVPROPTYPE = 0x00000019 + DEVPROP_TYPE_DEVPROPKEY DEVPROPTYPE = 0x00000015 + + DEVPROP_TYPE_DEVPROPTYPE DEVPROPTYPE = 0x00000016 + + DEVPROP_TYPE_BINARY DEVPROPTYPE = DEVPROP_TYPE_BYTE | DEVPROP_TYPEMOD_ARRAY + + DEVPROP_TYPE_ERROR DEVPROPTYPE = 0x00000017 + + DEVPROP_TYPE_NTSTATUS DEVPROPTYPE = 0x00000018 + + DEVPROP_TYPE_STRING_INDIRECT DEVPROPTYPE = 0x00000019 + + MAX_DEVPROP_TYPE DEVPROPTYPE = 0x00000019 + MAX_DEVPROP_TYPEMOD DEVPROPTYPE = 0x00002000 - DEVPROP_MASK_TYPE DEVPROPTYPE = 0x00000FFF + DEVPROP_MASK_TYPE DEVPROPTYPE = 0x00000FFF + DEVPROP_MASK_TYPEMOD DEVPROPTYPE = 0x0000F000 ) // DEVPROPGUID specifies a property category. + type DEVPROPGUID GUID // DEVPROPID uniquely identifies the property within the property category. + type DEVPROPID uint32 const DEVPROPID_FIRST_USABLE DEVPROPID = 2 // DEVPROPKEY represents a device property key for a device property in the + // unified device property model. + type DEVPROPKEY struct { FmtID DEVPROPGUID - PID DEVPROPID + + PID DEVPROPID } // CONFIGRET is a return value or error code from cfgmgr32 APIs + type CONFIGRET uint32 func (ret CONFIGRET) Error() string { + if win32Error, ok := ret.Unwrap().(Errno); ok { + return fmt.Sprintf("%s (CfgMgr error: 0x%08x)", win32Error.Error(), uint32(ret)) + } + return fmt.Sprintf("CfgMgr error: 0x%08x", uint32(ret)) + } func (ret CONFIGRET) Win32Error(defaultError Errno) Errno { + return cm_MapCrToWin32Err(ret, defaultError) + } func (ret CONFIGRET) Unwrap() error { + const noMatch = Errno(^uintptr(0)) + win32Error := ret.Win32Error(noMatch) + if win32Error == noMatch { + return nil + } + return win32Error + } const ( - CR_SUCCESS CONFIGRET = 0x00000000 - CR_DEFAULT CONFIGRET = 0x00000001 - CR_OUT_OF_MEMORY CONFIGRET = 0x00000002 - CR_INVALID_POINTER CONFIGRET = 0x00000003 - CR_INVALID_FLAG CONFIGRET = 0x00000004 - CR_INVALID_DEVNODE CONFIGRET = 0x00000005 - CR_INVALID_DEVINST = CR_INVALID_DEVNODE - CR_INVALID_RES_DES CONFIGRET = 0x00000006 - CR_INVALID_LOG_CONF CONFIGRET = 0x00000007 - CR_INVALID_ARBITRATOR CONFIGRET = 0x00000008 - CR_INVALID_NODELIST CONFIGRET = 0x00000009 - CR_DEVNODE_HAS_REQS CONFIGRET = 0x0000000A - CR_DEVINST_HAS_REQS = CR_DEVNODE_HAS_REQS - CR_INVALID_RESOURCEID CONFIGRET = 0x0000000B - CR_DLVXD_NOT_FOUND CONFIGRET = 0x0000000C - CR_NO_SUCH_DEVNODE CONFIGRET = 0x0000000D - CR_NO_SUCH_DEVINST = CR_NO_SUCH_DEVNODE - CR_NO_MORE_LOG_CONF CONFIGRET = 0x0000000E - CR_NO_MORE_RES_DES CONFIGRET = 0x0000000F - CR_ALREADY_SUCH_DEVNODE CONFIGRET = 0x00000010 - CR_ALREADY_SUCH_DEVINST = CR_ALREADY_SUCH_DEVNODE - CR_INVALID_RANGE_LIST CONFIGRET = 0x00000011 - CR_INVALID_RANGE CONFIGRET = 0x00000012 - CR_FAILURE CONFIGRET = 0x00000013 - CR_NO_SUCH_LOGICAL_DEV CONFIGRET = 0x00000014 - CR_CREATE_BLOCKED CONFIGRET = 0x00000015 - CR_NOT_SYSTEM_VM CONFIGRET = 0x00000016 - CR_REMOVE_VETOED CONFIGRET = 0x00000017 - CR_APM_VETOED CONFIGRET = 0x00000018 - CR_INVALID_LOAD_TYPE CONFIGRET = 0x00000019 - CR_BUFFER_SMALL CONFIGRET = 0x0000001A - CR_NO_ARBITRATOR CONFIGRET = 0x0000001B - CR_NO_REGISTRY_HANDLE CONFIGRET = 0x0000001C - CR_REGISTRY_ERROR CONFIGRET = 0x0000001D - CR_INVALID_DEVICE_ID CONFIGRET = 0x0000001E - CR_INVALID_DATA CONFIGRET = 0x0000001F - CR_INVALID_API CONFIGRET = 0x00000020 - CR_DEVLOADER_NOT_READY CONFIGRET = 0x00000021 - CR_NEED_RESTART CONFIGRET = 0x00000022 - CR_NO_MORE_HW_PROFILES CONFIGRET = 0x00000023 - CR_DEVICE_NOT_THERE CONFIGRET = 0x00000024 - CR_NO_SUCH_VALUE CONFIGRET = 0x00000025 - CR_WRONG_TYPE CONFIGRET = 0x00000026 - CR_INVALID_PRIORITY CONFIGRET = 0x00000027 - CR_NOT_DISABLEABLE CONFIGRET = 0x00000028 - CR_FREE_RESOURCES CONFIGRET = 0x00000029 - CR_QUERY_VETOED CONFIGRET = 0x0000002A - CR_CANT_SHARE_IRQ CONFIGRET = 0x0000002B - CR_NO_DEPENDENT CONFIGRET = 0x0000002C - CR_SAME_RESOURCES CONFIGRET = 0x0000002D - CR_NO_SUCH_REGISTRY_KEY CONFIGRET = 0x0000002E - CR_INVALID_MACHINENAME CONFIGRET = 0x0000002F - CR_REMOTE_COMM_FAILURE CONFIGRET = 0x00000030 - CR_MACHINE_UNAVAILABLE CONFIGRET = 0x00000031 - CR_NO_CM_SERVICES CONFIGRET = 0x00000032 - CR_ACCESS_DENIED CONFIGRET = 0x00000033 - CR_CALL_NOT_IMPLEMENTED CONFIGRET = 0x00000034 - CR_INVALID_PROPERTY CONFIGRET = 0x00000035 - CR_DEVICE_INTERFACE_ACTIVE CONFIGRET = 0x00000036 + CR_SUCCESS CONFIGRET = 0x00000000 + + CR_DEFAULT CONFIGRET = 0x00000001 + + CR_OUT_OF_MEMORY CONFIGRET = 0x00000002 + + CR_INVALID_POINTER CONFIGRET = 0x00000003 + + CR_INVALID_FLAG CONFIGRET = 0x00000004 + + CR_INVALID_DEVNODE CONFIGRET = 0x00000005 + + CR_INVALID_DEVINST = CR_INVALID_DEVNODE + + CR_INVALID_RES_DES CONFIGRET = 0x00000006 + + CR_INVALID_LOG_CONF CONFIGRET = 0x00000007 + + CR_INVALID_ARBITRATOR CONFIGRET = 0x00000008 + + CR_INVALID_NODELIST CONFIGRET = 0x00000009 + + CR_DEVNODE_HAS_REQS CONFIGRET = 0x0000000A + + CR_DEVINST_HAS_REQS = CR_DEVNODE_HAS_REQS + + CR_INVALID_RESOURCEID CONFIGRET = 0x0000000B + + CR_DLVXD_NOT_FOUND CONFIGRET = 0x0000000C + + CR_NO_SUCH_DEVNODE CONFIGRET = 0x0000000D + + CR_NO_SUCH_DEVINST = CR_NO_SUCH_DEVNODE + + CR_NO_MORE_LOG_CONF CONFIGRET = 0x0000000E + + CR_NO_MORE_RES_DES CONFIGRET = 0x0000000F + + CR_ALREADY_SUCH_DEVNODE CONFIGRET = 0x00000010 + + CR_ALREADY_SUCH_DEVINST = CR_ALREADY_SUCH_DEVNODE + + CR_INVALID_RANGE_LIST CONFIGRET = 0x00000011 + + CR_INVALID_RANGE CONFIGRET = 0x00000012 + + CR_FAILURE CONFIGRET = 0x00000013 + + CR_NO_SUCH_LOGICAL_DEV CONFIGRET = 0x00000014 + + CR_CREATE_BLOCKED CONFIGRET = 0x00000015 + + CR_NOT_SYSTEM_VM CONFIGRET = 0x00000016 + + CR_REMOVE_VETOED CONFIGRET = 0x00000017 + + CR_APM_VETOED CONFIGRET = 0x00000018 + + CR_INVALID_LOAD_TYPE CONFIGRET = 0x00000019 + + CR_BUFFER_SMALL CONFIGRET = 0x0000001A + + CR_NO_ARBITRATOR CONFIGRET = 0x0000001B + + CR_NO_REGISTRY_HANDLE CONFIGRET = 0x0000001C + + CR_REGISTRY_ERROR CONFIGRET = 0x0000001D + + CR_INVALID_DEVICE_ID CONFIGRET = 0x0000001E + + CR_INVALID_DATA CONFIGRET = 0x0000001F + + CR_INVALID_API CONFIGRET = 0x00000020 + + CR_DEVLOADER_NOT_READY CONFIGRET = 0x00000021 + + CR_NEED_RESTART CONFIGRET = 0x00000022 + + CR_NO_MORE_HW_PROFILES CONFIGRET = 0x00000023 + + CR_DEVICE_NOT_THERE CONFIGRET = 0x00000024 + + CR_NO_SUCH_VALUE CONFIGRET = 0x00000025 + + CR_WRONG_TYPE CONFIGRET = 0x00000026 + + CR_INVALID_PRIORITY CONFIGRET = 0x00000027 + + CR_NOT_DISABLEABLE CONFIGRET = 0x00000028 + + CR_FREE_RESOURCES CONFIGRET = 0x00000029 + + CR_QUERY_VETOED CONFIGRET = 0x0000002A + + CR_CANT_SHARE_IRQ CONFIGRET = 0x0000002B + + CR_NO_DEPENDENT CONFIGRET = 0x0000002C + + CR_SAME_RESOURCES CONFIGRET = 0x0000002D + + CR_NO_SUCH_REGISTRY_KEY CONFIGRET = 0x0000002E + + CR_INVALID_MACHINENAME CONFIGRET = 0x0000002F + + CR_REMOTE_COMM_FAILURE CONFIGRET = 0x00000030 + + CR_MACHINE_UNAVAILABLE CONFIGRET = 0x00000031 + + CR_NO_CM_SERVICES CONFIGRET = 0x00000032 + + CR_ACCESS_DENIED CONFIGRET = 0x00000033 + + CR_CALL_NOT_IMPLEMENTED CONFIGRET = 0x00000034 + + CR_INVALID_PROPERTY CONFIGRET = 0x00000035 + + CR_DEVICE_INTERFACE_ACTIVE CONFIGRET = 0x00000036 + CR_NO_SUCH_DEVICE_INTERFACE CONFIGRET = 0x00000037 + CR_INVALID_REFERENCE_STRING CONFIGRET = 0x00000038 - CR_INVALID_CONFLICT_LIST CONFIGRET = 0x00000039 - CR_INVALID_INDEX CONFIGRET = 0x0000003A - CR_INVALID_STRUCTURE_SIZE CONFIGRET = 0x0000003B - NUM_CR_RESULTS CONFIGRET = 0x0000003C + + CR_INVALID_CONFLICT_LIST CONFIGRET = 0x00000039 + + CR_INVALID_INDEX CONFIGRET = 0x0000003A + + CR_INVALID_STRUCTURE_SIZE CONFIGRET = 0x0000003B + + NUM_CR_RESULTS CONFIGRET = 0x0000003C ) const ( - CM_GET_DEVICE_INTERFACE_LIST_PRESENT = 0 // only currently 'live' device interfaces + CM_GET_DEVICE_INTERFACE_LIST_PRESENT = 0 // only currently 'live' device interfaces + CM_GET_DEVICE_INTERFACE_LIST_ALL_DEVICES = 1 // all registered device interfaces, live or not + ) const ( - DN_ROOT_ENUMERATED = 0x00000001 // Was enumerated by ROOT - DN_DRIVER_LOADED = 0x00000002 // Has Register_Device_Driver - DN_ENUM_LOADED = 0x00000004 // Has Register_Enumerator - DN_STARTED = 0x00000008 // Is currently configured - DN_MANUAL = 0x00000010 // Manually installed - DN_NEED_TO_ENUM = 0x00000020 // May need reenumeration - DN_NOT_FIRST_TIME = 0x00000040 // Has received a config - DN_HARDWARE_ENUM = 0x00000080 // Enum generates hardware ID - DN_LIAR = 0x00000100 // Lied about can reconfig once - DN_HAS_MARK = 0x00000200 // Not CM_Create_DevInst lately - DN_HAS_PROBLEM = 0x00000400 // Need device installer - DN_FILTERED = 0x00000800 // Is filtered - DN_MOVED = 0x00001000 // Has been moved - DN_DISABLEABLE = 0x00002000 // Can be disabled - DN_REMOVABLE = 0x00004000 // Can be removed - DN_PRIVATE_PROBLEM = 0x00008000 // Has a private problem - DN_MF_PARENT = 0x00010000 // Multi function parent - DN_MF_CHILD = 0x00020000 // Multi function child - DN_WILL_BE_REMOVED = 0x00040000 // DevInst is being removed - DN_NOT_FIRST_TIMEE = 0x00080000 // Has received a config enumerate - DN_STOP_FREE_RES = 0x00100000 // When child is stopped, free resources - DN_REBAL_CANDIDATE = 0x00200000 // Don't skip during rebalance - DN_BAD_PARTIAL = 0x00400000 // This devnode's log_confs do not have same resources - DN_NT_ENUMERATOR = 0x00800000 // This devnode's is an NT enumerator - DN_NT_DRIVER = 0x01000000 // This devnode's is an NT driver - DN_NEEDS_LOCKING = 0x02000000 // Devnode need lock resume processing - DN_ARM_WAKEUP = 0x04000000 // Devnode can be the wakeup device - DN_APM_ENUMERATOR = 0x08000000 // APM aware enumerator - DN_APM_DRIVER = 0x10000000 // APM aware driver - DN_SILENT_INSTALL = 0x20000000 // Silent install - DN_NO_SHOW_IN_DM = 0x40000000 // No show in device manager - DN_BOOT_LOG_PROB = 0x80000000 // Had a problem during preassignment of boot log conf - DN_NEED_RESTART = DN_LIAR // System needs to be restarted for this Devnode to work properly - DN_DRIVER_BLOCKED = DN_NOT_FIRST_TIME // One or more drivers are blocked from loading for this Devnode - DN_LEGACY_DRIVER = DN_MOVED // This device is using a legacy driver - DN_CHILD_WITH_INVALID_ID = DN_HAS_MARK // One or more children have invalid IDs - DN_DEVICE_DISCONNECTED = DN_NEEDS_LOCKING // The function driver for a device reported that the device is not connected. Typically this means a wireless device is out of range. - DN_QUERY_REMOVE_PENDING = DN_MF_PARENT // Device is part of a set of related devices collectively pending query-removal - DN_QUERY_REMOVE_ACTIVE = DN_MF_CHILD // Device is actively engaged in a query-remove IRP - DN_CHANGEABLE_FLAGS = DN_NOT_FIRST_TIME | DN_HARDWARE_ENUM | DN_HAS_MARK | DN_DISABLEABLE | DN_REMOVABLE | DN_MF_CHILD | DN_MF_PARENT | DN_NOT_FIRST_TIMEE | DN_STOP_FREE_RES | DN_REBAL_CANDIDATE | DN_NT_ENUMERATOR | DN_NT_DRIVER | DN_SILENT_INSTALL | DN_NO_SHOW_IN_DM + DN_ROOT_ENUMERATED = 0x00000001 // Was enumerated by ROOT + + DN_DRIVER_LOADED = 0x00000002 // Has Register_Device_Driver + + DN_ENUM_LOADED = 0x00000004 // Has Register_Enumerator + + DN_STARTED = 0x00000008 // Is currently configured + + DN_MANUAL = 0x00000010 // Manually installed + + DN_NEED_TO_ENUM = 0x00000020 // May need reenumeration + + DN_NOT_FIRST_TIME = 0x00000040 // Has received a config + + DN_HARDWARE_ENUM = 0x00000080 // Enum generates hardware ID + + DN_LIAR = 0x00000100 // Lied about can reconfig once + + DN_HAS_MARK = 0x00000200 // Not CM_Create_DevInst lately + + DN_HAS_PROBLEM = 0x00000400 // Need device installer + + DN_FILTERED = 0x00000800 // Is filtered + + DN_MOVED = 0x00001000 // Has been moved + + DN_DISABLEABLE = 0x00002000 // Can be disabled + + DN_REMOVABLE = 0x00004000 // Can be removed + + DN_PRIVATE_PROBLEM = 0x00008000 // Has a private problem + + DN_MF_PARENT = 0x00010000 // Multi function parent + + DN_MF_CHILD = 0x00020000 // Multi function child + + DN_WILL_BE_REMOVED = 0x00040000 // DevInst is being removed + + DN_NOT_FIRST_TIMEE = 0x00080000 // Has received a config enumerate + + DN_STOP_FREE_RES = 0x00100000 // When child is stopped, free resources + + DN_REBAL_CANDIDATE = 0x00200000 // Don't skip during rebalance + + DN_BAD_PARTIAL = 0x00400000 // This devnode's log_confs do not have same resources + + DN_NT_ENUMERATOR = 0x00800000 // This devnode's is an NT enumerator + + DN_NT_DRIVER = 0x01000000 // This devnode's is an NT driver + + DN_NEEDS_LOCKING = 0x02000000 // Devnode need lock resume processing + + DN_ARM_WAKEUP = 0x04000000 // Devnode can be the wakeup device + + DN_APM_ENUMERATOR = 0x08000000 // APM aware enumerator + + DN_APM_DRIVER = 0x10000000 // APM aware driver + + DN_SILENT_INSTALL = 0x20000000 // Silent install + + DN_NO_SHOW_IN_DM = 0x40000000 // No show in device manager + + DN_BOOT_LOG_PROB = 0x80000000 // Had a problem during preassignment of boot log conf + + DN_NEED_RESTART = DN_LIAR // System needs to be restarted for this Devnode to work properly + + DN_DRIVER_BLOCKED = DN_NOT_FIRST_TIME // One or more drivers are blocked from loading for this Devnode + + DN_LEGACY_DRIVER = DN_MOVED // This device is using a legacy driver + + DN_CHILD_WITH_INVALID_ID = DN_HAS_MARK // One or more children have invalid IDs + + DN_DEVICE_DISCONNECTED = DN_NEEDS_LOCKING // The function driver for a device reported that the device is not connected. Typically this means a wireless device is out of range. + + DN_QUERY_REMOVE_PENDING = DN_MF_PARENT // Device is part of a set of related devices collectively pending query-removal + + DN_QUERY_REMOVE_ACTIVE = DN_MF_CHILD // Device is actively engaged in a query-remove IRP + + DN_CHANGEABLE_FLAGS = DN_NOT_FIRST_TIME | DN_HARDWARE_ENUM | DN_HAS_MARK | DN_DISABLEABLE | DN_REMOVABLE | DN_MF_CHILD | DN_MF_PARENT | DN_NOT_FIRST_TIMEE | DN_STOP_FREE_RES | DN_REBAL_CANDIDATE | DN_NT_ENUMERATOR | DN_NT_DRIVER | DN_SILENT_INSTALL | DN_NO_SHOW_IN_DM ) //sys setupDiCreateDeviceInfoListEx(classGUID *GUID, hwndParent uintptr, machineName *uint16, reserved uintptr) (handle DevInfo, err error) [failretval==DevInfo(InvalidHandle)] = setupapi.SetupDiCreateDeviceInfoListExW // SetupDiCreateDeviceInfoListEx function creates an empty device information set on a remote or a local computer and optionally associates the set with a device setup class. + func SetupDiCreateDeviceInfoListEx(classGUID *GUID, hwndParent uintptr, machineName string) (deviceInfoSet DevInfo, err error) { + var machineNameUTF16 *uint16 + if machineName != "" { + machineNameUTF16, err = UTF16PtrFromString(machineName) + if err != nil { + return + } + } + return setupDiCreateDeviceInfoListEx(classGUID, hwndParent, machineNameUTF16, 0) + } //sys setupDiGetDeviceInfoListDetail(deviceInfoSet DevInfo, deviceInfoSetDetailData *DevInfoListDetailData) (err error) = setupapi.SetupDiGetDeviceInfoListDetailW // SetupDiGetDeviceInfoListDetail function retrieves information associated with a device information set including the class GUID, remote computer handle, and remote computer name. + func SetupDiGetDeviceInfoListDetail(deviceInfoSet DevInfo) (deviceInfoSetDetailData *DevInfoListDetailData, err error) { + data := &DevInfoListDetailData{} + data.size = data.unsafeSizeOf() return data, setupDiGetDeviceInfoListDetail(deviceInfoSet, data) + } // DeviceInfoListDetail method retrieves information associated with a device information set including the class GUID, remote computer handle, and remote computer name. + func (deviceInfoSet DevInfo) DeviceInfoListDetail() (*DevInfoListDetailData, error) { + return SetupDiGetDeviceInfoListDetail(deviceInfoSet) + } //sys setupDiCreateDeviceInfo(deviceInfoSet DevInfo, DeviceName *uint16, classGUID *GUID, DeviceDescription *uint16, hwndParent uintptr, CreationFlags DICD, deviceInfoData *DevInfoData) (err error) = setupapi.SetupDiCreateDeviceInfoW // SetupDiCreateDeviceInfo function creates a new device information element and adds it as a new member to the specified device information set. + func SetupDiCreateDeviceInfo(deviceInfoSet DevInfo, deviceName string, classGUID *GUID, deviceDescription string, hwndParent uintptr, creationFlags DICD) (deviceInfoData *DevInfoData, err error) { + deviceNameUTF16, err := UTF16PtrFromString(deviceName) + if err != nil { + return + } var deviceDescriptionUTF16 *uint16 + if deviceDescription != "" { + deviceDescriptionUTF16, err = UTF16PtrFromString(deviceDescription) + if err != nil { + return + } + } data := &DevInfoData{} + data.size = uint32(unsafe.Sizeof(*data)) return data, setupDiCreateDeviceInfo(deviceInfoSet, deviceNameUTF16, classGUID, deviceDescriptionUTF16, hwndParent, creationFlags, data) + } // CreateDeviceInfo method creates a new device information element and adds it as a new member to the specified device information set. + func (deviceInfoSet DevInfo) CreateDeviceInfo(deviceName string, classGUID *GUID, deviceDescription string, hwndParent uintptr, creationFlags DICD) (*DevInfoData, error) { + return SetupDiCreateDeviceInfo(deviceInfoSet, deviceName, classGUID, deviceDescription, hwndParent, creationFlags) + } //sys setupDiEnumDeviceInfo(deviceInfoSet DevInfo, memberIndex uint32, deviceInfoData *DevInfoData) (err error) = setupapi.SetupDiEnumDeviceInfo // SetupDiEnumDeviceInfo function returns a DevInfoData structure that specifies a device information element in a device information set. + func SetupDiEnumDeviceInfo(deviceInfoSet DevInfo, memberIndex int) (*DevInfoData, error) { + data := &DevInfoData{} + data.size = uint32(unsafe.Sizeof(*data)) return data, setupDiEnumDeviceInfo(deviceInfoSet, uint32(memberIndex), data) + } // EnumDeviceInfo method returns a DevInfoData structure that specifies a device information element in a device information set. + func (deviceInfoSet DevInfo) EnumDeviceInfo(memberIndex int) (*DevInfoData, error) { + return SetupDiEnumDeviceInfo(deviceInfoSet, memberIndex) + } // SetupDiDestroyDeviceInfoList function deletes a device information set and frees all associated memory. + //sys SetupDiDestroyDeviceInfoList(deviceInfoSet DevInfo) (err error) = setupapi.SetupDiDestroyDeviceInfoList // Close method deletes a device information set and frees all associated memory. + func (deviceInfoSet DevInfo) Close() error { + return SetupDiDestroyDeviceInfoList(deviceInfoSet) + } //sys SetupDiBuildDriverInfoList(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, driverType SPDIT) (err error) = setupapi.SetupDiBuildDriverInfoList // BuildDriverInfoList method builds a list of drivers that is associated with a specific device or with the global class driver list for a device information set. + func (deviceInfoSet DevInfo) BuildDriverInfoList(deviceInfoData *DevInfoData, driverType SPDIT) error { + return SetupDiBuildDriverInfoList(deviceInfoSet, deviceInfoData, driverType) + } //sys SetupDiCancelDriverInfoSearch(deviceInfoSet DevInfo) (err error) = setupapi.SetupDiCancelDriverInfoSearch // CancelDriverInfoSearch method cancels a driver list search that is currently in progress in a different thread. + func (deviceInfoSet DevInfo) CancelDriverInfoSearch() error { + return SetupDiCancelDriverInfoSearch(deviceInfoSet) + } //sys setupDiEnumDriverInfo(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, driverType SPDIT, memberIndex uint32, driverInfoData *DrvInfoData) (err error) = setupapi.SetupDiEnumDriverInfoW // SetupDiEnumDriverInfo function enumerates the members of a driver list. + func SetupDiEnumDriverInfo(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, driverType SPDIT, memberIndex int) (*DrvInfoData, error) { + data := &DrvInfoData{} + data.size = uint32(unsafe.Sizeof(*data)) return data, setupDiEnumDriverInfo(deviceInfoSet, deviceInfoData, driverType, uint32(memberIndex), data) + } // EnumDriverInfo method enumerates the members of a driver list. + func (deviceInfoSet DevInfo) EnumDriverInfo(deviceInfoData *DevInfoData, driverType SPDIT, memberIndex int) (*DrvInfoData, error) { + return SetupDiEnumDriverInfo(deviceInfoSet, deviceInfoData, driverType, memberIndex) + } //sys setupDiGetSelectedDriver(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, driverInfoData *DrvInfoData) (err error) = setupapi.SetupDiGetSelectedDriverW // SetupDiGetSelectedDriver function retrieves the selected driver for a device information set or a particular device information element. + func SetupDiGetSelectedDriver(deviceInfoSet DevInfo, deviceInfoData *DevInfoData) (*DrvInfoData, error) { + data := &DrvInfoData{} + data.size = uint32(unsafe.Sizeof(*data)) return data, setupDiGetSelectedDriver(deviceInfoSet, deviceInfoData, data) + } // SelectedDriver method retrieves the selected driver for a device information set or a particular device information element. + func (deviceInfoSet DevInfo) SelectedDriver(deviceInfoData *DevInfoData) (*DrvInfoData, error) { + return SetupDiGetSelectedDriver(deviceInfoSet, deviceInfoData) + } //sys SetupDiSetSelectedDriver(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, driverInfoData *DrvInfoData) (err error) = setupapi.SetupDiSetSelectedDriverW // SetSelectedDriver method sets, or resets, the selected driver for a device information element or the selected class driver for a device information set. + func (deviceInfoSet DevInfo) SetSelectedDriver(deviceInfoData *DevInfoData, driverInfoData *DrvInfoData) error { + return SetupDiSetSelectedDriver(deviceInfoSet, deviceInfoData, driverInfoData) + } //sys setupDiGetDriverInfoDetail(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, driverInfoData *DrvInfoData, driverInfoDetailData *DrvInfoDetailData, driverInfoDetailDataSize uint32, requiredSize *uint32) (err error) = setupapi.SetupDiGetDriverInfoDetailW // SetupDiGetDriverInfoDetail function retrieves driver information detail for a device information set or a particular device information element in the device information set. + func SetupDiGetDriverInfoDetail(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, driverInfoData *DrvInfoData) (*DrvInfoDetailData, error) { + reqSize := uint32(2048) + for { + buf := make([]byte, reqSize) + data := (*DrvInfoDetailData)(unsafe.Pointer(&buf[0])) + data.size = data.unsafeSizeOf() + err := setupDiGetDriverInfoDetail(deviceInfoSet, deviceInfoData, driverInfoData, data, uint32(len(buf)), &reqSize) + if err == ERROR_INSUFFICIENT_BUFFER { + continue + } + if err != nil { + return nil, err + } + data.size = reqSize + return data, nil + } + } // DriverInfoDetail method retrieves driver information detail for a device information set or a particular device information element in the device information set. + func (deviceInfoSet DevInfo) DriverInfoDetail(deviceInfoData *DevInfoData, driverInfoData *DrvInfoData) (*DrvInfoDetailData, error) { + return SetupDiGetDriverInfoDetail(deviceInfoSet, deviceInfoData, driverInfoData) + } //sys SetupDiDestroyDriverInfoList(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, driverType SPDIT) (err error) = setupapi.SetupDiDestroyDriverInfoList // DestroyDriverInfoList method deletes a driver list. + func (deviceInfoSet DevInfo) DestroyDriverInfoList(deviceInfoData *DevInfoData, driverType SPDIT) error { + return SetupDiDestroyDriverInfoList(deviceInfoSet, deviceInfoData, driverType) + } //sys setupDiGetClassDevsEx(classGUID *GUID, Enumerator *uint16, hwndParent uintptr, Flags DIGCF, deviceInfoSet DevInfo, machineName *uint16, reserved uintptr) (handle DevInfo, err error) [failretval==DevInfo(InvalidHandle)] = setupapi.SetupDiGetClassDevsExW // SetupDiGetClassDevsEx function returns a handle to a device information set that contains requested device information elements for a local or a remote computer. + func SetupDiGetClassDevsEx(classGUID *GUID, enumerator string, hwndParent uintptr, flags DIGCF, deviceInfoSet DevInfo, machineName string) (handle DevInfo, err error) { + var enumeratorUTF16 *uint16 + if enumerator != "" { + enumeratorUTF16, err = UTF16PtrFromString(enumerator) + if err != nil { + return + } + } + var machineNameUTF16 *uint16 + if machineName != "" { + machineNameUTF16, err = UTF16PtrFromString(machineName) + if err != nil { + return + } + } + return setupDiGetClassDevsEx(classGUID, enumeratorUTF16, hwndParent, flags, deviceInfoSet, machineNameUTF16, 0) + } // SetupDiCallClassInstaller function calls the appropriate class installer, and any registered co-installers, with the specified installation request (DIF code). + //sys SetupDiCallClassInstaller(installFunction DI_FUNCTION, deviceInfoSet DevInfo, deviceInfoData *DevInfoData) (err error) = setupapi.SetupDiCallClassInstaller // CallClassInstaller member calls the appropriate class installer, and any registered co-installers, with the specified installation request (DIF code). + func (deviceInfoSet DevInfo) CallClassInstaller(installFunction DI_FUNCTION, deviceInfoData *DevInfoData) error { + return SetupDiCallClassInstaller(installFunction, deviceInfoSet, deviceInfoData) + } // SetupDiOpenDevRegKey function opens a registry key for device-specific configuration information. + //sys SetupDiOpenDevRegKey(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, Scope DICS_FLAG, HwProfile uint32, KeyType DIREG, samDesired uint32) (key Handle, err error) [failretval==InvalidHandle] = setupapi.SetupDiOpenDevRegKey // OpenDevRegKey method opens a registry key for device-specific configuration information. + func (deviceInfoSet DevInfo) OpenDevRegKey(DeviceInfoData *DevInfoData, Scope DICS_FLAG, HwProfile uint32, KeyType DIREG, samDesired uint32) (Handle, error) { + return SetupDiOpenDevRegKey(deviceInfoSet, DeviceInfoData, Scope, HwProfile, KeyType, samDesired) + } //sys setupDiGetDeviceProperty(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, propertyKey *DEVPROPKEY, propertyType *DEVPROPTYPE, propertyBuffer *byte, propertyBufferSize uint32, requiredSize *uint32, flags uint32) (err error) = setupapi.SetupDiGetDevicePropertyW // SetupDiGetDeviceProperty function retrieves a specified device instance property. + func SetupDiGetDeviceProperty(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, propertyKey *DEVPROPKEY) (value interface{}, err error) { + reqSize := uint32(256) + for { + var dataType DEVPROPTYPE + buf := make([]byte, reqSize) + err = setupDiGetDeviceProperty(deviceInfoSet, deviceInfoData, propertyKey, &dataType, &buf[0], uint32(len(buf)), &reqSize, 0) + if err == ERROR_INSUFFICIENT_BUFFER { + continue + } + if err != nil { + return + } + switch dataType { + case DEVPROP_TYPE_STRING: + ret := UTF16ToString(bufToUTF16(buf)) + runtime.KeepAlive(buf) + return ret, nil + } + return nil, errors.New("unimplemented property type") + } + } //sys setupDiGetDeviceRegistryProperty(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, property SPDRP, propertyRegDataType *uint32, propertyBuffer *byte, propertyBufferSize uint32, requiredSize *uint32) (err error) = setupapi.SetupDiGetDeviceRegistryPropertyW // SetupDiGetDeviceRegistryProperty function retrieves a specified Plug and Play device property. + func SetupDiGetDeviceRegistryProperty(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, property SPDRP) (value interface{}, err error) { + reqSize := uint32(256) + for { + var dataType uint32 + buf := make([]byte, reqSize) + err = setupDiGetDeviceRegistryProperty(deviceInfoSet, deviceInfoData, property, &dataType, &buf[0], uint32(len(buf)), &reqSize) + if err == ERROR_INSUFFICIENT_BUFFER { + continue + } + if err != nil { + return + } + return getRegistryValue(buf[:reqSize], dataType) + } + } func getRegistryValue(buf []byte, dataType uint32) (interface{}, error) { + switch dataType { + case REG_SZ: + ret := UTF16ToString(bufToUTF16(buf)) + runtime.KeepAlive(buf) + return ret, nil + case REG_EXPAND_SZ: + value := UTF16ToString(bufToUTF16(buf)) + if value == "" { + return "", nil + } + p, err := syscall.UTF16PtrFromString(value) + if err != nil { + return "", err + } + ret := make([]uint16, 100) + for { + n, err := ExpandEnvironmentStrings(p, &ret[0], uint32(len(ret))) + if err != nil { + return "", err + } + if n <= uint32(len(ret)) { + return UTF16ToString(ret[:n]), nil + } + ret = make([]uint16, n) + } + case REG_BINARY: + return buf, nil + case REG_DWORD_LITTLE_ENDIAN: + return binary.LittleEndian.Uint32(buf), nil + case REG_DWORD_BIG_ENDIAN: + return binary.BigEndian.Uint32(buf), nil + case REG_MULTI_SZ: + bufW := bufToUTF16(buf) + a := []string{} + for i := 0; i < len(bufW); { + j := i + wcslen(bufW[i:]) + if i < j { + a = append(a, UTF16ToString(bufW[i:j])) + } + i = j + 1 + } + runtime.KeepAlive(buf) + return a, nil + case REG_QWORD_LITTLE_ENDIAN: + return binary.LittleEndian.Uint64(buf), nil + default: + return nil, fmt.Errorf("Unsupported registry value type: %v", dataType) + } + } // bufToUTF16 function reinterprets []byte buffer as []uint16 + func bufToUTF16(buf []byte) []uint16 { + sl := struct { addr *uint16 - len int - cap int + + len int + + cap int }{(*uint16)(unsafe.Pointer(&buf[0])), len(buf) / 2, cap(buf) / 2} + return *(*[]uint16)(unsafe.Pointer(&sl)) + } // utf16ToBuf function reinterprets []uint16 as []byte + func utf16ToBuf(buf []uint16) []byte { + sl := struct { addr *byte - len int - cap int + + len int + + cap int }{(*byte)(unsafe.Pointer(&buf[0])), len(buf) * 2, cap(buf) * 2} + return *(*[]byte)(unsafe.Pointer(&sl)) + } func wcslen(str []uint16) int { + for i := 0; i < len(str); i++ { + if str[i] == 0 { + return i + } + } + return len(str) + } // DeviceRegistryProperty method retrieves a specified Plug and Play device property. + func (deviceInfoSet DevInfo) DeviceRegistryProperty(deviceInfoData *DevInfoData, property SPDRP) (interface{}, error) { + return SetupDiGetDeviceRegistryProperty(deviceInfoSet, deviceInfoData, property) + } //sys setupDiSetDeviceRegistryProperty(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, property SPDRP, propertyBuffer *byte, propertyBufferSize uint32) (err error) = setupapi.SetupDiSetDeviceRegistryPropertyW // SetupDiSetDeviceRegistryProperty function sets a Plug and Play device property for a device. + func SetupDiSetDeviceRegistryProperty(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, property SPDRP, propertyBuffers []byte) error { + return setupDiSetDeviceRegistryProperty(deviceInfoSet, deviceInfoData, property, &propertyBuffers[0], uint32(len(propertyBuffers))) + } // SetDeviceRegistryProperty function sets a Plug and Play device property for a device. + func (deviceInfoSet DevInfo) SetDeviceRegistryProperty(deviceInfoData *DevInfoData, property SPDRP, propertyBuffers []byte) error { + return SetupDiSetDeviceRegistryProperty(deviceInfoSet, deviceInfoData, property, propertyBuffers) + } // SetDeviceRegistryPropertyString method sets a Plug and Play device property string for a device. + func (deviceInfoSet DevInfo) SetDeviceRegistryPropertyString(deviceInfoData *DevInfoData, property SPDRP, str string) error { + str16, err := UTF16FromString(str) + if err != nil { + return err + } + err = SetupDiSetDeviceRegistryProperty(deviceInfoSet, deviceInfoData, property, utf16ToBuf(append(str16, 0))) + runtime.KeepAlive(str16) + return err + } //sys setupDiGetDeviceInstallParams(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, deviceInstallParams *DevInstallParams) (err error) = setupapi.SetupDiGetDeviceInstallParamsW // SetupDiGetDeviceInstallParams function retrieves device installation parameters for a device information set or a particular device information element. + func SetupDiGetDeviceInstallParams(deviceInfoSet DevInfo, deviceInfoData *DevInfoData) (*DevInstallParams, error) { + params := &DevInstallParams{} + params.size = uint32(unsafe.Sizeof(*params)) return params, setupDiGetDeviceInstallParams(deviceInfoSet, deviceInfoData, params) + } // DeviceInstallParams method retrieves device installation parameters for a device information set or a particular device information element. + func (deviceInfoSet DevInfo) DeviceInstallParams(deviceInfoData *DevInfoData) (*DevInstallParams, error) { + return SetupDiGetDeviceInstallParams(deviceInfoSet, deviceInfoData) + } //sys setupDiGetDeviceInstanceId(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, instanceId *uint16, instanceIdSize uint32, instanceIdRequiredSize *uint32) (err error) = setupapi.SetupDiGetDeviceInstanceIdW // SetupDiGetDeviceInstanceId function retrieves the instance ID of the device. + func SetupDiGetDeviceInstanceId(deviceInfoSet DevInfo, deviceInfoData *DevInfoData) (string, error) { + reqSize := uint32(1024) + for { + buf := make([]uint16, reqSize) + err := setupDiGetDeviceInstanceId(deviceInfoSet, deviceInfoData, &buf[0], uint32(len(buf)), &reqSize) + if err == ERROR_INSUFFICIENT_BUFFER { + continue + } + if err != nil { + return "", err + } + return UTF16ToString(buf), nil + } + } // DeviceInstanceID method retrieves the instance ID of the device. + func (deviceInfoSet DevInfo) DeviceInstanceID(deviceInfoData *DevInfoData) (string, error) { + return SetupDiGetDeviceInstanceId(deviceInfoSet, deviceInfoData) + } // SetupDiGetClassInstallParams function retrieves class installation parameters for a device information set or a particular device information element. + //sys SetupDiGetClassInstallParams(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, classInstallParams *ClassInstallHeader, classInstallParamsSize uint32, requiredSize *uint32) (err error) = setupapi.SetupDiGetClassInstallParamsW // ClassInstallParams method retrieves class installation parameters for a device information set or a particular device information element. + func (deviceInfoSet DevInfo) ClassInstallParams(deviceInfoData *DevInfoData, classInstallParams *ClassInstallHeader, classInstallParamsSize uint32, requiredSize *uint32) error { + return SetupDiGetClassInstallParams(deviceInfoSet, deviceInfoData, classInstallParams, classInstallParamsSize, requiredSize) + } //sys SetupDiSetDeviceInstallParams(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, deviceInstallParams *DevInstallParams) (err error) = setupapi.SetupDiSetDeviceInstallParamsW // SetDeviceInstallParams member sets device installation parameters for a device information set or a particular device information element. + func (deviceInfoSet DevInfo) SetDeviceInstallParams(deviceInfoData *DevInfoData, deviceInstallParams *DevInstallParams) error { + return SetupDiSetDeviceInstallParams(deviceInfoSet, deviceInfoData, deviceInstallParams) + } // SetupDiSetClassInstallParams function sets or clears class install parameters for a device information set or a particular device information element. + //sys SetupDiSetClassInstallParams(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, classInstallParams *ClassInstallHeader, classInstallParamsSize uint32) (err error) = setupapi.SetupDiSetClassInstallParamsW // SetClassInstallParams method sets or clears class install parameters for a device information set or a particular device information element. + func (deviceInfoSet DevInfo) SetClassInstallParams(deviceInfoData *DevInfoData, classInstallParams *ClassInstallHeader, classInstallParamsSize uint32) error { + return SetupDiSetClassInstallParams(deviceInfoSet, deviceInfoData, classInstallParams, classInstallParamsSize) + } //sys setupDiClassNameFromGuidEx(classGUID *GUID, className *uint16, classNameSize uint32, requiredSize *uint32, machineName *uint16, reserved uintptr) (err error) = setupapi.SetupDiClassNameFromGuidExW // SetupDiClassNameFromGuidEx function retrieves the class name associated with a class GUID. The class can be installed on a local or remote computer. + func SetupDiClassNameFromGuidEx(classGUID *GUID, machineName string) (className string, err error) { + var classNameUTF16 [MAX_CLASS_NAME_LEN]uint16 var machineNameUTF16 *uint16 + if machineName != "" { + machineNameUTF16, err = UTF16PtrFromString(machineName) + if err != nil { + return + } + } err = setupDiClassNameFromGuidEx(classGUID, &classNameUTF16[0], MAX_CLASS_NAME_LEN, nil, machineNameUTF16, 0) + if err != nil { + return + } className = UTF16ToString(classNameUTF16[:]) + return + } //sys setupDiClassGuidsFromNameEx(className *uint16, classGuidList *GUID, classGuidListSize uint32, requiredSize *uint32, machineName *uint16, reserved uintptr) (err error) = setupapi.SetupDiClassGuidsFromNameExW // SetupDiClassGuidsFromNameEx function retrieves the GUIDs associated with the specified class name. This resulting list contains the classes currently installed on a local or remote computer. + func SetupDiClassGuidsFromNameEx(className string, machineName string) ([]GUID, error) { + classNameUTF16, err := UTF16PtrFromString(className) + if err != nil { + return nil, err + } var machineNameUTF16 *uint16 + if machineName != "" { + machineNameUTF16, err = UTF16PtrFromString(machineName) + if err != nil { + return nil, err + } + } reqSize := uint32(4) + for { + buf := make([]GUID, reqSize) + err = setupDiClassGuidsFromNameEx(classNameUTF16, &buf[0], uint32(len(buf)), &reqSize, machineNameUTF16, 0) + if err == ERROR_INSUFFICIENT_BUFFER { + continue + } + if err != nil { + return nil, err + } + return buf[:reqSize], nil + } + } //sys setupDiGetSelectedDevice(deviceInfoSet DevInfo, deviceInfoData *DevInfoData) (err error) = setupapi.SetupDiGetSelectedDevice // SetupDiGetSelectedDevice function retrieves the selected device information element in a device information set. + func SetupDiGetSelectedDevice(deviceInfoSet DevInfo) (*DevInfoData, error) { + data := &DevInfoData{} + data.size = uint32(unsafe.Sizeof(*data)) return data, setupDiGetSelectedDevice(deviceInfoSet, data) + } // SelectedDevice method retrieves the selected device information element in a device information set. + func (deviceInfoSet DevInfo) SelectedDevice() (*DevInfoData, error) { + return SetupDiGetSelectedDevice(deviceInfoSet) + } // SetupDiSetSelectedDevice function sets a device information element as the selected member of a device information set. This function is typically used by an installation wizard. + //sys SetupDiSetSelectedDevice(deviceInfoSet DevInfo, deviceInfoData *DevInfoData) (err error) = setupapi.SetupDiSetSelectedDevice // SetSelectedDevice method sets a device information element as the selected member of a device information set. This function is typically used by an installation wizard. + func (deviceInfoSet DevInfo) SetSelectedDevice(deviceInfoData *DevInfoData) error { + return SetupDiSetSelectedDevice(deviceInfoSet, deviceInfoData) + } //sys setupUninstallOEMInf(infFileName *uint16, flags SUOI, reserved uintptr) (err error) = setupapi.SetupUninstallOEMInfW // SetupUninstallOEMInf uninstalls the specified driver. + func SetupUninstallOEMInf(infFileName string, flags SUOI) error { + infFileName16, err := UTF16PtrFromString(infFileName) + if err != nil { + return err + } + return setupUninstallOEMInf(infFileName16, flags, 0) + } //sys cm_MapCrToWin32Err(configRet CONFIGRET, defaultWin32Error Errno) (ret Errno) = CfgMgr32.CM_MapCrToWin32Err //sys cm_Get_Device_Interface_List_Size(len *uint32, interfaceClass *GUID, deviceID *uint16, flags uint32) (ret CONFIGRET) = CfgMgr32.CM_Get_Device_Interface_List_SizeW + //sys cm_Get_Device_Interface_List(interfaceClass *GUID, deviceID *uint16, buffer *uint16, bufferLen uint32, flags uint32) (ret CONFIGRET) = CfgMgr32.CM_Get_Device_Interface_ListW func CM_Get_Device_Interface_List(deviceID string, interfaceClass *GUID, flags uint32) ([]string, error) { + deviceID16, err := UTF16PtrFromString(deviceID) + if err != nil { + return nil, err + } + var buf []uint16 + var buflen uint32 + for { + if ret := cm_Get_Device_Interface_List_Size(&buflen, interfaceClass, deviceID16, flags); ret != CR_SUCCESS { + return nil, ret + } + buf = make([]uint16, buflen) + if ret := cm_Get_Device_Interface_List(interfaceClass, deviceID16, &buf[0], buflen, flags); ret == CR_SUCCESS { + break + } else if ret != CR_BUFFER_SMALL { + return nil, ret + } + } + var interfaces []string + for i := 0; i < len(buf); { + j := i + wcslen(buf[i:]) + if i < j { + interfaces = append(interfaces, UTF16ToString(buf[i:j])) + } + i = j + 1 + } + if interfaces == nil { + return nil, ERROR_NO_SUCH_DEVICE_INTERFACE + } + return interfaces, nil + } //sys cm_Get_DevNode_Status(status *uint32, problemNumber *uint32, devInst DEVINST, flags uint32) (ret CONFIGRET) = CfgMgr32.CM_Get_DevNode_Status func CM_Get_DevNode_Status(status *uint32, problemNumber *uint32, devInst DEVINST, flags uint32) error { + ret := cm_Get_DevNode_Status(status, problemNumber, devInst, flags) + if ret == CR_SUCCESS { + return nil + } + return ret + } diff --git a/vendor/golang.org/x/sys/windows/syscall.go b/vendor/golang.org/x/sys/windows/syscall.go index e85ed6b..6405159 100644 --- a/vendor/golang.org/x/sys/windows/syscall.go +++ b/vendor/golang.org/x/sys/windows/syscall.go @@ -1,27 +1,47 @@ // Copyright 2009 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build windows // Package windows contains an interface to the low-level operating system + // primitives. OS details vary depending on the underlying system, and + // by default, godoc will display the OS-specific documentation for the current + // system. If you want godoc to display syscall documentation for another + // system, set $GOOS and $GOARCH to the desired system. For example, if + // you want to view documentation for freebsd/arm on linux/amd64, set $GOOS + // to freebsd and $GOARCH to arm. + // + // The primary use of this package is inside other packages that provide a more + // portable interface to the system, such as "os", "time" and "net". Use + // those packages rather than this one if you can. + // + // For details of the functions and data types in this package consult + // the manuals for the appropriate operating system. + // + // These calls return err == nil to indicate success; otherwise + // err represents an operating system error describing the failure and + // holds a value of type syscall.Errno. + package windows // import "golang.org/x/sys/windows" import ( @@ -32,73 +52,123 @@ import ( ) // ByteSliceFromString returns a NUL-terminated slice of bytes + // containing the text of s. If s contains a NUL byte at any + // location, it returns (nil, syscall.EINVAL). + func ByteSliceFromString(s string) ([]byte, error) { + if strings.IndexByte(s, 0) != -1 { + return nil, syscall.EINVAL + } + a := make([]byte, len(s)+1) + copy(a, s) + return a, nil + } // BytePtrFromString returns a pointer to a NUL-terminated array of + // bytes containing the text of s. If s contains a NUL byte at any + // location, it returns (nil, syscall.EINVAL). + func BytePtrFromString(s string) (*byte, error) { + a, err := ByteSliceFromString(s) + if err != nil { + return nil, err + } + return &a[0], nil + } // ByteSliceToString returns a string form of the text represented by the slice s, with a terminating NUL and any + // bytes after the NUL removed. + func ByteSliceToString(s []byte) string { + if i := bytes.IndexByte(s, 0); i != -1 { + s = s[:i] + } + return string(s) + } // BytePtrToString takes a pointer to a sequence of text and returns the corresponding string. + // If the pointer is nil, it returns the empty string. It assumes that the text sequence is terminated + // at a zero byte; if the zero byte is not present, the program may crash. + func BytePtrToString(p *byte) string { + if p == nil { + return "" + } + if *p == 0 { + return "" + } // Find NUL terminator. + n := 0 + for ptr := unsafe.Pointer(p); *(*byte)(ptr) != 0; n++ { + ptr = unsafe.Pointer(uintptr(ptr) + 1) + } return string(unsafe.Slice(p, n)) + } // Single-word zero for use when we need a valid pointer to 0 bytes. + // See mksyscall.pl. + var _zero uintptr func (ts *Timespec) Unix() (sec int64, nsec int64) { + return int64(ts.Sec), int64(ts.Nsec) + } func (tv *Timeval) Unix() (sec int64, nsec int64) { + return int64(tv.Sec), int64(tv.Usec) * 1000 + } func (ts *Timespec) Nano() int64 { + return int64(ts.Sec)*1e9 + int64(ts.Nsec) + } func (tv *Timeval) Nano() int64 { + return int64(tv.Sec)*1e9 + int64(tv.Usec)*1000 + } diff --git a/vendor/golang.org/x/sys/windows/syscall_windows.go b/vendor/golang.org/x/sys/windows/syscall_windows.go index 6525c62..1df30e5 100644 --- a/vendor/golang.org/x/sys/windows/syscall_windows.go +++ b/vendor/golang.org/x/sys/windows/syscall_windows.go @@ -1,5 +1,7 @@ // Copyright 2009 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Windows system calls. @@ -18,823 +20,1511 @@ import ( ) type Handle uintptr + type HWND uintptr const ( InvalidHandle = ^Handle(0) - InvalidHWND = ^HWND(0) + + InvalidHWND = ^HWND(0) // Flags for DefineDosDevice. + DDD_EXACT_MATCH_ON_REMOVE = 0x00000004 - DDD_NO_BROADCAST_SYSTEM = 0x00000008 - DDD_RAW_TARGET_PATH = 0x00000001 - DDD_REMOVE_DEFINITION = 0x00000002 + + DDD_NO_BROADCAST_SYSTEM = 0x00000008 + + DDD_RAW_TARGET_PATH = 0x00000001 + + DDD_REMOVE_DEFINITION = 0x00000002 // Return values for GetDriveType. - DRIVE_UNKNOWN = 0 + + DRIVE_UNKNOWN = 0 + DRIVE_NO_ROOT_DIR = 1 - DRIVE_REMOVABLE = 2 - DRIVE_FIXED = 3 - DRIVE_REMOTE = 4 - DRIVE_CDROM = 5 - DRIVE_RAMDISK = 6 + + DRIVE_REMOVABLE = 2 + + DRIVE_FIXED = 3 + + DRIVE_REMOTE = 4 + + DRIVE_CDROM = 5 + + DRIVE_RAMDISK = 6 // File system flags from GetVolumeInformation and GetVolumeInformationByHandle. - FILE_CASE_SENSITIVE_SEARCH = 0x00000001 - FILE_CASE_PRESERVED_NAMES = 0x00000002 - FILE_FILE_COMPRESSION = 0x00000010 - FILE_DAX_VOLUME = 0x20000000 - FILE_NAMED_STREAMS = 0x00040000 - FILE_PERSISTENT_ACLS = 0x00000008 - FILE_READ_ONLY_VOLUME = 0x00080000 - FILE_SEQUENTIAL_WRITE_ONCE = 0x00100000 - FILE_SUPPORTS_ENCRYPTION = 0x00020000 + + FILE_CASE_SENSITIVE_SEARCH = 0x00000001 + + FILE_CASE_PRESERVED_NAMES = 0x00000002 + + FILE_FILE_COMPRESSION = 0x00000010 + + FILE_DAX_VOLUME = 0x20000000 + + FILE_NAMED_STREAMS = 0x00040000 + + FILE_PERSISTENT_ACLS = 0x00000008 + + FILE_READ_ONLY_VOLUME = 0x00080000 + + FILE_SEQUENTIAL_WRITE_ONCE = 0x00100000 + + FILE_SUPPORTS_ENCRYPTION = 0x00020000 + FILE_SUPPORTS_EXTENDED_ATTRIBUTES = 0x00800000 - FILE_SUPPORTS_HARD_LINKS = 0x00400000 - FILE_SUPPORTS_OBJECT_IDS = 0x00010000 - FILE_SUPPORTS_OPEN_BY_FILE_ID = 0x01000000 - FILE_SUPPORTS_REPARSE_POINTS = 0x00000080 - FILE_SUPPORTS_SPARSE_FILES = 0x00000040 - FILE_SUPPORTS_TRANSACTIONS = 0x00200000 - FILE_SUPPORTS_USN_JOURNAL = 0x02000000 - FILE_UNICODE_ON_DISK = 0x00000004 - FILE_VOLUME_IS_COMPRESSED = 0x00008000 - FILE_VOLUME_QUOTAS = 0x00000020 + + FILE_SUPPORTS_HARD_LINKS = 0x00400000 + + FILE_SUPPORTS_OBJECT_IDS = 0x00010000 + + FILE_SUPPORTS_OPEN_BY_FILE_ID = 0x01000000 + + FILE_SUPPORTS_REPARSE_POINTS = 0x00000080 + + FILE_SUPPORTS_SPARSE_FILES = 0x00000040 + + FILE_SUPPORTS_TRANSACTIONS = 0x00200000 + + FILE_SUPPORTS_USN_JOURNAL = 0x02000000 + + FILE_UNICODE_ON_DISK = 0x00000004 + + FILE_VOLUME_IS_COMPRESSED = 0x00008000 + + FILE_VOLUME_QUOTAS = 0x00000020 // Flags for LockFileEx. + LOCKFILE_FAIL_IMMEDIATELY = 0x00000001 - LOCKFILE_EXCLUSIVE_LOCK = 0x00000002 + + LOCKFILE_EXCLUSIVE_LOCK = 0x00000002 // Return value of SleepEx and other APC functions + WAIT_IO_COMPLETION = 0x000000C0 ) // StringToUTF16 is deprecated. Use UTF16FromString instead. + // If s contains a NUL byte this function panics instead of + // returning an error. + func StringToUTF16(s string) []uint16 { + a, err := UTF16FromString(s) + if err != nil { + panic("windows: string with NUL passed to StringToUTF16") + } + return a + } // UTF16FromString returns the UTF-16 encoding of the UTF-8 string + // s, with a terminating NUL added. If s contains a NUL byte at any + // location, it returns (nil, syscall.EINVAL). + func UTF16FromString(s string) ([]uint16, error) { + return syscall.UTF16FromString(s) + } // UTF16ToString returns the UTF-8 encoding of the UTF-16 sequence s, + // with a terminating NUL and any bytes after the NUL removed. + func UTF16ToString(s []uint16) string { + return syscall.UTF16ToString(s) + } // StringToUTF16Ptr is deprecated. Use UTF16PtrFromString instead. + // If s contains a NUL byte this function panics instead of + // returning an error. + func StringToUTF16Ptr(s string) *uint16 { return &StringToUTF16(s)[0] } // UTF16PtrFromString returns pointer to the UTF-16 encoding of + // the UTF-8 string s, with a terminating NUL added. If s + // contains a NUL byte at any location, it returns (nil, syscall.EINVAL). + func UTF16PtrFromString(s string) (*uint16, error) { + a, err := UTF16FromString(s) + if err != nil { + return nil, err + } + return &a[0], nil + } // UTF16PtrToString takes a pointer to a UTF-16 sequence and returns the corresponding UTF-8 encoded string. + // If the pointer is nil, it returns the empty string. It assumes that the UTF-16 sequence is terminated + // at a zero word; if the zero word is not present, the program may crash. + func UTF16PtrToString(p *uint16) string { + if p == nil { + return "" + } + if *p == 0 { + return "" + } // Find NUL terminator. + n := 0 + for ptr := unsafe.Pointer(p); *(*uint16)(ptr) != 0; n++ { + ptr = unsafe.Pointer(uintptr(ptr) + unsafe.Sizeof(*p)) + } + return UTF16ToString(unsafe.Slice(p, n)) + } func Getpagesize() int { return 4096 } // NewCallback converts a Go function to a function pointer conforming to the stdcall calling convention. + // This is useful when interoperating with Windows code requiring callbacks. + // The argument is expected to be a function with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr. + func NewCallback(fn interface{}) uintptr { + return syscall.NewCallback(fn) + } // NewCallbackCDecl converts a Go function to a function pointer conforming to the cdecl calling convention. + // This is useful when interoperating with Windows code requiring callbacks. + // The argument is expected to be a function with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr. + func NewCallbackCDecl(fn interface{}) uintptr { + return syscall.NewCallbackCDecl(fn) + } // windows api calls //sys GetLastError() (lasterr error) + //sys LoadLibrary(libname string) (handle Handle, err error) = LoadLibraryW + //sys LoadLibraryEx(libname string, zero Handle, flags uintptr) (handle Handle, err error) = LoadLibraryExW + //sys FreeLibrary(handle Handle) (err error) + //sys GetProcAddress(module Handle, procname string) (proc uintptr, err error) + //sys GetModuleFileName(module Handle, filename *uint16, size uint32) (n uint32, err error) = kernel32.GetModuleFileNameW + //sys GetModuleHandleEx(flags uint32, moduleName *uint16, module *Handle) (err error) = kernel32.GetModuleHandleExW + //sys SetDefaultDllDirectories(directoryFlags uint32) (err error) + //sys AddDllDirectory(path *uint16) (cookie uintptr, err error) = kernel32.AddDllDirectory + //sys RemoveDllDirectory(cookie uintptr) (err error) = kernel32.RemoveDllDirectory + //sys SetDllDirectory(path string) (err error) = kernel32.SetDllDirectoryW + //sys GetVersion() (ver uint32, err error) + //sys FormatMessage(flags uint32, msgsrc uintptr, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) = FormatMessageW + //sys ExitProcess(exitcode uint32) + //sys IsWow64Process(handle Handle, isWow64 *bool) (err error) = IsWow64Process + //sys IsWow64Process2(handle Handle, processMachine *uint16, nativeMachine *uint16) (err error) = IsWow64Process2? + //sys CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile Handle) (handle Handle, err error) [failretval==InvalidHandle] = CreateFileW + //sys CreateNamedPipe(name *uint16, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *SecurityAttributes) (handle Handle, err error) [failretval==InvalidHandle] = CreateNamedPipeW + //sys ConnectNamedPipe(pipe Handle, overlapped *Overlapped) (err error) + //sys DisconnectNamedPipe(pipe Handle) (err error) + //sys GetNamedPipeInfo(pipe Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) + //sys GetNamedPipeHandleState(pipe Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) = GetNamedPipeHandleStateW + //sys SetNamedPipeHandleState(pipe Handle, state *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32) (err error) = SetNamedPipeHandleState + //sys readFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) = ReadFile + //sys writeFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) = WriteFile + //sys GetOverlappedResult(handle Handle, overlapped *Overlapped, done *uint32, wait bool) (err error) + //sys SetFilePointer(handle Handle, lowoffset int32, highoffsetptr *int32, whence uint32) (newlowoffset uint32, err error) [failretval==0xffffffff] + //sys CloseHandle(handle Handle) (err error) + //sys GetStdHandle(stdhandle uint32) (handle Handle, err error) [failretval==InvalidHandle] + //sys SetStdHandle(stdhandle uint32, handle Handle) (err error) + //sys findFirstFile1(name *uint16, data *win32finddata1) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstFileW + //sys findNextFile1(handle Handle, data *win32finddata1) (err error) = FindNextFileW + //sys FindClose(handle Handle) (err error) + //sys GetFileInformationByHandle(handle Handle, data *ByHandleFileInformation) (err error) + //sys GetFileInformationByHandleEx(handle Handle, class uint32, outBuffer *byte, outBufferLen uint32) (err error) + //sys SetFileInformationByHandle(handle Handle, class uint32, inBuffer *byte, inBufferLen uint32) (err error) + //sys GetCurrentDirectory(buflen uint32, buf *uint16) (n uint32, err error) = GetCurrentDirectoryW + //sys SetCurrentDirectory(path *uint16) (err error) = SetCurrentDirectoryW + //sys CreateDirectory(path *uint16, sa *SecurityAttributes) (err error) = CreateDirectoryW + //sys RemoveDirectory(path *uint16) (err error) = RemoveDirectoryW + //sys DeleteFile(path *uint16) (err error) = DeleteFileW + //sys MoveFile(from *uint16, to *uint16) (err error) = MoveFileW + //sys MoveFileEx(from *uint16, to *uint16, flags uint32) (err error) = MoveFileExW + //sys LockFileEx(file Handle, flags uint32, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error) + //sys UnlockFileEx(file Handle, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error) + //sys GetComputerName(buf *uint16, n *uint32) (err error) = GetComputerNameW + //sys GetComputerNameEx(nametype uint32, buf *uint16, n *uint32) (err error) = GetComputerNameExW + //sys SetEndOfFile(handle Handle) (err error) + //sys SetFileValidData(handle Handle, validDataLength int64) (err error) + //sys GetSystemTimeAsFileTime(time *Filetime) + //sys GetSystemTimePreciseAsFileTime(time *Filetime) + //sys GetTimeZoneInformation(tzi *Timezoneinformation) (rc uint32, err error) [failretval==0xffffffff] + //sys CreateIoCompletionPort(filehandle Handle, cphandle Handle, key uintptr, threadcnt uint32) (handle Handle, err error) + //sys GetQueuedCompletionStatus(cphandle Handle, qty *uint32, key *uintptr, overlapped **Overlapped, timeout uint32) (err error) + //sys PostQueuedCompletionStatus(cphandle Handle, qty uint32, key uintptr, overlapped *Overlapped) (err error) + //sys CancelIo(s Handle) (err error) + //sys CancelIoEx(s Handle, o *Overlapped) (err error) + //sys CreateProcess(appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error) = CreateProcessW + //sys CreateProcessAsUser(token Token, appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error) = advapi32.CreateProcessAsUserW + //sys initializeProcThreadAttributeList(attrlist *ProcThreadAttributeList, attrcount uint32, flags uint32, size *uintptr) (err error) = InitializeProcThreadAttributeList + //sys deleteProcThreadAttributeList(attrlist *ProcThreadAttributeList) = DeleteProcThreadAttributeList + //sys updateProcThreadAttribute(attrlist *ProcThreadAttributeList, flags uint32, attr uintptr, value unsafe.Pointer, size uintptr, prevvalue unsafe.Pointer, returnedsize *uintptr) (err error) = UpdateProcThreadAttribute + //sys OpenProcess(desiredAccess uint32, inheritHandle bool, processId uint32) (handle Handle, err error) + //sys ShellExecute(hwnd Handle, verb *uint16, file *uint16, args *uint16, cwd *uint16, showCmd int32) (err error) [failretval<=32] = shell32.ShellExecuteW + //sys GetWindowThreadProcessId(hwnd HWND, pid *uint32) (tid uint32, err error) = user32.GetWindowThreadProcessId + //sys GetShellWindow() (shellWindow HWND) = user32.GetShellWindow + //sys MessageBox(hwnd HWND, text *uint16, caption *uint16, boxtype uint32) (ret int32, err error) [failretval==0] = user32.MessageBoxW + //sys ExitWindowsEx(flags uint32, reason uint32) (err error) = user32.ExitWindowsEx + //sys shGetKnownFolderPath(id *KNOWNFOLDERID, flags uint32, token Token, path **uint16) (ret error) = shell32.SHGetKnownFolderPath + //sys TerminateProcess(handle Handle, exitcode uint32) (err error) + //sys GetExitCodeProcess(handle Handle, exitcode *uint32) (err error) + //sys getStartupInfo(startupInfo *StartupInfo) = GetStartupInfoW + //sys GetProcessTimes(handle Handle, creationTime *Filetime, exitTime *Filetime, kernelTime *Filetime, userTime *Filetime) (err error) + //sys DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetProcessHandle Handle, lpTargetHandle *Handle, dwDesiredAccess uint32, bInheritHandle bool, dwOptions uint32) (err error) + //sys WaitForSingleObject(handle Handle, waitMilliseconds uint32) (event uint32, err error) [failretval==0xffffffff] + //sys waitForMultipleObjects(count uint32, handles uintptr, waitAll bool, waitMilliseconds uint32) (event uint32, err error) [failretval==0xffffffff] = WaitForMultipleObjects + //sys GetTempPath(buflen uint32, buf *uint16) (n uint32, err error) = GetTempPathW + //sys CreatePipe(readhandle *Handle, writehandle *Handle, sa *SecurityAttributes, size uint32) (err error) + //sys GetFileType(filehandle Handle) (n uint32, err error) + //sys CryptAcquireContext(provhandle *Handle, container *uint16, provider *uint16, provtype uint32, flags uint32) (err error) = advapi32.CryptAcquireContextW + //sys CryptReleaseContext(provhandle Handle, flags uint32) (err error) = advapi32.CryptReleaseContext + //sys CryptGenRandom(provhandle Handle, buflen uint32, buf *byte) (err error) = advapi32.CryptGenRandom + //sys GetEnvironmentStrings() (envs *uint16, err error) [failretval==nil] = kernel32.GetEnvironmentStringsW + //sys FreeEnvironmentStrings(envs *uint16) (err error) = kernel32.FreeEnvironmentStringsW + //sys GetEnvironmentVariable(name *uint16, buffer *uint16, size uint32) (n uint32, err error) = kernel32.GetEnvironmentVariableW + //sys SetEnvironmentVariable(name *uint16, value *uint16) (err error) = kernel32.SetEnvironmentVariableW + //sys ExpandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error) = kernel32.ExpandEnvironmentStringsW + //sys CreateEnvironmentBlock(block **uint16, token Token, inheritExisting bool) (err error) = userenv.CreateEnvironmentBlock + //sys DestroyEnvironmentBlock(block *uint16) (err error) = userenv.DestroyEnvironmentBlock + //sys getTickCount64() (ms uint64) = kernel32.GetTickCount64 + //sys GetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error) + //sys SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error) + //sys GetFileAttributes(name *uint16) (attrs uint32, err error) [failretval==INVALID_FILE_ATTRIBUTES] = kernel32.GetFileAttributesW + //sys SetFileAttributes(name *uint16, attrs uint32) (err error) = kernel32.SetFileAttributesW + //sys GetFileAttributesEx(name *uint16, level uint32, info *byte) (err error) = kernel32.GetFileAttributesExW + //sys GetCommandLine() (cmd *uint16) = kernel32.GetCommandLineW + //sys commandLineToArgv(cmd *uint16, argc *int32) (argv **uint16, err error) [failretval==nil] = shell32.CommandLineToArgvW + //sys LocalFree(hmem Handle) (handle Handle, err error) [failretval!=0] + //sys LocalAlloc(flags uint32, length uint32) (ptr uintptr, err error) + //sys SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error) + //sys FlushFileBuffers(handle Handle) (err error) + //sys GetFullPathName(path *uint16, buflen uint32, buf *uint16, fname **uint16) (n uint32, err error) = kernel32.GetFullPathNameW + //sys GetLongPathName(path *uint16, buf *uint16, buflen uint32) (n uint32, err error) = kernel32.GetLongPathNameW + //sys GetShortPathName(longpath *uint16, shortpath *uint16, buflen uint32) (n uint32, err error) = kernel32.GetShortPathNameW + //sys GetFinalPathNameByHandle(file Handle, filePath *uint16, filePathSize uint32, flags uint32) (n uint32, err error) = kernel32.GetFinalPathNameByHandleW + //sys CreateFileMapping(fhandle Handle, sa *SecurityAttributes, prot uint32, maxSizeHigh uint32, maxSizeLow uint32, name *uint16) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateFileMappingW + //sys MapViewOfFile(handle Handle, access uint32, offsetHigh uint32, offsetLow uint32, length uintptr) (addr uintptr, err error) + //sys UnmapViewOfFile(addr uintptr) (err error) + //sys FlushViewOfFile(addr uintptr, length uintptr) (err error) + //sys VirtualLock(addr uintptr, length uintptr) (err error) + //sys VirtualUnlock(addr uintptr, length uintptr) (err error) + //sys VirtualAlloc(address uintptr, size uintptr, alloctype uint32, protect uint32) (value uintptr, err error) = kernel32.VirtualAlloc + //sys VirtualFree(address uintptr, size uintptr, freetype uint32) (err error) = kernel32.VirtualFree + //sys VirtualProtect(address uintptr, size uintptr, newprotect uint32, oldprotect *uint32) (err error) = kernel32.VirtualProtect + //sys VirtualProtectEx(process Handle, address uintptr, size uintptr, newProtect uint32, oldProtect *uint32) (err error) = kernel32.VirtualProtectEx + //sys VirtualQuery(address uintptr, buffer *MemoryBasicInformation, length uintptr) (err error) = kernel32.VirtualQuery + //sys VirtualQueryEx(process Handle, address uintptr, buffer *MemoryBasicInformation, length uintptr) (err error) = kernel32.VirtualQueryEx + //sys ReadProcessMemory(process Handle, baseAddress uintptr, buffer *byte, size uintptr, numberOfBytesRead *uintptr) (err error) = kernel32.ReadProcessMemory + //sys WriteProcessMemory(process Handle, baseAddress uintptr, buffer *byte, size uintptr, numberOfBytesWritten *uintptr) (err error) = kernel32.WriteProcessMemory + //sys TransmitFile(s Handle, handle Handle, bytesToWrite uint32, bytsPerSend uint32, overlapped *Overlapped, transmitFileBuf *TransmitFileBuffers, flags uint32) (err error) = mswsock.TransmitFile + //sys ReadDirectoryChanges(handle Handle, buf *byte, buflen uint32, watchSubTree bool, mask uint32, retlen *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) = kernel32.ReadDirectoryChangesW + //sys FindFirstChangeNotification(path string, watchSubtree bool, notifyFilter uint32) (handle Handle, err error) [failretval==InvalidHandle] = kernel32.FindFirstChangeNotificationW + //sys FindNextChangeNotification(handle Handle) (err error) + //sys FindCloseChangeNotification(handle Handle) (err error) + //sys CertOpenSystemStore(hprov Handle, name *uint16) (store Handle, err error) = crypt32.CertOpenSystemStoreW + //sys CertOpenStore(storeProvider uintptr, msgAndCertEncodingType uint32, cryptProv uintptr, flags uint32, para uintptr) (handle Handle, err error) = crypt32.CertOpenStore + //sys CertEnumCertificatesInStore(store Handle, prevContext *CertContext) (context *CertContext, err error) [failretval==nil] = crypt32.CertEnumCertificatesInStore + //sys CertAddCertificateContextToStore(store Handle, certContext *CertContext, addDisposition uint32, storeContext **CertContext) (err error) = crypt32.CertAddCertificateContextToStore + //sys CertCloseStore(store Handle, flags uint32) (err error) = crypt32.CertCloseStore + //sys CertDeleteCertificateFromStore(certContext *CertContext) (err error) = crypt32.CertDeleteCertificateFromStore + //sys CertDuplicateCertificateContext(certContext *CertContext) (dupContext *CertContext) = crypt32.CertDuplicateCertificateContext + //sys PFXImportCertStore(pfx *CryptDataBlob, password *uint16, flags uint32) (store Handle, err error) = crypt32.PFXImportCertStore + //sys CertGetCertificateChain(engine Handle, leaf *CertContext, time *Filetime, additionalStore Handle, para *CertChainPara, flags uint32, reserved uintptr, chainCtx **CertChainContext) (err error) = crypt32.CertGetCertificateChain + //sys CertFreeCertificateChain(ctx *CertChainContext) = crypt32.CertFreeCertificateChain + //sys CertCreateCertificateContext(certEncodingType uint32, certEncoded *byte, encodedLen uint32) (context *CertContext, err error) [failretval==nil] = crypt32.CertCreateCertificateContext + //sys CertFreeCertificateContext(ctx *CertContext) (err error) = crypt32.CertFreeCertificateContext + //sys CertVerifyCertificateChainPolicy(policyOID uintptr, chain *CertChainContext, para *CertChainPolicyPara, status *CertChainPolicyStatus) (err error) = crypt32.CertVerifyCertificateChainPolicy + //sys CertGetNameString(certContext *CertContext, nameType uint32, flags uint32, typePara unsafe.Pointer, name *uint16, size uint32) (chars uint32) = crypt32.CertGetNameStringW + //sys CertFindExtension(objId *byte, countExtensions uint32, extensions *CertExtension) (ret *CertExtension) = crypt32.CertFindExtension + //sys CertFindCertificateInStore(store Handle, certEncodingType uint32, findFlags uint32, findType uint32, findPara unsafe.Pointer, prevCertContext *CertContext) (cert *CertContext, err error) [failretval==nil] = crypt32.CertFindCertificateInStore + //sys CertFindChainInStore(store Handle, certEncodingType uint32, findFlags uint32, findType uint32, findPara unsafe.Pointer, prevChainContext *CertChainContext) (certchain *CertChainContext, err error) [failretval==nil] = crypt32.CertFindChainInStore + //sys CryptAcquireCertificatePrivateKey(cert *CertContext, flags uint32, parameters unsafe.Pointer, cryptProvOrNCryptKey *Handle, keySpec *uint32, callerFreeProvOrNCryptKey *bool) (err error) = crypt32.CryptAcquireCertificatePrivateKey + //sys CryptQueryObject(objectType uint32, object unsafe.Pointer, expectedContentTypeFlags uint32, expectedFormatTypeFlags uint32, flags uint32, msgAndCertEncodingType *uint32, contentType *uint32, formatType *uint32, certStore *Handle, msg *Handle, context *unsafe.Pointer) (err error) = crypt32.CryptQueryObject + //sys CryptDecodeObject(encodingType uint32, structType *byte, encodedBytes *byte, lenEncodedBytes uint32, flags uint32, decoded unsafe.Pointer, decodedLen *uint32) (err error) = crypt32.CryptDecodeObject + //sys CryptProtectData(dataIn *DataBlob, name *uint16, optionalEntropy *DataBlob, reserved uintptr, promptStruct *CryptProtectPromptStruct, flags uint32, dataOut *DataBlob) (err error) = crypt32.CryptProtectData + //sys CryptUnprotectData(dataIn *DataBlob, name **uint16, optionalEntropy *DataBlob, reserved uintptr, promptStruct *CryptProtectPromptStruct, flags uint32, dataOut *DataBlob) (err error) = crypt32.CryptUnprotectData + //sys WinVerifyTrustEx(hwnd HWND, actionId *GUID, data *WinTrustData) (ret error) = wintrust.WinVerifyTrustEx + //sys RegOpenKeyEx(key Handle, subkey *uint16, options uint32, desiredAccess uint32, result *Handle) (regerrno error) = advapi32.RegOpenKeyExW + //sys RegCloseKey(key Handle) (regerrno error) = advapi32.RegCloseKey + //sys RegQueryInfoKey(key Handle, class *uint16, classLen *uint32, reserved *uint32, subkeysLen *uint32, maxSubkeyLen *uint32, maxClassLen *uint32, valuesLen *uint32, maxValueNameLen *uint32, maxValueLen *uint32, saLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegQueryInfoKeyW + //sys RegEnumKeyEx(key Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, class *uint16, classLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegEnumKeyExW + //sys RegQueryValueEx(key Handle, name *uint16, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) = advapi32.RegQueryValueExW + //sys RegNotifyChangeKeyValue(key Handle, watchSubtree bool, notifyFilter uint32, event Handle, asynchronous bool) (regerrno error) = advapi32.RegNotifyChangeKeyValue + //sys GetCurrentProcessId() (pid uint32) = kernel32.GetCurrentProcessId + //sys ProcessIdToSessionId(pid uint32, sessionid *uint32) (err error) = kernel32.ProcessIdToSessionId + //sys ClosePseudoConsole(console Handle) = kernel32.ClosePseudoConsole + //sys createPseudoConsole(size uint32, in Handle, out Handle, flags uint32, pconsole *Handle) (hr error) = kernel32.CreatePseudoConsole + //sys GetConsoleMode(console Handle, mode *uint32) (err error) = kernel32.GetConsoleMode + //sys SetConsoleMode(console Handle, mode uint32) (err error) = kernel32.SetConsoleMode + //sys GetConsoleScreenBufferInfo(console Handle, info *ConsoleScreenBufferInfo) (err error) = kernel32.GetConsoleScreenBufferInfo + //sys setConsoleCursorPosition(console Handle, position uint32) (err error) = kernel32.SetConsoleCursorPosition + //sys WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error) = kernel32.WriteConsoleW + //sys ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error) = kernel32.ReadConsoleW + //sys resizePseudoConsole(pconsole Handle, size uint32) (hr error) = kernel32.ResizePseudoConsole + //sys CreateToolhelp32Snapshot(flags uint32, processId uint32) (handle Handle, err error) [failretval==InvalidHandle] = kernel32.CreateToolhelp32Snapshot + //sys Module32First(snapshot Handle, moduleEntry *ModuleEntry32) (err error) = kernel32.Module32FirstW + //sys Module32Next(snapshot Handle, moduleEntry *ModuleEntry32) (err error) = kernel32.Module32NextW + //sys Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32FirstW + //sys Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32NextW + //sys Thread32First(snapshot Handle, threadEntry *ThreadEntry32) (err error) + //sys Thread32Next(snapshot Handle, threadEntry *ThreadEntry32) (err error) + //sys DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesReturned *uint32, overlapped *Overlapped) (err error) + // This function returns 1 byte BOOLEAN rather than the 4 byte BOOL. + //sys CreateSymbolicLink(symlinkfilename *uint16, targetfilename *uint16, flags uint32) (err error) [failretval&0xff==0] = CreateSymbolicLinkW + //sys CreateHardLink(filename *uint16, existingfilename *uint16, reserved uintptr) (err error) [failretval&0xff==0] = CreateHardLinkW + //sys GetCurrentThreadId() (id uint32) + //sys CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateEventW + //sys CreateEventEx(eventAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateEventExW + //sys OpenEvent(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) = kernel32.OpenEventW + //sys SetEvent(event Handle) (err error) = kernel32.SetEvent + //sys ResetEvent(event Handle) (err error) = kernel32.ResetEvent + //sys PulseEvent(event Handle) (err error) = kernel32.PulseEvent + //sys CreateMutex(mutexAttrs *SecurityAttributes, initialOwner bool, name *uint16) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateMutexW + //sys CreateMutexEx(mutexAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateMutexExW + //sys OpenMutex(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) = kernel32.OpenMutexW + //sys ReleaseMutex(mutex Handle) (err error) = kernel32.ReleaseMutex + //sys SleepEx(milliseconds uint32, alertable bool) (ret uint32) = kernel32.SleepEx + //sys CreateJobObject(jobAttr *SecurityAttributes, name *uint16) (handle Handle, err error) = kernel32.CreateJobObjectW + //sys AssignProcessToJobObject(job Handle, process Handle) (err error) = kernel32.AssignProcessToJobObject + //sys TerminateJobObject(job Handle, exitCode uint32) (err error) = kernel32.TerminateJobObject + //sys SetErrorMode(mode uint32) (ret uint32) = kernel32.SetErrorMode + //sys ResumeThread(thread Handle) (ret uint32, err error) [failretval==0xffffffff] = kernel32.ResumeThread + //sys SetPriorityClass(process Handle, priorityClass uint32) (err error) = kernel32.SetPriorityClass + //sys GetPriorityClass(process Handle) (ret uint32, err error) = kernel32.GetPriorityClass + //sys QueryInformationJobObject(job Handle, JobObjectInformationClass int32, JobObjectInformation uintptr, JobObjectInformationLength uint32, retlen *uint32) (err error) = kernel32.QueryInformationJobObject + //sys SetInformationJobObject(job Handle, JobObjectInformationClass uint32, JobObjectInformation uintptr, JobObjectInformationLength uint32) (ret int, err error) + //sys GenerateConsoleCtrlEvent(ctrlEvent uint32, processGroupID uint32) (err error) + //sys GetProcessId(process Handle) (id uint32, err error) + //sys QueryFullProcessImageName(proc Handle, flags uint32, exeName *uint16, size *uint32) (err error) = kernel32.QueryFullProcessImageNameW + //sys OpenThread(desiredAccess uint32, inheritHandle bool, threadId uint32) (handle Handle, err error) + //sys SetProcessPriorityBoost(process Handle, disable bool) (err error) = kernel32.SetProcessPriorityBoost + //sys GetProcessWorkingSetSizeEx(hProcess Handle, lpMinimumWorkingSetSize *uintptr, lpMaximumWorkingSetSize *uintptr, flags *uint32) + //sys SetProcessWorkingSetSizeEx(hProcess Handle, dwMinimumWorkingSetSize uintptr, dwMaximumWorkingSetSize uintptr, flags uint32) (err error) + //sys ClearCommBreak(handle Handle) (err error) + //sys ClearCommError(handle Handle, lpErrors *uint32, lpStat *ComStat) (err error) + //sys EscapeCommFunction(handle Handle, dwFunc uint32) (err error) + //sys GetCommState(handle Handle, lpDCB *DCB) (err error) + //sys GetCommModemStatus(handle Handle, lpModemStat *uint32) (err error) + //sys GetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error) + //sys PurgeComm(handle Handle, dwFlags uint32) (err error) + //sys SetCommBreak(handle Handle) (err error) + //sys SetCommMask(handle Handle, dwEvtMask uint32) (err error) + //sys SetCommState(handle Handle, lpDCB *DCB) (err error) + //sys SetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error) + //sys SetupComm(handle Handle, dwInQueue uint32, dwOutQueue uint32) (err error) + //sys WaitCommEvent(handle Handle, lpEvtMask *uint32, lpOverlapped *Overlapped) (err error) + //sys GetActiveProcessorCount(groupNumber uint16) (ret uint32) + //sys GetMaximumProcessorCount(groupNumber uint16) (ret uint32) + //sys EnumWindows(enumFunc uintptr, param unsafe.Pointer) (err error) = user32.EnumWindows + //sys EnumChildWindows(hwnd HWND, enumFunc uintptr, param unsafe.Pointer) = user32.EnumChildWindows + //sys GetClassName(hwnd HWND, className *uint16, maxCount int32) (copied int32, err error) = user32.GetClassNameW + //sys GetDesktopWindow() (hwnd HWND) = user32.GetDesktopWindow + //sys GetForegroundWindow() (hwnd HWND) = user32.GetForegroundWindow + //sys IsWindow(hwnd HWND) (isWindow bool) = user32.IsWindow + //sys IsWindowUnicode(hwnd HWND) (isUnicode bool) = user32.IsWindowUnicode + //sys IsWindowVisible(hwnd HWND) (isVisible bool) = user32.IsWindowVisible + //sys GetGUIThreadInfo(thread uint32, info *GUIThreadInfo) (err error) = user32.GetGUIThreadInfo + //sys GetLargePageMinimum() (size uintptr) // Volume Management Functions + //sys DefineDosDevice(flags uint32, deviceName *uint16, targetPath *uint16) (err error) = DefineDosDeviceW + //sys DeleteVolumeMountPoint(volumeMountPoint *uint16) (err error) = DeleteVolumeMountPointW + //sys FindFirstVolume(volumeName *uint16, bufferLength uint32) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstVolumeW + //sys FindFirstVolumeMountPoint(rootPathName *uint16, volumeMountPoint *uint16, bufferLength uint32) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstVolumeMountPointW + //sys FindNextVolume(findVolume Handle, volumeName *uint16, bufferLength uint32) (err error) = FindNextVolumeW + //sys FindNextVolumeMountPoint(findVolumeMountPoint Handle, volumeMountPoint *uint16, bufferLength uint32) (err error) = FindNextVolumeMountPointW + //sys FindVolumeClose(findVolume Handle) (err error) + //sys FindVolumeMountPointClose(findVolumeMountPoint Handle) (err error) + //sys GetDiskFreeSpaceEx(directoryName *uint16, freeBytesAvailableToCaller *uint64, totalNumberOfBytes *uint64, totalNumberOfFreeBytes *uint64) (err error) = GetDiskFreeSpaceExW + //sys GetDriveType(rootPathName *uint16) (driveType uint32) = GetDriveTypeW + //sys GetLogicalDrives() (drivesBitMask uint32, err error) [failretval==0] + //sys GetLogicalDriveStrings(bufferLength uint32, buffer *uint16) (n uint32, err error) [failretval==0] = GetLogicalDriveStringsW + //sys GetVolumeInformation(rootPathName *uint16, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) = GetVolumeInformationW + //sys GetVolumeInformationByHandle(file Handle, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) = GetVolumeInformationByHandleW + //sys GetVolumeNameForVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16, bufferlength uint32) (err error) = GetVolumeNameForVolumeMountPointW + //sys GetVolumePathName(fileName *uint16, volumePathName *uint16, bufferLength uint32) (err error) = GetVolumePathNameW + //sys GetVolumePathNamesForVolumeName(volumeName *uint16, volumePathNames *uint16, bufferLength uint32, returnLength *uint32) (err error) = GetVolumePathNamesForVolumeNameW + //sys QueryDosDevice(deviceName *uint16, targetPath *uint16, max uint32) (n uint32, err error) [failretval==0] = QueryDosDeviceW + //sys SetVolumeLabel(rootPathName *uint16, volumeName *uint16) (err error) = SetVolumeLabelW + //sys SetVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16) (err error) = SetVolumeMountPointW + //sys InitiateSystemShutdownEx(machineName *uint16, message *uint16, timeout uint32, forceAppsClosed bool, rebootAfterShutdown bool, reason uint32) (err error) = advapi32.InitiateSystemShutdownExW + //sys SetProcessShutdownParameters(level uint32, flags uint32) (err error) = kernel32.SetProcessShutdownParameters + //sys GetProcessShutdownParameters(level *uint32, flags *uint32) (err error) = kernel32.GetProcessShutdownParameters + //sys clsidFromString(lpsz *uint16, pclsid *GUID) (ret error) = ole32.CLSIDFromString + //sys stringFromGUID2(rguid *GUID, lpsz *uint16, cchMax int32) (chars int32) = ole32.StringFromGUID2 + //sys coCreateGuid(pguid *GUID) (ret error) = ole32.CoCreateGuid + //sys CoTaskMemFree(address unsafe.Pointer) = ole32.CoTaskMemFree + //sys CoInitializeEx(reserved uintptr, coInit uint32) (ret error) = ole32.CoInitializeEx + //sys CoUninitialize() = ole32.CoUninitialize + //sys CoGetObject(name *uint16, bindOpts *BIND_OPTS3, guid *GUID, functionTable **uintptr) (ret error) = ole32.CoGetObject + //sys getProcessPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetProcessPreferredUILanguages + //sys getThreadPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetThreadPreferredUILanguages + //sys getUserPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetUserPreferredUILanguages + //sys getSystemPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetSystemPreferredUILanguages + //sys findResource(module Handle, name uintptr, resType uintptr) (resInfo Handle, err error) = kernel32.FindResourceW + //sys SizeofResource(module Handle, resInfo Handle) (size uint32, err error) = kernel32.SizeofResource + //sys LoadResource(module Handle, resInfo Handle) (resData Handle, err error) = kernel32.LoadResource + //sys LockResource(resData Handle) (addr uintptr, err error) = kernel32.LockResource // Version APIs + //sys GetFileVersionInfoSize(filename string, zeroHandle *Handle) (bufSize uint32, err error) = version.GetFileVersionInfoSizeW + //sys GetFileVersionInfo(filename string, handle uint32, bufSize uint32, buffer unsafe.Pointer) (err error) = version.GetFileVersionInfoW + //sys VerQueryValue(block unsafe.Pointer, subBlock string, pointerToBufferPointer unsafe.Pointer, bufSize *uint32) (err error) = version.VerQueryValueW // Process Status API (PSAPI) + //sys enumProcesses(processIds *uint32, nSize uint32, bytesReturned *uint32) (err error) = psapi.EnumProcesses + //sys EnumProcessModules(process Handle, module *Handle, cb uint32, cbNeeded *uint32) (err error) = psapi.EnumProcessModules + //sys EnumProcessModulesEx(process Handle, module *Handle, cb uint32, cbNeeded *uint32, filterFlag uint32) (err error) = psapi.EnumProcessModulesEx + //sys GetModuleInformation(process Handle, module Handle, modinfo *ModuleInfo, cb uint32) (err error) = psapi.GetModuleInformation + //sys GetModuleFileNameEx(process Handle, module Handle, filename *uint16, size uint32) (err error) = psapi.GetModuleFileNameExW + //sys GetModuleBaseName(process Handle, module Handle, baseName *uint16, size uint32) (err error) = psapi.GetModuleBaseNameW + //sys QueryWorkingSetEx(process Handle, pv uintptr, cb uint32) (err error) = psapi.QueryWorkingSetEx // NT Native APIs + //sys rtlNtStatusToDosErrorNoTeb(ntstatus NTStatus) (ret syscall.Errno) = ntdll.RtlNtStatusToDosErrorNoTeb + //sys rtlGetVersion(info *OsVersionInfoEx) (ntstatus error) = ntdll.RtlGetVersion + //sys rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32) = ntdll.RtlGetNtVersionNumbers + //sys RtlGetCurrentPeb() (peb *PEB) = ntdll.RtlGetCurrentPeb + //sys RtlInitUnicodeString(destinationString *NTUnicodeString, sourceString *uint16) = ntdll.RtlInitUnicodeString + //sys RtlInitString(destinationString *NTString, sourceString *byte) = ntdll.RtlInitString + //sys NtCreateFile(handle *Handle, access uint32, oa *OBJECT_ATTRIBUTES, iosb *IO_STATUS_BLOCK, allocationSize *int64, attributes uint32, share uint32, disposition uint32, options uint32, eabuffer uintptr, ealength uint32) (ntstatus error) = ntdll.NtCreateFile + //sys NtCreateNamedPipeFile(pipe *Handle, access uint32, oa *OBJECT_ATTRIBUTES, iosb *IO_STATUS_BLOCK, share uint32, disposition uint32, options uint32, typ uint32, readMode uint32, completionMode uint32, maxInstances uint32, inboundQuota uint32, outputQuota uint32, timeout *int64) (ntstatus error) = ntdll.NtCreateNamedPipeFile + //sys NtSetInformationFile(handle Handle, iosb *IO_STATUS_BLOCK, inBuffer *byte, inBufferLen uint32, class uint32) (ntstatus error) = ntdll.NtSetInformationFile + //sys RtlDosPathNameToNtPathName(dosName *uint16, ntName *NTUnicodeString, ntFileNamePart *uint16, relativeName *RTL_RELATIVE_NAME) (ntstatus error) = ntdll.RtlDosPathNameToNtPathName_U_WithStatus + //sys RtlDosPathNameToRelativeNtPathName(dosName *uint16, ntName *NTUnicodeString, ntFileNamePart *uint16, relativeName *RTL_RELATIVE_NAME) (ntstatus error) = ntdll.RtlDosPathNameToRelativeNtPathName_U_WithStatus + //sys RtlDefaultNpAcl(acl **ACL) (ntstatus error) = ntdll.RtlDefaultNpAcl + //sys NtQueryInformationProcess(proc Handle, procInfoClass int32, procInfo unsafe.Pointer, procInfoLen uint32, retLen *uint32) (ntstatus error) = ntdll.NtQueryInformationProcess + //sys NtSetInformationProcess(proc Handle, procInfoClass int32, procInfo unsafe.Pointer, procInfoLen uint32) (ntstatus error) = ntdll.NtSetInformationProcess + //sys NtQuerySystemInformation(sysInfoClass int32, sysInfo unsafe.Pointer, sysInfoLen uint32, retLen *uint32) (ntstatus error) = ntdll.NtQuerySystemInformation + //sys NtSetSystemInformation(sysInfoClass int32, sysInfo unsafe.Pointer, sysInfoLen uint32) (ntstatus error) = ntdll.NtSetSystemInformation + //sys RtlAddFunctionTable(functionTable *RUNTIME_FUNCTION, entryCount uint32, baseAddress uintptr) (ret bool) = ntdll.RtlAddFunctionTable + //sys RtlDeleteFunctionTable(functionTable *RUNTIME_FUNCTION) (ret bool) = ntdll.RtlDeleteFunctionTable // Desktop Window Manager API (Dwmapi) + //sys DwmGetWindowAttribute(hwnd HWND, attribute uint32, value unsafe.Pointer, size uint32) (ret error) = dwmapi.DwmGetWindowAttribute + //sys DwmSetWindowAttribute(hwnd HWND, attribute uint32, value unsafe.Pointer, size uint32) (ret error) = dwmapi.DwmSetWindowAttribute // Windows Multimedia API + //sys TimeBeginPeriod (period uint32) (err error) [failretval != 0] = winmm.timeBeginPeriod + //sys TimeEndPeriod (period uint32) (err error) [failretval != 0] = winmm.timeEndPeriod // syscall interface implementation for other packages // GetCurrentProcess returns the handle for the current process. + // It is a pseudo handle that does not need to be closed. + // The returned error is always nil. + // + // Deprecated: use CurrentProcess for the same Handle without the nil + // error. + func GetCurrentProcess() (Handle, error) { + return CurrentProcess(), nil + } // CurrentProcess returns the handle for the current process. + // It is a pseudo handle that does not need to be closed. + func CurrentProcess() Handle { return Handle(^uintptr(1 - 1)) } // GetCurrentThread returns the handle for the current thread. + // It is a pseudo handle that does not need to be closed. + // The returned error is always nil. + // + // Deprecated: use CurrentThread for the same Handle without the nil + // error. + func GetCurrentThread() (Handle, error) { + return CurrentThread(), nil + } // CurrentThread returns the handle for the current thread. + // It is a pseudo handle that does not need to be closed. + func CurrentThread() Handle { return Handle(^uintptr(2 - 1)) } // GetProcAddressByOrdinal retrieves the address of the exported + // function from module by ordinal. + func GetProcAddressByOrdinal(module Handle, ordinal uintptr) (proc uintptr, err error) { + r0, _, e1 := syscall.Syscall(procGetProcAddress.Addr(), 2, uintptr(module), ordinal, 0) + proc = uintptr(r0) + if proc == 0 { + err = errnoErr(e1) + } + return + } func Exit(code int) { ExitProcess(uint32(code)) } func makeInheritSa() *SecurityAttributes { + var sa SecurityAttributes + sa.Length = uint32(unsafe.Sizeof(sa)) + sa.InheritHandle = 1 + return &sa + } func Open(path string, mode int, perm uint32) (fd Handle, err error) { + if len(path) == 0 { + return InvalidHandle, ERROR_FILE_NOT_FOUND + } + pathp, err := UTF16PtrFromString(path) + if err != nil { + return InvalidHandle, err + } + var access uint32 + switch mode & (O_RDONLY | O_WRONLY | O_RDWR) { + case O_RDONLY: + access = GENERIC_READ + case O_WRONLY: + access = GENERIC_WRITE + case O_RDWR: + access = GENERIC_READ | GENERIC_WRITE + } + if mode&O_CREAT != 0 { + access |= GENERIC_WRITE + } + if mode&O_APPEND != 0 { + access &^= GENERIC_WRITE + access |= FILE_APPEND_DATA + } + sharemode := uint32(FILE_SHARE_READ | FILE_SHARE_WRITE) + var sa *SecurityAttributes + if mode&O_CLOEXEC == 0 { + sa = makeInheritSa() + } + var createmode uint32 + switch { + case mode&(O_CREAT|O_EXCL) == (O_CREAT | O_EXCL): + createmode = CREATE_NEW + case mode&(O_CREAT|O_TRUNC) == (O_CREAT | O_TRUNC): + createmode = CREATE_ALWAYS + case mode&O_CREAT == O_CREAT: + createmode = OPEN_ALWAYS + case mode&O_TRUNC == O_TRUNC: + createmode = TRUNCATE_EXISTING + default: + createmode = OPEN_EXISTING + } + var attrs uint32 = FILE_ATTRIBUTE_NORMAL + if perm&S_IWRITE == 0 { + attrs = FILE_ATTRIBUTE_READONLY + } + h, e := CreateFile(pathp, access, sharemode, sa, createmode, attrs, 0) + return h, e + } func Read(fd Handle, p []byte) (n int, err error) { + var done uint32 + e := ReadFile(fd, p, &done, nil) + if e != nil { + if e == ERROR_BROKEN_PIPE { + // NOTE(brainman): work around ERROR_BROKEN_PIPE is returned on reading EOF from stdin + return 0, nil + } + return 0, e + } + return int(done), nil + } func Write(fd Handle, p []byte) (n int, err error) { + if raceenabled { + raceReleaseMerge(unsafe.Pointer(&ioSync)) + } + var done uint32 + e := WriteFile(fd, p, &done, nil) + if e != nil { + return 0, e + } + return int(done), nil + } func ReadFile(fd Handle, p []byte, done *uint32, overlapped *Overlapped) error { + err := readFile(fd, p, done, overlapped) + if raceenabled { + if *done > 0 { + raceWriteRange(unsafe.Pointer(&p[0]), int(*done)) + } + raceAcquire(unsafe.Pointer(&ioSync)) + } + return err + } func WriteFile(fd Handle, p []byte, done *uint32, overlapped *Overlapped) error { + if raceenabled { + raceReleaseMerge(unsafe.Pointer(&ioSync)) + } + err := writeFile(fd, p, done, overlapped) + if raceenabled && *done > 0 { + raceReadRange(unsafe.Pointer(&p[0]), int(*done)) + } + return err + } var ioSync int64 func Seek(fd Handle, offset int64, whence int) (newoffset int64, err error) { + var w uint32 + switch whence { + case 0: + w = FILE_BEGIN + case 1: + w = FILE_CURRENT + case 2: + w = FILE_END + } + hi := int32(offset >> 32) + lo := int32(offset) + // use GetFileType to check pipe, pipe can't do seek + ft, _ := GetFileType(fd) + if ft == FILE_TYPE_PIPE { + return 0, syscall.EPIPE + } + rlo, e := SetFilePointer(fd, lo, &hi, w) + if e != nil { + return 0, e + } + return int64(hi)<<32 + int64(rlo), nil + } func Close(fd Handle) (err error) { + return CloseHandle(fd) + } var ( - Stdin = getStdHandle(STD_INPUT_HANDLE) + Stdin = getStdHandle(STD_INPUT_HANDLE) + Stdout = getStdHandle(STD_OUTPUT_HANDLE) + Stderr = getStdHandle(STD_ERROR_HANDLE) ) func getStdHandle(stdhandle uint32) (fd Handle) { + r, _ := GetStdHandle(stdhandle) + return r + } const ImplementsGetwd = true func Getwd() (wd string, err error) { + b := make([]uint16, 300) + n, e := GetCurrentDirectory(uint32(len(b)), &b[0]) + if e != nil { + return "", e + } + return string(utf16.Decode(b[0:n])), nil + } func Chdir(path string) (err error) { + pathp, err := UTF16PtrFromString(path) + if err != nil { + return err + } + return SetCurrentDirectory(pathp) + } func Mkdir(path string, mode uint32) (err error) { + pathp, err := UTF16PtrFromString(path) + if err != nil { + return err + } + return CreateDirectory(pathp, nil) + } func Rmdir(path string) (err error) { + pathp, err := UTF16PtrFromString(path) + if err != nil { + return err + } + return RemoveDirectory(pathp) + } func Unlink(path string) (err error) { + pathp, err := UTF16PtrFromString(path) + if err != nil { + return err + } + return DeleteFile(pathp) + } func Rename(oldpath, newpath string) (err error) { + from, err := UTF16PtrFromString(oldpath) + if err != nil { + return err + } + to, err := UTF16PtrFromString(newpath) + if err != nil { + return err + } + return MoveFileEx(from, to, MOVEFILE_REPLACE_EXISTING) + } func ComputerName() (name string, err error) { + var n uint32 = MAX_COMPUTERNAME_LENGTH + 1 + b := make([]uint16, n) + e := GetComputerName(&b[0], &n) + if e != nil { + return "", e + } + return string(utf16.Decode(b[0:n])), nil + } func DurationSinceBoot() time.Duration { + return time.Duration(getTickCount64()) * time.Millisecond + } func Ftruncate(fd Handle, length int64) (err error) { + curoffset, e := Seek(fd, 0, 1) + if e != nil { + return e + } + defer Seek(fd, curoffset, 0) + _, e = Seek(fd, length, 0) + if e != nil { + return e + } + e = SetEndOfFile(fd) + if e != nil { + return e + } + return nil + } func Gettimeofday(tv *Timeval) (err error) { + var ft Filetime + GetSystemTimeAsFileTime(&ft) + *tv = NsecToTimeval(ft.Nanoseconds()) + return nil + } func Pipe(p []Handle) (err error) { + if len(p) != 2 { + return syscall.EINVAL + } + var r, w Handle + e := CreatePipe(&r, &w, makeInheritSa(), 0) + if e != nil { + return e + } + p[0] = r + p[1] = w + return nil + } func Utimes(path string, tv []Timeval) (err error) { + if len(tv) != 2 { + return syscall.EINVAL + } + pathp, e := UTF16PtrFromString(path) + if e != nil { + return e + } + h, e := CreateFile(pathp, + FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil, + OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0) + if e != nil { + return e + } + defer CloseHandle(h) + a := NsecToFiletime(tv[0].Nanoseconds()) + w := NsecToFiletime(tv[1].Nanoseconds()) + return SetFileTime(h, nil, &a, &w) + } func UtimesNano(path string, ts []Timespec) (err error) { + if len(ts) != 2 { + return syscall.EINVAL + } + pathp, e := UTF16PtrFromString(path) + if e != nil { + return e + } + h, e := CreateFile(pathp, + FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil, + OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0) + if e != nil { + return e + } + defer CloseHandle(h) + a := NsecToFiletime(TimespecToNsec(ts[0])) + w := NsecToFiletime(TimespecToNsec(ts[1])) + return SetFileTime(h, nil, &a, &w) + } func Fsync(fd Handle) (err error) { + return FlushFileBuffers(fd) + } func Chmod(path string, mode uint32) (err error) { + p, e := UTF16PtrFromString(path) + if e != nil { + return e + } + attrs, e := GetFileAttributes(p) + if e != nil { + return e + } + if mode&S_IWRITE != 0 { + attrs &^= FILE_ATTRIBUTE_READONLY + } else { + attrs |= FILE_ATTRIBUTE_READONLY + } + return SetFileAttributes(p, attrs) + } func LoadGetSystemTimePreciseAsFileTime() error { + return procGetSystemTimePreciseAsFileTime.Find() + } func LoadCancelIoEx() error { + return procCancelIoEx.Find() + } func LoadSetFileCompletionNotificationModes() error { + return procSetFileCompletionNotificationModes.Find() + } func WaitForMultipleObjects(handles []Handle, waitAll bool, waitMilliseconds uint32) (event uint32, err error) { + // Every other win32 array API takes arguments as "pointer, count", except for this function. So we + // can't declare it as a usual [] type, because mksyscall will use the opposite order. We therefore + // trivially stub this ourselves. var handlePtr *Handle + if len(handles) > 0 { + handlePtr = &handles[0] + } + return waitForMultipleObjects(uint32(len(handles)), uintptr(unsafe.Pointer(handlePtr)), waitAll, waitMilliseconds) + } // net api calls @@ -842,425 +1532,733 @@ func WaitForMultipleObjects(handles []Handle, waitAll bool, waitMilliseconds uin const socket_error = uintptr(^uint32(0)) //sys WSAStartup(verreq uint32, data *WSAData) (sockerr error) = ws2_32.WSAStartup + //sys WSACleanup() (err error) [failretval==socket_error] = ws2_32.WSACleanup + //sys WSAIoctl(s Handle, iocc uint32, inbuf *byte, cbif uint32, outbuf *byte, cbob uint32, cbbr *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) [failretval==socket_error] = ws2_32.WSAIoctl + //sys WSALookupServiceBegin(querySet *WSAQUERYSET, flags uint32, handle *Handle) (err error) [failretval==socket_error] = ws2_32.WSALookupServiceBeginW + //sys WSALookupServiceNext(handle Handle, flags uint32, size *int32, querySet *WSAQUERYSET) (err error) [failretval==socket_error] = ws2_32.WSALookupServiceNextW + //sys WSALookupServiceEnd(handle Handle) (err error) [failretval==socket_error] = ws2_32.WSALookupServiceEnd + //sys socket(af int32, typ int32, protocol int32) (handle Handle, err error) [failretval==InvalidHandle] = ws2_32.socket + //sys sendto(s Handle, buf []byte, flags int32, to unsafe.Pointer, tolen int32) (err error) [failretval==socket_error] = ws2_32.sendto + //sys recvfrom(s Handle, buf []byte, flags int32, from *RawSockaddrAny, fromlen *int32) (n int32, err error) [failretval==-1] = ws2_32.recvfrom + //sys Setsockopt(s Handle, level int32, optname int32, optval *byte, optlen int32) (err error) [failretval==socket_error] = ws2_32.setsockopt + //sys Getsockopt(s Handle, level int32, optname int32, optval *byte, optlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockopt + //sys bind(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.bind + //sys connect(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.connect + //sys getsockname(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockname + //sys getpeername(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getpeername + //sys listen(s Handle, backlog int32) (err error) [failretval==socket_error] = ws2_32.listen + //sys shutdown(s Handle, how int32) (err error) [failretval==socket_error] = ws2_32.shutdown + //sys Closesocket(s Handle) (err error) [failretval==socket_error] = ws2_32.closesocket + //sys AcceptEx(ls Handle, as Handle, buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, recvd *uint32, overlapped *Overlapped) (err error) = mswsock.AcceptEx + //sys GetAcceptExSockaddrs(buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, lrsa **RawSockaddrAny, lrsalen *int32, rrsa **RawSockaddrAny, rrsalen *int32) = mswsock.GetAcceptExSockaddrs + //sys WSARecv(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSARecv + //sys WSASend(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSASend + //sys WSARecvFrom(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, from *RawSockaddrAny, fromlen *int32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSARecvFrom + //sys WSASendTo(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to *RawSockaddrAny, tolen int32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSASendTo + //sys WSASocket(af int32, typ int32, protocol int32, protoInfo *WSAProtocolInfo, group uint32, flags uint32) (handle Handle, err error) [failretval==InvalidHandle] = ws2_32.WSASocketW + //sys GetHostByName(name string) (h *Hostent, err error) [failretval==nil] = ws2_32.gethostbyname + //sys GetServByName(name string, proto string) (s *Servent, err error) [failretval==nil] = ws2_32.getservbyname + //sys Ntohs(netshort uint16) (u uint16) = ws2_32.ntohs + //sys GetProtoByName(name string) (p *Protoent, err error) [failretval==nil] = ws2_32.getprotobyname + //sys DnsQuery(name string, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error) = dnsapi.DnsQuery_W + //sys DnsRecordListFree(rl *DNSRecord, freetype uint32) = dnsapi.DnsRecordListFree + //sys DnsNameCompare(name1 *uint16, name2 *uint16) (same bool) = dnsapi.DnsNameCompare_W + //sys GetAddrInfoW(nodename *uint16, servicename *uint16, hints *AddrinfoW, result **AddrinfoW) (sockerr error) = ws2_32.GetAddrInfoW + //sys FreeAddrInfoW(addrinfo *AddrinfoW) = ws2_32.FreeAddrInfoW + //sys GetIfEntry(pIfRow *MibIfRow) (errcode error) = iphlpapi.GetIfEntry + //sys GetAdaptersInfo(ai *IpAdapterInfo, ol *uint32) (errcode error) = iphlpapi.GetAdaptersInfo + //sys SetFileCompletionNotificationModes(handle Handle, flags uint8) (err error) = kernel32.SetFileCompletionNotificationModes + //sys WSAEnumProtocols(protocols *int32, protocolBuffer *WSAProtocolInfo, bufferLength *uint32) (n int32, err error) [failretval==-1] = ws2_32.WSAEnumProtocolsW + //sys WSAGetOverlappedResult(h Handle, o *Overlapped, bytes *uint32, wait bool, flags *uint32) (err error) = ws2_32.WSAGetOverlappedResult + //sys GetAdaptersAddresses(family uint32, flags uint32, reserved uintptr, adapterAddresses *IpAdapterAddresses, sizePointer *uint32) (errcode error) = iphlpapi.GetAdaptersAddresses + //sys GetACP() (acp uint32) = kernel32.GetACP + //sys MultiByteToWideChar(codePage uint32, dwFlags uint32, str *byte, nstr int32, wchar *uint16, nwchar int32) (nwrite int32, err error) = kernel32.MultiByteToWideChar + //sys getBestInterfaceEx(sockaddr unsafe.Pointer, pdwBestIfIndex *uint32) (errcode error) = iphlpapi.GetBestInterfaceEx // For testing: clients can set this flag to force + // creation of IPv6 sockets to return EAFNOSUPPORT. + var SocketDisableIPv6 bool type RawSockaddrInet4 struct { Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]uint8 + + Port uint16 + + Addr [4]byte /* in_addr */ + + Zero [8]uint8 } type RawSockaddrInet6 struct { - Family uint16 - Port uint16 + Family uint16 + + Port uint16 + Flowinfo uint32 - Addr [16]byte /* in6_addr */ + + Addr [16]byte /* in6_addr */ + Scope_id uint32 } type RawSockaddr struct { Family uint16 - Data [14]int8 + + Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr - Pad [100]int8 + + Pad [100]int8 } type Sockaddr interface { sockaddr() (ptr unsafe.Pointer, len int32, err error) // lowercase; only we can define Sockaddrs + } type SockaddrInet4 struct { Port int + Addr [4]byte - raw RawSockaddrInet4 + + raw RawSockaddrInet4 } func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, int32, error) { + if sa.Port < 0 || sa.Port > 0xFFFF { + return nil, 0, syscall.EINVAL + } + sa.raw.Family = AF_INET + p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) + p[0] = byte(sa.Port >> 8) + p[1] = byte(sa.Port) + sa.raw.Addr = sa.Addr + return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil + } type SockaddrInet6 struct { - Port int + Port int + ZoneId uint32 - Addr [16]byte - raw RawSockaddrInet6 + + Addr [16]byte + + raw RawSockaddrInet6 } func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, int32, error) { + if sa.Port < 0 || sa.Port > 0xFFFF { + return nil, 0, syscall.EINVAL + } + sa.raw.Family = AF_INET6 + p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) + p[0] = byte(sa.Port >> 8) + p[1] = byte(sa.Port) + sa.raw.Scope_id = sa.ZoneId + sa.raw.Addr = sa.Addr + return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil + } type RawSockaddrUnix struct { Family uint16 - Path [UNIX_PATH_MAX]int8 + + Path [UNIX_PATH_MAX]int8 } type SockaddrUnix struct { Name string - raw RawSockaddrUnix + + raw RawSockaddrUnix } func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, int32, error) { + name := sa.Name + n := len(name) + if n > len(sa.raw.Path) { + return nil, 0, syscall.EINVAL + } + if n == len(sa.raw.Path) && name[0] != '@' { + return nil, 0, syscall.EINVAL + } + sa.raw.Family = AF_UNIX + for i := 0; i < n; i++ { + sa.raw.Path[i] = int8(name[i]) + } + // length is family (uint16), name, NUL. + sl := int32(2) + if n > 0 { + sl += int32(n) + 1 + } + if sa.raw.Path[0] == '@' || (sa.raw.Path[0] == 0 && sl > 3) { + // Check sl > 3 so we don't change unnamed socket behavior. + sa.raw.Path[0] = 0 + // Don't count trailing NUL for abstract address. + sl-- + } return unsafe.Pointer(&sa.raw), sl, nil + } type RawSockaddrBth struct { - AddressFamily [2]byte - BtAddr [8]byte + AddressFamily [2]byte + + BtAddr [8]byte + ServiceClassId [16]byte - Port [4]byte + + Port [4]byte } type SockaddrBth struct { - BtAddr uint64 + BtAddr uint64 + ServiceClassId GUID - Port uint32 + + Port uint32 raw RawSockaddrBth } func (sa *SockaddrBth) sockaddr() (unsafe.Pointer, int32, error) { + family := AF_BTH + sa.raw = RawSockaddrBth{ - AddressFamily: *(*[2]byte)(unsafe.Pointer(&family)), - BtAddr: *(*[8]byte)(unsafe.Pointer(&sa.BtAddr)), - Port: *(*[4]byte)(unsafe.Pointer(&sa.Port)), + + AddressFamily: *(*[2]byte)(unsafe.Pointer(&family)), + + BtAddr: *(*[8]byte)(unsafe.Pointer(&sa.BtAddr)), + + Port: *(*[4]byte)(unsafe.Pointer(&sa.Port)), + ServiceClassId: *(*[16]byte)(unsafe.Pointer(&sa.ServiceClassId)), } + return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil + } func (rsa *RawSockaddrAny) Sockaddr() (Sockaddr, error) { + switch rsa.Addr.Family { + case AF_UNIX: + pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa)) + sa := new(SockaddrUnix) + if pp.Path[0] == 0 { + // "Abstract" Unix domain socket. + // Rewrite leading NUL as @ for textual display. + // (This is the standard convention.) + // Not friendly to overwrite in place, + // but the callers below don't care. + pp.Path[0] = '@' + } // Assume path ends at NUL. + // This is not technically the Linux semantics for + // abstract Unix domain sockets--they are supposed + // to be uninterpreted fixed-size binary blobs--but + // everyone uses this convention. + n := 0 + for n < len(pp.Path) && pp.Path[n] != 0 { + n++ + } + sa.Name = string(unsafe.Slice((*byte)(unsafe.Pointer(&pp.Path[0])), n)) + return sa, nil case AF_INET: + pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa)) + sa := new(SockaddrInet4) + p := (*[2]byte)(unsafe.Pointer(&pp.Port)) + sa.Port = int(p[0])<<8 + int(p[1]) + sa.Addr = pp.Addr + return sa, nil case AF_INET6: + pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa)) + sa := new(SockaddrInet6) + p := (*[2]byte)(unsafe.Pointer(&pp.Port)) + sa.Port = int(p[0])<<8 + int(p[1]) + sa.ZoneId = pp.Scope_id + sa.Addr = pp.Addr + return sa, nil + } + return nil, syscall.EAFNOSUPPORT + } func Socket(domain, typ, proto int) (fd Handle, err error) { + if domain == AF_INET6 && SocketDisableIPv6 { + return InvalidHandle, syscall.EAFNOSUPPORT + } + return socket(int32(domain), int32(typ), int32(proto)) + } func SetsockoptInt(fd Handle, level, opt int, value int) (err error) { + v := int32(value) + return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&v)), int32(unsafe.Sizeof(v))) + } func Bind(fd Handle, sa Sockaddr) (err error) { + ptr, n, err := sa.sockaddr() + if err != nil { + return err + } + return bind(fd, ptr, n) + } func Connect(fd Handle, sa Sockaddr) (err error) { + ptr, n, err := sa.sockaddr() + if err != nil { + return err + } + return connect(fd, ptr, n) + } func GetBestInterfaceEx(sa Sockaddr, pdwBestIfIndex *uint32) (err error) { + ptr, _, err := sa.sockaddr() + if err != nil { + return err + } + return getBestInterfaceEx(ptr, pdwBestIfIndex) + } func Getsockname(fd Handle) (sa Sockaddr, err error) { + var rsa RawSockaddrAny + l := int32(unsafe.Sizeof(rsa)) + if err = getsockname(fd, &rsa, &l); err != nil { + return + } + return rsa.Sockaddr() + } func Getpeername(fd Handle) (sa Sockaddr, err error) { + var rsa RawSockaddrAny + l := int32(unsafe.Sizeof(rsa)) + if err = getpeername(fd, &rsa, &l); err != nil { + return + } + return rsa.Sockaddr() + } func Listen(s Handle, n int) (err error) { + return listen(s, int32(n)) + } func Shutdown(fd Handle, how int) (err error) { + return shutdown(fd, int32(how)) + } func WSASendto(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to Sockaddr, overlapped *Overlapped, croutine *byte) (err error) { + var rsa unsafe.Pointer + var l int32 + if to != nil { + rsa, l, err = to.sockaddr() + if err != nil { + return err + } + } + return WSASendTo(s, bufs, bufcnt, sent, flags, (*RawSockaddrAny)(unsafe.Pointer(rsa)), l, overlapped, croutine) + } func LoadGetAddrInfo() error { + return procGetAddrInfoW.Find() + } var connectExFunc struct { once sync.Once + addr uintptr - err error + + err error } func LoadConnectEx() error { + connectExFunc.once.Do(func() { + var s Handle + s, connectExFunc.err = Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) + if connectExFunc.err != nil { + return + } + defer CloseHandle(s) + var n uint32 + connectExFunc.err = WSAIoctl(s, + SIO_GET_EXTENSION_FUNCTION_POINTER, + (*byte)(unsafe.Pointer(&WSAID_CONNECTEX)), + uint32(unsafe.Sizeof(WSAID_CONNECTEX)), + (*byte)(unsafe.Pointer(&connectExFunc.addr)), + uint32(unsafe.Sizeof(connectExFunc.addr)), + &n, nil, 0) + }) + return connectExFunc.err + } func connectEx(s Handle, name unsafe.Pointer, namelen int32, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) (err error) { + r1, _, e1 := syscall.Syscall9(connectExFunc.addr, 7, uintptr(s), uintptr(name), uintptr(namelen), uintptr(unsafe.Pointer(sendBuf)), uintptr(sendDataLen), uintptr(unsafe.Pointer(bytesSent)), uintptr(unsafe.Pointer(overlapped)), 0, 0) + if r1 == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return + } func ConnectEx(fd Handle, sa Sockaddr, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) error { + err := LoadConnectEx() + if err != nil { + return errorspkg.New("failed to find ConnectEx: " + err.Error()) + } + ptr, n, err := sa.sockaddr() + if err != nil { + return err + } + return connectEx(fd, ptr, n, sendBuf, sendDataLen, bytesSent, overlapped) + } var sendRecvMsgFunc struct { - once sync.Once + once sync.Once + sendAddr uintptr + recvAddr uintptr - err error + + err error } func loadWSASendRecvMsg() error { + sendRecvMsgFunc.once.Do(func() { + var s Handle + s, sendRecvMsgFunc.err = Socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP) + if sendRecvMsgFunc.err != nil { + return + } + defer CloseHandle(s) + var n uint32 + sendRecvMsgFunc.err = WSAIoctl(s, + SIO_GET_EXTENSION_FUNCTION_POINTER, + (*byte)(unsafe.Pointer(&WSAID_WSARECVMSG)), + uint32(unsafe.Sizeof(WSAID_WSARECVMSG)), + (*byte)(unsafe.Pointer(&sendRecvMsgFunc.recvAddr)), + uint32(unsafe.Sizeof(sendRecvMsgFunc.recvAddr)), + &n, nil, 0) + if sendRecvMsgFunc.err != nil { + return + } + sendRecvMsgFunc.err = WSAIoctl(s, + SIO_GET_EXTENSION_FUNCTION_POINTER, + (*byte)(unsafe.Pointer(&WSAID_WSASENDMSG)), + uint32(unsafe.Sizeof(WSAID_WSASENDMSG)), + (*byte)(unsafe.Pointer(&sendRecvMsgFunc.sendAddr)), + uint32(unsafe.Sizeof(sendRecvMsgFunc.sendAddr)), + &n, nil, 0) + }) + return sendRecvMsgFunc.err + } func WSASendMsg(fd Handle, msg *WSAMsg, flags uint32, bytesSent *uint32, overlapped *Overlapped, croutine *byte) error { + err := loadWSASendRecvMsg() + if err != nil { + return err + } + r1, _, e1 := syscall.Syscall6(sendRecvMsgFunc.sendAddr, 6, uintptr(fd), uintptr(unsafe.Pointer(msg)), uintptr(flags), uintptr(unsafe.Pointer(bytesSent)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine))) + if r1 == socket_error { + err = errnoErr(e1) + } + return err + } func WSARecvMsg(fd Handle, msg *WSAMsg, bytesReceived *uint32, overlapped *Overlapped, croutine *byte) error { + err := loadWSASendRecvMsg() + if err != nil { + return err + } + r1, _, e1 := syscall.Syscall6(sendRecvMsgFunc.recvAddr, 5, uintptr(fd), uintptr(unsafe.Pointer(msg)), uintptr(unsafe.Pointer(bytesReceived)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)), 0) + if r1 == socket_error { + err = errnoErr(e1) + } + return err + } // Invented structures to support what package os expects. + type Rusage struct { CreationTime Filetime - ExitTime Filetime - KernelTime Filetime - UserTime Filetime + + ExitTime Filetime + + KernelTime Filetime + + UserTime Filetime } type WaitStatus struct { @@ -1286,18 +2284,25 @@ func (w WaitStatus) Signaled() bool { return false } func (w WaitStatus) TrapCause() int { return -1 } // Timespec is an invented structure on Windows, but here for + // consistency with the corresponding package for other operating systems. + type Timespec struct { - Sec int64 + Sec int64 + Nsec int64 } func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { + ts.Sec = nsec / 1e9 + ts.Nsec = nsec % 1e9 + return + } // TODO(brainman): fix all needed for net @@ -1305,159 +2310,266 @@ func NsecToTimespec(nsec int64) (ts Timespec) { func Accept(fd Handle) (nfd Handle, sa Sockaddr, err error) { return 0, nil, syscall.EWINDOWS } func Recvfrom(fd Handle, p []byte, flags int) (n int, from Sockaddr, err error) { + var rsa RawSockaddrAny + l := int32(unsafe.Sizeof(rsa)) + n32, err := recvfrom(fd, p, int32(flags), &rsa, &l) + n = int(n32) + if err != nil { + return + } + from, err = rsa.Sockaddr() + return + } func Sendto(fd Handle, p []byte, flags int, to Sockaddr) (err error) { + ptr, l, err := to.sockaddr() + if err != nil { + return err + } + return sendto(fd, p, int32(flags), ptr, l) + } func SetsockoptTimeval(fd Handle, level, opt int, tv *Timeval) (err error) { return syscall.EWINDOWS } // The Linger struct is wrong but we only noticed after Go 1. + // sysLinger is the real system call structure. // BUG(brainman): The definition of Linger is not appropriate for direct use + // with Setsockopt and Getsockopt. + // Use SetsockoptLinger instead. type Linger struct { - Onoff int32 + Onoff int32 + Linger int32 } type sysLinger struct { - Onoff uint16 + Onoff uint16 + Linger uint16 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ + Interface [4]byte /* in_addr */ + } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ + Interface uint32 } func GetsockoptInt(fd Handle, level, opt int) (int, error) { + v := int32(0) + l := int32(unsafe.Sizeof(v)) + err := Getsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&v)), &l) + return int(v), err + } func SetsockoptLinger(fd Handle, level, opt int, l *Linger) (err error) { + sys := sysLinger{Onoff: uint16(l.Onoff), Linger: uint16(l.Linger)} + return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&sys)), int32(unsafe.Sizeof(sys))) + } func SetsockoptInet4Addr(fd Handle, level, opt int, value [4]byte) (err error) { + return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&value[0])), 4) + } + func SetsockoptIPMreq(fd Handle, level, opt int, mreq *IPMreq) (err error) { + return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(mreq)), int32(unsafe.Sizeof(*mreq))) + } + func SetsockoptIPv6Mreq(fd Handle, level, opt int, mreq *IPv6Mreq) (err error) { + return syscall.EWINDOWS + } func EnumProcesses(processIds []uint32, bytesReturned *uint32) error { + // EnumProcesses syscall expects the size parameter to be in bytes, but the code generated with mksyscall uses + // the length of the processIds slice instead. Hence, this wrapper function is added to fix the discrepancy. + var p *uint32 + if len(processIds) > 0 { + p = &processIds[0] + } + size := uint32(len(processIds) * 4) + return enumProcesses(p, size, bytesReturned) + } func Getpid() (pid int) { return int(GetCurrentProcessId()) } func FindFirstFile(name *uint16, data *Win32finddata) (handle Handle, err error) { + // NOTE(rsc): The Win32finddata struct is wrong for the system call: + // the two paths are each one uint16 short. Use the correct struct, + // a win32finddata1, and then copy the results out. + // There is no loss of expressivity here, because the final + // uint16, if it is used, is supposed to be a NUL, and Go doesn't need that. + // For Go 1.1, we might avoid the allocation of win32finddata1 here + // by adding a final Bug [2]uint16 field to the struct and then + // adjusting the fields in the result directly. + var data1 win32finddata1 + handle, err = findFirstFile1(name, &data1) + if err == nil { + copyFindData(data, &data1) + } + return + } func FindNextFile(handle Handle, data *Win32finddata) (err error) { + var data1 win32finddata1 + err = findNextFile1(handle, &data1) + if err == nil { + copyFindData(data, &data1) + } + return + } func getProcessEntry(pid int) (*ProcessEntry32, error) { + snapshot, err := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) + if err != nil { + return nil, err + } + defer CloseHandle(snapshot) + var procEntry ProcessEntry32 + procEntry.Size = uint32(unsafe.Sizeof(procEntry)) + if err = Process32First(snapshot, &procEntry); err != nil { + return nil, err + } + for { + if procEntry.ProcessID == uint32(pid) { + return &procEntry, nil + } + err = Process32Next(snapshot, &procEntry) + if err != nil { + return nil, err + } + } + } func Getppid() (ppid int) { + pe, err := getProcessEntry(Getpid()) + if err != nil { + return -1 + } + return int(pe.ParentProcessID) + } // TODO(brainman): fix all needed for os -func Fchdir(fd Handle) (err error) { return syscall.EWINDOWS } + +func Fchdir(fd Handle) (err error) { return syscall.EWINDOWS } + func Link(oldpath, newpath string) (err error) { return syscall.EWINDOWS } -func Symlink(path, link string) (err error) { return syscall.EWINDOWS } -func Fchmod(fd Handle, mode uint32) (err error) { return syscall.EWINDOWS } -func Chown(path string, uid int, gid int) (err error) { return syscall.EWINDOWS } +func Symlink(path, link string) (err error) { return syscall.EWINDOWS } + +func Fchmod(fd Handle, mode uint32) (err error) { return syscall.EWINDOWS } + +func Chown(path string, uid int, gid int) (err error) { return syscall.EWINDOWS } + func Lchown(path string, uid int, gid int) (err error) { return syscall.EWINDOWS } -func Fchown(fd Handle, uid int, gid int) (err error) { return syscall.EWINDOWS } -func Getuid() (uid int) { return -1 } -func Geteuid() (euid int) { return -1 } -func Getgid() (gid int) { return -1 } -func Getegid() (egid int) { return -1 } +func Fchown(fd Handle, uid int, gid int) (err error) { return syscall.EWINDOWS } + +func Getuid() (uid int) { return -1 } + +func Geteuid() (euid int) { return -1 } + +func Getgid() (gid int) { return -1 } + +func Getegid() (egid int) { return -1 } + func Getgroups() (gids []int, err error) { return nil, syscall.EWINDOWS } type Signal int @@ -1465,454 +2577,792 @@ type Signal int func (s Signal) Signal() {} func (s Signal) String() string { + if 0 <= s && int(s) < len(signals) { + str := signals[s] + if str != "" { + return str + } + } + return "signal " + itoa(int(s)) + } func LoadCreateSymbolicLink() error { + return procCreateSymbolicLinkW.Find() + } // Readlink returns the destination of the named symbolic link. + func Readlink(path string, buf []byte) (n int, err error) { + fd, err := CreateFile(StringToUTF16Ptr(path), GENERIC_READ, 0, nil, OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS, 0) + if err != nil { + return -1, err + } + defer CloseHandle(fd) rdbbuf := make([]byte, MAXIMUM_REPARSE_DATA_BUFFER_SIZE) + var bytesReturned uint32 + err = DeviceIoControl(fd, FSCTL_GET_REPARSE_POINT, nil, 0, &rdbbuf[0], uint32(len(rdbbuf)), &bytesReturned, nil) + if err != nil { + return -1, err + } rdb := (*reparseDataBuffer)(unsafe.Pointer(&rdbbuf[0])) + var s string + switch rdb.ReparseTag { + case IO_REPARSE_TAG_SYMLINK: + data := (*symbolicLinkReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer)) + p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0])) + s = UTF16ToString(p[data.PrintNameOffset/2 : (data.PrintNameLength-data.PrintNameOffset)/2]) + case IO_REPARSE_TAG_MOUNT_POINT: + data := (*mountPointReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer)) + p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0])) + s = UTF16ToString(p[data.PrintNameOffset/2 : (data.PrintNameLength-data.PrintNameOffset)/2]) + default: + // the path is not a symlink or junction but another type of reparse + // point + return -1, syscall.ENOENT + } + n = copy(buf, []byte(s)) return n, nil + } // GUIDFromString parses a string in the form of + // "{XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" into a GUID. + func GUIDFromString(str string) (GUID, error) { + guid := GUID{} + str16, err := syscall.UTF16PtrFromString(str) + if err != nil { + return guid, err + } + err = clsidFromString(str16, &guid) + if err != nil { + return guid, err + } + return guid, nil + } // GenerateGUID creates a new random GUID. + func GenerateGUID() (GUID, error) { + guid := GUID{} + err := coCreateGuid(&guid) + if err != nil { + return guid, err + } + return guid, nil + } // String returns the canonical string form of the GUID, + // in the form of "{XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}". + func (guid GUID) String() string { + var str [100]uint16 + chars := stringFromGUID2(&guid, &str[0], int32(len(str))) + if chars <= 1 { + return "" + } + return string(utf16.Decode(str[:chars-1])) + } // KnownFolderPath returns a well-known folder path for the current user, specified by one of + // the FOLDERID_ constants, and chosen and optionally created based on a KF_ flag. + func KnownFolderPath(folderID *KNOWNFOLDERID, flags uint32) (string, error) { + return Token(0).KnownFolderPath(folderID, flags) + } // KnownFolderPath returns a well-known folder path for the user token, specified by one of + // the FOLDERID_ constants, and chosen and optionally created based on a KF_ flag. + func (t Token) KnownFolderPath(folderID *KNOWNFOLDERID, flags uint32) (string, error) { + var p *uint16 + err := shGetKnownFolderPath(folderID, flags, t, &p) + if err != nil { + return "", err + } + defer CoTaskMemFree(unsafe.Pointer(p)) + return UTF16PtrToString(p), nil + } // RtlGetVersion returns the version of the underlying operating system, ignoring + // manifest semantics but is affected by the application compatibility layer. + func RtlGetVersion() *OsVersionInfoEx { + info := &OsVersionInfoEx{} + info.osVersionInfoSize = uint32(unsafe.Sizeof(*info)) + // According to documentation, this function always succeeds. + // The function doesn't even check the validity of the + // osVersionInfoSize member. Disassembling ntdll.dll indicates + // that the documentation is indeed correct about that. + _ = rtlGetVersion(info) + return info + } // RtlGetNtVersionNumbers returns the version of the underlying operating system, + // ignoring manifest semantics and the application compatibility layer. + func RtlGetNtVersionNumbers() (majorVersion, minorVersion, buildNumber uint32) { + rtlGetNtVersionNumbers(&majorVersion, &minorVersion, &buildNumber) + buildNumber &= 0xffff + return + } // GetProcessPreferredUILanguages retrieves the process preferred UI languages. + func GetProcessPreferredUILanguages(flags uint32) ([]string, error) { + return getUILanguages(flags, getProcessPreferredUILanguages) + } // GetThreadPreferredUILanguages retrieves the thread preferred UI languages for the current thread. + func GetThreadPreferredUILanguages(flags uint32) ([]string, error) { + return getUILanguages(flags, getThreadPreferredUILanguages) + } // GetUserPreferredUILanguages retrieves information about the user preferred UI languages. + func GetUserPreferredUILanguages(flags uint32) ([]string, error) { + return getUILanguages(flags, getUserPreferredUILanguages) + } // GetSystemPreferredUILanguages retrieves the system preferred UI languages. + func GetSystemPreferredUILanguages(flags uint32) ([]string, error) { + return getUILanguages(flags, getSystemPreferredUILanguages) + } func getUILanguages(flags uint32, f func(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) error) ([]string, error) { + size := uint32(128) + for { + var numLanguages uint32 + buf := make([]uint16, size) + err := f(flags, &numLanguages, &buf[0], &size) + if err == ERROR_INSUFFICIENT_BUFFER { + continue + } + if err != nil { + return nil, err + } + buf = buf[:size] + if numLanguages == 0 || len(buf) == 0 { // GetProcessPreferredUILanguages may return numLanguages==0 with "\0\0" + return []string{}, nil + } + if buf[len(buf)-1] == 0 { + buf = buf[:len(buf)-1] // remove terminating null + } + languages := make([]string, 0, numLanguages) + from := 0 + for i, c := range buf { + if c == 0 { + languages = append(languages, string(utf16.Decode(buf[from:i]))) + from = i + 1 + } + } + return languages, nil + } + } func SetConsoleCursorPosition(console Handle, position Coord) error { + return setConsoleCursorPosition(console, *((*uint32)(unsafe.Pointer(&position)))) + } func GetStartupInfo(startupInfo *StartupInfo) error { + getStartupInfo(startupInfo) + return nil + } func (s NTStatus) Errno() syscall.Errno { + return rtlNtStatusToDosErrorNoTeb(s) + } func langID(pri, sub uint16) uint32 { return uint32(sub)<<10 | uint32(pri) } func (s NTStatus) Error() string { + b := make([]uint16, 300) + n, err := FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_FROM_HMODULE|FORMAT_MESSAGE_ARGUMENT_ARRAY, modntdll.Handle(), uint32(s), langID(LANG_ENGLISH, SUBLANG_ENGLISH_US), b, nil) + if err != nil { + return fmt.Sprintf("NTSTATUS 0x%08x", uint32(s)) + } + // trim terminating \r and \n + for ; n > 0 && (b[n-1] == '\n' || b[n-1] == '\r'); n-- { + } + return string(utf16.Decode(b[:n])) + } // NewNTUnicodeString returns a new NTUnicodeString structure for use with native + // NT APIs that work over the NTUnicodeString type. Note that most Windows APIs + // do not use NTUnicodeString, and instead UTF16PtrFromString should be used for + // the more common *uint16 string type. + func NewNTUnicodeString(s string) (*NTUnicodeString, error) { + var u NTUnicodeString + s16, err := UTF16PtrFromString(s) + if err != nil { + return nil, err + } + RtlInitUnicodeString(&u, s16) + return &u, nil + } // Slice returns a uint16 slice that aliases the data in the NTUnicodeString. + func (s *NTUnicodeString) Slice() []uint16 { + slice := unsafe.Slice(s.Buffer, s.MaximumLength) + return slice[:s.Length] + } func (s *NTUnicodeString) String() string { + return UTF16ToString(s.Slice()) + } // NewNTString returns a new NTString structure for use with native + // NT APIs that work over the NTString type. Note that most Windows APIs + // do not use NTString, and instead UTF16PtrFromString should be used for + // the more common *uint16 string type. + func NewNTString(s string) (*NTString, error) { + var nts NTString + s8, err := BytePtrFromString(s) + if err != nil { + return nil, err + } + RtlInitString(&nts, s8) + return &nts, nil + } // Slice returns a byte slice that aliases the data in the NTString. + func (s *NTString) Slice() []byte { + slice := unsafe.Slice(s.Buffer, s.MaximumLength) + return slice[:s.Length] + } func (s *NTString) String() string { + return ByteSliceToString(s.Slice()) + } // FindResource resolves a resource of the given name and resource type. + func FindResource(module Handle, name, resType ResourceIDOrString) (Handle, error) { + var namePtr, resTypePtr uintptr + var name16, resType16 *uint16 + var err error + resolvePtr := func(i interface{}, keep **uint16) (uintptr, error) { + switch v := i.(type) { + case string: + *keep, err = UTF16PtrFromString(v) + if err != nil { + return 0, err + } + return uintptr(unsafe.Pointer(*keep)), nil + case ResourceID: + return uintptr(v), nil + } + return 0, errorspkg.New("parameter must be a ResourceID or a string") + } + namePtr, err = resolvePtr(name, &name16) + if err != nil { + return 0, err + } + resTypePtr, err = resolvePtr(resType, &resType16) + if err != nil { + return 0, err + } + resInfo, err := findResource(module, namePtr, resTypePtr) + runtime.KeepAlive(name16) + runtime.KeepAlive(resType16) + return resInfo, err + } func LoadResourceData(module, resInfo Handle) (data []byte, err error) { + size, err := SizeofResource(module, resInfo) + if err != nil { + return + } + resData, err := LoadResource(module, resInfo) + if err != nil { + return + } + ptr, err := LockResource(resData) + if err != nil { + return + } + data = unsafe.Slice((*byte)(unsafe.Pointer(ptr)), size) + return + } // PSAPI_WORKING_SET_EX_BLOCK contains extended working set information for a page. + type PSAPI_WORKING_SET_EX_BLOCK uint64 // Valid returns the validity of this page. + // If this bit is 1, the subsequent members are valid; otherwise they should be ignored. + func (b PSAPI_WORKING_SET_EX_BLOCK) Valid() bool { + return (b & 1) == 1 + } // ShareCount is the number of processes that share this page. The maximum value of this member is 7. + func (b PSAPI_WORKING_SET_EX_BLOCK) ShareCount() uint64 { + return b.intField(1, 3) + } // Win32Protection is the memory protection attributes of the page. For a list of values, see + // https://docs.microsoft.com/en-us/windows/win32/memory/memory-protection-constants + func (b PSAPI_WORKING_SET_EX_BLOCK) Win32Protection() uint64 { + return b.intField(4, 11) + } // Shared returns the shared status of this page. + // If this bit is 1, the page can be shared. + func (b PSAPI_WORKING_SET_EX_BLOCK) Shared() bool { + return (b & (1 << 15)) == 1 + } // Node is the NUMA node. The maximum value of this member is 63. + func (b PSAPI_WORKING_SET_EX_BLOCK) Node() uint64 { + return b.intField(16, 6) + } // Locked returns the locked status of this page. + // If this bit is 1, the virtual page is locked in physical memory. + func (b PSAPI_WORKING_SET_EX_BLOCK) Locked() bool { + return (b & (1 << 22)) == 1 + } // LargePage returns the large page status of this page. + // If this bit is 1, the page is a large page. + func (b PSAPI_WORKING_SET_EX_BLOCK) LargePage() bool { + return (b & (1 << 23)) == 1 + } // Bad returns the bad status of this page. + // If this bit is 1, the page is has been reported as bad. + func (b PSAPI_WORKING_SET_EX_BLOCK) Bad() bool { + return (b & (1 << 31)) == 1 + } // intField extracts an integer field in the PSAPI_WORKING_SET_EX_BLOCK union. + func (b PSAPI_WORKING_SET_EX_BLOCK) intField(start, length int) uint64 { + var mask PSAPI_WORKING_SET_EX_BLOCK + for pos := start; pos < start+length; pos++ { + mask |= (1 << pos) + } masked := b & mask + return uint64(masked >> start) + } // PSAPI_WORKING_SET_EX_INFORMATION contains extended working set information for a process. + type PSAPI_WORKING_SET_EX_INFORMATION struct { + // The virtual address. + VirtualAddress Pointer + // A PSAPI_WORKING_SET_EX_BLOCK union that indicates the attributes of the page at VirtualAddress. + VirtualAttributes PSAPI_WORKING_SET_EX_BLOCK } // CreatePseudoConsole creates a windows pseudo console. + func CreatePseudoConsole(size Coord, in Handle, out Handle, flags uint32, pconsole *Handle) error { + // We need this wrapper to manually cast Coord to uint32. The autogenerated wrappers only + // accept arguments that can be casted to uintptr, and Coord can't. + return createPseudoConsole(*((*uint32)(unsafe.Pointer(&size))), in, out, flags, pconsole) + } // ResizePseudoConsole resizes the internal buffers of the pseudo console to the width and height specified in `size`. + func ResizePseudoConsole(pconsole Handle, size Coord) error { + // We need this wrapper to manually cast Coord to uint32. The autogenerated wrappers only + // accept arguments that can be casted to uintptr, and Coord can't. + return resizePseudoConsole(pconsole, *((*uint32)(unsafe.Pointer(&size)))) + } // DCB constants. See https://learn.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-dcb. + const ( - CBR_110 = 110 - CBR_300 = 300 - CBR_600 = 600 - CBR_1200 = 1200 - CBR_2400 = 2400 - CBR_4800 = 4800 - CBR_9600 = 9600 - CBR_14400 = 14400 - CBR_19200 = 19200 - CBR_38400 = 38400 - CBR_57600 = 57600 + CBR_110 = 110 + + CBR_300 = 300 + + CBR_600 = 600 + + CBR_1200 = 1200 + + CBR_2400 = 2400 + + CBR_4800 = 4800 + + CBR_9600 = 9600 + + CBR_14400 = 14400 + + CBR_19200 = 19200 + + CBR_38400 = 38400 + + CBR_57600 = 57600 + CBR_115200 = 115200 + CBR_128000 = 128000 + CBR_256000 = 256000 - DTR_CONTROL_DISABLE = 0x00000000 - DTR_CONTROL_ENABLE = 0x00000010 + DTR_CONTROL_DISABLE = 0x00000000 + + DTR_CONTROL_ENABLE = 0x00000010 + DTR_CONTROL_HANDSHAKE = 0x00000020 - RTS_CONTROL_DISABLE = 0x00000000 - RTS_CONTROL_ENABLE = 0x00001000 - RTS_CONTROL_HANDSHAKE = 0x00002000 - RTS_CONTROL_TOGGLE = 0x00003000 + RTS_CONTROL_DISABLE = 0x00000000 + + RTS_CONTROL_ENABLE = 0x00001000 + + RTS_CONTROL_HANDSHAKE = 0x00002000 + + RTS_CONTROL_TOGGLE = 0x00003000 + + NOPARITY = 0 + + ODDPARITY = 1 + + EVENPARITY = 2 + + MARKPARITY = 3 - NOPARITY = 0 - ODDPARITY = 1 - EVENPARITY = 2 - MARKPARITY = 3 SPACEPARITY = 4 - ONESTOPBIT = 0 + ONESTOPBIT = 0 + ONE5STOPBITS = 1 - TWOSTOPBITS = 2 + + TWOSTOPBITS = 2 ) // EscapeCommFunction constants. See https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-escapecommfunction. + const ( - SETXOFF = 1 - SETXON = 2 - SETRTS = 3 - CLRRTS = 4 - SETDTR = 5 - CLRDTR = 6 + SETXOFF = 1 + + SETXON = 2 + + SETRTS = 3 + + CLRRTS = 4 + + SETDTR = 5 + + CLRDTR = 6 + SETBREAK = 8 + CLRBREAK = 9 ) // PurgeComm constants. See https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-purgecomm. + const ( PURGE_TXABORT = 0x0001 + PURGE_RXABORT = 0x0002 + PURGE_TXCLEAR = 0x0004 + PURGE_RXCLEAR = 0x0008 ) // SetCommMask constants. See https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setcommmask. + const ( - EV_RXCHAR = 0x0001 - EV_RXFLAG = 0x0002 + EV_RXCHAR = 0x0001 + + EV_RXFLAG = 0x0002 + EV_TXEMPTY = 0x0004 - EV_CTS = 0x0008 - EV_DSR = 0x0010 - EV_RLSD = 0x0020 - EV_BREAK = 0x0040 - EV_ERR = 0x0080 - EV_RING = 0x0100 + + EV_CTS = 0x0008 + + EV_DSR = 0x0010 + + EV_RLSD = 0x0020 + + EV_BREAK = 0x0040 + + EV_ERR = 0x0080 + + EV_RING = 0x0100 ) diff --git a/vendor/golang.org/x/sys/windows/types_windows.go b/vendor/golang.org/x/sys/windows/types_windows.go index d8cb71d..f327af0 100644 --- a/vendor/golang.org/x/sys/windows/types_windows.go +++ b/vendor/golang.org/x/sys/windows/types_windows.go @@ -1,5 +1,7 @@ // Copyright 2011 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package windows @@ -11,149 +13,255 @@ import ( ) // NTStatus corresponds with NTSTATUS, error values returned by ntdll.dll and + // other native functions. + type NTStatus uint32 const ( + // Invented values to support what package os expects. - O_RDONLY = 0x00000 - O_WRONLY = 0x00001 - O_RDWR = 0x00002 - O_CREAT = 0x00040 - O_EXCL = 0x00080 - O_NOCTTY = 0x00100 - O_TRUNC = 0x00200 + + O_RDONLY = 0x00000 + + O_WRONLY = 0x00001 + + O_RDWR = 0x00002 + + O_CREAT = 0x00040 + + O_EXCL = 0x00080 + + O_NOCTTY = 0x00100 + + O_TRUNC = 0x00200 + O_NONBLOCK = 0x00800 - O_APPEND = 0x00400 - O_SYNC = 0x01000 - O_ASYNC = 0x02000 - O_CLOEXEC = 0x80000 + + O_APPEND = 0x00400 + + O_SYNC = 0x01000 + + O_ASYNC = 0x02000 + + O_CLOEXEC = 0x80000 ) const ( + // More invented values for signals - SIGHUP = Signal(0x1) - SIGINT = Signal(0x2) + + SIGHUP = Signal(0x1) + + SIGINT = Signal(0x2) + SIGQUIT = Signal(0x3) - SIGILL = Signal(0x4) + + SIGILL = Signal(0x4) + SIGTRAP = Signal(0x5) + SIGABRT = Signal(0x6) - SIGBUS = Signal(0x7) - SIGFPE = Signal(0x8) + + SIGBUS = Signal(0x7) + + SIGFPE = Signal(0x8) + SIGKILL = Signal(0x9) + SIGSEGV = Signal(0xb) + SIGPIPE = Signal(0xd) + SIGALRM = Signal(0xe) + SIGTERM = Signal(0xf) ) var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/breakpoint trap", - 6: "aborted", - 7: "bus error", - 8: "floating point exception", - 9: "killed", + + 1: "hangup", + + 2: "interrupt", + + 3: "quit", + + 4: "illegal instruction", + + 5: "trace/breakpoint trap", + + 6: "aborted", + + 7: "bus error", + + 8: "floating point exception", + + 9: "killed", + 10: "user defined signal 1", + 11: "segmentation fault", + 12: "user defined signal 2", + 13: "broken pipe", + 14: "alarm clock", + 15: "terminated", } const ( - FILE_READ_DATA = 0x00000001 - FILE_READ_ATTRIBUTES = 0x00000080 - FILE_READ_EA = 0x00000008 - FILE_WRITE_DATA = 0x00000002 - FILE_WRITE_ATTRIBUTES = 0x00000100 - FILE_WRITE_EA = 0x00000010 - FILE_APPEND_DATA = 0x00000004 - FILE_EXECUTE = 0x00000020 + FILE_READ_DATA = 0x00000001 + + FILE_READ_ATTRIBUTES = 0x00000080 + + FILE_READ_EA = 0x00000008 + + FILE_WRITE_DATA = 0x00000002 + + FILE_WRITE_ATTRIBUTES = 0x00000100 + + FILE_WRITE_EA = 0x00000010 + + FILE_APPEND_DATA = 0x00000004 + + FILE_EXECUTE = 0x00000020 + + FILE_GENERIC_READ = STANDARD_RIGHTS_READ | FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_READ_EA | SYNCHRONIZE + + FILE_GENERIC_WRITE = STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | FILE_APPEND_DATA | SYNCHRONIZE - FILE_GENERIC_READ = STANDARD_RIGHTS_READ | FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_READ_EA | SYNCHRONIZE - FILE_GENERIC_WRITE = STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | FILE_APPEND_DATA | SYNCHRONIZE FILE_GENERIC_EXECUTE = STANDARD_RIGHTS_EXECUTE | FILE_READ_ATTRIBUTES | FILE_EXECUTE | SYNCHRONIZE FILE_LIST_DIRECTORY = 0x00000001 - FILE_TRAVERSE = 0x00000020 - FILE_SHARE_READ = 0x00000001 - FILE_SHARE_WRITE = 0x00000002 + FILE_TRAVERSE = 0x00000020 + + FILE_SHARE_READ = 0x00000001 + + FILE_SHARE_WRITE = 0x00000002 + FILE_SHARE_DELETE = 0x00000004 - FILE_ATTRIBUTE_READONLY = 0x00000001 - FILE_ATTRIBUTE_HIDDEN = 0x00000002 - FILE_ATTRIBUTE_SYSTEM = 0x00000004 - FILE_ATTRIBUTE_DIRECTORY = 0x00000010 - FILE_ATTRIBUTE_ARCHIVE = 0x00000020 - FILE_ATTRIBUTE_DEVICE = 0x00000040 - FILE_ATTRIBUTE_NORMAL = 0x00000080 - FILE_ATTRIBUTE_TEMPORARY = 0x00000100 - FILE_ATTRIBUTE_SPARSE_FILE = 0x00000200 - FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400 - FILE_ATTRIBUTE_COMPRESSED = 0x00000800 - FILE_ATTRIBUTE_OFFLINE = 0x00001000 - FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 0x00002000 - FILE_ATTRIBUTE_ENCRYPTED = 0x00004000 - FILE_ATTRIBUTE_INTEGRITY_STREAM = 0x00008000 - FILE_ATTRIBUTE_VIRTUAL = 0x00010000 - FILE_ATTRIBUTE_NO_SCRUB_DATA = 0x00020000 - FILE_ATTRIBUTE_RECALL_ON_OPEN = 0x00040000 + FILE_ATTRIBUTE_READONLY = 0x00000001 + + FILE_ATTRIBUTE_HIDDEN = 0x00000002 + + FILE_ATTRIBUTE_SYSTEM = 0x00000004 + + FILE_ATTRIBUTE_DIRECTORY = 0x00000010 + + FILE_ATTRIBUTE_ARCHIVE = 0x00000020 + + FILE_ATTRIBUTE_DEVICE = 0x00000040 + + FILE_ATTRIBUTE_NORMAL = 0x00000080 + + FILE_ATTRIBUTE_TEMPORARY = 0x00000100 + + FILE_ATTRIBUTE_SPARSE_FILE = 0x00000200 + + FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400 + + FILE_ATTRIBUTE_COMPRESSED = 0x00000800 + + FILE_ATTRIBUTE_OFFLINE = 0x00001000 + + FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 0x00002000 + + FILE_ATTRIBUTE_ENCRYPTED = 0x00004000 + + FILE_ATTRIBUTE_INTEGRITY_STREAM = 0x00008000 + + FILE_ATTRIBUTE_VIRTUAL = 0x00010000 + + FILE_ATTRIBUTE_NO_SCRUB_DATA = 0x00020000 + + FILE_ATTRIBUTE_RECALL_ON_OPEN = 0x00040000 + FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS = 0x00400000 INVALID_FILE_ATTRIBUTES = 0xffffffff - CREATE_NEW = 1 - CREATE_ALWAYS = 2 - OPEN_EXISTING = 3 - OPEN_ALWAYS = 4 + CREATE_NEW = 1 + + CREATE_ALWAYS = 2 + + OPEN_EXISTING = 3 + + OPEN_ALWAYS = 4 + TRUNCATE_EXISTING = 5 FILE_FLAG_OPEN_REQUIRING_OPLOCK = 0x00040000 - FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000 - FILE_FLAG_OPEN_NO_RECALL = 0x00100000 - FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000 - FILE_FLAG_SESSION_AWARE = 0x00800000 - FILE_FLAG_POSIX_SEMANTICS = 0x01000000 - FILE_FLAG_BACKUP_SEMANTICS = 0x02000000 - FILE_FLAG_DELETE_ON_CLOSE = 0x04000000 - FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000 - FILE_FLAG_RANDOM_ACCESS = 0x10000000 - FILE_FLAG_NO_BUFFERING = 0x20000000 - FILE_FLAG_OVERLAPPED = 0x40000000 - FILE_FLAG_WRITE_THROUGH = 0x80000000 - HANDLE_FLAG_INHERIT = 0x00000001 - STARTF_USESTDHANDLES = 0x00000100 - STARTF_USESHOWWINDOW = 0x00000001 + FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000 + + FILE_FLAG_OPEN_NO_RECALL = 0x00100000 + + FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000 + + FILE_FLAG_SESSION_AWARE = 0x00800000 + + FILE_FLAG_POSIX_SEMANTICS = 0x01000000 + + FILE_FLAG_BACKUP_SEMANTICS = 0x02000000 + + FILE_FLAG_DELETE_ON_CLOSE = 0x04000000 + + FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000 + + FILE_FLAG_RANDOM_ACCESS = 0x10000000 + + FILE_FLAG_NO_BUFFERING = 0x20000000 + + FILE_FLAG_OVERLAPPED = 0x40000000 + + FILE_FLAG_WRITE_THROUGH = 0x80000000 + + HANDLE_FLAG_INHERIT = 0x00000001 + + STARTF_USESTDHANDLES = 0x00000100 + + STARTF_USESHOWWINDOW = 0x00000001 + DUPLICATE_CLOSE_SOURCE = 0x00000001 - DUPLICATE_SAME_ACCESS = 0x00000002 - STD_INPUT_HANDLE = -10 & (1<<32 - 1) + DUPLICATE_SAME_ACCESS = 0x00000002 + + STD_INPUT_HANDLE = -10 & (1<<32 - 1) + STD_OUTPUT_HANDLE = -11 & (1<<32 - 1) - STD_ERROR_HANDLE = -12 & (1<<32 - 1) - FILE_BEGIN = 0 + STD_ERROR_HANDLE = -12 & (1<<32 - 1) + + FILE_BEGIN = 0 + FILE_CURRENT = 1 - FILE_END = 2 - LANG_ENGLISH = 0x09 + FILE_END = 2 + + LANG_ENGLISH = 0x09 + SUBLANG_ENGLISH_US = 0x01 FORMAT_MESSAGE_ALLOCATE_BUFFER = 256 - FORMAT_MESSAGE_IGNORE_INSERTS = 512 - FORMAT_MESSAGE_FROM_STRING = 1024 - FORMAT_MESSAGE_FROM_HMODULE = 2048 - FORMAT_MESSAGE_FROM_SYSTEM = 4096 - FORMAT_MESSAGE_ARGUMENT_ARRAY = 8192 - FORMAT_MESSAGE_MAX_WIDTH_MASK = 255 - MAX_PATH = 260 + FORMAT_MESSAGE_IGNORE_INSERTS = 512 + + FORMAT_MESSAGE_FROM_STRING = 1024 + + FORMAT_MESSAGE_FROM_HMODULE = 2048 + + FORMAT_MESSAGE_FROM_SYSTEM = 4096 + + FORMAT_MESSAGE_ARGUMENT_ARRAY = 8192 + + FORMAT_MESSAGE_MAX_WIDTH_MASK = 255 + + MAX_PATH = 260 + MAX_LONG_PATH = 32768 MAX_MODULE_NAME32 = 255 @@ -164,1163 +272,2018 @@ const ( MAX_DNS_SUFFIX_STRING_LENGTH = 256 - TIME_ZONE_ID_UNKNOWN = 0 + TIME_ZONE_ID_UNKNOWN = 0 + TIME_ZONE_ID_STANDARD = 1 TIME_ZONE_ID_DAYLIGHT = 2 - IGNORE = 0 - INFINITE = 0xffffffff + + IGNORE = 0 + + INFINITE = 0xffffffff WAIT_ABANDONED = 0x00000080 - WAIT_OBJECT_0 = 0x00000000 - WAIT_FAILED = 0xFFFFFFFF + + WAIT_OBJECT_0 = 0x00000000 + + WAIT_FAILED = 0xFFFFFFFF // Access rights for process. - PROCESS_CREATE_PROCESS = 0x0080 - PROCESS_CREATE_THREAD = 0x0002 - PROCESS_DUP_HANDLE = 0x0040 - PROCESS_QUERY_INFORMATION = 0x0400 + + PROCESS_CREATE_PROCESS = 0x0080 + + PROCESS_CREATE_THREAD = 0x0002 + + PROCESS_DUP_HANDLE = 0x0040 + + PROCESS_QUERY_INFORMATION = 0x0400 + PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 - PROCESS_SET_INFORMATION = 0x0200 - PROCESS_SET_QUOTA = 0x0100 - PROCESS_SUSPEND_RESUME = 0x0800 - PROCESS_TERMINATE = 0x0001 - PROCESS_VM_OPERATION = 0x0008 - PROCESS_VM_READ = 0x0010 - PROCESS_VM_WRITE = 0x0020 + + PROCESS_SET_INFORMATION = 0x0200 + + PROCESS_SET_QUOTA = 0x0100 + + PROCESS_SUSPEND_RESUME = 0x0800 + + PROCESS_TERMINATE = 0x0001 + + PROCESS_VM_OPERATION = 0x0008 + + PROCESS_VM_READ = 0x0010 + + PROCESS_VM_WRITE = 0x0020 // Access rights for thread. - THREAD_DIRECT_IMPERSONATION = 0x0200 - THREAD_GET_CONTEXT = 0x0008 - THREAD_IMPERSONATE = 0x0100 - THREAD_QUERY_INFORMATION = 0x0040 - THREAD_QUERY_LIMITED_INFORMATION = 0x0800 - THREAD_SET_CONTEXT = 0x0010 - THREAD_SET_INFORMATION = 0x0020 - THREAD_SET_LIMITED_INFORMATION = 0x0400 - THREAD_SET_THREAD_TOKEN = 0x0080 - THREAD_SUSPEND_RESUME = 0x0002 - THREAD_TERMINATE = 0x0001 - FILE_MAP_COPY = 0x01 - FILE_MAP_WRITE = 0x02 - FILE_MAP_READ = 0x04 + THREAD_DIRECT_IMPERSONATION = 0x0200 + + THREAD_GET_CONTEXT = 0x0008 + + THREAD_IMPERSONATE = 0x0100 + + THREAD_QUERY_INFORMATION = 0x0040 + + THREAD_QUERY_LIMITED_INFORMATION = 0x0800 + + THREAD_SET_CONTEXT = 0x0010 + + THREAD_SET_INFORMATION = 0x0020 + + THREAD_SET_LIMITED_INFORMATION = 0x0400 + + THREAD_SET_THREAD_TOKEN = 0x0080 + + THREAD_SUSPEND_RESUME = 0x0002 + + THREAD_TERMINATE = 0x0001 + + FILE_MAP_COPY = 0x01 + + FILE_MAP_WRITE = 0x02 + + FILE_MAP_READ = 0x04 + FILE_MAP_EXECUTE = 0x20 - CTRL_C_EVENT = 0 - CTRL_BREAK_EVENT = 1 - CTRL_CLOSE_EVENT = 2 - CTRL_LOGOFF_EVENT = 5 + CTRL_C_EVENT = 0 + + CTRL_BREAK_EVENT = 1 + + CTRL_CLOSE_EVENT = 2 + + CTRL_LOGOFF_EVENT = 5 + CTRL_SHUTDOWN_EVENT = 6 // Windows reserves errors >= 1<<29 for application use. + APPLICATION_ERROR = 1 << 29 ) const ( + // Process creation flags. - CREATE_BREAKAWAY_FROM_JOB = 0x01000000 - CREATE_DEFAULT_ERROR_MODE = 0x04000000 - CREATE_NEW_CONSOLE = 0x00000010 - CREATE_NEW_PROCESS_GROUP = 0x00000200 - CREATE_NO_WINDOW = 0x08000000 - CREATE_PROTECTED_PROCESS = 0x00040000 + + CREATE_BREAKAWAY_FROM_JOB = 0x01000000 + + CREATE_DEFAULT_ERROR_MODE = 0x04000000 + + CREATE_NEW_CONSOLE = 0x00000010 + + CREATE_NEW_PROCESS_GROUP = 0x00000200 + + CREATE_NO_WINDOW = 0x08000000 + + CREATE_PROTECTED_PROCESS = 0x00040000 + CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000 - CREATE_SEPARATE_WOW_VDM = 0x00000800 - CREATE_SHARED_WOW_VDM = 0x00001000 - CREATE_SUSPENDED = 0x00000004 - CREATE_UNICODE_ENVIRONMENT = 0x00000400 - DEBUG_ONLY_THIS_PROCESS = 0x00000002 - DEBUG_PROCESS = 0x00000001 - DETACHED_PROCESS = 0x00000008 - EXTENDED_STARTUPINFO_PRESENT = 0x00080000 - INHERIT_PARENT_AFFINITY = 0x00010000 + + CREATE_SEPARATE_WOW_VDM = 0x00000800 + + CREATE_SHARED_WOW_VDM = 0x00001000 + + CREATE_SUSPENDED = 0x00000004 + + CREATE_UNICODE_ENVIRONMENT = 0x00000400 + + DEBUG_ONLY_THIS_PROCESS = 0x00000002 + + DEBUG_PROCESS = 0x00000001 + + DETACHED_PROCESS = 0x00000008 + + EXTENDED_STARTUPINFO_PRESENT = 0x00080000 + + INHERIT_PARENT_AFFINITY = 0x00010000 ) const ( + // attributes for ProcThreadAttributeList - PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = 0x00020000 - PROC_THREAD_ATTRIBUTE_HANDLE_LIST = 0x00020002 - PROC_THREAD_ATTRIBUTE_GROUP_AFFINITY = 0x00030003 - PROC_THREAD_ATTRIBUTE_PREFERRED_NODE = 0x00020004 - PROC_THREAD_ATTRIBUTE_IDEAL_PROCESSOR = 0x00030005 + + PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = 0x00020000 + + PROC_THREAD_ATTRIBUTE_HANDLE_LIST = 0x00020002 + + PROC_THREAD_ATTRIBUTE_GROUP_AFFINITY = 0x00030003 + + PROC_THREAD_ATTRIBUTE_PREFERRED_NODE = 0x00020004 + + PROC_THREAD_ATTRIBUTE_IDEAL_PROCESSOR = 0x00030005 + PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY = 0x00020007 - PROC_THREAD_ATTRIBUTE_UMS_THREAD = 0x00030006 - PROC_THREAD_ATTRIBUTE_PROTECTION_LEVEL = 0x0002000b - PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE = 0x00020016 + + PROC_THREAD_ATTRIBUTE_UMS_THREAD = 0x00030006 + + PROC_THREAD_ATTRIBUTE_PROTECTION_LEVEL = 0x0002000b + + PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE = 0x00020016 ) const ( + // flags for CreateToolhelp32Snapshot + TH32CS_SNAPHEAPLIST = 0x01 - TH32CS_SNAPPROCESS = 0x02 - TH32CS_SNAPTHREAD = 0x04 - TH32CS_SNAPMODULE = 0x08 + + TH32CS_SNAPPROCESS = 0x02 + + TH32CS_SNAPTHREAD = 0x04 + + TH32CS_SNAPMODULE = 0x08 + TH32CS_SNAPMODULE32 = 0x10 - TH32CS_SNAPALL = TH32CS_SNAPHEAPLIST | TH32CS_SNAPMODULE | TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD - TH32CS_INHERIT = 0x80000000 + + TH32CS_SNAPALL = TH32CS_SNAPHEAPLIST | TH32CS_SNAPMODULE | TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD + + TH32CS_INHERIT = 0x80000000 ) const ( + // flags for EnumProcessModulesEx - LIST_MODULES_32BIT = 0x01 - LIST_MODULES_64BIT = 0x02 - LIST_MODULES_ALL = 0x03 + + LIST_MODULES_32BIT = 0x01 + + LIST_MODULES_64BIT = 0x02 + + LIST_MODULES_ALL = 0x03 + LIST_MODULES_DEFAULT = 0x00 ) const ( + // filters for ReadDirectoryChangesW and FindFirstChangeNotificationW - FILE_NOTIFY_CHANGE_FILE_NAME = 0x001 - FILE_NOTIFY_CHANGE_DIR_NAME = 0x002 - FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x004 - FILE_NOTIFY_CHANGE_SIZE = 0x008 - FILE_NOTIFY_CHANGE_LAST_WRITE = 0x010 + + FILE_NOTIFY_CHANGE_FILE_NAME = 0x001 + + FILE_NOTIFY_CHANGE_DIR_NAME = 0x002 + + FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x004 + + FILE_NOTIFY_CHANGE_SIZE = 0x008 + + FILE_NOTIFY_CHANGE_LAST_WRITE = 0x010 + FILE_NOTIFY_CHANGE_LAST_ACCESS = 0x020 - FILE_NOTIFY_CHANGE_CREATION = 0x040 - FILE_NOTIFY_CHANGE_SECURITY = 0x100 + + FILE_NOTIFY_CHANGE_CREATION = 0x040 + + FILE_NOTIFY_CHANGE_SECURITY = 0x100 ) const ( + // do not reorder + FILE_ACTION_ADDED = iota + 1 + FILE_ACTION_REMOVED + FILE_ACTION_MODIFIED + FILE_ACTION_RENAMED_OLD_NAME + FILE_ACTION_RENAMED_NEW_NAME ) const ( + // wincrypt.h + /* certenrolld_begin -- PROV_RSA_*/ - PROV_RSA_FULL = 1 - PROV_RSA_SIG = 2 - PROV_DSS = 3 - PROV_FORTEZZA = 4 - PROV_MS_EXCHANGE = 5 - PROV_SSL = 6 - PROV_RSA_SCHANNEL = 12 - PROV_DSS_DH = 13 - PROV_EC_ECDSA_SIG = 14 - PROV_EC_ECNRA_SIG = 15 + + PROV_RSA_FULL = 1 + + PROV_RSA_SIG = 2 + + PROV_DSS = 3 + + PROV_FORTEZZA = 4 + + PROV_MS_EXCHANGE = 5 + + PROV_SSL = 6 + + PROV_RSA_SCHANNEL = 12 + + PROV_DSS_DH = 13 + + PROV_EC_ECDSA_SIG = 14 + + PROV_EC_ECNRA_SIG = 15 + PROV_EC_ECDSA_FULL = 16 + PROV_EC_ECNRA_FULL = 17 - PROV_DH_SCHANNEL = 18 - PROV_SPYRUS_LYNKS = 20 - PROV_RNG = 21 - PROV_INTEL_SEC = 22 - PROV_REPLACE_OWF = 23 - PROV_RSA_AES = 24 + + PROV_DH_SCHANNEL = 18 + + PROV_SPYRUS_LYNKS = 20 + + PROV_RNG = 21 + + PROV_INTEL_SEC = 22 + + PROV_REPLACE_OWF = 23 + + PROV_RSA_AES = 24 /* dwFlags definitions for CryptAcquireContext */ - CRYPT_VERIFYCONTEXT = 0xF0000000 - CRYPT_NEWKEYSET = 0x00000008 - CRYPT_DELETEKEYSET = 0x00000010 - CRYPT_MACHINE_KEYSET = 0x00000020 - CRYPT_SILENT = 0x00000040 + + CRYPT_VERIFYCONTEXT = 0xF0000000 + + CRYPT_NEWKEYSET = 0x00000008 + + CRYPT_DELETEKEYSET = 0x00000010 + + CRYPT_MACHINE_KEYSET = 0x00000020 + + CRYPT_SILENT = 0x00000040 + CRYPT_DEFAULT_CONTAINER_OPTIONAL = 0x00000080 /* Flags for PFXImportCertStore */ - CRYPT_EXPORTABLE = 0x00000001 - CRYPT_USER_PROTECTED = 0x00000002 - CRYPT_USER_KEYSET = 0x00001000 - PKCS12_PREFER_CNG_KSP = 0x00000100 - PKCS12_ALWAYS_CNG_KSP = 0x00000200 - PKCS12_ALLOW_OVERWRITE_KEY = 0x00004000 - PKCS12_NO_PERSIST_KEY = 0x00008000 + + CRYPT_EXPORTABLE = 0x00000001 + + CRYPT_USER_PROTECTED = 0x00000002 + + CRYPT_USER_KEYSET = 0x00001000 + + PKCS12_PREFER_CNG_KSP = 0x00000100 + + PKCS12_ALWAYS_CNG_KSP = 0x00000200 + + PKCS12_ALLOW_OVERWRITE_KEY = 0x00004000 + + PKCS12_NO_PERSIST_KEY = 0x00008000 + PKCS12_INCLUDE_EXTENDED_PROPERTIES = 0x00000010 /* Flags for CryptAcquireCertificatePrivateKey */ - CRYPT_ACQUIRE_CACHE_FLAG = 0x00000001 - CRYPT_ACQUIRE_USE_PROV_INFO_FLAG = 0x00000002 - CRYPT_ACQUIRE_COMPARE_KEY_FLAG = 0x00000004 - CRYPT_ACQUIRE_NO_HEALING = 0x00000008 - CRYPT_ACQUIRE_SILENT_FLAG = 0x00000040 - CRYPT_ACQUIRE_WINDOW_HANDLE_FLAG = 0x00000080 - CRYPT_ACQUIRE_NCRYPT_KEY_FLAGS_MASK = 0x00070000 - CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG = 0x00010000 + + CRYPT_ACQUIRE_CACHE_FLAG = 0x00000001 + + CRYPT_ACQUIRE_USE_PROV_INFO_FLAG = 0x00000002 + + CRYPT_ACQUIRE_COMPARE_KEY_FLAG = 0x00000004 + + CRYPT_ACQUIRE_NO_HEALING = 0x00000008 + + CRYPT_ACQUIRE_SILENT_FLAG = 0x00000040 + + CRYPT_ACQUIRE_WINDOW_HANDLE_FLAG = 0x00000080 + + CRYPT_ACQUIRE_NCRYPT_KEY_FLAGS_MASK = 0x00070000 + + CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG = 0x00010000 + CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG = 0x00020000 - CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG = 0x00040000 + + CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG = 0x00040000 /* pdwKeySpec for CryptAcquireCertificatePrivateKey */ - AT_KEYEXCHANGE = 1 - AT_SIGNATURE = 2 + + AT_KEYEXCHANGE = 1 + + AT_SIGNATURE = 2 + CERT_NCRYPT_KEY_SPEC = 0xFFFFFFFF /* Default usage match type is AND with value zero */ + USAGE_MATCH_TYPE_AND = 0 - USAGE_MATCH_TYPE_OR = 1 + + USAGE_MATCH_TYPE_OR = 1 /* msgAndCertEncodingType values for CertOpenStore function */ - X509_ASN_ENCODING = 0x00000001 + + X509_ASN_ENCODING = 0x00000001 + PKCS_7_ASN_ENCODING = 0x00010000 /* storeProvider values for CertOpenStore function */ - CERT_STORE_PROV_MSG = 1 - CERT_STORE_PROV_MEMORY = 2 - CERT_STORE_PROV_FILE = 3 - CERT_STORE_PROV_REG = 4 - CERT_STORE_PROV_PKCS7 = 5 - CERT_STORE_PROV_SERIALIZED = 6 - CERT_STORE_PROV_FILENAME_A = 7 - CERT_STORE_PROV_FILENAME_W = 8 - CERT_STORE_PROV_FILENAME = CERT_STORE_PROV_FILENAME_W - CERT_STORE_PROV_SYSTEM_A = 9 - CERT_STORE_PROV_SYSTEM_W = 10 - CERT_STORE_PROV_SYSTEM = CERT_STORE_PROV_SYSTEM_W - CERT_STORE_PROV_COLLECTION = 11 + + CERT_STORE_PROV_MSG = 1 + + CERT_STORE_PROV_MEMORY = 2 + + CERT_STORE_PROV_FILE = 3 + + CERT_STORE_PROV_REG = 4 + + CERT_STORE_PROV_PKCS7 = 5 + + CERT_STORE_PROV_SERIALIZED = 6 + + CERT_STORE_PROV_FILENAME_A = 7 + + CERT_STORE_PROV_FILENAME_W = 8 + + CERT_STORE_PROV_FILENAME = CERT_STORE_PROV_FILENAME_W + + CERT_STORE_PROV_SYSTEM_A = 9 + + CERT_STORE_PROV_SYSTEM_W = 10 + + CERT_STORE_PROV_SYSTEM = CERT_STORE_PROV_SYSTEM_W + + CERT_STORE_PROV_COLLECTION = 11 + CERT_STORE_PROV_SYSTEM_REGISTRY_A = 12 + CERT_STORE_PROV_SYSTEM_REGISTRY_W = 13 - CERT_STORE_PROV_SYSTEM_REGISTRY = CERT_STORE_PROV_SYSTEM_REGISTRY_W - CERT_STORE_PROV_PHYSICAL_W = 14 - CERT_STORE_PROV_PHYSICAL = CERT_STORE_PROV_PHYSICAL_W - CERT_STORE_PROV_SMART_CARD_W = 15 - CERT_STORE_PROV_SMART_CARD = CERT_STORE_PROV_SMART_CARD_W - CERT_STORE_PROV_LDAP_W = 16 - CERT_STORE_PROV_LDAP = CERT_STORE_PROV_LDAP_W - CERT_STORE_PROV_PKCS12 = 17 + + CERT_STORE_PROV_SYSTEM_REGISTRY = CERT_STORE_PROV_SYSTEM_REGISTRY_W + + CERT_STORE_PROV_PHYSICAL_W = 14 + + CERT_STORE_PROV_PHYSICAL = CERT_STORE_PROV_PHYSICAL_W + + CERT_STORE_PROV_SMART_CARD_W = 15 + + CERT_STORE_PROV_SMART_CARD = CERT_STORE_PROV_SMART_CARD_W + + CERT_STORE_PROV_LDAP_W = 16 + + CERT_STORE_PROV_LDAP = CERT_STORE_PROV_LDAP_W + + CERT_STORE_PROV_PKCS12 = 17 /* store characteristics (low WORD of flag) for CertOpenStore function */ - CERT_STORE_NO_CRYPT_RELEASE_FLAG = 0x00000001 - CERT_STORE_SET_LOCALIZED_NAME_FLAG = 0x00000002 + + CERT_STORE_NO_CRYPT_RELEASE_FLAG = 0x00000001 + + CERT_STORE_SET_LOCALIZED_NAME_FLAG = 0x00000002 + CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG = 0x00000004 - CERT_STORE_DELETE_FLAG = 0x00000010 - CERT_STORE_UNSAFE_PHYSICAL_FLAG = 0x00000020 - CERT_STORE_SHARE_STORE_FLAG = 0x00000040 - CERT_STORE_SHARE_CONTEXT_FLAG = 0x00000080 - CERT_STORE_MANIFOLD_FLAG = 0x00000100 - CERT_STORE_ENUM_ARCHIVED_FLAG = 0x00000200 - CERT_STORE_UPDATE_KEYID_FLAG = 0x00000400 - CERT_STORE_BACKUP_RESTORE_FLAG = 0x00000800 - CERT_STORE_MAXIMUM_ALLOWED_FLAG = 0x00001000 - CERT_STORE_CREATE_NEW_FLAG = 0x00002000 - CERT_STORE_OPEN_EXISTING_FLAG = 0x00004000 - CERT_STORE_READONLY_FLAG = 0x00008000 + + CERT_STORE_DELETE_FLAG = 0x00000010 + + CERT_STORE_UNSAFE_PHYSICAL_FLAG = 0x00000020 + + CERT_STORE_SHARE_STORE_FLAG = 0x00000040 + + CERT_STORE_SHARE_CONTEXT_FLAG = 0x00000080 + + CERT_STORE_MANIFOLD_FLAG = 0x00000100 + + CERT_STORE_ENUM_ARCHIVED_FLAG = 0x00000200 + + CERT_STORE_UPDATE_KEYID_FLAG = 0x00000400 + + CERT_STORE_BACKUP_RESTORE_FLAG = 0x00000800 + + CERT_STORE_MAXIMUM_ALLOWED_FLAG = 0x00001000 + + CERT_STORE_CREATE_NEW_FLAG = 0x00002000 + + CERT_STORE_OPEN_EXISTING_FLAG = 0x00004000 + + CERT_STORE_READONLY_FLAG = 0x00008000 /* store locations (high WORD of flag) for CertOpenStore function */ - CERT_SYSTEM_STORE_CURRENT_USER = 0x00010000 - CERT_SYSTEM_STORE_LOCAL_MACHINE = 0x00020000 - CERT_SYSTEM_STORE_CURRENT_SERVICE = 0x00040000 - CERT_SYSTEM_STORE_SERVICES = 0x00050000 - CERT_SYSTEM_STORE_USERS = 0x00060000 - CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY = 0x00070000 + + CERT_SYSTEM_STORE_CURRENT_USER = 0x00010000 + + CERT_SYSTEM_STORE_LOCAL_MACHINE = 0x00020000 + + CERT_SYSTEM_STORE_CURRENT_SERVICE = 0x00040000 + + CERT_SYSTEM_STORE_SERVICES = 0x00050000 + + CERT_SYSTEM_STORE_USERS = 0x00060000 + + CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY = 0x00070000 + CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY = 0x00080000 - CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE = 0x00090000 - CERT_SYSTEM_STORE_UNPROTECTED_FLAG = 0x40000000 - CERT_SYSTEM_STORE_RELOCATE_FLAG = 0x80000000 + + CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE = 0x00090000 + + CERT_SYSTEM_STORE_UNPROTECTED_FLAG = 0x40000000 + + CERT_SYSTEM_STORE_RELOCATE_FLAG = 0x80000000 /* Miscellaneous high-WORD flags for CertOpenStore function */ - CERT_REGISTRY_STORE_REMOTE_FLAG = 0x00010000 - CERT_REGISTRY_STORE_SERIALIZED_FLAG = 0x00020000 - CERT_REGISTRY_STORE_ROAMING_FLAG = 0x00040000 + + CERT_REGISTRY_STORE_REMOTE_FLAG = 0x00010000 + + CERT_REGISTRY_STORE_SERIALIZED_FLAG = 0x00020000 + + CERT_REGISTRY_STORE_ROAMING_FLAG = 0x00040000 + CERT_REGISTRY_STORE_MY_IE_DIRTY_FLAG = 0x00080000 - CERT_REGISTRY_STORE_LM_GPT_FLAG = 0x01000000 - CERT_REGISTRY_STORE_CLIENT_GPT_FLAG = 0x80000000 - CERT_FILE_STORE_COMMIT_ENABLE_FLAG = 0x00010000 - CERT_LDAP_STORE_SIGN_FLAG = 0x00010000 - CERT_LDAP_STORE_AREC_EXCLUSIVE_FLAG = 0x00020000 - CERT_LDAP_STORE_OPENED_FLAG = 0x00040000 - CERT_LDAP_STORE_UNBIND_FLAG = 0x00080000 + + CERT_REGISTRY_STORE_LM_GPT_FLAG = 0x01000000 + + CERT_REGISTRY_STORE_CLIENT_GPT_FLAG = 0x80000000 + + CERT_FILE_STORE_COMMIT_ENABLE_FLAG = 0x00010000 + + CERT_LDAP_STORE_SIGN_FLAG = 0x00010000 + + CERT_LDAP_STORE_AREC_EXCLUSIVE_FLAG = 0x00020000 + + CERT_LDAP_STORE_OPENED_FLAG = 0x00040000 + + CERT_LDAP_STORE_UNBIND_FLAG = 0x00080000 /* addDisposition values for CertAddCertificateContextToStore function */ - CERT_STORE_ADD_NEW = 1 - CERT_STORE_ADD_USE_EXISTING = 2 - CERT_STORE_ADD_REPLACE_EXISTING = 3 - CERT_STORE_ADD_ALWAYS = 4 + + CERT_STORE_ADD_NEW = 1 + + CERT_STORE_ADD_USE_EXISTING = 2 + + CERT_STORE_ADD_REPLACE_EXISTING = 3 + + CERT_STORE_ADD_ALWAYS = 4 + CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES = 5 - CERT_STORE_ADD_NEWER = 6 - CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES = 7 + + CERT_STORE_ADD_NEWER = 6 + + CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES = 7 /* ErrorStatus values for CertTrustStatus struct */ - CERT_TRUST_NO_ERROR = 0x00000000 - CERT_TRUST_IS_NOT_TIME_VALID = 0x00000001 - CERT_TRUST_IS_REVOKED = 0x00000004 - CERT_TRUST_IS_NOT_SIGNATURE_VALID = 0x00000008 - CERT_TRUST_IS_NOT_VALID_FOR_USAGE = 0x00000010 - CERT_TRUST_IS_UNTRUSTED_ROOT = 0x00000020 - CERT_TRUST_REVOCATION_STATUS_UNKNOWN = 0x00000040 - CERT_TRUST_IS_CYCLIC = 0x00000080 - CERT_TRUST_INVALID_EXTENSION = 0x00000100 - CERT_TRUST_INVALID_POLICY_CONSTRAINTS = 0x00000200 - CERT_TRUST_INVALID_BASIC_CONSTRAINTS = 0x00000400 - CERT_TRUST_INVALID_NAME_CONSTRAINTS = 0x00000800 + + CERT_TRUST_NO_ERROR = 0x00000000 + + CERT_TRUST_IS_NOT_TIME_VALID = 0x00000001 + + CERT_TRUST_IS_REVOKED = 0x00000004 + + CERT_TRUST_IS_NOT_SIGNATURE_VALID = 0x00000008 + + CERT_TRUST_IS_NOT_VALID_FOR_USAGE = 0x00000010 + + CERT_TRUST_IS_UNTRUSTED_ROOT = 0x00000020 + + CERT_TRUST_REVOCATION_STATUS_UNKNOWN = 0x00000040 + + CERT_TRUST_IS_CYCLIC = 0x00000080 + + CERT_TRUST_INVALID_EXTENSION = 0x00000100 + + CERT_TRUST_INVALID_POLICY_CONSTRAINTS = 0x00000200 + + CERT_TRUST_INVALID_BASIC_CONSTRAINTS = 0x00000400 + + CERT_TRUST_INVALID_NAME_CONSTRAINTS = 0x00000800 + CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT = 0x00001000 - CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT = 0x00002000 + + CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT = 0x00002000 + CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT = 0x00004000 - CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT = 0x00008000 - CERT_TRUST_IS_PARTIAL_CHAIN = 0x00010000 - CERT_TRUST_CTL_IS_NOT_TIME_VALID = 0x00020000 - CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID = 0x00040000 - CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE = 0x00080000 - CERT_TRUST_HAS_WEAK_SIGNATURE = 0x00100000 - CERT_TRUST_IS_OFFLINE_REVOCATION = 0x01000000 - CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY = 0x02000000 - CERT_TRUST_IS_EXPLICIT_DISTRUST = 0x04000000 - CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT = 0x08000000 + + CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT = 0x00008000 + + CERT_TRUST_IS_PARTIAL_CHAIN = 0x00010000 + + CERT_TRUST_CTL_IS_NOT_TIME_VALID = 0x00020000 + + CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID = 0x00040000 + + CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE = 0x00080000 + + CERT_TRUST_HAS_WEAK_SIGNATURE = 0x00100000 + + CERT_TRUST_IS_OFFLINE_REVOCATION = 0x01000000 + + CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY = 0x02000000 + + CERT_TRUST_IS_EXPLICIT_DISTRUST = 0x04000000 + + CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT = 0x08000000 /* InfoStatus values for CertTrustStatus struct */ - CERT_TRUST_HAS_EXACT_MATCH_ISSUER = 0x00000001 - CERT_TRUST_HAS_KEY_MATCH_ISSUER = 0x00000002 - CERT_TRUST_HAS_NAME_MATCH_ISSUER = 0x00000004 - CERT_TRUST_IS_SELF_SIGNED = 0x00000008 - CERT_TRUST_HAS_PREFERRED_ISSUER = 0x00000100 - CERT_TRUST_HAS_ISSUANCE_CHAIN_POLICY = 0x00000400 - CERT_TRUST_HAS_VALID_NAME_CONSTRAINTS = 0x00000400 - CERT_TRUST_IS_PEER_TRUSTED = 0x00000800 - CERT_TRUST_HAS_CRL_VALIDITY_EXTENDED = 0x00001000 + + CERT_TRUST_HAS_EXACT_MATCH_ISSUER = 0x00000001 + + CERT_TRUST_HAS_KEY_MATCH_ISSUER = 0x00000002 + + CERT_TRUST_HAS_NAME_MATCH_ISSUER = 0x00000004 + + CERT_TRUST_IS_SELF_SIGNED = 0x00000008 + + CERT_TRUST_HAS_PREFERRED_ISSUER = 0x00000100 + + CERT_TRUST_HAS_ISSUANCE_CHAIN_POLICY = 0x00000400 + + CERT_TRUST_HAS_VALID_NAME_CONSTRAINTS = 0x00000400 + + CERT_TRUST_IS_PEER_TRUSTED = 0x00000800 + + CERT_TRUST_HAS_CRL_VALIDITY_EXTENDED = 0x00001000 + CERT_TRUST_IS_FROM_EXCLUSIVE_TRUST_STORE = 0x00002000 - CERT_TRUST_IS_CA_TRUSTED = 0x00004000 - CERT_TRUST_IS_COMPLEX_CHAIN = 0x00010000 + + CERT_TRUST_IS_CA_TRUSTED = 0x00004000 + + CERT_TRUST_IS_COMPLEX_CHAIN = 0x00010000 /* Certificate Information Flags */ - CERT_INFO_VERSION_FLAG = 1 - CERT_INFO_SERIAL_NUMBER_FLAG = 2 - CERT_INFO_SIGNATURE_ALGORITHM_FLAG = 3 - CERT_INFO_ISSUER_FLAG = 4 - CERT_INFO_NOT_BEFORE_FLAG = 5 - CERT_INFO_NOT_AFTER_FLAG = 6 - CERT_INFO_SUBJECT_FLAG = 7 + + CERT_INFO_VERSION_FLAG = 1 + + CERT_INFO_SERIAL_NUMBER_FLAG = 2 + + CERT_INFO_SIGNATURE_ALGORITHM_FLAG = 3 + + CERT_INFO_ISSUER_FLAG = 4 + + CERT_INFO_NOT_BEFORE_FLAG = 5 + + CERT_INFO_NOT_AFTER_FLAG = 6 + + CERT_INFO_SUBJECT_FLAG = 7 + CERT_INFO_SUBJECT_PUBLIC_KEY_INFO_FLAG = 8 - CERT_INFO_ISSUER_UNIQUE_ID_FLAG = 9 - CERT_INFO_SUBJECT_UNIQUE_ID_FLAG = 10 - CERT_INFO_EXTENSION_FLAG = 11 + + CERT_INFO_ISSUER_UNIQUE_ID_FLAG = 9 + + CERT_INFO_SUBJECT_UNIQUE_ID_FLAG = 10 + + CERT_INFO_EXTENSION_FLAG = 11 /* dwFindType for CertFindCertificateInStore */ - CERT_COMPARE_MASK = 0xFFFF - CERT_COMPARE_SHIFT = 16 - CERT_COMPARE_ANY = 0 - CERT_COMPARE_SHA1_HASH = 1 - CERT_COMPARE_NAME = 2 - CERT_COMPARE_ATTR = 3 - CERT_COMPARE_MD5_HASH = 4 - CERT_COMPARE_PROPERTY = 5 - CERT_COMPARE_PUBLIC_KEY = 6 - CERT_COMPARE_HASH = CERT_COMPARE_SHA1_HASH - CERT_COMPARE_NAME_STR_A = 7 - CERT_COMPARE_NAME_STR_W = 8 - CERT_COMPARE_KEY_SPEC = 9 - CERT_COMPARE_ENHKEY_USAGE = 10 - CERT_COMPARE_CTL_USAGE = CERT_COMPARE_ENHKEY_USAGE - CERT_COMPARE_SUBJECT_CERT = 11 - CERT_COMPARE_ISSUER_OF = 12 - CERT_COMPARE_EXISTING = 13 - CERT_COMPARE_SIGNATURE_HASH = 14 - CERT_COMPARE_KEY_IDENTIFIER = 15 - CERT_COMPARE_CERT_ID = 16 - CERT_COMPARE_CROSS_CERT_DIST_POINTS = 17 - CERT_COMPARE_PUBKEY_MD5_HASH = 18 - CERT_COMPARE_SUBJECT_INFO_ACCESS = 19 - CERT_COMPARE_HASH_STR = 20 - CERT_COMPARE_HAS_PRIVATE_KEY = 21 - CERT_FIND_ANY = (CERT_COMPARE_ANY << CERT_COMPARE_SHIFT) - CERT_FIND_SHA1_HASH = (CERT_COMPARE_SHA1_HASH << CERT_COMPARE_SHIFT) - CERT_FIND_MD5_HASH = (CERT_COMPARE_MD5_HASH << CERT_COMPARE_SHIFT) - CERT_FIND_SIGNATURE_HASH = (CERT_COMPARE_SIGNATURE_HASH << CERT_COMPARE_SHIFT) - CERT_FIND_KEY_IDENTIFIER = (CERT_COMPARE_KEY_IDENTIFIER << CERT_COMPARE_SHIFT) - CERT_FIND_HASH = CERT_FIND_SHA1_HASH - CERT_FIND_PROPERTY = (CERT_COMPARE_PROPERTY << CERT_COMPARE_SHIFT) - CERT_FIND_PUBLIC_KEY = (CERT_COMPARE_PUBLIC_KEY << CERT_COMPARE_SHIFT) - CERT_FIND_SUBJECT_NAME = (CERT_COMPARE_NAME<> 32 & 0xffffffff) + return ft + } type Win32finddata struct { - FileAttributes uint32 - CreationTime Filetime - LastAccessTime Filetime - LastWriteTime Filetime - FileSizeHigh uint32 - FileSizeLow uint32 - Reserved0 uint32 - Reserved1 uint32 - FileName [MAX_PATH - 1]uint16 + FileAttributes uint32 + + CreationTime Filetime + + LastAccessTime Filetime + + LastWriteTime Filetime + + FileSizeHigh uint32 + + FileSizeLow uint32 + + Reserved0 uint32 + + Reserved1 uint32 + + FileName [MAX_PATH - 1]uint16 + AlternateFileName [13]uint16 } // This is the actual system call structure. + // Win32finddata is what we committed to in Go 1. + type win32finddata1 struct { - FileAttributes uint32 - CreationTime Filetime - LastAccessTime Filetime - LastWriteTime Filetime - FileSizeHigh uint32 - FileSizeLow uint32 - Reserved0 uint32 - Reserved1 uint32 - FileName [MAX_PATH]uint16 + FileAttributes uint32 + + CreationTime Filetime + + LastAccessTime Filetime + + LastWriteTime Filetime + + FileSizeHigh uint32 + + FileSizeLow uint32 + + Reserved0 uint32 + + Reserved1 uint32 + + FileName [MAX_PATH]uint16 + AlternateFileName [14]uint16 // The Microsoft documentation for this struct¹ describes three additional + // fields: dwFileType, dwCreatorType, and wFinderFlags. However, those fields + // are empirically only present in the macOS port of the Win32 API,² and thus + // not needed for binaries built for Windows. + // + // ¹ https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-win32_find_dataw describe + // ² https://golang.org/issue/42637#issuecomment-760715755. + } func copyFindData(dst *Win32finddata, src *win32finddata1) { + dst.FileAttributes = src.FileAttributes + dst.CreationTime = src.CreationTime + dst.LastAccessTime = src.LastAccessTime + dst.LastWriteTime = src.LastWriteTime + dst.FileSizeHigh = src.FileSizeHigh + dst.FileSizeLow = src.FileSizeLow + dst.Reserved0 = src.Reserved0 + dst.Reserved1 = src.Reserved1 // The src is 1 element bigger than dst, but it must be NUL. + copy(dst.FileName[:], src.FileName[:]) + copy(dst.AlternateFileName[:], src.AlternateFileName[:]) + } type ByHandleFileInformation struct { - FileAttributes uint32 - CreationTime Filetime - LastAccessTime Filetime - LastWriteTime Filetime + FileAttributes uint32 + + CreationTime Filetime + + LastAccessTime Filetime + + LastWriteTime Filetime + VolumeSerialNumber uint32 - FileSizeHigh uint32 - FileSizeLow uint32 - NumberOfLinks uint32 - FileIndexHigh uint32 - FileIndexLow uint32 + + FileSizeHigh uint32 + + FileSizeLow uint32 + + NumberOfLinks uint32 + + FileIndexHigh uint32 + + FileIndexLow uint32 } const ( GetFileExInfoStandard = 0 + GetFileExMaxInfoLevel = 1 ) type Win32FileAttributeData struct { FileAttributes uint32 - CreationTime Filetime + + CreationTime Filetime + LastAccessTime Filetime - LastWriteTime Filetime - FileSizeHigh uint32 - FileSizeLow uint32 + + LastWriteTime Filetime + + FileSizeHigh uint32 + + FileSizeLow uint32 } // ShowWindow constants + const ( + // winuser.h - SW_HIDE = 0 - SW_NORMAL = 1 - SW_SHOWNORMAL = 1 - SW_SHOWMINIMIZED = 2 - SW_SHOWMAXIMIZED = 3 - SW_MAXIMIZE = 3 - SW_SHOWNOACTIVATE = 4 - SW_SHOW = 5 - SW_MINIMIZE = 6 + + SW_HIDE = 0 + + SW_NORMAL = 1 + + SW_SHOWNORMAL = 1 + + SW_SHOWMINIMIZED = 2 + + SW_SHOWMAXIMIZED = 3 + + SW_MAXIMIZE = 3 + + SW_SHOWNOACTIVATE = 4 + + SW_SHOW = 5 + + SW_MINIMIZE = 6 + SW_SHOWMINNOACTIVE = 7 - SW_SHOWNA = 8 - SW_RESTORE = 9 - SW_SHOWDEFAULT = 10 - SW_FORCEMINIMIZE = 11 + + SW_SHOWNA = 8 + + SW_RESTORE = 9 + + SW_SHOWDEFAULT = 10 + + SW_FORCEMINIMIZE = 11 ) type StartupInfo struct { - Cb uint32 - _ *uint16 - Desktop *uint16 - Title *uint16 - X uint32 - Y uint32 - XSize uint32 - YSize uint32 - XCountChars uint32 - YCountChars uint32 + Cb uint32 + + _ *uint16 + + Desktop *uint16 + + Title *uint16 + + X uint32 + + Y uint32 + + XSize uint32 + + YSize uint32 + + XCountChars uint32 + + YCountChars uint32 + FillAttribute uint32 - Flags uint32 - ShowWindow uint16 - _ uint16 - _ *byte - StdInput Handle - StdOutput Handle - StdErr Handle + + Flags uint32 + + ShowWindow uint16 + + _ uint16 + + _ *byte + + StdInput Handle + + StdOutput Handle + + StdErr Handle } type StartupInfoEx struct { StartupInfo + ProcThreadAttributeList *ProcThreadAttributeList } // ProcThreadAttributeList is a placeholder type to represent a PROC_THREAD_ATTRIBUTE_LIST. + // + // To create a *ProcThreadAttributeList, use NewProcThreadAttributeList, update + // it with ProcThreadAttributeListContainer.Update, free its memory using + // ProcThreadAttributeListContainer.Delete, and access the list itself using + // ProcThreadAttributeListContainer.List. + type ProcThreadAttributeList struct{} type ProcThreadAttributeListContainer struct { - data *ProcThreadAttributeList + data *ProcThreadAttributeList + pointers []unsafe.Pointer } type ProcessInformation struct { - Process Handle - Thread Handle + Process Handle + + Thread Handle + ProcessId uint32 - ThreadId uint32 + + ThreadId uint32 } type ProcessEntry32 struct { - Size uint32 - Usage uint32 - ProcessID uint32 - DefaultHeapID uintptr - ModuleID uint32 - Threads uint32 + Size uint32 + + Usage uint32 + + ProcessID uint32 + + DefaultHeapID uintptr + + ModuleID uint32 + + Threads uint32 + ParentProcessID uint32 - PriClassBase int32 - Flags uint32 - ExeFile [MAX_PATH]uint16 + + PriClassBase int32 + + Flags uint32 + + ExeFile [MAX_PATH]uint16 } type ThreadEntry32 struct { - Size uint32 - Usage uint32 - ThreadID uint32 + Size uint32 + + Usage uint32 + + ThreadID uint32 + OwnerProcessID uint32 - BasePri int32 - DeltaPri int32 - Flags uint32 + + BasePri int32 + + DeltaPri int32 + + Flags uint32 } type ModuleEntry32 struct { - Size uint32 - ModuleID uint32 - ProcessID uint32 + Size uint32 + + ModuleID uint32 + + ProcessID uint32 + GlblcntUsage uint32 + ProccntUsage uint32 - ModBaseAddr uintptr - ModBaseSize uint32 + + ModBaseAddr uintptr + + ModBaseSize uint32 + ModuleHandle Handle - Module [MAX_MODULE_NAME32 + 1]uint16 - ExePath [MAX_PATH]uint16 + + Module [MAX_MODULE_NAME32 + 1]uint16 + + ExePath [MAX_PATH]uint16 } const SizeofModuleEntry32 = unsafe.Sizeof(ModuleEntry32{}) type Systemtime struct { - Year uint16 - Month uint16 - DayOfWeek uint16 - Day uint16 - Hour uint16 - Minute uint16 - Second uint16 + Year uint16 + + Month uint16 + + DayOfWeek uint16 + + Day uint16 + + Hour uint16 + + Minute uint16 + + Second uint16 + Milliseconds uint16 } type Timezoneinformation struct { - Bias int32 + Bias int32 + StandardName [32]uint16 + StandardDate Systemtime + StandardBias int32 + DaylightName [32]uint16 + DaylightDate Systemtime + DaylightBias int32 } // Socket related. const ( - AF_UNSPEC = 0 - AF_UNIX = 1 - AF_INET = 2 - AF_NETBIOS = 17 - AF_INET6 = 23 - AF_IRDA = 26 - AF_BTH = 32 + AF_UNSPEC = 0 + + AF_UNIX = 1 + + AF_INET = 2 + + AF_NETBIOS = 17 + + AF_INET6 = 23 + + AF_IRDA = 26 + + AF_BTH = 32 + + SOCK_STREAM = 1 + + SOCK_DGRAM = 2 + + SOCK_RAW = 3 + + SOCK_RDM = 4 - SOCK_STREAM = 1 - SOCK_DGRAM = 2 - SOCK_RAW = 3 - SOCK_RDM = 4 SOCK_SEQPACKET = 5 - IPPROTO_IP = 0 - IPPROTO_ICMP = 1 - IPPROTO_IGMP = 2 - BTHPROTO_RFCOMM = 3 - IPPROTO_TCP = 6 - IPPROTO_UDP = 17 - IPPROTO_IPV6 = 41 - IPPROTO_ICMPV6 = 58 - IPPROTO_RM = 113 + IPPROTO_IP = 0 + + IPPROTO_ICMP = 1 + + IPPROTO_IGMP = 2 + + BTHPROTO_RFCOMM = 3 + + IPPROTO_TCP = 6 + + IPPROTO_UDP = 17 + + IPPROTO_IPV6 = 41 + + IPPROTO_ICMPV6 = 58 + + IPPROTO_RM = 113 + + SOL_SOCKET = 0xffff + + SO_REUSEADDR = 4 + + SO_KEEPALIVE = 8 + + SO_DONTROUTE = 16 + + SO_BROADCAST = 32 + + SO_LINGER = 128 + + SO_RCVBUF = 0x1002 + + SO_RCVTIMEO = 0x1006 + + SO_SNDBUF = 0x1001 + + SO_UPDATE_ACCEPT_CONTEXT = 0x700b - SOL_SOCKET = 0xffff - SO_REUSEADDR = 4 - SO_KEEPALIVE = 8 - SO_DONTROUTE = 16 - SO_BROADCAST = 32 - SO_LINGER = 128 - SO_RCVBUF = 0x1002 - SO_RCVTIMEO = 0x1006 - SO_SNDBUF = 0x1001 - SO_UPDATE_ACCEPT_CONTEXT = 0x700b SO_UPDATE_CONNECT_CONTEXT = 0x7010 - IOC_OUT = 0x40000000 - IOC_IN = 0x80000000 - IOC_VENDOR = 0x18000000 - IOC_INOUT = IOC_IN | IOC_OUT - IOC_WS2 = 0x08000000 + IOC_OUT = 0x40000000 + + IOC_IN = 0x80000000 + + IOC_VENDOR = 0x18000000 + + IOC_INOUT = IOC_IN | IOC_OUT + + IOC_WS2 = 0x08000000 + SIO_GET_EXTENSION_FUNCTION_POINTER = IOC_INOUT | IOC_WS2 | 6 - SIO_KEEPALIVE_VALS = IOC_IN | IOC_VENDOR | 4 - SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12 + + SIO_KEEPALIVE_VALS = IOC_IN | IOC_VENDOR | 4 + + SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12 // cf. http://support.microsoft.com/default.aspx?scid=kb;en-us;257460 - IP_HDRINCL = 0x2 - IP_TOS = 0x3 - IP_TTL = 0x4 - IP_MULTICAST_IF = 0x9 - IP_MULTICAST_TTL = 0xa - IP_MULTICAST_LOOP = 0xb - IP_ADD_MEMBERSHIP = 0xc + IP_HDRINCL = 0x2 + + IP_TOS = 0x3 + + IP_TTL = 0x4 + + IP_MULTICAST_IF = 0x9 + + IP_MULTICAST_TTL = 0xa + + IP_MULTICAST_LOOP = 0xb + + IP_ADD_MEMBERSHIP = 0xc + IP_DROP_MEMBERSHIP = 0xd - IP_PKTINFO = 0x13 - IPV6_V6ONLY = 0x1b - IPV6_UNICAST_HOPS = 0x4 - IPV6_MULTICAST_IF = 0x9 + IP_PKTINFO = 0x13 + + IPV6_V6ONLY = 0x1b + + IPV6_UNICAST_HOPS = 0x4 + + IPV6_MULTICAST_IF = 0x9 + IPV6_MULTICAST_HOPS = 0xa + IPV6_MULTICAST_LOOP = 0xb - IPV6_JOIN_GROUP = 0xc - IPV6_LEAVE_GROUP = 0xd - IPV6_PKTINFO = 0x13 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 + IPV6_JOIN_GROUP = 0xc + + IPV6_LEAVE_GROUP = 0xd + + IPV6_PKTINFO = 0x13 + + MSG_OOB = 0x1 + + MSG_PEEK = 0x2 + MSG_DONTROUTE = 0x4 - MSG_WAITALL = 0x8 - MSG_TRUNC = 0x0100 + MSG_WAITALL = 0x8 + + MSG_TRUNC = 0x0100 + MSG_CTRUNC = 0x0200 - MSG_BCAST = 0x0400 - MSG_MCAST = 0x0800 + + MSG_BCAST = 0x0400 + + MSG_MCAST = 0x0800 SOMAXCONN = 0x7fffffff - TCP_NODELAY = 1 - TCP_EXPEDITED_1122 = 2 - TCP_KEEPALIVE = 3 - TCP_MAXSEG = 4 - TCP_MAXRT = 5 - TCP_STDURG = 6 - TCP_NOURG = 7 - TCP_ATMARK = 8 - TCP_NOSYNRETRIES = 9 - TCP_TIMESTAMPS = 10 - TCP_OFFLOAD_PREFERENCE = 11 - TCP_CONGESTION_ALGORITHM = 12 - TCP_DELAY_FIN_ACK = 13 - TCP_MAXRTMS = 14 - TCP_FASTOPEN = 15 - TCP_KEEPCNT = 16 - TCP_KEEPIDLE = TCP_KEEPALIVE - TCP_KEEPINTVL = 17 - TCP_FAIL_CONNECT_ON_ICMP_ERROR = 18 - TCP_ICMP_ERROR_INFO = 19 + TCP_NODELAY = 1 + + TCP_EXPEDITED_1122 = 2 + + TCP_KEEPALIVE = 3 + + TCP_MAXSEG = 4 + + TCP_MAXRT = 5 + + TCP_STDURG = 6 + + TCP_NOURG = 7 + + TCP_ATMARK = 8 + + TCP_NOSYNRETRIES = 9 + + TCP_TIMESTAMPS = 10 + + TCP_OFFLOAD_PREFERENCE = 11 + + TCP_CONGESTION_ALGORITHM = 12 + + TCP_DELAY_FIN_ACK = 13 + + TCP_MAXRTMS = 14 + + TCP_FASTOPEN = 15 + + TCP_KEEPCNT = 16 + + TCP_KEEPIDLE = TCP_KEEPALIVE + + TCP_KEEPINTVL = 17 + + TCP_FAIL_CONNECT_ON_ICMP_ERROR = 18 + + TCP_ICMP_ERROR_INFO = 19 + + UDP_NOCHECKSUM = 1 + + UDP_SEND_MSG_SIZE = 2 - UDP_NOCHECKSUM = 1 - UDP_SEND_MSG_SIZE = 2 UDP_RECV_MAX_COALESCED_SIZE = 3 - UDP_CHECKSUM_COVERAGE = 20 + + UDP_CHECKSUM_COVERAGE = 20 UDP_COALESCED_INFO = 3 - SHUT_RD = 0 - SHUT_WR = 1 + SHUT_RD = 0 + + SHUT_WR = 1 + SHUT_RDWR = 2 WSADESCRIPTION_LEN = 256 - WSASYS_STATUS_LEN = 128 + + WSASYS_STATUS_LEN = 128 ) type WSABuf struct { Len uint32 + Buf *byte } type WSAMsg struct { - Name *syscall.RawSockaddrAny - Namelen int32 - Buffers *WSABuf + Name *syscall.RawSockaddrAny + + Namelen int32 + + Buffers *WSABuf + BufferCount uint32 - Control WSABuf - Flags uint32 + + Control WSABuf + + Flags uint32 } // Flags for WSASocket + const ( - WSA_FLAG_OVERLAPPED = 0x01 - WSA_FLAG_MULTIPOINT_C_ROOT = 0x02 - WSA_FLAG_MULTIPOINT_C_LEAF = 0x04 - WSA_FLAG_MULTIPOINT_D_ROOT = 0x08 - WSA_FLAG_MULTIPOINT_D_LEAF = 0x10 + WSA_FLAG_OVERLAPPED = 0x01 + + WSA_FLAG_MULTIPOINT_C_ROOT = 0x02 + + WSA_FLAG_MULTIPOINT_C_LEAF = 0x04 + + WSA_FLAG_MULTIPOINT_D_ROOT = 0x08 + + WSA_FLAG_MULTIPOINT_D_LEAF = 0x10 + WSA_FLAG_ACCESS_SYSTEM_SECURITY = 0x40 - WSA_FLAG_NO_HANDLE_INHERIT = 0x80 - WSA_FLAG_REGISTERED_IO = 0x100 + + WSA_FLAG_NO_HANDLE_INHERIT = 0x80 + + WSA_FLAG_REGISTERED_IO = 0x100 ) // Invented values to support what package os expects. + const ( - S_IFMT = 0x1f000 - S_IFIFO = 0x1000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFBLK = 0x6000 - S_IFREG = 0x8000 - S_IFLNK = 0xa000 + S_IFMT = 0x1f000 + + S_IFIFO = 0x1000 + + S_IFCHR = 0x2000 + + S_IFDIR = 0x4000 + + S_IFBLK = 0x6000 + + S_IFREG = 0x8000 + + S_IFLNK = 0xa000 + S_IFSOCK = 0xc000 - S_ISUID = 0x800 - S_ISGID = 0x400 - S_ISVTX = 0x200 - S_IRUSR = 0x100 + + S_ISUID = 0x800 + + S_ISGID = 0x400 + + S_ISVTX = 0x200 + + S_IRUSR = 0x100 + S_IWRITE = 0x80 - S_IWUSR = 0x80 - S_IXUSR = 0x40 + + S_IWUSR = 0x80 + + S_IXUSR = 0x40 ) const ( - FILE_TYPE_CHAR = 0x0002 - FILE_TYPE_DISK = 0x0001 - FILE_TYPE_PIPE = 0x0003 - FILE_TYPE_REMOTE = 0x8000 + FILE_TYPE_CHAR = 0x0002 + + FILE_TYPE_DISK = 0x0001 + + FILE_TYPE_PIPE = 0x0003 + + FILE_TYPE_REMOTE = 0x8000 + FILE_TYPE_UNKNOWN = 0x0000 ) type Hostent struct { - Name *byte - Aliases **byte + Name *byte + + Aliases **byte + AddrType uint16 - Length uint16 + + Length uint16 + AddrList **byte } type Protoent struct { - Name *byte + Name *byte + Aliases **byte - Proto uint16 + + Proto uint16 } const ( - DNS_TYPE_A = 0x0001 - DNS_TYPE_NS = 0x0002 - DNS_TYPE_MD = 0x0003 - DNS_TYPE_MF = 0x0004 - DNS_TYPE_CNAME = 0x0005 - DNS_TYPE_SOA = 0x0006 - DNS_TYPE_MB = 0x0007 - DNS_TYPE_MG = 0x0008 - DNS_TYPE_MR = 0x0009 - DNS_TYPE_NULL = 0x000a - DNS_TYPE_WKS = 0x000b - DNS_TYPE_PTR = 0x000c - DNS_TYPE_HINFO = 0x000d - DNS_TYPE_MINFO = 0x000e - DNS_TYPE_MX = 0x000f - DNS_TYPE_TEXT = 0x0010 - DNS_TYPE_RP = 0x0011 - DNS_TYPE_AFSDB = 0x0012 - DNS_TYPE_X25 = 0x0013 - DNS_TYPE_ISDN = 0x0014 - DNS_TYPE_RT = 0x0015 - DNS_TYPE_NSAP = 0x0016 + DNS_TYPE_A = 0x0001 + + DNS_TYPE_NS = 0x0002 + + DNS_TYPE_MD = 0x0003 + + DNS_TYPE_MF = 0x0004 + + DNS_TYPE_CNAME = 0x0005 + + DNS_TYPE_SOA = 0x0006 + + DNS_TYPE_MB = 0x0007 + + DNS_TYPE_MG = 0x0008 + + DNS_TYPE_MR = 0x0009 + + DNS_TYPE_NULL = 0x000a + + DNS_TYPE_WKS = 0x000b + + DNS_TYPE_PTR = 0x000c + + DNS_TYPE_HINFO = 0x000d + + DNS_TYPE_MINFO = 0x000e + + DNS_TYPE_MX = 0x000f + + DNS_TYPE_TEXT = 0x0010 + + DNS_TYPE_RP = 0x0011 + + DNS_TYPE_AFSDB = 0x0012 + + DNS_TYPE_X25 = 0x0013 + + DNS_TYPE_ISDN = 0x0014 + + DNS_TYPE_RT = 0x0015 + + DNS_TYPE_NSAP = 0x0016 + DNS_TYPE_NSAPPTR = 0x0017 - DNS_TYPE_SIG = 0x0018 - DNS_TYPE_KEY = 0x0019 - DNS_TYPE_PX = 0x001a - DNS_TYPE_GPOS = 0x001b - DNS_TYPE_AAAA = 0x001c - DNS_TYPE_LOC = 0x001d - DNS_TYPE_NXT = 0x001e - DNS_TYPE_EID = 0x001f - DNS_TYPE_NIMLOC = 0x0020 - DNS_TYPE_SRV = 0x0021 - DNS_TYPE_ATMA = 0x0022 - DNS_TYPE_NAPTR = 0x0023 - DNS_TYPE_KX = 0x0024 - DNS_TYPE_CERT = 0x0025 - DNS_TYPE_A6 = 0x0026 - DNS_TYPE_DNAME = 0x0027 - DNS_TYPE_SINK = 0x0028 - DNS_TYPE_OPT = 0x0029 - DNS_TYPE_DS = 0x002B - DNS_TYPE_RRSIG = 0x002E - DNS_TYPE_NSEC = 0x002F - DNS_TYPE_DNSKEY = 0x0030 - DNS_TYPE_DHCID = 0x0031 - DNS_TYPE_UINFO = 0x0064 - DNS_TYPE_UID = 0x0065 - DNS_TYPE_GID = 0x0066 - DNS_TYPE_UNSPEC = 0x0067 - DNS_TYPE_ADDRS = 0x00f8 - DNS_TYPE_TKEY = 0x00f9 - DNS_TYPE_TSIG = 0x00fa - DNS_TYPE_IXFR = 0x00fb - DNS_TYPE_AXFR = 0x00fc - DNS_TYPE_MAILB = 0x00fd - DNS_TYPE_MAILA = 0x00fe - DNS_TYPE_ALL = 0x00ff - DNS_TYPE_ANY = 0x00ff - DNS_TYPE_WINS = 0xff01 - DNS_TYPE_WINSR = 0xff02 - DNS_TYPE_NBSTAT = 0xff01 + + DNS_TYPE_SIG = 0x0018 + + DNS_TYPE_KEY = 0x0019 + + DNS_TYPE_PX = 0x001a + + DNS_TYPE_GPOS = 0x001b + + DNS_TYPE_AAAA = 0x001c + + DNS_TYPE_LOC = 0x001d + + DNS_TYPE_NXT = 0x001e + + DNS_TYPE_EID = 0x001f + + DNS_TYPE_NIMLOC = 0x0020 + + DNS_TYPE_SRV = 0x0021 + + DNS_TYPE_ATMA = 0x0022 + + DNS_TYPE_NAPTR = 0x0023 + + DNS_TYPE_KX = 0x0024 + + DNS_TYPE_CERT = 0x0025 + + DNS_TYPE_A6 = 0x0026 + + DNS_TYPE_DNAME = 0x0027 + + DNS_TYPE_SINK = 0x0028 + + DNS_TYPE_OPT = 0x0029 + + DNS_TYPE_DS = 0x002B + + DNS_TYPE_RRSIG = 0x002E + + DNS_TYPE_NSEC = 0x002F + + DNS_TYPE_DNSKEY = 0x0030 + + DNS_TYPE_DHCID = 0x0031 + + DNS_TYPE_UINFO = 0x0064 + + DNS_TYPE_UID = 0x0065 + + DNS_TYPE_GID = 0x0066 + + DNS_TYPE_UNSPEC = 0x0067 + + DNS_TYPE_ADDRS = 0x00f8 + + DNS_TYPE_TKEY = 0x00f9 + + DNS_TYPE_TSIG = 0x00fa + + DNS_TYPE_IXFR = 0x00fb + + DNS_TYPE_AXFR = 0x00fc + + DNS_TYPE_MAILB = 0x00fd + + DNS_TYPE_MAILA = 0x00fe + + DNS_TYPE_ALL = 0x00ff + + DNS_TYPE_ANY = 0x00ff + + DNS_TYPE_WINS = 0xff01 + + DNS_TYPE_WINSR = 0xff02 + + DNS_TYPE_NBSTAT = 0xff01 ) const ( + // flags inside DNSRecord.Dw - DnsSectionQuestion = 0x0000 - DnsSectionAnswer = 0x0001 - DnsSectionAuthority = 0x0002 + + DnsSectionQuestion = 0x0000 + + DnsSectionAnswer = 0x0001 + + DnsSectionAuthority = 0x0002 + DnsSectionAdditional = 0x0003 ) const ( - // flags of WSALookupService - LUP_DEEP = 0x0001 - LUP_CONTAINERS = 0x0002 - LUP_NOCONTAINERS = 0x0004 - LUP_NEAREST = 0x0008 - LUP_RETURN_NAME = 0x0010 - LUP_RETURN_TYPE = 0x0020 - LUP_RETURN_VERSION = 0x0040 - LUP_RETURN_COMMENT = 0x0080 - LUP_RETURN_ADDR = 0x0100 - LUP_RETURN_BLOB = 0x0200 - LUP_RETURN_ALIASES = 0x0400 - LUP_RETURN_QUERY_STRING = 0x0800 - LUP_RETURN_ALL = 0x0FF0 - LUP_RES_SERVICE = 0x8000 - LUP_FLUSHCACHE = 0x1000 + // flags of WSALookupService + + LUP_DEEP = 0x0001 + + LUP_CONTAINERS = 0x0002 + + LUP_NOCONTAINERS = 0x0004 + + LUP_NEAREST = 0x0008 + + LUP_RETURN_NAME = 0x0010 + + LUP_RETURN_TYPE = 0x0020 + + LUP_RETURN_VERSION = 0x0040 + + LUP_RETURN_COMMENT = 0x0080 + + LUP_RETURN_ADDR = 0x0100 + + LUP_RETURN_BLOB = 0x0200 + + LUP_RETURN_ALIASES = 0x0400 + + LUP_RETURN_QUERY_STRING = 0x0800 + + LUP_RETURN_ALL = 0x0FF0 + + LUP_RES_SERVICE = 0x8000 + + LUP_FLUSHCACHE = 0x1000 + LUP_FLUSHPREVIOUS = 0x2000 - LUP_NON_AUTHORITATIVE = 0x4000 - LUP_SECURE = 0x8000 - LUP_RETURN_PREFERRED_NAMES = 0x10000 - LUP_DNS_ONLY = 0x20000 + LUP_NON_AUTHORITATIVE = 0x4000 + + LUP_SECURE = 0x8000 + + LUP_RETURN_PREFERRED_NAMES = 0x10000 + + LUP_DNS_ONLY = 0x20000 + + LUP_ADDRCONFIG = 0x100000 + + LUP_DUAL_ADDR = 0x200000 + + LUP_FILESERVER = 0x400000 - LUP_ADDRCONFIG = 0x100000 - LUP_DUAL_ADDR = 0x200000 - LUP_FILESERVER = 0x400000 LUP_DISABLE_IDN_ENCODING = 0x00800000 - LUP_API_ANSI = 0x01000000 + + LUP_API_ANSI = 0x01000000 LUP_RESOLUTION_HANDLE = 0x80000000 ) const ( + // values of WSAQUERYSET's namespace - NS_ALL = 0 - NS_DNS = 12 - NS_NLA = 15 - NS_BTH = 16 - NS_EMAIL = 37 - NS_PNRPNAME = 38 + + NS_ALL = 0 + + NS_DNS = 12 + + NS_NLA = 15 + + NS_BTH = 16 + + NS_EMAIL = 37 + + NS_PNRPNAME = 38 + NS_PNRPCLOUD = 39 ) type DNSSRVData struct { - Target *uint16 + Target *uint16 + Priority uint16 - Weight uint16 - Port uint16 - Pad uint16 + + Weight uint16 + + Port uint16 + + Pad uint16 } type DNSPTRData struct { @@ -1329,62 +2292,88 @@ type DNSPTRData struct { type DNSMXData struct { NameExchange *uint16 - Preference uint16 - Pad uint16 + + Preference uint16 + + Pad uint16 } type DNSTXTData struct { StringCount uint16 + StringArray [1]*uint16 } type DNSRecord struct { - Next *DNSRecord - Name *uint16 - Type uint16 - Length uint16 - Dw uint32 - Ttl uint32 + Next *DNSRecord + + Name *uint16 + + Type uint16 + + Length uint16 + + Dw uint32 + + Ttl uint32 + Reserved uint32 - Data [40]byte + + Data [40]byte } const ( - TF_DISCONNECT = 1 - TF_REUSE_SOCKET = 2 - TF_WRITE_BEHIND = 4 + TF_DISCONNECT = 1 + + TF_REUSE_SOCKET = 2 + + TF_WRITE_BEHIND = 4 + TF_USE_DEFAULT_WORKER = 0 - TF_USE_SYSTEM_THREAD = 16 - TF_USE_KERNEL_APC = 32 + + TF_USE_SYSTEM_THREAD = 16 + + TF_USE_KERNEL_APC = 32 ) type TransmitFileBuffers struct { - Head uintptr + Head uintptr + HeadLength uint32 - Tail uintptr + + Tail uintptr + TailLength uint32 } const ( - IFF_UP = 1 - IFF_BROADCAST = 2 - IFF_LOOPBACK = 4 + IFF_UP = 1 + + IFF_BROADCAST = 2 + + IFF_LOOPBACK = 4 + IFF_POINTTOPOINT = 8 - IFF_MULTICAST = 16 + + IFF_MULTICAST = 16 ) const SIO_GET_INTERFACE_LIST = 0x4004747F // TODO(mattn): SockaddrGen is union of sockaddr/sockaddr_in/sockaddr_in6_old. + // will be fixed to change variable type as suitable. type SockaddrGen [24]byte type InterfaceInfo struct { - Flags uint32 - Address SockaddrGen + Flags uint32 + + Address SockaddrGen + BroadcastAddress SockaddrGen - Netmask SockaddrGen + + Netmask SockaddrGen } type IpAddressString struct { @@ -1394,858 +2383,1394 @@ type IpAddressString struct { type IpMaskString IpAddressString type IpAddrString struct { - Next *IpAddrString + Next *IpAddrString + IpAddress IpAddressString - IpMask IpMaskString - Context uint32 + + IpMask IpMaskString + + Context uint32 } const MAX_ADAPTER_NAME_LENGTH = 256 + const MAX_ADAPTER_DESCRIPTION_LENGTH = 128 + const MAX_ADAPTER_ADDRESS_LENGTH = 8 type IpAdapterInfo struct { - Next *IpAdapterInfo - ComboIndex uint32 - AdapterName [MAX_ADAPTER_NAME_LENGTH + 4]byte - Description [MAX_ADAPTER_DESCRIPTION_LENGTH + 4]byte - AddressLength uint32 - Address [MAX_ADAPTER_ADDRESS_LENGTH]byte - Index uint32 - Type uint32 - DhcpEnabled uint32 - CurrentIpAddress *IpAddrString - IpAddressList IpAddrString - GatewayList IpAddrString - DhcpServer IpAddrString - HaveWins bool - PrimaryWinsServer IpAddrString + Next *IpAdapterInfo + + ComboIndex uint32 + + AdapterName [MAX_ADAPTER_NAME_LENGTH + 4]byte + + Description [MAX_ADAPTER_DESCRIPTION_LENGTH + 4]byte + + AddressLength uint32 + + Address [MAX_ADAPTER_ADDRESS_LENGTH]byte + + Index uint32 + + Type uint32 + + DhcpEnabled uint32 + + CurrentIpAddress *IpAddrString + + IpAddressList IpAddrString + + GatewayList IpAddrString + + DhcpServer IpAddrString + + HaveWins bool + + PrimaryWinsServer IpAddrString + SecondaryWinsServer IpAddrString - LeaseObtained int64 - LeaseExpires int64 + + LeaseObtained int64 + + LeaseExpires int64 } const MAXLEN_PHYSADDR = 8 + const MAX_INTERFACE_NAME_LEN = 256 + const MAXLEN_IFDESCR = 256 type MibIfRow struct { - Name [MAX_INTERFACE_NAME_LEN]uint16 - Index uint32 - Type uint32 - Mtu uint32 - Speed uint32 - PhysAddrLen uint32 - PhysAddr [MAXLEN_PHYSADDR]byte - AdminStatus uint32 - OperStatus uint32 - LastChange uint32 - InOctets uint32 - InUcastPkts uint32 - InNUcastPkts uint32 - InDiscards uint32 - InErrors uint32 + Name [MAX_INTERFACE_NAME_LEN]uint16 + + Index uint32 + + Type uint32 + + Mtu uint32 + + Speed uint32 + + PhysAddrLen uint32 + + PhysAddr [MAXLEN_PHYSADDR]byte + + AdminStatus uint32 + + OperStatus uint32 + + LastChange uint32 + + InOctets uint32 + + InUcastPkts uint32 + + InNUcastPkts uint32 + + InDiscards uint32 + + InErrors uint32 + InUnknownProtos uint32 - OutOctets uint32 - OutUcastPkts uint32 - OutNUcastPkts uint32 - OutDiscards uint32 - OutErrors uint32 - OutQLen uint32 - DescrLen uint32 - Descr [MAXLEN_IFDESCR]byte + + OutOctets uint32 + + OutUcastPkts uint32 + + OutNUcastPkts uint32 + + OutDiscards uint32 + + OutErrors uint32 + + OutQLen uint32 + + DescrLen uint32 + + Descr [MAXLEN_IFDESCR]byte } type CertInfo struct { - Version uint32 - SerialNumber CryptIntegerBlob - SignatureAlgorithm CryptAlgorithmIdentifier - Issuer CertNameBlob - NotBefore Filetime - NotAfter Filetime - Subject CertNameBlob + Version uint32 + + SerialNumber CryptIntegerBlob + + SignatureAlgorithm CryptAlgorithmIdentifier + + Issuer CertNameBlob + + NotBefore Filetime + + NotAfter Filetime + + Subject CertNameBlob + SubjectPublicKeyInfo CertPublicKeyInfo - IssuerUniqueId CryptBitBlob - SubjectUniqueId CryptBitBlob - CountExtensions uint32 - Extensions *CertExtension + + IssuerUniqueId CryptBitBlob + + SubjectUniqueId CryptBitBlob + + CountExtensions uint32 + + Extensions *CertExtension } type CertExtension struct { - ObjId *byte + ObjId *byte + Critical int32 - Value CryptObjidBlob + + Value CryptObjidBlob } type CryptAlgorithmIdentifier struct { - ObjId *byte + ObjId *byte + Parameters CryptObjidBlob } type CertPublicKeyInfo struct { Algorithm CryptAlgorithmIdentifier + PublicKey CryptBitBlob } type DataBlob struct { Size uint32 + Data *byte } + type CryptIntegerBlob DataBlob + type CryptUintBlob DataBlob + type CryptObjidBlob DataBlob + type CertNameBlob DataBlob + type CertRdnValueBlob DataBlob + type CertBlob DataBlob + type CrlBlob DataBlob + type CryptDataBlob DataBlob + type CryptHashBlob DataBlob + type CryptDigestBlob DataBlob + type CryptDerBlob DataBlob + type CryptAttrBlob DataBlob type CryptBitBlob struct { - Size uint32 - Data *byte + Size uint32 + + Data *byte + UnusedBits uint32 } type CertContext struct { EncodingType uint32 - EncodedCert *byte - Length uint32 - CertInfo *CertInfo - Store Handle + + EncodedCert *byte + + Length uint32 + + CertInfo *CertInfo + + Store Handle } type CertChainContext struct { - Size uint32 - TrustStatus CertTrustStatus - ChainCount uint32 - Chains **CertSimpleChain - LowerQualityChainCount uint32 - LowerQualityChains **CertChainContext + Size uint32 + + TrustStatus CertTrustStatus + + ChainCount uint32 + + Chains **CertSimpleChain + + LowerQualityChainCount uint32 + + LowerQualityChains **CertChainContext + HasRevocationFreshnessTime uint32 - RevocationFreshnessTime uint32 + + RevocationFreshnessTime uint32 } type CertTrustListInfo struct { + // Not implemented + } type CertSimpleChain struct { - Size uint32 - TrustStatus CertTrustStatus - NumElements uint32 - Elements **CertChainElement - TrustListInfo *CertTrustListInfo + Size uint32 + + TrustStatus CertTrustStatus + + NumElements uint32 + + Elements **CertChainElement + + TrustListInfo *CertTrustListInfo + HasRevocationFreshnessTime uint32 - RevocationFreshnessTime uint32 + + RevocationFreshnessTime uint32 } type CertChainElement struct { - Size uint32 - CertContext *CertContext - TrustStatus CertTrustStatus - RevocationInfo *CertRevocationInfo - IssuanceUsage *CertEnhKeyUsage - ApplicationUsage *CertEnhKeyUsage + Size uint32 + + CertContext *CertContext + + TrustStatus CertTrustStatus + + RevocationInfo *CertRevocationInfo + + IssuanceUsage *CertEnhKeyUsage + + ApplicationUsage *CertEnhKeyUsage + ExtendedErrorInfo *uint16 } type CertRevocationCrlInfo struct { + // Not implemented + } type CertRevocationInfo struct { - Size uint32 + Size uint32 + RevocationResult uint32 - RevocationOid *byte - OidSpecificInfo Pointer + + RevocationOid *byte + + OidSpecificInfo Pointer + HasFreshnessTime uint32 - FreshnessTime uint32 - CrlInfo *CertRevocationCrlInfo + + FreshnessTime uint32 + + CrlInfo *CertRevocationCrlInfo } type CertTrustStatus struct { ErrorStatus uint32 - InfoStatus uint32 + + InfoStatus uint32 } type CertUsageMatch struct { - Type uint32 + Type uint32 + Usage CertEnhKeyUsage } type CertEnhKeyUsage struct { - Length uint32 + Length uint32 + UsageIdentifiers **byte } type CertChainPara struct { - Size uint32 - RequestedUsage CertUsageMatch - RequstedIssuancePolicy CertUsageMatch - URLRetrievalTimeout uint32 + Size uint32 + + RequestedUsage CertUsageMatch + + RequstedIssuancePolicy CertUsageMatch + + URLRetrievalTimeout uint32 + CheckRevocationFreshnessTime uint32 - RevocationFreshnessTime uint32 - CacheResync *Filetime + + RevocationFreshnessTime uint32 + + CacheResync *Filetime } type CertChainPolicyPara struct { - Size uint32 - Flags uint32 + Size uint32 + + Flags uint32 + ExtraPolicyPara Pointer } type SSLExtraCertChainPolicyPara struct { - Size uint32 - AuthType uint32 - Checks uint32 + Size uint32 + + AuthType uint32 + + Checks uint32 + ServerName *uint16 } type CertChainPolicyStatus struct { - Size uint32 - Error uint32 - ChainIndex uint32 - ElementIndex uint32 + Size uint32 + + Error uint32 + + ChainIndex uint32 + + ElementIndex uint32 + ExtraPolicyStatus Pointer } type CertPolicyInfo struct { - Identifier *byte + Identifier *byte + CountQualifiers uint32 - Qualifiers *CertPolicyQualifierInfo + + Qualifiers *CertPolicyQualifierInfo } type CertPoliciesInfo struct { - Count uint32 + Count uint32 + PolicyInfos *CertPolicyInfo } type CertPolicyQualifierInfo struct { + // Not implemented + } type CertStrongSignPara struct { - Size uint32 - InfoChoice uint32 + Size uint32 + + InfoChoice uint32 + InfoOrSerializedInfoOrOID unsafe.Pointer } type CryptProtectPromptStruct struct { - Size uint32 + Size uint32 + PromptFlags uint32 - App HWND - Prompt *uint16 + + App HWND + + Prompt *uint16 } type CertChainFindByIssuerPara struct { - Size uint32 - UsageIdentifier *byte - KeySpec uint32 + Size uint32 + + UsageIdentifier *byte + + KeySpec uint32 + AcquirePrivateKeyFlags uint32 - IssuerCount uint32 - Issuer Pointer - FindCallback Pointer - FindArg Pointer - IssuerChainIndex *uint32 - IssuerElementIndex *uint32 + + IssuerCount uint32 + + Issuer Pointer + + FindCallback Pointer + + FindArg Pointer + + IssuerChainIndex *uint32 + + IssuerElementIndex *uint32 } type WinTrustData struct { - Size uint32 - PolicyCallbackData uintptr - SIPClientData uintptr - UIChoice uint32 - RevocationChecks uint32 - UnionChoice uint32 + Size uint32 + + PolicyCallbackData uintptr + + SIPClientData uintptr + + UIChoice uint32 + + RevocationChecks uint32 + + UnionChoice uint32 + FileOrCatalogOrBlobOrSgnrOrCert unsafe.Pointer - StateAction uint32 - StateData Handle - URLReference *uint16 - ProvFlags uint32 - UIContext uint32 - SignatureSettings *WinTrustSignatureSettings + + StateAction uint32 + + StateData Handle + + URLReference *uint16 + + ProvFlags uint32 + + UIContext uint32 + + SignatureSettings *WinTrustSignatureSettings } type WinTrustFileInfo struct { - Size uint32 - FilePath *uint16 - File Handle + Size uint32 + + FilePath *uint16 + + File Handle + KnownSubject *GUID } type WinTrustSignatureSettings struct { - Size uint32 - Index uint32 - Flags uint32 - SecondarySigs uint32 + Size uint32 + + Index uint32 + + Flags uint32 + + SecondarySigs uint32 + VerifiedSigIndex uint32 - CryptoPolicy *CertStrongSignPara + + CryptoPolicy *CertStrongSignPara } const ( + // do not reorder + HKEY_CLASSES_ROOT = 0x80000000 + iota + HKEY_CURRENT_USER + HKEY_LOCAL_MACHINE + HKEY_USERS + HKEY_PERFORMANCE_DATA + HKEY_CURRENT_CONFIG + HKEY_DYN_DATA - KEY_QUERY_VALUE = 1 - KEY_SET_VALUE = 2 - KEY_CREATE_SUB_KEY = 4 + KEY_QUERY_VALUE = 1 + + KEY_SET_VALUE = 2 + + KEY_CREATE_SUB_KEY = 4 + KEY_ENUMERATE_SUB_KEYS = 8 - KEY_NOTIFY = 16 - KEY_CREATE_LINK = 32 - KEY_WRITE = 0x20006 - KEY_EXECUTE = 0x20019 - KEY_READ = 0x20019 - KEY_WOW64_64KEY = 0x0100 - KEY_WOW64_32KEY = 0x0200 - KEY_ALL_ACCESS = 0xf003f + + KEY_NOTIFY = 16 + + KEY_CREATE_LINK = 32 + + KEY_WRITE = 0x20006 + + KEY_EXECUTE = 0x20019 + + KEY_READ = 0x20019 + + KEY_WOW64_64KEY = 0x0100 + + KEY_WOW64_32KEY = 0x0200 + + KEY_ALL_ACCESS = 0xf003f ) const ( + // do not reorder + REG_NONE = iota + REG_SZ + REG_EXPAND_SZ + REG_BINARY + REG_DWORD_LITTLE_ENDIAN + REG_DWORD_BIG_ENDIAN + REG_LINK + REG_MULTI_SZ + REG_RESOURCE_LIST + REG_FULL_RESOURCE_DESCRIPTOR + REG_RESOURCE_REQUIREMENTS_LIST + REG_QWORD_LITTLE_ENDIAN + REG_DWORD = REG_DWORD_LITTLE_ENDIAN + REG_QWORD = REG_QWORD_LITTLE_ENDIAN ) const ( EVENT_MODIFY_STATE = 0x0002 - EVENT_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3 + + EVENT_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3 MUTANT_QUERY_STATE = 0x0001 - MUTANT_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | MUTANT_QUERY_STATE + + MUTANT_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | MUTANT_QUERY_STATE SEMAPHORE_MODIFY_STATE = 0x0002 - SEMAPHORE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3 - TIMER_QUERY_STATE = 0x0001 + SEMAPHORE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3 + + TIMER_QUERY_STATE = 0x0001 + TIMER_MODIFY_STATE = 0x0002 - TIMER_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | TIMER_QUERY_STATE | TIMER_MODIFY_STATE + + TIMER_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | TIMER_QUERY_STATE | TIMER_MODIFY_STATE MUTEX_MODIFY_STATE = MUTANT_QUERY_STATE - MUTEX_ALL_ACCESS = MUTANT_ALL_ACCESS - CREATE_EVENT_MANUAL_RESET = 0x1 - CREATE_EVENT_INITIAL_SET = 0x2 + MUTEX_ALL_ACCESS = MUTANT_ALL_ACCESS + + CREATE_EVENT_MANUAL_RESET = 0x1 + + CREATE_EVENT_INITIAL_SET = 0x2 + CREATE_MUTEX_INITIAL_OWNER = 0x1 ) type AddrinfoW struct { - Flags int32 - Family int32 - Socktype int32 - Protocol int32 - Addrlen uintptr + Flags int32 + + Family int32 + + Socktype int32 + + Protocol int32 + + Addrlen uintptr + Canonname *uint16 - Addr uintptr - Next *AddrinfoW + + Addr uintptr + + Next *AddrinfoW } const ( - AI_PASSIVE = 1 - AI_CANONNAME = 2 + AI_PASSIVE = 1 + + AI_CANONNAME = 2 + AI_NUMERICHOST = 4 ) type GUID struct { Data1 uint32 + Data2 uint16 + Data3 uint16 + Data4 [8]byte } var WSAID_CONNECTEX = GUID{ + 0x25a207b9, + 0xddf3, + 0x4660, + [8]byte{0x8e, 0xe9, 0x76, 0xe5, 0x8c, 0x74, 0x06, 0x3e}, } var WSAID_WSASENDMSG = GUID{ + 0xa441e712, + 0x754f, + 0x43ca, + [8]byte{0x84, 0xa7, 0x0d, 0xee, 0x44, 0xcf, 0x60, 0x6d}, } var WSAID_WSARECVMSG = GUID{ + 0xf689d7c8, + 0x6f1f, + 0x436b, + [8]byte{0x8a, 0x53, 0xe5, 0x4f, 0xe3, 0x51, 0xc3, 0x22}, } const ( FILE_SKIP_COMPLETION_PORT_ON_SUCCESS = 1 - FILE_SKIP_SET_EVENT_ON_HANDLE = 2 + + FILE_SKIP_SET_EVENT_ON_HANDLE = 2 ) const ( - WSAPROTOCOL_LEN = 255 + WSAPROTOCOL_LEN = 255 + MAX_PROTOCOL_CHAIN = 7 - BASE_PROTOCOL = 1 - LAYERED_PROTOCOL = 0 - XP1_CONNECTIONLESS = 0x00000001 - XP1_GUARANTEED_DELIVERY = 0x00000002 - XP1_GUARANTEED_ORDER = 0x00000004 - XP1_MESSAGE_ORIENTED = 0x00000008 - XP1_PSEUDO_STREAM = 0x00000010 - XP1_GRACEFUL_CLOSE = 0x00000020 - XP1_EXPEDITED_DATA = 0x00000040 - XP1_CONNECT_DATA = 0x00000080 - XP1_DISCONNECT_DATA = 0x00000100 - XP1_SUPPORT_BROADCAST = 0x00000200 - XP1_SUPPORT_MULTIPOINT = 0x00000400 + BASE_PROTOCOL = 1 + + LAYERED_PROTOCOL = 0 + + XP1_CONNECTIONLESS = 0x00000001 + + XP1_GUARANTEED_DELIVERY = 0x00000002 + + XP1_GUARANTEED_ORDER = 0x00000004 + + XP1_MESSAGE_ORIENTED = 0x00000008 + + XP1_PSEUDO_STREAM = 0x00000010 + + XP1_GRACEFUL_CLOSE = 0x00000020 + + XP1_EXPEDITED_DATA = 0x00000040 + + XP1_CONNECT_DATA = 0x00000080 + + XP1_DISCONNECT_DATA = 0x00000100 + + XP1_SUPPORT_BROADCAST = 0x00000200 + + XP1_SUPPORT_MULTIPOINT = 0x00000400 + XP1_MULTIPOINT_CONTROL_PLANE = 0x00000800 - XP1_MULTIPOINT_DATA_PLANE = 0x00001000 - XP1_QOS_SUPPORTED = 0x00002000 - XP1_UNI_SEND = 0x00008000 - XP1_UNI_RECV = 0x00010000 - XP1_IFS_HANDLES = 0x00020000 - XP1_PARTIAL_MESSAGE = 0x00040000 - XP1_SAN_SUPPORT_SDP = 0x00080000 - PFL_MULTIPLE_PROTO_ENTRIES = 0x00000001 + XP1_MULTIPOINT_DATA_PLANE = 0x00001000 + + XP1_QOS_SUPPORTED = 0x00002000 + + XP1_UNI_SEND = 0x00008000 + + XP1_UNI_RECV = 0x00010000 + + XP1_IFS_HANDLES = 0x00020000 + + XP1_PARTIAL_MESSAGE = 0x00040000 + + XP1_SAN_SUPPORT_SDP = 0x00080000 + + PFL_MULTIPLE_PROTO_ENTRIES = 0x00000001 + PFL_RECOMMENDED_PROTO_ENTRY = 0x00000002 - PFL_HIDDEN = 0x00000004 - PFL_MATCHES_PROTOCOL_ZERO = 0x00000008 - PFL_NETWORKDIRECT_PROVIDER = 0x00000010 + + PFL_HIDDEN = 0x00000004 + + PFL_MATCHES_PROTOCOL_ZERO = 0x00000008 + + PFL_NETWORKDIRECT_PROVIDER = 0x00000010 ) type WSAProtocolInfo struct { - ServiceFlags1 uint32 - ServiceFlags2 uint32 - ServiceFlags3 uint32 - ServiceFlags4 uint32 - ProviderFlags uint32 - ProviderId GUID - CatalogEntryId uint32 - ProtocolChain WSAProtocolChain - Version int32 - AddressFamily int32 - MaxSockAddr int32 - MinSockAddr int32 - SocketType int32 - Protocol int32 + ServiceFlags1 uint32 + + ServiceFlags2 uint32 + + ServiceFlags3 uint32 + + ServiceFlags4 uint32 + + ProviderFlags uint32 + + ProviderId GUID + + CatalogEntryId uint32 + + ProtocolChain WSAProtocolChain + + Version int32 + + AddressFamily int32 + + MaxSockAddr int32 + + MinSockAddr int32 + + SocketType int32 + + Protocol int32 + ProtocolMaxOffset int32 - NetworkByteOrder int32 - SecurityScheme int32 - MessageSize uint32 - ProviderReserved uint32 - ProtocolName [WSAPROTOCOL_LEN + 1]uint16 + + NetworkByteOrder int32 + + SecurityScheme int32 + + MessageSize uint32 + + ProviderReserved uint32 + + ProtocolName [WSAPROTOCOL_LEN + 1]uint16 } type WSAProtocolChain struct { - ChainLen int32 + ChainLen int32 + ChainEntries [MAX_PROTOCOL_CHAIN]uint32 } type TCPKeepalive struct { - OnOff uint32 - Time uint32 + OnOff uint32 + + Time uint32 + Interval uint32 } type symbolicLinkReparseBuffer struct { SubstituteNameOffset uint16 + SubstituteNameLength uint16 - PrintNameOffset uint16 - PrintNameLength uint16 - Flags uint32 - PathBuffer [1]uint16 + + PrintNameOffset uint16 + + PrintNameLength uint16 + + Flags uint32 + + PathBuffer [1]uint16 } type mountPointReparseBuffer struct { SubstituteNameOffset uint16 + SubstituteNameLength uint16 - PrintNameOffset uint16 - PrintNameLength uint16 - PathBuffer [1]uint16 + + PrintNameOffset uint16 + + PrintNameLength uint16 + + PathBuffer [1]uint16 } type reparseDataBuffer struct { - ReparseTag uint32 + ReparseTag uint32 + ReparseDataLength uint16 - Reserved uint16 + + Reserved uint16 // GenericReparseBuffer + reparseBuffer byte } const ( - FSCTL_CREATE_OR_GET_OBJECT_ID = 0x0900C0 - FSCTL_DELETE_OBJECT_ID = 0x0900A0 - FSCTL_DELETE_REPARSE_POINT = 0x0900AC - FSCTL_DUPLICATE_EXTENTS_TO_FILE = 0x098344 - FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX = 0x0983E8 - FSCTL_FILESYSTEM_GET_STATISTICS = 0x090060 - FSCTL_FILE_LEVEL_TRIM = 0x098208 - FSCTL_FIND_FILES_BY_SID = 0x09008F - FSCTL_GET_COMPRESSION = 0x09003C - FSCTL_GET_INTEGRITY_INFORMATION = 0x09027C - FSCTL_GET_NTFS_VOLUME_DATA = 0x090064 - FSCTL_GET_REFS_VOLUME_DATA = 0x0902D8 - FSCTL_GET_OBJECT_ID = 0x09009C - FSCTL_GET_REPARSE_POINT = 0x0900A8 - FSCTL_GET_RETRIEVAL_POINTER_COUNT = 0x09042B - FSCTL_GET_RETRIEVAL_POINTERS = 0x090073 + FSCTL_CREATE_OR_GET_OBJECT_ID = 0x0900C0 + + FSCTL_DELETE_OBJECT_ID = 0x0900A0 + + FSCTL_DELETE_REPARSE_POINT = 0x0900AC + + FSCTL_DUPLICATE_EXTENTS_TO_FILE = 0x098344 + + FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX = 0x0983E8 + + FSCTL_FILESYSTEM_GET_STATISTICS = 0x090060 + + FSCTL_FILE_LEVEL_TRIM = 0x098208 + + FSCTL_FIND_FILES_BY_SID = 0x09008F + + FSCTL_GET_COMPRESSION = 0x09003C + + FSCTL_GET_INTEGRITY_INFORMATION = 0x09027C + + FSCTL_GET_NTFS_VOLUME_DATA = 0x090064 + + FSCTL_GET_REFS_VOLUME_DATA = 0x0902D8 + + FSCTL_GET_OBJECT_ID = 0x09009C + + FSCTL_GET_REPARSE_POINT = 0x0900A8 + + FSCTL_GET_RETRIEVAL_POINTER_COUNT = 0x09042B + + FSCTL_GET_RETRIEVAL_POINTERS = 0x090073 + FSCTL_GET_RETRIEVAL_POINTERS_AND_REFCOUNT = 0x0903D3 - FSCTL_IS_PATHNAME_VALID = 0x09002C - FSCTL_LMR_SET_LINK_TRACKING_INFORMATION = 0x1400EC - FSCTL_MARK_HANDLE = 0x0900FC - FSCTL_OFFLOAD_READ = 0x094264 - FSCTL_OFFLOAD_WRITE = 0x098268 - FSCTL_PIPE_PEEK = 0x11400C - FSCTL_PIPE_TRANSCEIVE = 0x11C017 - FSCTL_PIPE_WAIT = 0x110018 - FSCTL_QUERY_ALLOCATED_RANGES = 0x0940CF - FSCTL_QUERY_FAT_BPB = 0x090058 - FSCTL_QUERY_FILE_REGIONS = 0x090284 - FSCTL_QUERY_ON_DISK_VOLUME_INFO = 0x09013C - FSCTL_QUERY_SPARING_INFO = 0x090138 - FSCTL_READ_FILE_USN_DATA = 0x0900EB - FSCTL_RECALL_FILE = 0x090117 - FSCTL_REFS_STREAM_SNAPSHOT_MANAGEMENT = 0x090440 - FSCTL_SET_COMPRESSION = 0x09C040 - FSCTL_SET_DEFECT_MANAGEMENT = 0x098134 - FSCTL_SET_ENCRYPTION = 0x0900D7 - FSCTL_SET_INTEGRITY_INFORMATION = 0x09C280 - FSCTL_SET_INTEGRITY_INFORMATION_EX = 0x090380 - FSCTL_SET_OBJECT_ID = 0x090098 - FSCTL_SET_OBJECT_ID_EXTENDED = 0x0900BC - FSCTL_SET_REPARSE_POINT = 0x0900A4 - FSCTL_SET_SPARSE = 0x0900C4 - FSCTL_SET_ZERO_DATA = 0x0980C8 - FSCTL_SET_ZERO_ON_DEALLOCATION = 0x090194 - FSCTL_SIS_COPYFILE = 0x090100 - FSCTL_WRITE_USN_CLOSE_RECORD = 0x0900EF + + FSCTL_IS_PATHNAME_VALID = 0x09002C + + FSCTL_LMR_SET_LINK_TRACKING_INFORMATION = 0x1400EC + + FSCTL_MARK_HANDLE = 0x0900FC + + FSCTL_OFFLOAD_READ = 0x094264 + + FSCTL_OFFLOAD_WRITE = 0x098268 + + FSCTL_PIPE_PEEK = 0x11400C + + FSCTL_PIPE_TRANSCEIVE = 0x11C017 + + FSCTL_PIPE_WAIT = 0x110018 + + FSCTL_QUERY_ALLOCATED_RANGES = 0x0940CF + + FSCTL_QUERY_FAT_BPB = 0x090058 + + FSCTL_QUERY_FILE_REGIONS = 0x090284 + + FSCTL_QUERY_ON_DISK_VOLUME_INFO = 0x09013C + + FSCTL_QUERY_SPARING_INFO = 0x090138 + + FSCTL_READ_FILE_USN_DATA = 0x0900EB + + FSCTL_RECALL_FILE = 0x090117 + + FSCTL_REFS_STREAM_SNAPSHOT_MANAGEMENT = 0x090440 + + FSCTL_SET_COMPRESSION = 0x09C040 + + FSCTL_SET_DEFECT_MANAGEMENT = 0x098134 + + FSCTL_SET_ENCRYPTION = 0x0900D7 + + FSCTL_SET_INTEGRITY_INFORMATION = 0x09C280 + + FSCTL_SET_INTEGRITY_INFORMATION_EX = 0x090380 + + FSCTL_SET_OBJECT_ID = 0x090098 + + FSCTL_SET_OBJECT_ID_EXTENDED = 0x0900BC + + FSCTL_SET_REPARSE_POINT = 0x0900A4 + + FSCTL_SET_SPARSE = 0x0900C4 + + FSCTL_SET_ZERO_DATA = 0x0980C8 + + FSCTL_SET_ZERO_ON_DEALLOCATION = 0x090194 + + FSCTL_SIS_COPYFILE = 0x090100 + + FSCTL_WRITE_USN_CLOSE_RECORD = 0x0900EF MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16 * 1024 - IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003 - IO_REPARSE_TAG_SYMLINK = 0xA000000C - SYMBOLIC_LINK_FLAG_DIRECTORY = 0x1 + + IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003 + + IO_REPARSE_TAG_SYMLINK = 0xA000000C + + SYMBOLIC_LINK_FLAG_DIRECTORY = 0x1 ) const ( - ComputerNameNetBIOS = 0 - ComputerNameDnsHostname = 1 - ComputerNameDnsDomain = 2 - ComputerNameDnsFullyQualified = 3 - ComputerNamePhysicalNetBIOS = 4 - ComputerNamePhysicalDnsHostname = 5 - ComputerNamePhysicalDnsDomain = 6 + ComputerNameNetBIOS = 0 + + ComputerNameDnsHostname = 1 + + ComputerNameDnsDomain = 2 + + ComputerNameDnsFullyQualified = 3 + + ComputerNamePhysicalNetBIOS = 4 + + ComputerNamePhysicalDnsHostname = 5 + + ComputerNamePhysicalDnsDomain = 6 + ComputerNamePhysicalDnsFullyQualified = 7 - ComputerNameMax = 8 + + ComputerNameMax = 8 ) // For MessageBox() + const ( - MB_OK = 0x00000000 - MB_OKCANCEL = 0x00000001 - MB_ABORTRETRYIGNORE = 0x00000002 - MB_YESNOCANCEL = 0x00000003 - MB_YESNO = 0x00000004 - MB_RETRYCANCEL = 0x00000005 - MB_CANCELTRYCONTINUE = 0x00000006 - MB_ICONHAND = 0x00000010 - MB_ICONQUESTION = 0x00000020 - MB_ICONEXCLAMATION = 0x00000030 - MB_ICONASTERISK = 0x00000040 - MB_USERICON = 0x00000080 - MB_ICONWARNING = MB_ICONEXCLAMATION - MB_ICONERROR = MB_ICONHAND - MB_ICONINFORMATION = MB_ICONASTERISK - MB_ICONSTOP = MB_ICONHAND - MB_DEFBUTTON1 = 0x00000000 - MB_DEFBUTTON2 = 0x00000100 - MB_DEFBUTTON3 = 0x00000200 - MB_DEFBUTTON4 = 0x00000300 - MB_APPLMODAL = 0x00000000 - MB_SYSTEMMODAL = 0x00001000 - MB_TASKMODAL = 0x00002000 - MB_HELP = 0x00004000 - MB_NOFOCUS = 0x00008000 - MB_SETFOREGROUND = 0x00010000 + MB_OK = 0x00000000 + + MB_OKCANCEL = 0x00000001 + + MB_ABORTRETRYIGNORE = 0x00000002 + + MB_YESNOCANCEL = 0x00000003 + + MB_YESNO = 0x00000004 + + MB_RETRYCANCEL = 0x00000005 + + MB_CANCELTRYCONTINUE = 0x00000006 + + MB_ICONHAND = 0x00000010 + + MB_ICONQUESTION = 0x00000020 + + MB_ICONEXCLAMATION = 0x00000030 + + MB_ICONASTERISK = 0x00000040 + + MB_USERICON = 0x00000080 + + MB_ICONWARNING = MB_ICONEXCLAMATION + + MB_ICONERROR = MB_ICONHAND + + MB_ICONINFORMATION = MB_ICONASTERISK + + MB_ICONSTOP = MB_ICONHAND + + MB_DEFBUTTON1 = 0x00000000 + + MB_DEFBUTTON2 = 0x00000100 + + MB_DEFBUTTON3 = 0x00000200 + + MB_DEFBUTTON4 = 0x00000300 + + MB_APPLMODAL = 0x00000000 + + MB_SYSTEMMODAL = 0x00001000 + + MB_TASKMODAL = 0x00002000 + + MB_HELP = 0x00004000 + + MB_NOFOCUS = 0x00008000 + + MB_SETFOREGROUND = 0x00010000 + MB_DEFAULT_DESKTOP_ONLY = 0x00020000 - MB_TOPMOST = 0x00040000 - MB_RIGHT = 0x00080000 - MB_RTLREADING = 0x00100000 + + MB_TOPMOST = 0x00040000 + + MB_RIGHT = 0x00080000 + + MB_RTLREADING = 0x00100000 + MB_SERVICE_NOTIFICATION = 0x00200000 ) const ( - MOVEFILE_REPLACE_EXISTING = 0x1 - MOVEFILE_COPY_ALLOWED = 0x2 - MOVEFILE_DELAY_UNTIL_REBOOT = 0x4 - MOVEFILE_WRITE_THROUGH = 0x8 - MOVEFILE_CREATE_HARDLINK = 0x10 + MOVEFILE_REPLACE_EXISTING = 0x1 + + MOVEFILE_COPY_ALLOWED = 0x2 + + MOVEFILE_DELAY_UNTIL_REBOOT = 0x4 + + MOVEFILE_WRITE_THROUGH = 0x8 + + MOVEFILE_CREATE_HARDLINK = 0x10 + MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x20 ) const GAA_FLAG_INCLUDE_PREFIX = 0x00000010 const ( - IF_TYPE_OTHER = 1 - IF_TYPE_ETHERNET_CSMACD = 6 + IF_TYPE_OTHER = 1 + + IF_TYPE_ETHERNET_CSMACD = 6 + IF_TYPE_ISO88025_TOKENRING = 9 - IF_TYPE_PPP = 23 - IF_TYPE_SOFTWARE_LOOPBACK = 24 - IF_TYPE_ATM = 37 - IF_TYPE_IEEE80211 = 71 - IF_TYPE_TUNNEL = 131 - IF_TYPE_IEEE1394 = 144 + + IF_TYPE_PPP = 23 + + IF_TYPE_SOFTWARE_LOOPBACK = 24 + + IF_TYPE_ATM = 37 + + IF_TYPE_IEEE80211 = 71 + + IF_TYPE_TUNNEL = 131 + + IF_TYPE_IEEE1394 = 144 ) type SocketAddress struct { - Sockaddr *syscall.RawSockaddrAny + Sockaddr *syscall.RawSockaddrAny + SockaddrLength int32 } // IP returns an IPv4 or IPv6 address, or nil if the underlying SocketAddress is neither. + func (addr *SocketAddress) IP() net.IP { + if uintptr(addr.SockaddrLength) >= unsafe.Sizeof(RawSockaddrInet4{}) && addr.Sockaddr.Addr.Family == AF_INET { + return (*RawSockaddrInet4)(unsafe.Pointer(addr.Sockaddr)).Addr[:] + } else if uintptr(addr.SockaddrLength) >= unsafe.Sizeof(RawSockaddrInet6{}) && addr.Sockaddr.Addr.Family == AF_INET6 { + return (*RawSockaddrInet6)(unsafe.Pointer(addr.Sockaddr)).Addr[:] + } + return nil + } type IpAdapterUnicastAddress struct { - Length uint32 - Flags uint32 - Next *IpAdapterUnicastAddress - Address SocketAddress - PrefixOrigin int32 - SuffixOrigin int32 - DadState int32 - ValidLifetime uint32 - PreferredLifetime uint32 - LeaseLifetime uint32 + Length uint32 + + Flags uint32 + + Next *IpAdapterUnicastAddress + + Address SocketAddress + + PrefixOrigin int32 + + SuffixOrigin int32 + + DadState int32 + + ValidLifetime uint32 + + PreferredLifetime uint32 + + LeaseLifetime uint32 + OnLinkPrefixLength uint8 } type IpAdapterAnycastAddress struct { - Length uint32 - Flags uint32 - Next *IpAdapterAnycastAddress + Length uint32 + + Flags uint32 + + Next *IpAdapterAnycastAddress + Address SocketAddress } type IpAdapterMulticastAddress struct { - Length uint32 - Flags uint32 - Next *IpAdapterMulticastAddress + Length uint32 + + Flags uint32 + + Next *IpAdapterMulticastAddress + Address SocketAddress } type IpAdapterDnsServerAdapter struct { - Length uint32 + Length uint32 + Reserved uint32 - Next *IpAdapterDnsServerAdapter - Address SocketAddress + + Next *IpAdapterDnsServerAdapter + + Address SocketAddress } type IpAdapterPrefix struct { - Length uint32 - Flags uint32 - Next *IpAdapterPrefix - Address SocketAddress + Length uint32 + + Flags uint32 + + Next *IpAdapterPrefix + + Address SocketAddress + PrefixLength uint32 } type IpAdapterAddresses struct { - Length uint32 - IfIndex uint32 - Next *IpAdapterAddresses - AdapterName *byte - FirstUnicastAddress *IpAdapterUnicastAddress - FirstAnycastAddress *IpAdapterAnycastAddress - FirstMulticastAddress *IpAdapterMulticastAddress - FirstDnsServerAddress *IpAdapterDnsServerAdapter - DnsSuffix *uint16 - Description *uint16 - FriendlyName *uint16 - PhysicalAddress [syscall.MAX_ADAPTER_ADDRESS_LENGTH]byte - PhysicalAddressLength uint32 - Flags uint32 - Mtu uint32 - IfType uint32 - OperStatus uint32 - Ipv6IfIndex uint32 - ZoneIndices [16]uint32 - FirstPrefix *IpAdapterPrefix - TransmitLinkSpeed uint64 - ReceiveLinkSpeed uint64 + Length uint32 + + IfIndex uint32 + + Next *IpAdapterAddresses + + AdapterName *byte + + FirstUnicastAddress *IpAdapterUnicastAddress + + FirstAnycastAddress *IpAdapterAnycastAddress + + FirstMulticastAddress *IpAdapterMulticastAddress + + FirstDnsServerAddress *IpAdapterDnsServerAdapter + + DnsSuffix *uint16 + + Description *uint16 + + FriendlyName *uint16 + + PhysicalAddress [syscall.MAX_ADAPTER_ADDRESS_LENGTH]byte + + PhysicalAddressLength uint32 + + Flags uint32 + + Mtu uint32 + + IfType uint32 + + OperStatus uint32 + + Ipv6IfIndex uint32 + + ZoneIndices [16]uint32 + + FirstPrefix *IpAdapterPrefix + + TransmitLinkSpeed uint64 + + ReceiveLinkSpeed uint64 + FirstWinsServerAddress *IpAdapterWinsServerAddress - FirstGatewayAddress *IpAdapterGatewayAddress - Ipv4Metric uint32 - Ipv6Metric uint32 - Luid uint64 - Dhcpv4Server SocketAddress - CompartmentId uint32 - NetworkGuid GUID - ConnectionType uint32 - TunnelType uint32 - Dhcpv6Server SocketAddress - Dhcpv6ClientDuid [MAX_DHCPV6_DUID_LENGTH]byte + + FirstGatewayAddress *IpAdapterGatewayAddress + + Ipv4Metric uint32 + + Ipv6Metric uint32 + + Luid uint64 + + Dhcpv4Server SocketAddress + + CompartmentId uint32 + + NetworkGuid GUID + + ConnectionType uint32 + + TunnelType uint32 + + Dhcpv6Server SocketAddress + + Dhcpv6ClientDuid [MAX_DHCPV6_DUID_LENGTH]byte + Dhcpv6ClientDuidLength uint32 - Dhcpv6Iaid uint32 - FirstDnsSuffix *IpAdapterDNSSuffix + + Dhcpv6Iaid uint32 + + FirstDnsSuffix *IpAdapterDNSSuffix } type IpAdapterWinsServerAddress struct { - Length uint32 + Length uint32 + Reserved uint32 - Next *IpAdapterWinsServerAddress - Address SocketAddress + + Next *IpAdapterWinsServerAddress + + Address SocketAddress } type IpAdapterGatewayAddress struct { - Length uint32 + Length uint32 + Reserved uint32 - Next *IpAdapterGatewayAddress - Address SocketAddress + + Next *IpAdapterGatewayAddress + + Address SocketAddress } type IpAdapterDNSSuffix struct { - Next *IpAdapterDNSSuffix + Next *IpAdapterDNSSuffix + String [MAX_DNS_SUFFIX_STRING_LENGTH]uint16 } const ( - IfOperStatusUp = 1 - IfOperStatusDown = 2 - IfOperStatusTesting = 3 - IfOperStatusUnknown = 4 - IfOperStatusDormant = 5 - IfOperStatusNotPresent = 6 + IfOperStatusUp = 1 + + IfOperStatusDown = 2 + + IfOperStatusTesting = 3 + + IfOperStatusUnknown = 4 + + IfOperStatusDormant = 5 + + IfOperStatusNotPresent = 6 + IfOperStatusLowerLayerDown = 7 ) // Console related constants used for the mode parameter to SetConsoleMode. See + // https://docs.microsoft.com/en-us/windows/console/setconsolemode for details. const ( - ENABLE_PROCESSED_INPUT = 0x1 - ENABLE_LINE_INPUT = 0x2 - ENABLE_ECHO_INPUT = 0x4 - ENABLE_WINDOW_INPUT = 0x8 - ENABLE_MOUSE_INPUT = 0x10 - ENABLE_INSERT_MODE = 0x20 - ENABLE_QUICK_EDIT_MODE = 0x40 - ENABLE_EXTENDED_FLAGS = 0x80 - ENABLE_AUTO_POSITION = 0x100 + ENABLE_PROCESSED_INPUT = 0x1 + + ENABLE_LINE_INPUT = 0x2 + + ENABLE_ECHO_INPUT = 0x4 + + ENABLE_WINDOW_INPUT = 0x8 + + ENABLE_MOUSE_INPUT = 0x10 + + ENABLE_INSERT_MODE = 0x20 + + ENABLE_QUICK_EDIT_MODE = 0x40 + + ENABLE_EXTENDED_FLAGS = 0x80 + + ENABLE_AUTO_POSITION = 0x100 + ENABLE_VIRTUAL_TERMINAL_INPUT = 0x200 - ENABLE_PROCESSED_OUTPUT = 0x1 - ENABLE_WRAP_AT_EOL_OUTPUT = 0x2 + ENABLE_PROCESSED_OUTPUT = 0x1 + + ENABLE_WRAP_AT_EOL_OUTPUT = 0x2 + ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x4 - DISABLE_NEWLINE_AUTO_RETURN = 0x8 - ENABLE_LVB_GRID_WORLDWIDE = 0x10 + + DISABLE_NEWLINE_AUTO_RETURN = 0x8 + + ENABLE_LVB_GRID_WORLDWIDE = 0x10 ) // Pseudo console related constants used for the flags parameter to + // CreatePseudoConsole. See: https://learn.microsoft.com/en-us/windows/console/createpseudoconsole + const ( PSEUDOCONSOLE_INHERIT_CURSOR = 0x1 ) type Coord struct { X int16 + Y int16 } type SmallRect struct { - Left int16 - Top int16 - Right int16 + Left int16 + + Top int16 + + Right int16 + Bottom int16 } // Used with GetConsoleScreenBuffer to retrieve information about a console + // screen buffer. See + // https://docs.microsoft.com/en-us/windows/console/console-screen-buffer-info-str + // for details. type ConsoleScreenBufferInfo struct { - Size Coord - CursorPosition Coord - Attributes uint16 - Window SmallRect + Size Coord + + CursorPosition Coord + + Attributes uint16 + + Window SmallRect + MaximumWindowSize Coord } const UNIX_PATH_MAX = 108 // defined in afunix.h const ( + // flags for JOBOBJECT_BASIC_LIMIT_INFORMATION.LimitFlags - JOB_OBJECT_LIMIT_ACTIVE_PROCESS = 0x00000008 - JOB_OBJECT_LIMIT_AFFINITY = 0x00000010 - JOB_OBJECT_LIMIT_BREAKAWAY_OK = 0x00000800 + + JOB_OBJECT_LIMIT_ACTIVE_PROCESS = 0x00000008 + + JOB_OBJECT_LIMIT_AFFINITY = 0x00000010 + + JOB_OBJECT_LIMIT_BREAKAWAY_OK = 0x00000800 + JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION = 0x00000400 - JOB_OBJECT_LIMIT_JOB_MEMORY = 0x00000200 - JOB_OBJECT_LIMIT_JOB_TIME = 0x00000004 - JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000 - JOB_OBJECT_LIMIT_PRESERVE_JOB_TIME = 0x00000040 - JOB_OBJECT_LIMIT_PRIORITY_CLASS = 0x00000020 - JOB_OBJECT_LIMIT_PROCESS_MEMORY = 0x00000100 - JOB_OBJECT_LIMIT_PROCESS_TIME = 0x00000002 - JOB_OBJECT_LIMIT_SCHEDULING_CLASS = 0x00000080 - JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK = 0x00001000 - JOB_OBJECT_LIMIT_SUBSET_AFFINITY = 0x00004000 - JOB_OBJECT_LIMIT_WORKINGSET = 0x00000001 + + JOB_OBJECT_LIMIT_JOB_MEMORY = 0x00000200 + + JOB_OBJECT_LIMIT_JOB_TIME = 0x00000004 + + JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000 + + JOB_OBJECT_LIMIT_PRESERVE_JOB_TIME = 0x00000040 + + JOB_OBJECT_LIMIT_PRIORITY_CLASS = 0x00000020 + + JOB_OBJECT_LIMIT_PROCESS_MEMORY = 0x00000100 + + JOB_OBJECT_LIMIT_PROCESS_TIME = 0x00000002 + + JOB_OBJECT_LIMIT_SCHEDULING_CLASS = 0x00000080 + + JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK = 0x00001000 + + JOB_OBJECT_LIMIT_SUBSET_AFFINITY = 0x00004000 + + JOB_OBJECT_LIMIT_WORKINGSET = 0x00000001 ) type IO_COUNTERS struct { - ReadOperationCount uint64 + ReadOperationCount uint64 + WriteOperationCount uint64 + OtherOperationCount uint64 - ReadTransferCount uint64 - WriteTransferCount uint64 - OtherTransferCount uint64 + + ReadTransferCount uint64 + + WriteTransferCount uint64 + + OtherTransferCount uint64 } type JOBOBJECT_EXTENDED_LIMIT_INFORMATION struct { BasicLimitInformation JOBOBJECT_BASIC_LIMIT_INFORMATION - IoInfo IO_COUNTERS - ProcessMemoryLimit uintptr - JobMemoryLimit uintptr + + IoInfo IO_COUNTERS + + ProcessMemoryLimit uintptr + + JobMemoryLimit uintptr + PeakProcessMemoryUsed uintptr - PeakJobMemoryUsed uintptr + + PeakJobMemoryUsed uintptr } const ( + // UIRestrictionsClass - JOB_OBJECT_UILIMIT_DESKTOP = 0x00000040 - JOB_OBJECT_UILIMIT_DISPLAYSETTINGS = 0x00000010 - JOB_OBJECT_UILIMIT_EXITWINDOWS = 0x00000080 - JOB_OBJECT_UILIMIT_GLOBALATOMS = 0x00000020 - JOB_OBJECT_UILIMIT_HANDLES = 0x00000001 - JOB_OBJECT_UILIMIT_READCLIPBOARD = 0x00000002 + + JOB_OBJECT_UILIMIT_DESKTOP = 0x00000040 + + JOB_OBJECT_UILIMIT_DISPLAYSETTINGS = 0x00000010 + + JOB_OBJECT_UILIMIT_EXITWINDOWS = 0x00000080 + + JOB_OBJECT_UILIMIT_GLOBALATOMS = 0x00000020 + + JOB_OBJECT_UILIMIT_HANDLES = 0x00000001 + + JOB_OBJECT_UILIMIT_READCLIPBOARD = 0x00000002 + JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS = 0x00000008 - JOB_OBJECT_UILIMIT_WRITECLIPBOARD = 0x00000004 + + JOB_OBJECT_UILIMIT_WRITECLIPBOARD = 0x00000004 ) type JOBOBJECT_BASIC_UI_RESTRICTIONS struct { @@ -2253,292 +3778,497 @@ type JOBOBJECT_BASIC_UI_RESTRICTIONS struct { } const ( + // JobObjectInformationClass for QueryInformationJobObject and SetInformationJobObject + JobObjectAssociateCompletionPortInformation = 7 - JobObjectBasicAccountingInformation = 1 - JobObjectBasicAndIoAccountingInformation = 8 - JobObjectBasicLimitInformation = 2 - JobObjectBasicProcessIdList = 3 - JobObjectBasicUIRestrictions = 4 - JobObjectCpuRateControlInformation = 15 - JobObjectEndOfJobTimeInformation = 6 - JobObjectExtendedLimitInformation = 9 - JobObjectGroupInformation = 11 - JobObjectGroupInformationEx = 14 - JobObjectLimitViolationInformation = 13 - JobObjectLimitViolationInformation2 = 34 - JobObjectNetRateControlInformation = 32 - JobObjectNotificationLimitInformation = 12 - JobObjectNotificationLimitInformation2 = 33 - JobObjectSecurityLimitInformation = 5 + + JobObjectBasicAccountingInformation = 1 + + JobObjectBasicAndIoAccountingInformation = 8 + + JobObjectBasicLimitInformation = 2 + + JobObjectBasicProcessIdList = 3 + + JobObjectBasicUIRestrictions = 4 + + JobObjectCpuRateControlInformation = 15 + + JobObjectEndOfJobTimeInformation = 6 + + JobObjectExtendedLimitInformation = 9 + + JobObjectGroupInformation = 11 + + JobObjectGroupInformationEx = 14 + + JobObjectLimitViolationInformation = 13 + + JobObjectLimitViolationInformation2 = 34 + + JobObjectNetRateControlInformation = 32 + + JobObjectNotificationLimitInformation = 12 + + JobObjectNotificationLimitInformation2 = 33 + + JobObjectSecurityLimitInformation = 5 ) const ( - KF_FLAG_DEFAULT = 0x00000000 - KF_FLAG_FORCE_APP_DATA_REDIRECTION = 0x00080000 + KF_FLAG_DEFAULT = 0x00000000 + + KF_FLAG_FORCE_APP_DATA_REDIRECTION = 0x00080000 + KF_FLAG_RETURN_FILTER_REDIRECTION_TARGET = 0x00040000 - KF_FLAG_FORCE_PACKAGE_REDIRECTION = 0x00020000 - KF_FLAG_NO_PACKAGE_REDIRECTION = 0x00010000 - KF_FLAG_FORCE_APPCONTAINER_REDIRECTION = 0x00020000 - KF_FLAG_NO_APPCONTAINER_REDIRECTION = 0x00010000 - KF_FLAG_CREATE = 0x00008000 - KF_FLAG_DONT_VERIFY = 0x00004000 - KF_FLAG_DONT_UNEXPAND = 0x00002000 - KF_FLAG_NO_ALIAS = 0x00001000 - KF_FLAG_INIT = 0x00000800 - KF_FLAG_DEFAULT_PATH = 0x00000400 - KF_FLAG_NOT_PARENT_RELATIVE = 0x00000200 - KF_FLAG_SIMPLE_IDLIST = 0x00000100 - KF_FLAG_ALIAS_ONLY = 0x80000000 + + KF_FLAG_FORCE_PACKAGE_REDIRECTION = 0x00020000 + + KF_FLAG_NO_PACKAGE_REDIRECTION = 0x00010000 + + KF_FLAG_FORCE_APPCONTAINER_REDIRECTION = 0x00020000 + + KF_FLAG_NO_APPCONTAINER_REDIRECTION = 0x00010000 + + KF_FLAG_CREATE = 0x00008000 + + KF_FLAG_DONT_VERIFY = 0x00004000 + + KF_FLAG_DONT_UNEXPAND = 0x00002000 + + KF_FLAG_NO_ALIAS = 0x00001000 + + KF_FLAG_INIT = 0x00000800 + + KF_FLAG_DEFAULT_PATH = 0x00000400 + + KF_FLAG_NOT_PARENT_RELATIVE = 0x00000200 + + KF_FLAG_SIMPLE_IDLIST = 0x00000100 + + KF_FLAG_ALIAS_ONLY = 0x80000000 ) type OsVersionInfoEx struct { osVersionInfoSize uint32 - MajorVersion uint32 - MinorVersion uint32 - BuildNumber uint32 - PlatformId uint32 - CsdVersion [128]uint16 - ServicePackMajor uint16 - ServicePackMinor uint16 - SuiteMask uint16 - ProductType byte - _ byte + + MajorVersion uint32 + + MinorVersion uint32 + + BuildNumber uint32 + + PlatformId uint32 + + CsdVersion [128]uint16 + + ServicePackMajor uint16 + + ServicePackMinor uint16 + + SuiteMask uint16 + + ProductType byte + + _ byte } const ( - EWX_LOGOFF = 0x00000000 - EWX_SHUTDOWN = 0x00000001 - EWX_REBOOT = 0x00000002 - EWX_FORCE = 0x00000004 - EWX_POWEROFF = 0x00000008 - EWX_FORCEIFHUNG = 0x00000010 - EWX_QUICKRESOLVE = 0x00000020 - EWX_RESTARTAPPS = 0x00000040 - EWX_HYBRID_SHUTDOWN = 0x00400000 - EWX_BOOTOPTIONS = 0x01000000 + EWX_LOGOFF = 0x00000000 + + EWX_SHUTDOWN = 0x00000001 + + EWX_REBOOT = 0x00000002 + + EWX_FORCE = 0x00000004 + + EWX_POWEROFF = 0x00000008 + + EWX_FORCEIFHUNG = 0x00000010 + + EWX_QUICKRESOLVE = 0x00000020 + + EWX_RESTARTAPPS = 0x00000040 + + EWX_HYBRID_SHUTDOWN = 0x00400000 + + EWX_BOOTOPTIONS = 0x01000000 + + SHTDN_REASON_FLAG_COMMENT_REQUIRED = 0x01000000 - SHTDN_REASON_FLAG_COMMENT_REQUIRED = 0x01000000 SHTDN_REASON_FLAG_DIRTY_PROBLEM_ID_REQUIRED = 0x02000000 - SHTDN_REASON_FLAG_CLEAN_UI = 0x04000000 - SHTDN_REASON_FLAG_DIRTY_UI = 0x08000000 - SHTDN_REASON_FLAG_USER_DEFINED = 0x40000000 - SHTDN_REASON_FLAG_PLANNED = 0x80000000 - SHTDN_REASON_MAJOR_OTHER = 0x00000000 - SHTDN_REASON_MAJOR_NONE = 0x00000000 - SHTDN_REASON_MAJOR_HARDWARE = 0x00010000 - SHTDN_REASON_MAJOR_OPERATINGSYSTEM = 0x00020000 - SHTDN_REASON_MAJOR_SOFTWARE = 0x00030000 - SHTDN_REASON_MAJOR_APPLICATION = 0x00040000 - SHTDN_REASON_MAJOR_SYSTEM = 0x00050000 - SHTDN_REASON_MAJOR_POWER = 0x00060000 - SHTDN_REASON_MAJOR_LEGACY_API = 0x00070000 - SHTDN_REASON_MINOR_OTHER = 0x00000000 - SHTDN_REASON_MINOR_NONE = 0x000000ff - SHTDN_REASON_MINOR_MAINTENANCE = 0x00000001 - SHTDN_REASON_MINOR_INSTALLATION = 0x00000002 - SHTDN_REASON_MINOR_UPGRADE = 0x00000003 - SHTDN_REASON_MINOR_RECONFIG = 0x00000004 - SHTDN_REASON_MINOR_HUNG = 0x00000005 - SHTDN_REASON_MINOR_UNSTABLE = 0x00000006 - SHTDN_REASON_MINOR_DISK = 0x00000007 - SHTDN_REASON_MINOR_PROCESSOR = 0x00000008 - SHTDN_REASON_MINOR_NETWORKCARD = 0x00000009 - SHTDN_REASON_MINOR_POWER_SUPPLY = 0x0000000a - SHTDN_REASON_MINOR_CORDUNPLUGGED = 0x0000000b - SHTDN_REASON_MINOR_ENVIRONMENT = 0x0000000c - SHTDN_REASON_MINOR_HARDWARE_DRIVER = 0x0000000d - SHTDN_REASON_MINOR_OTHERDRIVER = 0x0000000e - SHTDN_REASON_MINOR_BLUESCREEN = 0x0000000F - SHTDN_REASON_MINOR_SERVICEPACK = 0x00000010 - SHTDN_REASON_MINOR_HOTFIX = 0x00000011 - SHTDN_REASON_MINOR_SECURITYFIX = 0x00000012 - SHTDN_REASON_MINOR_SECURITY = 0x00000013 - SHTDN_REASON_MINOR_NETWORK_CONNECTIVITY = 0x00000014 - SHTDN_REASON_MINOR_WMI = 0x00000015 - SHTDN_REASON_MINOR_SERVICEPACK_UNINSTALL = 0x00000016 - SHTDN_REASON_MINOR_HOTFIX_UNINSTALL = 0x00000017 - SHTDN_REASON_MINOR_SECURITYFIX_UNINSTALL = 0x00000018 - SHTDN_REASON_MINOR_MMC = 0x00000019 - SHTDN_REASON_MINOR_SYSTEMRESTORE = 0x0000001a - SHTDN_REASON_MINOR_TERMSRV = 0x00000020 - SHTDN_REASON_MINOR_DC_PROMOTION = 0x00000021 - SHTDN_REASON_MINOR_DC_DEMOTION = 0x00000022 - SHTDN_REASON_UNKNOWN = SHTDN_REASON_MINOR_NONE - SHTDN_REASON_LEGACY_API = SHTDN_REASON_MAJOR_LEGACY_API | SHTDN_REASON_FLAG_PLANNED - SHTDN_REASON_VALID_BIT_MASK = 0xc0ffffff + + SHTDN_REASON_FLAG_CLEAN_UI = 0x04000000 + + SHTDN_REASON_FLAG_DIRTY_UI = 0x08000000 + + SHTDN_REASON_FLAG_USER_DEFINED = 0x40000000 + + SHTDN_REASON_FLAG_PLANNED = 0x80000000 + + SHTDN_REASON_MAJOR_OTHER = 0x00000000 + + SHTDN_REASON_MAJOR_NONE = 0x00000000 + + SHTDN_REASON_MAJOR_HARDWARE = 0x00010000 + + SHTDN_REASON_MAJOR_OPERATINGSYSTEM = 0x00020000 + + SHTDN_REASON_MAJOR_SOFTWARE = 0x00030000 + + SHTDN_REASON_MAJOR_APPLICATION = 0x00040000 + + SHTDN_REASON_MAJOR_SYSTEM = 0x00050000 + + SHTDN_REASON_MAJOR_POWER = 0x00060000 + + SHTDN_REASON_MAJOR_LEGACY_API = 0x00070000 + + SHTDN_REASON_MINOR_OTHER = 0x00000000 + + SHTDN_REASON_MINOR_NONE = 0x000000ff + + SHTDN_REASON_MINOR_MAINTENANCE = 0x00000001 + + SHTDN_REASON_MINOR_INSTALLATION = 0x00000002 + + SHTDN_REASON_MINOR_UPGRADE = 0x00000003 + + SHTDN_REASON_MINOR_RECONFIG = 0x00000004 + + SHTDN_REASON_MINOR_HUNG = 0x00000005 + + SHTDN_REASON_MINOR_UNSTABLE = 0x00000006 + + SHTDN_REASON_MINOR_DISK = 0x00000007 + + SHTDN_REASON_MINOR_PROCESSOR = 0x00000008 + + SHTDN_REASON_MINOR_NETWORKCARD = 0x00000009 + + SHTDN_REASON_MINOR_POWER_SUPPLY = 0x0000000a + + SHTDN_REASON_MINOR_CORDUNPLUGGED = 0x0000000b + + SHTDN_REASON_MINOR_ENVIRONMENT = 0x0000000c + + SHTDN_REASON_MINOR_HARDWARE_DRIVER = 0x0000000d + + SHTDN_REASON_MINOR_OTHERDRIVER = 0x0000000e + + SHTDN_REASON_MINOR_BLUESCREEN = 0x0000000F + + SHTDN_REASON_MINOR_SERVICEPACK = 0x00000010 + + SHTDN_REASON_MINOR_HOTFIX = 0x00000011 + + SHTDN_REASON_MINOR_SECURITYFIX = 0x00000012 + + SHTDN_REASON_MINOR_SECURITY = 0x00000013 + + SHTDN_REASON_MINOR_NETWORK_CONNECTIVITY = 0x00000014 + + SHTDN_REASON_MINOR_WMI = 0x00000015 + + SHTDN_REASON_MINOR_SERVICEPACK_UNINSTALL = 0x00000016 + + SHTDN_REASON_MINOR_HOTFIX_UNINSTALL = 0x00000017 + + SHTDN_REASON_MINOR_SECURITYFIX_UNINSTALL = 0x00000018 + + SHTDN_REASON_MINOR_MMC = 0x00000019 + + SHTDN_REASON_MINOR_SYSTEMRESTORE = 0x0000001a + + SHTDN_REASON_MINOR_TERMSRV = 0x00000020 + + SHTDN_REASON_MINOR_DC_PROMOTION = 0x00000021 + + SHTDN_REASON_MINOR_DC_DEMOTION = 0x00000022 + + SHTDN_REASON_UNKNOWN = SHTDN_REASON_MINOR_NONE + + SHTDN_REASON_LEGACY_API = SHTDN_REASON_MAJOR_LEGACY_API | SHTDN_REASON_FLAG_PLANNED + + SHTDN_REASON_VALID_BIT_MASK = 0xc0ffffff SHUTDOWN_NORETRY = 0x1 ) // Flags used for GetModuleHandleEx + const ( - GET_MODULE_HANDLE_EX_FLAG_PIN = 1 + GET_MODULE_HANDLE_EX_FLAG_PIN = 1 + GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT = 2 - GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS = 4 + + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS = 4 ) // MUI function flag values -const ( - MUI_LANGUAGE_ID = 0x4 - MUI_LANGUAGE_NAME = 0x8 - MUI_MERGE_SYSTEM_FALLBACK = 0x10 - MUI_MERGE_USER_FALLBACK = 0x20 - MUI_UI_FALLBACK = MUI_MERGE_SYSTEM_FALLBACK | MUI_MERGE_USER_FALLBACK - MUI_THREAD_LANGUAGES = 0x40 - MUI_CONSOLE_FILTER = 0x100 - MUI_COMPLEX_SCRIPT_FILTER = 0x200 - MUI_RESET_FILTERS = 0x001 - MUI_USER_PREFERRED_UI_LANGUAGES = 0x10 - MUI_USE_INSTALLED_LANGUAGES = 0x20 - MUI_USE_SEARCH_ALL_LANGUAGES = 0x40 - MUI_LANG_NEUTRAL_PE_FILE = 0x100 - MUI_NON_LANG_NEUTRAL_FILE = 0x200 - MUI_MACHINE_LANGUAGE_SETTINGS = 0x400 - MUI_FILETYPE_NOT_LANGUAGE_NEUTRAL = 0x001 - MUI_FILETYPE_LANGUAGE_NEUTRAL_MAIN = 0x002 - MUI_FILETYPE_LANGUAGE_NEUTRAL_MUI = 0x004 - MUI_QUERY_TYPE = 0x001 - MUI_QUERY_CHECKSUM = 0x002 - MUI_QUERY_LANGUAGE_NAME = 0x004 - MUI_QUERY_RESOURCE_TYPES = 0x008 - MUI_FILEINFO_VERSION = 0x001 - MUI_FULL_LANGUAGE = 0x01 - MUI_PARTIAL_LANGUAGE = 0x02 - MUI_LIP_LANGUAGE = 0x04 +const ( + MUI_LANGUAGE_ID = 0x4 + + MUI_LANGUAGE_NAME = 0x8 + + MUI_MERGE_SYSTEM_FALLBACK = 0x10 + + MUI_MERGE_USER_FALLBACK = 0x20 + + MUI_UI_FALLBACK = MUI_MERGE_SYSTEM_FALLBACK | MUI_MERGE_USER_FALLBACK + + MUI_THREAD_LANGUAGES = 0x40 + + MUI_CONSOLE_FILTER = 0x100 + + MUI_COMPLEX_SCRIPT_FILTER = 0x200 + + MUI_RESET_FILTERS = 0x001 + + MUI_USER_PREFERRED_UI_LANGUAGES = 0x10 + + MUI_USE_INSTALLED_LANGUAGES = 0x20 + + MUI_USE_SEARCH_ALL_LANGUAGES = 0x40 + + MUI_LANG_NEUTRAL_PE_FILE = 0x100 + + MUI_NON_LANG_NEUTRAL_FILE = 0x200 + + MUI_MACHINE_LANGUAGE_SETTINGS = 0x400 + + MUI_FILETYPE_NOT_LANGUAGE_NEUTRAL = 0x001 + + MUI_FILETYPE_LANGUAGE_NEUTRAL_MAIN = 0x002 + + MUI_FILETYPE_LANGUAGE_NEUTRAL_MUI = 0x004 + + MUI_QUERY_TYPE = 0x001 + + MUI_QUERY_CHECKSUM = 0x002 + + MUI_QUERY_LANGUAGE_NAME = 0x004 + + MUI_QUERY_RESOURCE_TYPES = 0x008 + + MUI_FILEINFO_VERSION = 0x001 + + MUI_FULL_LANGUAGE = 0x01 + + MUI_PARTIAL_LANGUAGE = 0x02 + + MUI_LIP_LANGUAGE = 0x04 + MUI_LANGUAGE_INSTALLED = 0x20 - MUI_LANGUAGE_LICENSED = 0x40 + + MUI_LANGUAGE_LICENSED = 0x40 ) // FILE_INFO_BY_HANDLE_CLASS constants for SetFileInformationByHandle/GetFileInformationByHandleEx + const ( - FileBasicInfo = 0 - FileStandardInfo = 1 - FileNameInfo = 2 - FileRenameInfo = 3 - FileDispositionInfo = 4 - FileAllocationInfo = 5 - FileEndOfFileInfo = 6 - FileStreamInfo = 7 - FileCompressionInfo = 8 - FileAttributeTagInfo = 9 - FileIdBothDirectoryInfo = 10 + FileBasicInfo = 0 + + FileStandardInfo = 1 + + FileNameInfo = 2 + + FileRenameInfo = 3 + + FileDispositionInfo = 4 + + FileAllocationInfo = 5 + + FileEndOfFileInfo = 6 + + FileStreamInfo = 7 + + FileCompressionInfo = 8 + + FileAttributeTagInfo = 9 + + FileIdBothDirectoryInfo = 10 + FileIdBothDirectoryRestartInfo = 11 - FileIoPriorityHintInfo = 12 - FileRemoteProtocolInfo = 13 - FileFullDirectoryInfo = 14 - FileFullDirectoryRestartInfo = 15 - FileStorageInfo = 16 - FileAlignmentInfo = 17 - FileIdInfo = 18 - FileIdExtdDirectoryInfo = 19 + + FileIoPriorityHintInfo = 12 + + FileRemoteProtocolInfo = 13 + + FileFullDirectoryInfo = 14 + + FileFullDirectoryRestartInfo = 15 + + FileStorageInfo = 16 + + FileAlignmentInfo = 17 + + FileIdInfo = 18 + + FileIdExtdDirectoryInfo = 19 + FileIdExtdDirectoryRestartInfo = 20 - FileDispositionInfoEx = 21 - FileRenameInfoEx = 22 - FileCaseSensitiveInfo = 23 - FileNormalizedNameInfo = 24 + + FileDispositionInfoEx = 21 + + FileRenameInfoEx = 22 + + FileCaseSensitiveInfo = 23 + + FileNormalizedNameInfo = 24 ) // LoadLibrary flags for determining from where to search for a DLL + const ( - DONT_RESOLVE_DLL_REFERENCES = 0x1 - LOAD_LIBRARY_AS_DATAFILE = 0x2 - LOAD_WITH_ALTERED_SEARCH_PATH = 0x8 - LOAD_IGNORE_CODE_AUTHZ_LEVEL = 0x10 - LOAD_LIBRARY_AS_IMAGE_RESOURCE = 0x20 - LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE = 0x40 - LOAD_LIBRARY_REQUIRE_SIGNED_TARGET = 0x80 - LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR = 0x100 - LOAD_LIBRARY_SEARCH_APPLICATION_DIR = 0x200 - LOAD_LIBRARY_SEARCH_USER_DIRS = 0x400 - LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x800 - LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x1000 - LOAD_LIBRARY_SAFE_CURRENT_DIRS = 0x00002000 + DONT_RESOLVE_DLL_REFERENCES = 0x1 + + LOAD_LIBRARY_AS_DATAFILE = 0x2 + + LOAD_WITH_ALTERED_SEARCH_PATH = 0x8 + + LOAD_IGNORE_CODE_AUTHZ_LEVEL = 0x10 + + LOAD_LIBRARY_AS_IMAGE_RESOURCE = 0x20 + + LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE = 0x40 + + LOAD_LIBRARY_REQUIRE_SIGNED_TARGET = 0x80 + + LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR = 0x100 + + LOAD_LIBRARY_SEARCH_APPLICATION_DIR = 0x200 + + LOAD_LIBRARY_SEARCH_USER_DIRS = 0x400 + + LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x800 + + LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x1000 + + LOAD_LIBRARY_SAFE_CURRENT_DIRS = 0x00002000 + LOAD_LIBRARY_SEARCH_SYSTEM32_NO_FORWARDER = 0x00004000 - LOAD_LIBRARY_OS_INTEGRITY_CONTINUITY = 0x00008000 + + LOAD_LIBRARY_OS_INTEGRITY_CONTINUITY = 0x00008000 ) // RegNotifyChangeKeyValue notifyFilter flags. + const ( + // REG_NOTIFY_CHANGE_NAME notifies the caller if a subkey is added or deleted. + REG_NOTIFY_CHANGE_NAME = 0x00000001 // REG_NOTIFY_CHANGE_ATTRIBUTES notifies the caller of changes to the attributes of the key, such as the security descriptor information. + REG_NOTIFY_CHANGE_ATTRIBUTES = 0x00000002 // REG_NOTIFY_CHANGE_LAST_SET notifies the caller of changes to a value of the key. This can include adding or deleting a value, or changing an existing value. + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 // REG_NOTIFY_CHANGE_SECURITY notifies the caller of changes to the security descriptor of the key. + REG_NOTIFY_CHANGE_SECURITY = 0x00000008 // REG_NOTIFY_THREAD_AGNOSTIC indicates that the lifetime of the registration must not be tied to the lifetime of the thread issuing the RegNotifyChangeKeyValue call. Note: This flag value is only supported in Windows 8 and later. + REG_NOTIFY_THREAD_AGNOSTIC = 0x10000000 ) type CommTimeouts struct { - ReadIntervalTimeout uint32 - ReadTotalTimeoutMultiplier uint32 - ReadTotalTimeoutConstant uint32 + ReadIntervalTimeout uint32 + + ReadTotalTimeoutMultiplier uint32 + + ReadTotalTimeoutConstant uint32 + WriteTotalTimeoutMultiplier uint32 - WriteTotalTimeoutConstant uint32 + + WriteTotalTimeoutConstant uint32 } // NTUnicodeString is a UTF-16 string for NT native APIs, corresponding to UNICODE_STRING. + type NTUnicodeString struct { - Length uint16 + Length uint16 + MaximumLength uint16 - Buffer *uint16 + + Buffer *uint16 } // NTString is an ANSI string for NT native APIs, corresponding to STRING. + type NTString struct { - Length uint16 + Length uint16 + MaximumLength uint16 - Buffer *byte + + Buffer *byte } type LIST_ENTRY struct { Flink *LIST_ENTRY + Blink *LIST_ENTRY } type RUNTIME_FUNCTION struct { BeginAddress uint32 - EndAddress uint32 - UnwindData uint32 + + EndAddress uint32 + + UnwindData uint32 } type LDR_DATA_TABLE_ENTRY struct { - reserved1 [2]uintptr + reserved1 [2]uintptr + InMemoryOrderLinks LIST_ENTRY - reserved2 [2]uintptr - DllBase uintptr - reserved3 [2]uintptr - FullDllName NTUnicodeString - reserved4 [8]byte - reserved5 [3]uintptr - reserved6 uintptr - TimeDateStamp uint32 + + reserved2 [2]uintptr + + DllBase uintptr + + reserved3 [2]uintptr + + FullDllName NTUnicodeString + + reserved4 [8]byte + + reserved5 [3]uintptr + + reserved6 uintptr + + TimeDateStamp uint32 } type PEB_LDR_DATA struct { - reserved1 [8]byte - reserved2 [3]uintptr + reserved1 [8]byte + + reserved2 [3]uintptr + InMemoryOrderModuleList LIST_ENTRY } type CURDIR struct { DosPath NTUnicodeString - Handle Handle + + Handle Handle } type RTL_DRIVE_LETTER_CURDIR struct { - Flags uint16 - Length uint16 + Flags uint16 + + Length uint16 + TimeStamp uint32 - DosPath NTString + + DosPath NTString } type RTL_USER_PROCESS_PARAMETERS struct { @@ -2546,861 +4276,1518 @@ type RTL_USER_PROCESS_PARAMETERS struct { Flags, DebugFlags uint32 - ConsoleHandle Handle - ConsoleFlags uint32 + ConsoleHandle Handle + + ConsoleFlags uint32 + StandardInput, StandardOutput, StandardError Handle CurrentDirectory CURDIR - DllPath NTUnicodeString - ImagePathName NTUnicodeString - CommandLine NTUnicodeString - Environment unsafe.Pointer + + DllPath NTUnicodeString + + ImagePathName NTUnicodeString + + CommandLine NTUnicodeString + + Environment unsafe.Pointer StartingX, StartingY, CountX, CountY, CountCharsX, CountCharsY, FillAttribute uint32 - WindowFlags, ShowWindowFlags uint32 + WindowFlags, ShowWindowFlags uint32 + WindowTitle, DesktopInfo, ShellInfo, RuntimeData NTUnicodeString - CurrentDirectories [32]RTL_DRIVE_LETTER_CURDIR + + CurrentDirectories [32]RTL_DRIVE_LETTER_CURDIR EnvironmentSize, EnvironmentVersion uintptr PackageDependencyData unsafe.Pointer - ProcessGroupId uint32 - LoaderThreads uint32 - RedirectionDllName NTUnicodeString - HeapPartitionName NTUnicodeString - DefaultThreadpoolCpuSetMasks uintptr + ProcessGroupId uint32 + + LoaderThreads uint32 + + RedirectionDllName NTUnicodeString + + HeapPartitionName NTUnicodeString + + DefaultThreadpoolCpuSetMasks uintptr + DefaultThreadpoolCpuSetMaskCount uint32 } type PEB struct { - reserved1 [2]byte - BeingDebugged byte - BitField byte - reserved3 uintptr - ImageBaseAddress uintptr - Ldr *PEB_LDR_DATA - ProcessParameters *RTL_USER_PROCESS_PARAMETERS - reserved4 [3]uintptr - AtlThunkSListPtr uintptr - reserved5 uintptr - reserved6 uint32 - reserved7 uintptr - reserved8 uint32 - AtlThunkSListPtr32 uint32 - reserved9 [45]uintptr - reserved10 [96]byte + reserved1 [2]byte + + BeingDebugged byte + + BitField byte + + reserved3 uintptr + + ImageBaseAddress uintptr + + Ldr *PEB_LDR_DATA + + ProcessParameters *RTL_USER_PROCESS_PARAMETERS + + reserved4 [3]uintptr + + AtlThunkSListPtr uintptr + + reserved5 uintptr + + reserved6 uint32 + + reserved7 uintptr + + reserved8 uint32 + + AtlThunkSListPtr32 uint32 + + reserved9 [45]uintptr + + reserved10 [96]byte + PostProcessInitRoutine uintptr - reserved11 [128]byte - reserved12 [1]uintptr - SessionId uint32 + + reserved11 [128]byte + + reserved12 [1]uintptr + + SessionId uint32 } type OBJECT_ATTRIBUTES struct { - Length uint32 - RootDirectory Handle - ObjectName *NTUnicodeString - Attributes uint32 + Length uint32 + + RootDirectory Handle + + ObjectName *NTUnicodeString + + Attributes uint32 + SecurityDescriptor *SECURITY_DESCRIPTOR - SecurityQoS *SECURITY_QUALITY_OF_SERVICE + + SecurityQoS *SECURITY_QUALITY_OF_SERVICE } // Values for the Attributes member of OBJECT_ATTRIBUTES. + const ( - OBJ_INHERIT = 0x00000002 - OBJ_PERMANENT = 0x00000010 - OBJ_EXCLUSIVE = 0x00000020 - OBJ_CASE_INSENSITIVE = 0x00000040 - OBJ_OPENIF = 0x00000080 - OBJ_OPENLINK = 0x00000100 - OBJ_KERNEL_HANDLE = 0x00000200 - OBJ_FORCE_ACCESS_CHECK = 0x00000400 + OBJ_INHERIT = 0x00000002 + + OBJ_PERMANENT = 0x00000010 + + OBJ_EXCLUSIVE = 0x00000020 + + OBJ_CASE_INSENSITIVE = 0x00000040 + + OBJ_OPENIF = 0x00000080 + + OBJ_OPENLINK = 0x00000100 + + OBJ_KERNEL_HANDLE = 0x00000200 + + OBJ_FORCE_ACCESS_CHECK = 0x00000400 + OBJ_IGNORE_IMPERSONATED_DEVICEMAP = 0x00000800 - OBJ_DONT_REPARSE = 0x00001000 - OBJ_VALID_ATTRIBUTES = 0x00001FF2 + + OBJ_DONT_REPARSE = 0x00001000 + + OBJ_VALID_ATTRIBUTES = 0x00001FF2 ) type IO_STATUS_BLOCK struct { - Status NTStatus + Status NTStatus + Information uintptr } type RTLP_CURDIR_REF struct { RefCount int32 - Handle Handle + + Handle Handle } type RTL_RELATIVE_NAME struct { - RelativeName NTUnicodeString + RelativeName NTUnicodeString + ContainingDirectory Handle - CurDirRef *RTLP_CURDIR_REF + + CurDirRef *RTLP_CURDIR_REF } const ( + // CreateDisposition flags for NtCreateFile and NtCreateNamedPipeFile. - FILE_SUPERSEDE = 0x00000000 - FILE_OPEN = 0x00000001 - FILE_CREATE = 0x00000002 - FILE_OPEN_IF = 0x00000003 - FILE_OVERWRITE = 0x00000004 - FILE_OVERWRITE_IF = 0x00000005 + + FILE_SUPERSEDE = 0x00000000 + + FILE_OPEN = 0x00000001 + + FILE_CREATE = 0x00000002 + + FILE_OPEN_IF = 0x00000003 + + FILE_OVERWRITE = 0x00000004 + + FILE_OVERWRITE_IF = 0x00000005 + FILE_MAXIMUM_DISPOSITION = 0x00000005 // CreateOptions flags for NtCreateFile and NtCreateNamedPipeFile. - FILE_DIRECTORY_FILE = 0x00000001 - FILE_WRITE_THROUGH = 0x00000002 - FILE_SEQUENTIAL_ONLY = 0x00000004 + + FILE_DIRECTORY_FILE = 0x00000001 + + FILE_WRITE_THROUGH = 0x00000002 + + FILE_SEQUENTIAL_ONLY = 0x00000004 + FILE_NO_INTERMEDIATE_BUFFERING = 0x00000008 - FILE_SYNCHRONOUS_IO_ALERT = 0x00000010 - FILE_SYNCHRONOUS_IO_NONALERT = 0x00000020 - FILE_NON_DIRECTORY_FILE = 0x00000040 - FILE_CREATE_TREE_CONNECTION = 0x00000080 - FILE_COMPLETE_IF_OPLOCKED = 0x00000100 - FILE_NO_EA_KNOWLEDGE = 0x00000200 - FILE_OPEN_REMOTE_INSTANCE = 0x00000400 - FILE_RANDOM_ACCESS = 0x00000800 - FILE_DELETE_ON_CLOSE = 0x00001000 - FILE_OPEN_BY_FILE_ID = 0x00002000 - FILE_OPEN_FOR_BACKUP_INTENT = 0x00004000 - FILE_NO_COMPRESSION = 0x00008000 - FILE_OPEN_REQUIRING_OPLOCK = 0x00010000 - FILE_DISALLOW_EXCLUSIVE = 0x00020000 - FILE_RESERVE_OPFILTER = 0x00100000 - FILE_OPEN_REPARSE_POINT = 0x00200000 - FILE_OPEN_NO_RECALL = 0x00400000 + + FILE_SYNCHRONOUS_IO_ALERT = 0x00000010 + + FILE_SYNCHRONOUS_IO_NONALERT = 0x00000020 + + FILE_NON_DIRECTORY_FILE = 0x00000040 + + FILE_CREATE_TREE_CONNECTION = 0x00000080 + + FILE_COMPLETE_IF_OPLOCKED = 0x00000100 + + FILE_NO_EA_KNOWLEDGE = 0x00000200 + + FILE_OPEN_REMOTE_INSTANCE = 0x00000400 + + FILE_RANDOM_ACCESS = 0x00000800 + + FILE_DELETE_ON_CLOSE = 0x00001000 + + FILE_OPEN_BY_FILE_ID = 0x00002000 + + FILE_OPEN_FOR_BACKUP_INTENT = 0x00004000 + + FILE_NO_COMPRESSION = 0x00008000 + + FILE_OPEN_REQUIRING_OPLOCK = 0x00010000 + + FILE_DISALLOW_EXCLUSIVE = 0x00020000 + + FILE_RESERVE_OPFILTER = 0x00100000 + + FILE_OPEN_REPARSE_POINT = 0x00200000 + + FILE_OPEN_NO_RECALL = 0x00400000 + FILE_OPEN_FOR_FREE_SPACE_QUERY = 0x00800000 // Parameter constants for NtCreateNamedPipeFile. FILE_PIPE_BYTE_STREAM_TYPE = 0x00000000 - FILE_PIPE_MESSAGE_TYPE = 0x00000001 + + FILE_PIPE_MESSAGE_TYPE = 0x00000001 FILE_PIPE_ACCEPT_REMOTE_CLIENTS = 0x00000000 + FILE_PIPE_REJECT_REMOTE_CLIENTS = 0x00000002 FILE_PIPE_TYPE_VALID_MASK = 0x00000003 FILE_PIPE_BYTE_STREAM_MODE = 0x00000000 - FILE_PIPE_MESSAGE_MODE = 0x00000001 - FILE_PIPE_QUEUE_OPERATION = 0x00000000 + FILE_PIPE_MESSAGE_MODE = 0x00000001 + + FILE_PIPE_QUEUE_OPERATION = 0x00000000 + FILE_PIPE_COMPLETE_OPERATION = 0x00000001 - FILE_PIPE_INBOUND = 0x00000000 - FILE_PIPE_OUTBOUND = 0x00000001 + FILE_PIPE_INBOUND = 0x00000000 + + FILE_PIPE_OUTBOUND = 0x00000001 + FILE_PIPE_FULL_DUPLEX = 0x00000002 FILE_PIPE_DISCONNECTED_STATE = 0x00000001 - FILE_PIPE_LISTENING_STATE = 0x00000002 - FILE_PIPE_CONNECTED_STATE = 0x00000003 - FILE_PIPE_CLOSING_STATE = 0x00000004 + + FILE_PIPE_LISTENING_STATE = 0x00000002 + + FILE_PIPE_CONNECTED_STATE = 0x00000003 + + FILE_PIPE_CLOSING_STATE = 0x00000004 FILE_PIPE_CLIENT_END = 0x00000000 + FILE_PIPE_SERVER_END = 0x00000001 ) const ( + // FileInformationClass for NtSetInformationFile - FileBasicInformation = 4 - FileRenameInformation = 10 - FileDispositionInformation = 13 - FilePositionInformation = 14 - FileEndOfFileInformation = 20 - FileValidDataLengthInformation = 39 - FileShortNameInformation = 40 - FileIoPriorityHintInformation = 43 - FileReplaceCompletionInformation = 61 - FileDispositionInformationEx = 64 - FileCaseSensitiveInformation = 71 - FileLinkInformation = 72 + + FileBasicInformation = 4 + + FileRenameInformation = 10 + + FileDispositionInformation = 13 + + FilePositionInformation = 14 + + FileEndOfFileInformation = 20 + + FileValidDataLengthInformation = 39 + + FileShortNameInformation = 40 + + FileIoPriorityHintInformation = 43 + + FileReplaceCompletionInformation = 61 + + FileDispositionInformationEx = 64 + + FileCaseSensitiveInformation = 71 + + FileLinkInformation = 72 + FileCaseSensitiveInformationForceAccessCheck = 75 - FileKnownFolderInformation = 76 + + FileKnownFolderInformation = 76 // Flags for FILE_RENAME_INFORMATION - FILE_RENAME_REPLACE_IF_EXISTS = 0x00000001 - FILE_RENAME_POSIX_SEMANTICS = 0x00000002 - FILE_RENAME_SUPPRESS_PIN_STATE_INHERITANCE = 0x00000004 + + FILE_RENAME_REPLACE_IF_EXISTS = 0x00000001 + + FILE_RENAME_POSIX_SEMANTICS = 0x00000002 + + FILE_RENAME_SUPPRESS_PIN_STATE_INHERITANCE = 0x00000004 + FILE_RENAME_SUPPRESS_STORAGE_RESERVE_INHERITANCE = 0x00000008 - FILE_RENAME_NO_INCREASE_AVAILABLE_SPACE = 0x00000010 - FILE_RENAME_NO_DECREASE_AVAILABLE_SPACE = 0x00000020 - FILE_RENAME_PRESERVE_AVAILABLE_SPACE = 0x00000030 - FILE_RENAME_IGNORE_READONLY_ATTRIBUTE = 0x00000040 - FILE_RENAME_FORCE_RESIZE_TARGET_SR = 0x00000080 - FILE_RENAME_FORCE_RESIZE_SOURCE_SR = 0x00000100 - FILE_RENAME_FORCE_RESIZE_SR = 0x00000180 + + FILE_RENAME_NO_INCREASE_AVAILABLE_SPACE = 0x00000010 + + FILE_RENAME_NO_DECREASE_AVAILABLE_SPACE = 0x00000020 + + FILE_RENAME_PRESERVE_AVAILABLE_SPACE = 0x00000030 + + FILE_RENAME_IGNORE_READONLY_ATTRIBUTE = 0x00000040 + + FILE_RENAME_FORCE_RESIZE_TARGET_SR = 0x00000080 + + FILE_RENAME_FORCE_RESIZE_SOURCE_SR = 0x00000100 + + FILE_RENAME_FORCE_RESIZE_SR = 0x00000180 // Flags for FILE_DISPOSITION_INFORMATION_EX - FILE_DISPOSITION_DO_NOT_DELETE = 0x00000000 - FILE_DISPOSITION_DELETE = 0x00000001 - FILE_DISPOSITION_POSIX_SEMANTICS = 0x00000002 + + FILE_DISPOSITION_DO_NOT_DELETE = 0x00000000 + + FILE_DISPOSITION_DELETE = 0x00000001 + + FILE_DISPOSITION_POSIX_SEMANTICS = 0x00000002 + FILE_DISPOSITION_FORCE_IMAGE_SECTION_CHECK = 0x00000004 - FILE_DISPOSITION_ON_CLOSE = 0x00000008 + + FILE_DISPOSITION_ON_CLOSE = 0x00000008 + FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE = 0x00000010 // Flags for FILE_CASE_SENSITIVE_INFORMATION + FILE_CS_FLAG_CASE_SENSITIVE_DIR = 0x00000001 // Flags for FILE_LINK_INFORMATION - FILE_LINK_REPLACE_IF_EXISTS = 0x00000001 - FILE_LINK_POSIX_SEMANTICS = 0x00000002 + + FILE_LINK_REPLACE_IF_EXISTS = 0x00000001 + + FILE_LINK_POSIX_SEMANTICS = 0x00000002 + FILE_LINK_SUPPRESS_STORAGE_RESERVE_INHERITANCE = 0x00000008 - FILE_LINK_NO_INCREASE_AVAILABLE_SPACE = 0x00000010 - FILE_LINK_NO_DECREASE_AVAILABLE_SPACE = 0x00000020 - FILE_LINK_PRESERVE_AVAILABLE_SPACE = 0x00000030 - FILE_LINK_IGNORE_READONLY_ATTRIBUTE = 0x00000040 - FILE_LINK_FORCE_RESIZE_TARGET_SR = 0x00000080 - FILE_LINK_FORCE_RESIZE_SOURCE_SR = 0x00000100 - FILE_LINK_FORCE_RESIZE_SR = 0x00000180 + + FILE_LINK_NO_INCREASE_AVAILABLE_SPACE = 0x00000010 + + FILE_LINK_NO_DECREASE_AVAILABLE_SPACE = 0x00000020 + + FILE_LINK_PRESERVE_AVAILABLE_SPACE = 0x00000030 + + FILE_LINK_IGNORE_READONLY_ATTRIBUTE = 0x00000040 + + FILE_LINK_FORCE_RESIZE_TARGET_SR = 0x00000080 + + FILE_LINK_FORCE_RESIZE_SOURCE_SR = 0x00000100 + + FILE_LINK_FORCE_RESIZE_SR = 0x00000180 ) // ProcessInformationClasses for NtQueryInformationProcess and NtSetInformationProcess. + const ( ProcessBasicInformation = iota + ProcessQuotaLimits + ProcessIoCounters + ProcessVmCounters + ProcessTimes + ProcessBasePriority + ProcessRaisePriority + ProcessDebugPort + ProcessExceptionPort + ProcessAccessToken + ProcessLdtInformation + ProcessLdtSize + ProcessDefaultHardErrorMode + ProcessIoPortHandlers + ProcessPooledUsageAndLimits + ProcessWorkingSetWatch + ProcessUserModeIOPL + ProcessEnableAlignmentFaultFixup + ProcessPriorityClass + ProcessWx86Information + ProcessHandleCount + ProcessAffinityMask + ProcessPriorityBoost + ProcessDeviceMap + ProcessSessionInformation + ProcessForegroundInformation + ProcessWow64Information + ProcessImageFileName + ProcessLUIDDeviceMapsEnabled + ProcessBreakOnTermination + ProcessDebugObjectHandle + ProcessDebugFlags + ProcessHandleTracing + ProcessIoPriority + ProcessExecuteFlags + ProcessTlsInformation + ProcessCookie + ProcessImageInformation + ProcessCycleTime + ProcessPagePriority + ProcessInstrumentationCallback + ProcessThreadStackAllocation + ProcessWorkingSetWatchEx + ProcessImageFileNameWin32 + ProcessImageFileMapping + ProcessAffinityUpdateMode + ProcessMemoryAllocationMode + ProcessGroupInformation + ProcessTokenVirtualizationEnabled + ProcessConsoleHostProcess + ProcessWindowInformation + ProcessHandleInformation + ProcessMitigationPolicy + ProcessDynamicFunctionTableInformation + ProcessHandleCheckingMode + ProcessKeepAliveCount + ProcessRevokeFileHandles + ProcessWorkingSetControl + ProcessHandleTable + ProcessCheckStackExtentsMode + ProcessCommandLineInformation + ProcessProtectionInformation + ProcessMemoryExhaustion + ProcessFaultInformation + ProcessTelemetryIdInformation + ProcessCommitReleaseInformation + ProcessDefaultCpuSetsInformation + ProcessAllowedCpuSetsInformation + ProcessSubsystemProcess + ProcessJobMemoryInformation + ProcessInPrivate + ProcessRaiseUMExceptionOnInvalidHandleClose + ProcessIumChallengeResponse + ProcessChildProcessInformation + ProcessHighGraphicsPriorityInformation + ProcessSubsystemInformation + ProcessEnergyValues + ProcessActivityThrottleState + ProcessActivityThrottlePolicy + ProcessWin32kSyscallFilterInformation + ProcessDisableSystemAllowedCpuSets + ProcessWakeInformation + ProcessEnergyTrackingState + ProcessManageWritesToExecutableMemory + ProcessCaptureTrustletLiveDump + ProcessTelemetryCoverage + ProcessEnclaveInformation + ProcessEnableReadWriteVmLogging + ProcessUptimeInformation + ProcessImageSection + ProcessDebugAuthInformation + ProcessSystemResourceManagement + ProcessSequenceNumber + ProcessLoaderDetour + ProcessSecurityDomainInformation + ProcessCombineSecurityDomainsInformation + ProcessEnableLogging + ProcessLeapSecondInformation + ProcessFiberShadowStackAllocation + ProcessFreeFiberShadowStackAllocation + ProcessAltSystemCallInformation + ProcessDynamicEHContinuationTargets + ProcessDynamicEnforcedCetCompatibleRanges ) type PROCESS_BASIC_INFORMATION struct { - ExitStatus NTStatus - PebBaseAddress *PEB - AffinityMask uintptr - BasePriority int32 - UniqueProcessId uintptr + ExitStatus NTStatus + + PebBaseAddress *PEB + + AffinityMask uintptr + + BasePriority int32 + + UniqueProcessId uintptr + InheritedFromUniqueProcessId uintptr } type SYSTEM_PROCESS_INFORMATION struct { - NextEntryOffset uint32 - NumberOfThreads uint32 - WorkingSetPrivateSize int64 - HardFaultCount uint32 + NextEntryOffset uint32 + + NumberOfThreads uint32 + + WorkingSetPrivateSize int64 + + HardFaultCount uint32 + NumberOfThreadsHighWatermark uint32 - CycleTime uint64 - CreateTime int64 - UserTime int64 - KernelTime int64 - ImageName NTUnicodeString - BasePriority int32 - UniqueProcessID uintptr + + CycleTime uint64 + + CreateTime int64 + + UserTime int64 + + KernelTime int64 + + ImageName NTUnicodeString + + BasePriority int32 + + UniqueProcessID uintptr + InheritedFromUniqueProcessID uintptr - HandleCount uint32 - SessionID uint32 - UniqueProcessKey *uint32 - PeakVirtualSize uintptr - VirtualSize uintptr - PageFaultCount uint32 - PeakWorkingSetSize uintptr - WorkingSetSize uintptr - QuotaPeakPagedPoolUsage uintptr - QuotaPagedPoolUsage uintptr - QuotaPeakNonPagedPoolUsage uintptr - QuotaNonPagedPoolUsage uintptr - PagefileUsage uintptr - PeakPagefileUsage uintptr - PrivatePageCount uintptr - ReadOperationCount int64 - WriteOperationCount int64 - OtherOperationCount int64 - ReadTransferCount int64 - WriteTransferCount int64 - OtherTransferCount int64 + + HandleCount uint32 + + SessionID uint32 + + UniqueProcessKey *uint32 + + PeakVirtualSize uintptr + + VirtualSize uintptr + + PageFaultCount uint32 + + PeakWorkingSetSize uintptr + + WorkingSetSize uintptr + + QuotaPeakPagedPoolUsage uintptr + + QuotaPagedPoolUsage uintptr + + QuotaPeakNonPagedPoolUsage uintptr + + QuotaNonPagedPoolUsage uintptr + + PagefileUsage uintptr + + PeakPagefileUsage uintptr + + PrivatePageCount uintptr + + ReadOperationCount int64 + + WriteOperationCount int64 + + OtherOperationCount int64 + + ReadTransferCount int64 + + WriteTransferCount int64 + + OtherTransferCount int64 } // SystemInformationClasses for NtQuerySystemInformation and NtSetSystemInformation + const ( SystemBasicInformation = iota + SystemProcessorInformation + SystemPerformanceInformation + SystemTimeOfDayInformation + SystemPathInformation + SystemProcessInformation + SystemCallCountInformation + SystemDeviceInformation + SystemProcessorPerformanceInformation + SystemFlagsInformation + SystemCallTimeInformation + SystemModuleInformation + SystemLocksInformation + SystemStackTraceInformation + SystemPagedPoolInformation + SystemNonPagedPoolInformation + SystemHandleInformation + SystemObjectInformation + SystemPageFileInformation + SystemVdmInstemulInformation + SystemVdmBopInformation + SystemFileCacheInformation + SystemPoolTagInformation + SystemInterruptInformation + SystemDpcBehaviorInformation + SystemFullMemoryInformation + SystemLoadGdiDriverInformation + SystemUnloadGdiDriverInformation + SystemTimeAdjustmentInformation + SystemSummaryMemoryInformation + SystemMirrorMemoryInformation + SystemPerformanceTraceInformation + systemObsolete0 + SystemExceptionInformation + SystemCrashDumpStateInformation + SystemKernelDebuggerInformation + SystemContextSwitchInformation + SystemRegistryQuotaInformation + SystemExtendServiceTableInformation + SystemPrioritySeperation + SystemVerifierAddDriverInformation + SystemVerifierRemoveDriverInformation + SystemProcessorIdleInformation + SystemLegacyDriverInformation + SystemCurrentTimeZoneInformation + SystemLookasideInformation + SystemTimeSlipNotification + SystemSessionCreate + SystemSessionDetach + SystemSessionInformation + SystemRangeStartInformation + SystemVerifierInformation + SystemVerifierThunkExtend + SystemSessionProcessInformation + SystemLoadGdiDriverInSystemSpace + SystemNumaProcessorMap + SystemPrefetcherInformation + SystemExtendedProcessInformation + SystemRecommendedSharedDataAlignment + SystemComPlusPackage + SystemNumaAvailableMemory + SystemProcessorPowerInformation + SystemEmulationBasicInformation + SystemEmulationProcessorInformation + SystemExtendedHandleInformation + SystemLostDelayedWriteInformation + SystemBigPoolInformation + SystemSessionPoolTagInformation + SystemSessionMappedViewInformation + SystemHotpatchInformation + SystemObjectSecurityMode + SystemWatchdogTimerHandler + SystemWatchdogTimerInformation + SystemLogicalProcessorInformation + SystemWow64SharedInformationObsolete + SystemRegisterFirmwareTableInformationHandler + SystemFirmwareTableInformation + SystemModuleInformationEx + SystemVerifierTriageInformation + SystemSuperfetchInformation + SystemMemoryListInformation + SystemFileCacheInformationEx + SystemThreadPriorityClientIdInformation + SystemProcessorIdleCycleTimeInformation + SystemVerifierCancellationInformation + SystemProcessorPowerInformationEx + SystemRefTraceInformation + SystemSpecialPoolInformation + SystemProcessIdInformation + SystemErrorPortInformation + SystemBootEnvironmentInformation + SystemHypervisorInformation + SystemVerifierInformationEx + SystemTimeZoneInformation + SystemImageFileExecutionOptionsInformation + SystemCoverageInformation + SystemPrefetchPatchInformation + SystemVerifierFaultsInformation + SystemSystemPartitionInformation + SystemSystemDiskInformation + SystemProcessorPerformanceDistribution + SystemNumaProximityNodeInformation + SystemDynamicTimeZoneInformation + SystemCodeIntegrityInformation + SystemProcessorMicrocodeUpdateInformation + SystemProcessorBrandString + SystemVirtualAddressInformation + SystemLogicalProcessorAndGroupInformation + SystemProcessorCycleTimeInformation + SystemStoreInformation + SystemRegistryAppendString + SystemAitSamplingValue + SystemVhdBootInformation + SystemCpuQuotaInformation + SystemNativeBasicInformation + systemSpare1 + SystemLowPriorityIoInformation + SystemTpmBootEntropyInformation + SystemVerifierCountersInformation + SystemPagedPoolInformationEx + SystemSystemPtesInformationEx + SystemNodeDistanceInformation + SystemAcpiAuditInformation + SystemBasicPerformanceInformation + SystemQueryPerformanceCounterInformation + SystemSessionBigPoolInformation + SystemBootGraphicsInformation + SystemScrubPhysicalMemoryInformation + SystemBadPageInformation + SystemProcessorProfileControlArea + SystemCombinePhysicalMemoryInformation + SystemEntropyInterruptTimingCallback + SystemConsoleInformation + SystemPlatformBinaryInformation + SystemThrottleNotificationInformation + SystemHypervisorProcessorCountInformation + SystemDeviceDataInformation + SystemDeviceDataEnumerationInformation + SystemMemoryTopologyInformation + SystemMemoryChannelInformation + SystemBootLogoInformation + SystemProcessorPerformanceInformationEx + systemSpare0 + SystemSecureBootPolicyInformation + SystemPageFileInformationEx + SystemSecureBootInformation + SystemEntropyInterruptTimingRawInformation + SystemPortableWorkspaceEfiLauncherInformation + SystemFullProcessInformation + SystemKernelDebuggerInformationEx + SystemBootMetadataInformation + SystemSoftRebootInformation + SystemElamCertificateInformation + SystemOfflineDumpConfigInformation + SystemProcessorFeaturesInformation + SystemRegistryReconciliationInformation + SystemEdidInformation + SystemManufacturingInformation + SystemEnergyEstimationConfigInformation + SystemHypervisorDetailInformation + SystemProcessorCycleStatsInformation + SystemVmGenerationCountInformation + SystemTrustedPlatformModuleInformation + SystemKernelDebuggerFlags + SystemCodeIntegrityPolicyInformation + SystemIsolatedUserModeInformation + SystemHardwareSecurityTestInterfaceResultsInformation + SystemSingleModuleInformation + SystemAllowedCpuSetsInformation + SystemDmaProtectionInformation + SystemInterruptCpuSetsInformation + SystemSecureBootPolicyFullInformation + SystemCodeIntegrityPolicyFullInformation + SystemAffinitizedInterruptProcessorInformation + SystemRootSiloInformation ) type RTL_PROCESS_MODULE_INFORMATION struct { - Section Handle - MappedBase uintptr - ImageBase uintptr - ImageSize uint32 - Flags uint32 - LoadOrderIndex uint16 - InitOrderIndex uint16 - LoadCount uint16 + Section Handle + + MappedBase uintptr + + ImageBase uintptr + + ImageSize uint32 + + Flags uint32 + + LoadOrderIndex uint16 + + InitOrderIndex uint16 + + LoadCount uint16 + OffsetToFileName uint16 - FullPathName [256]byte + + FullPathName [256]byte } type RTL_PROCESS_MODULES struct { NumberOfModules uint32 - Modules [1]RTL_PROCESS_MODULE_INFORMATION + + Modules [1]RTL_PROCESS_MODULE_INFORMATION } // Constants for LocalAlloc flags. + const ( - LMEM_FIXED = 0x0 - LMEM_MOVEABLE = 0x2 - LMEM_NOCOMPACT = 0x10 - LMEM_NODISCARD = 0x20 - LMEM_ZEROINIT = 0x40 - LMEM_MODIFY = 0x80 - LMEM_DISCARDABLE = 0xf00 - LMEM_VALID_FLAGS = 0xf72 + LMEM_FIXED = 0x0 + + LMEM_MOVEABLE = 0x2 + + LMEM_NOCOMPACT = 0x10 + + LMEM_NODISCARD = 0x20 + + LMEM_ZEROINIT = 0x40 + + LMEM_MODIFY = 0x80 + + LMEM_DISCARDABLE = 0xf00 + + LMEM_VALID_FLAGS = 0xf72 + LMEM_INVALID_HANDLE = 0x8000 - LHND = LMEM_MOVEABLE | LMEM_ZEROINIT - LPTR = LMEM_FIXED | LMEM_ZEROINIT - NONZEROLHND = LMEM_MOVEABLE - NONZEROLPTR = LMEM_FIXED + + LHND = LMEM_MOVEABLE | LMEM_ZEROINIT + + LPTR = LMEM_FIXED | LMEM_ZEROINIT + + NONZEROLHND = LMEM_MOVEABLE + + NONZEROLPTR = LMEM_FIXED ) // Constants for the CreateNamedPipe-family of functions. + const ( - PIPE_ACCESS_INBOUND = 0x1 + PIPE_ACCESS_INBOUND = 0x1 + PIPE_ACCESS_OUTBOUND = 0x2 - PIPE_ACCESS_DUPLEX = 0x3 + + PIPE_ACCESS_DUPLEX = 0x3 PIPE_CLIENT_END = 0x0 + PIPE_SERVER_END = 0x1 - PIPE_WAIT = 0x0 - PIPE_NOWAIT = 0x1 - PIPE_READMODE_BYTE = 0x0 - PIPE_READMODE_MESSAGE = 0x2 - PIPE_TYPE_BYTE = 0x0 - PIPE_TYPE_MESSAGE = 0x4 + PIPE_WAIT = 0x0 + + PIPE_NOWAIT = 0x1 + + PIPE_READMODE_BYTE = 0x0 + + PIPE_READMODE_MESSAGE = 0x2 + + PIPE_TYPE_BYTE = 0x0 + + PIPE_TYPE_MESSAGE = 0x4 + PIPE_ACCEPT_REMOTE_CLIENTS = 0x0 + PIPE_REJECT_REMOTE_CLIENTS = 0x8 PIPE_UNLIMITED_INSTANCES = 255 ) // Constants for security attributes when opening named pipes. + const ( - SECURITY_ANONYMOUS = SecurityAnonymous << 16 + SECURITY_ANONYMOUS = SecurityAnonymous << 16 + SECURITY_IDENTIFICATION = SecurityIdentification << 16 - SECURITY_IMPERSONATION = SecurityImpersonation << 16 - SECURITY_DELEGATION = SecurityDelegation << 16 + + SECURITY_IMPERSONATION = SecurityImpersonation << 16 + + SECURITY_DELEGATION = SecurityDelegation << 16 SECURITY_CONTEXT_TRACKING = 0x40000 - SECURITY_EFFECTIVE_ONLY = 0x80000 - SECURITY_SQOS_PRESENT = 0x100000 + SECURITY_EFFECTIVE_ONLY = 0x80000 + + SECURITY_SQOS_PRESENT = 0x100000 + SECURITY_VALID_SQOS_FLAGS = 0x1f0000 ) // ResourceID represents a 16-bit resource identifier, traditionally created with the MAKEINTRESOURCE macro. + type ResourceID uint16 // ResourceIDOrString must be either a ResourceID, to specify a resource or resource type by ID, + // or a string, to specify a resource or resource type by name. + type ResourceIDOrString interface{} // Predefined resource names and types. + var ( + // Predefined names. - CREATEPROCESS_MANIFEST_RESOURCE_ID ResourceID = 1 - ISOLATIONAWARE_MANIFEST_RESOURCE_ID ResourceID = 2 + + CREATEPROCESS_MANIFEST_RESOURCE_ID ResourceID = 1 + + ISOLATIONAWARE_MANIFEST_RESOURCE_ID ResourceID = 2 + ISOLATIONAWARE_NOSTATICIMPORT_MANIFEST_RESOURCE_ID ResourceID = 3 - ISOLATIONPOLICY_MANIFEST_RESOURCE_ID ResourceID = 4 - ISOLATIONPOLICY_BROWSER_MANIFEST_RESOURCE_ID ResourceID = 5 - MINIMUM_RESERVED_MANIFEST_RESOURCE_ID ResourceID = 1 // inclusive - MAXIMUM_RESERVED_MANIFEST_RESOURCE_ID ResourceID = 16 // inclusive + + ISOLATIONPOLICY_MANIFEST_RESOURCE_ID ResourceID = 4 + + ISOLATIONPOLICY_BROWSER_MANIFEST_RESOURCE_ID ResourceID = 5 + + MINIMUM_RESERVED_MANIFEST_RESOURCE_ID ResourceID = 1 // inclusive + + MAXIMUM_RESERVED_MANIFEST_RESOURCE_ID ResourceID = 16 // inclusive // Predefined types. - RT_CURSOR ResourceID = 1 - RT_BITMAP ResourceID = 2 - RT_ICON ResourceID = 3 - RT_MENU ResourceID = 4 - RT_DIALOG ResourceID = 5 - RT_STRING ResourceID = 6 - RT_FONTDIR ResourceID = 7 - RT_FONT ResourceID = 8 - RT_ACCELERATOR ResourceID = 9 - RT_RCDATA ResourceID = 10 + + RT_CURSOR ResourceID = 1 + + RT_BITMAP ResourceID = 2 + + RT_ICON ResourceID = 3 + + RT_MENU ResourceID = 4 + + RT_DIALOG ResourceID = 5 + + RT_STRING ResourceID = 6 + + RT_FONTDIR ResourceID = 7 + + RT_FONT ResourceID = 8 + + RT_ACCELERATOR ResourceID = 9 + + RT_RCDATA ResourceID = 10 + RT_MESSAGETABLE ResourceID = 11 + RT_GROUP_CURSOR ResourceID = 12 - RT_GROUP_ICON ResourceID = 14 - RT_VERSION ResourceID = 16 - RT_DLGINCLUDE ResourceID = 17 - RT_PLUGPLAY ResourceID = 19 - RT_VXD ResourceID = 20 - RT_ANICURSOR ResourceID = 21 - RT_ANIICON ResourceID = 22 - RT_HTML ResourceID = 23 - RT_MANIFEST ResourceID = 24 + + RT_GROUP_ICON ResourceID = 14 + + RT_VERSION ResourceID = 16 + + RT_DLGINCLUDE ResourceID = 17 + + RT_PLUGPLAY ResourceID = 19 + + RT_VXD ResourceID = 20 + + RT_ANICURSOR ResourceID = 21 + + RT_ANIICON ResourceID = 22 + + RT_HTML ResourceID = 23 + + RT_MANIFEST ResourceID = 24 ) type VS_FIXEDFILEINFO struct { - Signature uint32 - StrucVersion uint32 - FileVersionMS uint32 - FileVersionLS uint32 + Signature uint32 + + StrucVersion uint32 + + FileVersionMS uint32 + + FileVersionLS uint32 + ProductVersionMS uint32 + ProductVersionLS uint32 - FileFlagsMask uint32 - FileFlags uint32 - FileOS uint32 - FileType uint32 - FileSubtype uint32 - FileDateMS uint32 - FileDateLS uint32 + + FileFlagsMask uint32 + + FileFlags uint32 + + FileOS uint32 + + FileType uint32 + + FileSubtype uint32 + + FileDateMS uint32 + + FileDateLS uint32 } type COAUTHIDENTITY struct { - User *uint16 - UserLength uint32 - Domain *uint16 - DomainLength uint32 - Password *uint16 + User *uint16 + + UserLength uint32 + + Domain *uint16 + + DomainLength uint32 + + Password *uint16 + PasswordLength uint32 - Flags uint32 + + Flags uint32 } type COAUTHINFO struct { - AuthnSvc uint32 - AuthzSvc uint32 - ServerPrincName *uint16 - AuthnLevel uint32 + AuthnSvc uint32 + + AuthzSvc uint32 + + ServerPrincName *uint16 + + AuthnLevel uint32 + ImpersonationLevel uint32 - AuthIdentityData *COAUTHIDENTITY - Capabilities uint32 + + AuthIdentityData *COAUTHIDENTITY + + Capabilities uint32 } type COSERVERINFO struct { Reserved1 uint32 - Aame *uint16 - AuthInfo *COAUTHINFO + + Aame *uint16 + + AuthInfo *COAUTHINFO + Reserved2 uint32 } type BIND_OPTS3 struct { - CbStruct uint32 - Flags uint32 - Mode uint32 + CbStruct uint32 + + Flags uint32 + + Mode uint32 + TickCountDeadline uint32 - TrackFlags uint32 - ClassContext uint32 - Locale uint32 - ServerInfo *COSERVERINFO - Hwnd HWND + + TrackFlags uint32 + + ClassContext uint32 + + Locale uint32 + + ServerInfo *COSERVERINFO + + Hwnd HWND } const ( - CLSCTX_INPROC_SERVER = 0x1 - CLSCTX_INPROC_HANDLER = 0x2 - CLSCTX_LOCAL_SERVER = 0x4 - CLSCTX_INPROC_SERVER16 = 0x8 - CLSCTX_REMOTE_SERVER = 0x10 - CLSCTX_INPROC_HANDLER16 = 0x20 - CLSCTX_RESERVED1 = 0x40 - CLSCTX_RESERVED2 = 0x80 - CLSCTX_RESERVED3 = 0x100 - CLSCTX_RESERVED4 = 0x200 - CLSCTX_NO_CODE_DOWNLOAD = 0x400 - CLSCTX_RESERVED5 = 0x800 - CLSCTX_NO_CUSTOM_MARSHAL = 0x1000 - CLSCTX_ENABLE_CODE_DOWNLOAD = 0x2000 - CLSCTX_NO_FAILURE_LOG = 0x4000 - CLSCTX_DISABLE_AAA = 0x8000 - CLSCTX_ENABLE_AAA = 0x10000 - CLSCTX_FROM_DEFAULT_CONTEXT = 0x20000 - CLSCTX_ACTIVATE_32_BIT_SERVER = 0x40000 - CLSCTX_ACTIVATE_64_BIT_SERVER = 0x80000 - CLSCTX_ENABLE_CLOAKING = 0x100000 - CLSCTX_APPCONTAINER = 0x400000 - CLSCTX_ACTIVATE_AAA_AS_IU = 0x800000 - CLSCTX_PS_DLL = 0x80000000 + CLSCTX_INPROC_SERVER = 0x1 + + CLSCTX_INPROC_HANDLER = 0x2 + + CLSCTX_LOCAL_SERVER = 0x4 + + CLSCTX_INPROC_SERVER16 = 0x8 + + CLSCTX_REMOTE_SERVER = 0x10 + + CLSCTX_INPROC_HANDLER16 = 0x20 + + CLSCTX_RESERVED1 = 0x40 + + CLSCTX_RESERVED2 = 0x80 + + CLSCTX_RESERVED3 = 0x100 + + CLSCTX_RESERVED4 = 0x200 + + CLSCTX_NO_CODE_DOWNLOAD = 0x400 + + CLSCTX_RESERVED5 = 0x800 + + CLSCTX_NO_CUSTOM_MARSHAL = 0x1000 + + CLSCTX_ENABLE_CODE_DOWNLOAD = 0x2000 + + CLSCTX_NO_FAILURE_LOG = 0x4000 + + CLSCTX_DISABLE_AAA = 0x8000 + + CLSCTX_ENABLE_AAA = 0x10000 + + CLSCTX_FROM_DEFAULT_CONTEXT = 0x20000 + + CLSCTX_ACTIVATE_32_BIT_SERVER = 0x40000 + + CLSCTX_ACTIVATE_64_BIT_SERVER = 0x80000 + + CLSCTX_ENABLE_CLOAKING = 0x100000 + + CLSCTX_APPCONTAINER = 0x400000 + + CLSCTX_ACTIVATE_AAA_AS_IU = 0x800000 + + CLSCTX_PS_DLL = 0x80000000 + + COINIT_MULTITHREADED = 0x0 - COINIT_MULTITHREADED = 0x0 COINIT_APARTMENTTHREADED = 0x2 - COINIT_DISABLE_OLE1DDE = 0x4 + + COINIT_DISABLE_OLE1DDE = 0x4 + COINIT_SPEED_OVER_MEMORY = 0x8 ) // Flag for QueryFullProcessImageName. + const PROCESS_NAME_NATIVE = 1 type ModuleInfo struct { - BaseOfDll uintptr + BaseOfDll uintptr + SizeOfImage uint32 - EntryPoint uintptr + + EntryPoint uintptr } const ALL_PROCESSOR_GROUPS = 0xFFFF type Rect struct { - Left int32 - Top int32 - Right int32 + Left int32 + + Top int32 + + Right int32 + Bottom int32 } type GUIThreadInfo struct { - Size uint32 - Flags uint32 - Active HWND - Focus HWND - Capture HWND - MenuOwner HWND - MoveSize HWND + Size uint32 + + Flags uint32 + + Active HWND + + Focus HWND + + Capture HWND + + MenuOwner HWND + + MoveSize HWND + CaretHandle HWND - CaretRect Rect + + CaretRect Rect } const ( - DWMWA_NCRENDERING_ENABLED = 1 - DWMWA_NCRENDERING_POLICY = 2 - DWMWA_TRANSITIONS_FORCEDISABLED = 3 - DWMWA_ALLOW_NCPAINT = 4 - DWMWA_CAPTION_BUTTON_BOUNDS = 5 - DWMWA_NONCLIENT_RTL_LAYOUT = 6 - DWMWA_FORCE_ICONIC_REPRESENTATION = 7 - DWMWA_FLIP3D_POLICY = 8 - DWMWA_EXTENDED_FRAME_BOUNDS = 9 - DWMWA_HAS_ICONIC_BITMAP = 10 - DWMWA_DISALLOW_PEEK = 11 - DWMWA_EXCLUDED_FROM_PEEK = 12 - DWMWA_CLOAK = 13 - DWMWA_CLOAKED = 14 - DWMWA_FREEZE_REPRESENTATION = 15 - DWMWA_PASSIVE_UPDATE_MODE = 16 - DWMWA_USE_HOSTBACKDROPBRUSH = 17 - DWMWA_USE_IMMERSIVE_DARK_MODE = 20 - DWMWA_WINDOW_CORNER_PREFERENCE = 33 - DWMWA_BORDER_COLOR = 34 - DWMWA_CAPTION_COLOR = 35 - DWMWA_TEXT_COLOR = 36 + DWMWA_NCRENDERING_ENABLED = 1 + + DWMWA_NCRENDERING_POLICY = 2 + + DWMWA_TRANSITIONS_FORCEDISABLED = 3 + + DWMWA_ALLOW_NCPAINT = 4 + + DWMWA_CAPTION_BUTTON_BOUNDS = 5 + + DWMWA_NONCLIENT_RTL_LAYOUT = 6 + + DWMWA_FORCE_ICONIC_REPRESENTATION = 7 + + DWMWA_FLIP3D_POLICY = 8 + + DWMWA_EXTENDED_FRAME_BOUNDS = 9 + + DWMWA_HAS_ICONIC_BITMAP = 10 + + DWMWA_DISALLOW_PEEK = 11 + + DWMWA_EXCLUDED_FROM_PEEK = 12 + + DWMWA_CLOAK = 13 + + DWMWA_CLOAKED = 14 + + DWMWA_FREEZE_REPRESENTATION = 15 + + DWMWA_PASSIVE_UPDATE_MODE = 16 + + DWMWA_USE_HOSTBACKDROPBRUSH = 17 + + DWMWA_USE_IMMERSIVE_DARK_MODE = 20 + + DWMWA_WINDOW_CORNER_PREFERENCE = 33 + + DWMWA_BORDER_COLOR = 34 + + DWMWA_CAPTION_COLOR = 35 + + DWMWA_TEXT_COLOR = 36 + DWMWA_VISIBLE_FRAME_BORDER_THICKNESS = 37 ) type WSAQUERYSET struct { - Size uint32 + Size uint32 + ServiceInstanceName *uint16 - ServiceClassId *GUID - Version *WSAVersion - Comment *uint16 - NameSpace uint32 - NSProviderId *GUID - Context *uint16 - NumberOfProtocols uint32 - AfpProtocols *AFProtocols - QueryString *uint16 - NumberOfCsAddrs uint32 - SaBuffer *CSAddrInfo - OutputFlags uint32 - Blob *BLOB + + ServiceClassId *GUID + + Version *WSAVersion + + Comment *uint16 + + NameSpace uint32 + + NSProviderId *GUID + + Context *uint16 + + NumberOfProtocols uint32 + + AfpProtocols *AFProtocols + + QueryString *uint16 + + NumberOfCsAddrs uint32 + + SaBuffer *CSAddrInfo + + OutputFlags uint32 + + Blob *BLOB } type WSAVersion struct { - Version uint32 + Version uint32 + EnumerationOfComparison int32 } type AFProtocols struct { AddressFamily int32 - Protocol int32 + + Protocol int32 } type CSAddrInfo struct { - LocalAddr SocketAddress + LocalAddr SocketAddress + RemoteAddr SocketAddress + SocketType int32 - Protocol int32 + + Protocol int32 } type BLOB struct { - Size uint32 + Size uint32 + BlobData *byte } type ComStat struct { - Flags uint32 - CBInQue uint32 + Flags uint32 + + CBInQue uint32 + CBOutQue uint32 } type DCB struct { - DCBlength uint32 - BaudRate uint32 - Flags uint32 - wReserved uint16 - XonLim uint16 - XoffLim uint16 - ByteSize uint8 - Parity uint8 - StopBits uint8 - XonChar byte - XoffChar byte - ErrorChar byte - EofChar byte - EvtChar byte + DCBlength uint32 + + BaudRate uint32 + + Flags uint32 + + wReserved uint16 + + XonLim uint16 + + XoffLim uint16 + + ByteSize uint8 + + Parity uint8 + + StopBits uint8 + + XonChar byte + + XoffChar byte + + ErrorChar byte + + EofChar byte + + EvtChar byte + wReserved1 uint16 } diff --git a/vendor/golang.org/x/sys/windows/zsyscall_windows.go b/vendor/golang.org/x/sys/windows/zsyscall_windows.go index 5c6035d..cddb27b 100644 --- a/vendor/golang.org/x/sys/windows/zsyscall_windows.go +++ b/vendor/golang.org/x/sys/windows/zsyscall_windows.go @@ -10,4517 +10,8057 @@ import ( var _ unsafe.Pointer // Do the interface allocations only once for common + // Errno values. + const ( errnoERROR_IO_PENDING = 997 ) var ( errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) - errERROR_EINVAL error = syscall.EINVAL + + errERROR_EINVAL error = syscall.EINVAL ) // errnoErr returns common boxed Errno values, to prevent + // allocations at runtime. + func errnoErr(e syscall.Errno) error { + switch e { + case 0: + return errERROR_EINVAL + case errnoERROR_IO_PENDING: + return errERROR_IO_PENDING + } + // TODO: add more here, after collecting data on the common + // error values see on Windows. (perhaps when running + // all.bat?) + return e + } var ( modCfgMgr32 = NewLazySystemDLL("CfgMgr32.dll") + modadvapi32 = NewLazySystemDLL("advapi32.dll") - modcrypt32 = NewLazySystemDLL("crypt32.dll") - moddnsapi = NewLazySystemDLL("dnsapi.dll") - moddwmapi = NewLazySystemDLL("dwmapi.dll") + + modcrypt32 = NewLazySystemDLL("crypt32.dll") + + moddnsapi = NewLazySystemDLL("dnsapi.dll") + + moddwmapi = NewLazySystemDLL("dwmapi.dll") + modiphlpapi = NewLazySystemDLL("iphlpapi.dll") + modkernel32 = NewLazySystemDLL("kernel32.dll") - modmswsock = NewLazySystemDLL("mswsock.dll") + + modmswsock = NewLazySystemDLL("mswsock.dll") + modnetapi32 = NewLazySystemDLL("netapi32.dll") - modntdll = NewLazySystemDLL("ntdll.dll") - modole32 = NewLazySystemDLL("ole32.dll") - modpsapi = NewLazySystemDLL("psapi.dll") - modsechost = NewLazySystemDLL("sechost.dll") - modsecur32 = NewLazySystemDLL("secur32.dll") + + modntdll = NewLazySystemDLL("ntdll.dll") + + modole32 = NewLazySystemDLL("ole32.dll") + + modpsapi = NewLazySystemDLL("psapi.dll") + + modsechost = NewLazySystemDLL("sechost.dll") + + modsecur32 = NewLazySystemDLL("secur32.dll") + modsetupapi = NewLazySystemDLL("setupapi.dll") - modshell32 = NewLazySystemDLL("shell32.dll") - moduser32 = NewLazySystemDLL("user32.dll") - moduserenv = NewLazySystemDLL("userenv.dll") - modversion = NewLazySystemDLL("version.dll") - modwinmm = NewLazySystemDLL("winmm.dll") + + modshell32 = NewLazySystemDLL("shell32.dll") + + moduser32 = NewLazySystemDLL("user32.dll") + + moduserenv = NewLazySystemDLL("userenv.dll") + + modversion = NewLazySystemDLL("version.dll") + + modwinmm = NewLazySystemDLL("winmm.dll") + modwintrust = NewLazySystemDLL("wintrust.dll") - modws2_32 = NewLazySystemDLL("ws2_32.dll") + + modws2_32 = NewLazySystemDLL("ws2_32.dll") + modwtsapi32 = NewLazySystemDLL("wtsapi32.dll") - procCM_Get_DevNode_Status = modCfgMgr32.NewProc("CM_Get_DevNode_Status") - procCM_Get_Device_Interface_ListW = modCfgMgr32.NewProc("CM_Get_Device_Interface_ListW") - procCM_Get_Device_Interface_List_SizeW = modCfgMgr32.NewProc("CM_Get_Device_Interface_List_SizeW") - procCM_MapCrToWin32Err = modCfgMgr32.NewProc("CM_MapCrToWin32Err") - procAdjustTokenGroups = modadvapi32.NewProc("AdjustTokenGroups") - procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges") - procAllocateAndInitializeSid = modadvapi32.NewProc("AllocateAndInitializeSid") - procBuildSecurityDescriptorW = modadvapi32.NewProc("BuildSecurityDescriptorW") - procChangeServiceConfig2W = modadvapi32.NewProc("ChangeServiceConfig2W") - procChangeServiceConfigW = modadvapi32.NewProc("ChangeServiceConfigW") - procCheckTokenMembership = modadvapi32.NewProc("CheckTokenMembership") - procCloseServiceHandle = modadvapi32.NewProc("CloseServiceHandle") - procControlService = modadvapi32.NewProc("ControlService") + procCM_Get_DevNode_Status = modCfgMgr32.NewProc("CM_Get_DevNode_Status") + + procCM_Get_Device_Interface_ListW = modCfgMgr32.NewProc("CM_Get_Device_Interface_ListW") + + procCM_Get_Device_Interface_List_SizeW = modCfgMgr32.NewProc("CM_Get_Device_Interface_List_SizeW") + + procCM_MapCrToWin32Err = modCfgMgr32.NewProc("CM_MapCrToWin32Err") + + procAdjustTokenGroups = modadvapi32.NewProc("AdjustTokenGroups") + + procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges") + + procAllocateAndInitializeSid = modadvapi32.NewProc("AllocateAndInitializeSid") + + procBuildSecurityDescriptorW = modadvapi32.NewProc("BuildSecurityDescriptorW") + + procChangeServiceConfig2W = modadvapi32.NewProc("ChangeServiceConfig2W") + + procChangeServiceConfigW = modadvapi32.NewProc("ChangeServiceConfigW") + + procCheckTokenMembership = modadvapi32.NewProc("CheckTokenMembership") + + procCloseServiceHandle = modadvapi32.NewProc("CloseServiceHandle") + + procControlService = modadvapi32.NewProc("ControlService") + procConvertSecurityDescriptorToStringSecurityDescriptorW = modadvapi32.NewProc("ConvertSecurityDescriptorToStringSecurityDescriptorW") - procConvertSidToStringSidW = modadvapi32.NewProc("ConvertSidToStringSidW") + + procConvertSidToStringSidW = modadvapi32.NewProc("ConvertSidToStringSidW") + procConvertStringSecurityDescriptorToSecurityDescriptorW = modadvapi32.NewProc("ConvertStringSecurityDescriptorToSecurityDescriptorW") - procConvertStringSidToSidW = modadvapi32.NewProc("ConvertStringSidToSidW") - procCopySid = modadvapi32.NewProc("CopySid") - procCreateProcessAsUserW = modadvapi32.NewProc("CreateProcessAsUserW") - procCreateServiceW = modadvapi32.NewProc("CreateServiceW") - procCreateWellKnownSid = modadvapi32.NewProc("CreateWellKnownSid") - procCryptAcquireContextW = modadvapi32.NewProc("CryptAcquireContextW") - procCryptGenRandom = modadvapi32.NewProc("CryptGenRandom") - procCryptReleaseContext = modadvapi32.NewProc("CryptReleaseContext") - procDeleteService = modadvapi32.NewProc("DeleteService") - procDeregisterEventSource = modadvapi32.NewProc("DeregisterEventSource") - procDuplicateTokenEx = modadvapi32.NewProc("DuplicateTokenEx") - procEnumDependentServicesW = modadvapi32.NewProc("EnumDependentServicesW") - procEnumServicesStatusExW = modadvapi32.NewProc("EnumServicesStatusExW") - procEqualSid = modadvapi32.NewProc("EqualSid") - procFreeSid = modadvapi32.NewProc("FreeSid") - procGetLengthSid = modadvapi32.NewProc("GetLengthSid") - procGetNamedSecurityInfoW = modadvapi32.NewProc("GetNamedSecurityInfoW") - procGetSecurityDescriptorControl = modadvapi32.NewProc("GetSecurityDescriptorControl") - procGetSecurityDescriptorDacl = modadvapi32.NewProc("GetSecurityDescriptorDacl") - procGetSecurityDescriptorGroup = modadvapi32.NewProc("GetSecurityDescriptorGroup") - procGetSecurityDescriptorLength = modadvapi32.NewProc("GetSecurityDescriptorLength") - procGetSecurityDescriptorOwner = modadvapi32.NewProc("GetSecurityDescriptorOwner") - procGetSecurityDescriptorRMControl = modadvapi32.NewProc("GetSecurityDescriptorRMControl") - procGetSecurityDescriptorSacl = modadvapi32.NewProc("GetSecurityDescriptorSacl") - procGetSecurityInfo = modadvapi32.NewProc("GetSecurityInfo") - procGetSidIdentifierAuthority = modadvapi32.NewProc("GetSidIdentifierAuthority") - procGetSidSubAuthority = modadvapi32.NewProc("GetSidSubAuthority") - procGetSidSubAuthorityCount = modadvapi32.NewProc("GetSidSubAuthorityCount") - procGetTokenInformation = modadvapi32.NewProc("GetTokenInformation") - procImpersonateSelf = modadvapi32.NewProc("ImpersonateSelf") - procInitializeSecurityDescriptor = modadvapi32.NewProc("InitializeSecurityDescriptor") - procInitiateSystemShutdownExW = modadvapi32.NewProc("InitiateSystemShutdownExW") - procIsTokenRestricted = modadvapi32.NewProc("IsTokenRestricted") - procIsValidSecurityDescriptor = modadvapi32.NewProc("IsValidSecurityDescriptor") - procIsValidSid = modadvapi32.NewProc("IsValidSid") - procIsWellKnownSid = modadvapi32.NewProc("IsWellKnownSid") - procLookupAccountNameW = modadvapi32.NewProc("LookupAccountNameW") - procLookupAccountSidW = modadvapi32.NewProc("LookupAccountSidW") - procLookupPrivilegeValueW = modadvapi32.NewProc("LookupPrivilegeValueW") - procMakeAbsoluteSD = modadvapi32.NewProc("MakeAbsoluteSD") - procMakeSelfRelativeSD = modadvapi32.NewProc("MakeSelfRelativeSD") - procNotifyServiceStatusChangeW = modadvapi32.NewProc("NotifyServiceStatusChangeW") - procOpenProcessToken = modadvapi32.NewProc("OpenProcessToken") - procOpenSCManagerW = modadvapi32.NewProc("OpenSCManagerW") - procOpenServiceW = modadvapi32.NewProc("OpenServiceW") - procOpenThreadToken = modadvapi32.NewProc("OpenThreadToken") - procQueryServiceConfig2W = modadvapi32.NewProc("QueryServiceConfig2W") - procQueryServiceConfigW = modadvapi32.NewProc("QueryServiceConfigW") - procQueryServiceDynamicInformation = modadvapi32.NewProc("QueryServiceDynamicInformation") - procQueryServiceLockStatusW = modadvapi32.NewProc("QueryServiceLockStatusW") - procQueryServiceStatus = modadvapi32.NewProc("QueryServiceStatus") - procQueryServiceStatusEx = modadvapi32.NewProc("QueryServiceStatusEx") - procRegCloseKey = modadvapi32.NewProc("RegCloseKey") - procRegEnumKeyExW = modadvapi32.NewProc("RegEnumKeyExW") - procRegNotifyChangeKeyValue = modadvapi32.NewProc("RegNotifyChangeKeyValue") - procRegOpenKeyExW = modadvapi32.NewProc("RegOpenKeyExW") - procRegQueryInfoKeyW = modadvapi32.NewProc("RegQueryInfoKeyW") - procRegQueryValueExW = modadvapi32.NewProc("RegQueryValueExW") - procRegisterEventSourceW = modadvapi32.NewProc("RegisterEventSourceW") - procRegisterServiceCtrlHandlerExW = modadvapi32.NewProc("RegisterServiceCtrlHandlerExW") - procReportEventW = modadvapi32.NewProc("ReportEventW") - procRevertToSelf = modadvapi32.NewProc("RevertToSelf") - procSetEntriesInAclW = modadvapi32.NewProc("SetEntriesInAclW") - procSetKernelObjectSecurity = modadvapi32.NewProc("SetKernelObjectSecurity") - procSetNamedSecurityInfoW = modadvapi32.NewProc("SetNamedSecurityInfoW") - procSetSecurityDescriptorControl = modadvapi32.NewProc("SetSecurityDescriptorControl") - procSetSecurityDescriptorDacl = modadvapi32.NewProc("SetSecurityDescriptorDacl") - procSetSecurityDescriptorGroup = modadvapi32.NewProc("SetSecurityDescriptorGroup") - procSetSecurityDescriptorOwner = modadvapi32.NewProc("SetSecurityDescriptorOwner") - procSetSecurityDescriptorRMControl = modadvapi32.NewProc("SetSecurityDescriptorRMControl") - procSetSecurityDescriptorSacl = modadvapi32.NewProc("SetSecurityDescriptorSacl") - procSetSecurityInfo = modadvapi32.NewProc("SetSecurityInfo") - procSetServiceStatus = modadvapi32.NewProc("SetServiceStatus") - procSetThreadToken = modadvapi32.NewProc("SetThreadToken") - procSetTokenInformation = modadvapi32.NewProc("SetTokenInformation") - procStartServiceCtrlDispatcherW = modadvapi32.NewProc("StartServiceCtrlDispatcherW") - procStartServiceW = modadvapi32.NewProc("StartServiceW") - procCertAddCertificateContextToStore = modcrypt32.NewProc("CertAddCertificateContextToStore") - procCertCloseStore = modcrypt32.NewProc("CertCloseStore") - procCertCreateCertificateContext = modcrypt32.NewProc("CertCreateCertificateContext") - procCertDeleteCertificateFromStore = modcrypt32.NewProc("CertDeleteCertificateFromStore") - procCertDuplicateCertificateContext = modcrypt32.NewProc("CertDuplicateCertificateContext") - procCertEnumCertificatesInStore = modcrypt32.NewProc("CertEnumCertificatesInStore") - procCertFindCertificateInStore = modcrypt32.NewProc("CertFindCertificateInStore") - procCertFindChainInStore = modcrypt32.NewProc("CertFindChainInStore") - procCertFindExtension = modcrypt32.NewProc("CertFindExtension") - procCertFreeCertificateChain = modcrypt32.NewProc("CertFreeCertificateChain") - procCertFreeCertificateContext = modcrypt32.NewProc("CertFreeCertificateContext") - procCertGetCertificateChain = modcrypt32.NewProc("CertGetCertificateChain") - procCertGetNameStringW = modcrypt32.NewProc("CertGetNameStringW") - procCertOpenStore = modcrypt32.NewProc("CertOpenStore") - procCertOpenSystemStoreW = modcrypt32.NewProc("CertOpenSystemStoreW") - procCertVerifyCertificateChainPolicy = modcrypt32.NewProc("CertVerifyCertificateChainPolicy") - procCryptAcquireCertificatePrivateKey = modcrypt32.NewProc("CryptAcquireCertificatePrivateKey") - procCryptDecodeObject = modcrypt32.NewProc("CryptDecodeObject") - procCryptProtectData = modcrypt32.NewProc("CryptProtectData") - procCryptQueryObject = modcrypt32.NewProc("CryptQueryObject") - procCryptUnprotectData = modcrypt32.NewProc("CryptUnprotectData") - procPFXImportCertStore = modcrypt32.NewProc("PFXImportCertStore") - procDnsNameCompare_W = moddnsapi.NewProc("DnsNameCompare_W") - procDnsQuery_W = moddnsapi.NewProc("DnsQuery_W") - procDnsRecordListFree = moddnsapi.NewProc("DnsRecordListFree") - procDwmGetWindowAttribute = moddwmapi.NewProc("DwmGetWindowAttribute") - procDwmSetWindowAttribute = moddwmapi.NewProc("DwmSetWindowAttribute") - procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses") - procGetAdaptersInfo = modiphlpapi.NewProc("GetAdaptersInfo") - procGetBestInterfaceEx = modiphlpapi.NewProc("GetBestInterfaceEx") - procGetIfEntry = modiphlpapi.NewProc("GetIfEntry") - procAddDllDirectory = modkernel32.NewProc("AddDllDirectory") - procAssignProcessToJobObject = modkernel32.NewProc("AssignProcessToJobObject") - procCancelIo = modkernel32.NewProc("CancelIo") - procCancelIoEx = modkernel32.NewProc("CancelIoEx") - procClearCommBreak = modkernel32.NewProc("ClearCommBreak") - procClearCommError = modkernel32.NewProc("ClearCommError") - procCloseHandle = modkernel32.NewProc("CloseHandle") - procClosePseudoConsole = modkernel32.NewProc("ClosePseudoConsole") - procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe") - procCreateDirectoryW = modkernel32.NewProc("CreateDirectoryW") - procCreateEventExW = modkernel32.NewProc("CreateEventExW") - procCreateEventW = modkernel32.NewProc("CreateEventW") - procCreateFileMappingW = modkernel32.NewProc("CreateFileMappingW") - procCreateFileW = modkernel32.NewProc("CreateFileW") - procCreateHardLinkW = modkernel32.NewProc("CreateHardLinkW") - procCreateIoCompletionPort = modkernel32.NewProc("CreateIoCompletionPort") - procCreateJobObjectW = modkernel32.NewProc("CreateJobObjectW") - procCreateMutexExW = modkernel32.NewProc("CreateMutexExW") - procCreateMutexW = modkernel32.NewProc("CreateMutexW") - procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW") - procCreatePipe = modkernel32.NewProc("CreatePipe") - procCreateProcessW = modkernel32.NewProc("CreateProcessW") - procCreatePseudoConsole = modkernel32.NewProc("CreatePseudoConsole") - procCreateSymbolicLinkW = modkernel32.NewProc("CreateSymbolicLinkW") - procCreateToolhelp32Snapshot = modkernel32.NewProc("CreateToolhelp32Snapshot") - procDefineDosDeviceW = modkernel32.NewProc("DefineDosDeviceW") - procDeleteFileW = modkernel32.NewProc("DeleteFileW") - procDeleteProcThreadAttributeList = modkernel32.NewProc("DeleteProcThreadAttributeList") - procDeleteVolumeMountPointW = modkernel32.NewProc("DeleteVolumeMountPointW") - procDeviceIoControl = modkernel32.NewProc("DeviceIoControl") - procDisconnectNamedPipe = modkernel32.NewProc("DisconnectNamedPipe") - procDuplicateHandle = modkernel32.NewProc("DuplicateHandle") - procEscapeCommFunction = modkernel32.NewProc("EscapeCommFunction") - procExitProcess = modkernel32.NewProc("ExitProcess") - procExpandEnvironmentStringsW = modkernel32.NewProc("ExpandEnvironmentStringsW") - procFindClose = modkernel32.NewProc("FindClose") - procFindCloseChangeNotification = modkernel32.NewProc("FindCloseChangeNotification") - procFindFirstChangeNotificationW = modkernel32.NewProc("FindFirstChangeNotificationW") - procFindFirstFileW = modkernel32.NewProc("FindFirstFileW") - procFindFirstVolumeMountPointW = modkernel32.NewProc("FindFirstVolumeMountPointW") - procFindFirstVolumeW = modkernel32.NewProc("FindFirstVolumeW") - procFindNextChangeNotification = modkernel32.NewProc("FindNextChangeNotification") - procFindNextFileW = modkernel32.NewProc("FindNextFileW") - procFindNextVolumeMountPointW = modkernel32.NewProc("FindNextVolumeMountPointW") - procFindNextVolumeW = modkernel32.NewProc("FindNextVolumeW") - procFindResourceW = modkernel32.NewProc("FindResourceW") - procFindVolumeClose = modkernel32.NewProc("FindVolumeClose") - procFindVolumeMountPointClose = modkernel32.NewProc("FindVolumeMountPointClose") - procFlushFileBuffers = modkernel32.NewProc("FlushFileBuffers") - procFlushViewOfFile = modkernel32.NewProc("FlushViewOfFile") - procFormatMessageW = modkernel32.NewProc("FormatMessageW") - procFreeEnvironmentStringsW = modkernel32.NewProc("FreeEnvironmentStringsW") - procFreeLibrary = modkernel32.NewProc("FreeLibrary") - procGenerateConsoleCtrlEvent = modkernel32.NewProc("GenerateConsoleCtrlEvent") - procGetACP = modkernel32.NewProc("GetACP") - procGetActiveProcessorCount = modkernel32.NewProc("GetActiveProcessorCount") - procGetCommModemStatus = modkernel32.NewProc("GetCommModemStatus") - procGetCommState = modkernel32.NewProc("GetCommState") - procGetCommTimeouts = modkernel32.NewProc("GetCommTimeouts") - procGetCommandLineW = modkernel32.NewProc("GetCommandLineW") - procGetComputerNameExW = modkernel32.NewProc("GetComputerNameExW") - procGetComputerNameW = modkernel32.NewProc("GetComputerNameW") - procGetConsoleMode = modkernel32.NewProc("GetConsoleMode") - procGetConsoleScreenBufferInfo = modkernel32.NewProc("GetConsoleScreenBufferInfo") - procGetCurrentDirectoryW = modkernel32.NewProc("GetCurrentDirectoryW") - procGetCurrentProcessId = modkernel32.NewProc("GetCurrentProcessId") - procGetCurrentThreadId = modkernel32.NewProc("GetCurrentThreadId") - procGetDiskFreeSpaceExW = modkernel32.NewProc("GetDiskFreeSpaceExW") - procGetDriveTypeW = modkernel32.NewProc("GetDriveTypeW") - procGetEnvironmentStringsW = modkernel32.NewProc("GetEnvironmentStringsW") - procGetEnvironmentVariableW = modkernel32.NewProc("GetEnvironmentVariableW") - procGetExitCodeProcess = modkernel32.NewProc("GetExitCodeProcess") - procGetFileAttributesExW = modkernel32.NewProc("GetFileAttributesExW") - procGetFileAttributesW = modkernel32.NewProc("GetFileAttributesW") - procGetFileInformationByHandle = modkernel32.NewProc("GetFileInformationByHandle") - procGetFileInformationByHandleEx = modkernel32.NewProc("GetFileInformationByHandleEx") - procGetFileTime = modkernel32.NewProc("GetFileTime") - procGetFileType = modkernel32.NewProc("GetFileType") - procGetFinalPathNameByHandleW = modkernel32.NewProc("GetFinalPathNameByHandleW") - procGetFullPathNameW = modkernel32.NewProc("GetFullPathNameW") - procGetLargePageMinimum = modkernel32.NewProc("GetLargePageMinimum") - procGetLastError = modkernel32.NewProc("GetLastError") - procGetLogicalDriveStringsW = modkernel32.NewProc("GetLogicalDriveStringsW") - procGetLogicalDrives = modkernel32.NewProc("GetLogicalDrives") - procGetLongPathNameW = modkernel32.NewProc("GetLongPathNameW") - procGetMaximumProcessorCount = modkernel32.NewProc("GetMaximumProcessorCount") - procGetModuleFileNameW = modkernel32.NewProc("GetModuleFileNameW") - procGetModuleHandleExW = modkernel32.NewProc("GetModuleHandleExW") - procGetNamedPipeHandleStateW = modkernel32.NewProc("GetNamedPipeHandleStateW") - procGetNamedPipeInfo = modkernel32.NewProc("GetNamedPipeInfo") - procGetOverlappedResult = modkernel32.NewProc("GetOverlappedResult") - procGetPriorityClass = modkernel32.NewProc("GetPriorityClass") - procGetProcAddress = modkernel32.NewProc("GetProcAddress") - procGetProcessId = modkernel32.NewProc("GetProcessId") - procGetProcessPreferredUILanguages = modkernel32.NewProc("GetProcessPreferredUILanguages") - procGetProcessShutdownParameters = modkernel32.NewProc("GetProcessShutdownParameters") - procGetProcessTimes = modkernel32.NewProc("GetProcessTimes") - procGetProcessWorkingSetSizeEx = modkernel32.NewProc("GetProcessWorkingSetSizeEx") - procGetQueuedCompletionStatus = modkernel32.NewProc("GetQueuedCompletionStatus") - procGetShortPathNameW = modkernel32.NewProc("GetShortPathNameW") - procGetStartupInfoW = modkernel32.NewProc("GetStartupInfoW") - procGetStdHandle = modkernel32.NewProc("GetStdHandle") - procGetSystemDirectoryW = modkernel32.NewProc("GetSystemDirectoryW") - procGetSystemPreferredUILanguages = modkernel32.NewProc("GetSystemPreferredUILanguages") - procGetSystemTimeAsFileTime = modkernel32.NewProc("GetSystemTimeAsFileTime") - procGetSystemTimePreciseAsFileTime = modkernel32.NewProc("GetSystemTimePreciseAsFileTime") - procGetSystemWindowsDirectoryW = modkernel32.NewProc("GetSystemWindowsDirectoryW") - procGetTempPathW = modkernel32.NewProc("GetTempPathW") - procGetThreadPreferredUILanguages = modkernel32.NewProc("GetThreadPreferredUILanguages") - procGetTickCount64 = modkernel32.NewProc("GetTickCount64") - procGetTimeZoneInformation = modkernel32.NewProc("GetTimeZoneInformation") - procGetUserPreferredUILanguages = modkernel32.NewProc("GetUserPreferredUILanguages") - procGetVersion = modkernel32.NewProc("GetVersion") - procGetVolumeInformationByHandleW = modkernel32.NewProc("GetVolumeInformationByHandleW") - procGetVolumeInformationW = modkernel32.NewProc("GetVolumeInformationW") - procGetVolumeNameForVolumeMountPointW = modkernel32.NewProc("GetVolumeNameForVolumeMountPointW") - procGetVolumePathNameW = modkernel32.NewProc("GetVolumePathNameW") - procGetVolumePathNamesForVolumeNameW = modkernel32.NewProc("GetVolumePathNamesForVolumeNameW") - procGetWindowsDirectoryW = modkernel32.NewProc("GetWindowsDirectoryW") - procInitializeProcThreadAttributeList = modkernel32.NewProc("InitializeProcThreadAttributeList") - procIsWow64Process = modkernel32.NewProc("IsWow64Process") - procIsWow64Process2 = modkernel32.NewProc("IsWow64Process2") - procLoadLibraryExW = modkernel32.NewProc("LoadLibraryExW") - procLoadLibraryW = modkernel32.NewProc("LoadLibraryW") - procLoadResource = modkernel32.NewProc("LoadResource") - procLocalAlloc = modkernel32.NewProc("LocalAlloc") - procLocalFree = modkernel32.NewProc("LocalFree") - procLockFileEx = modkernel32.NewProc("LockFileEx") - procLockResource = modkernel32.NewProc("LockResource") - procMapViewOfFile = modkernel32.NewProc("MapViewOfFile") - procModule32FirstW = modkernel32.NewProc("Module32FirstW") - procModule32NextW = modkernel32.NewProc("Module32NextW") - procMoveFileExW = modkernel32.NewProc("MoveFileExW") - procMoveFileW = modkernel32.NewProc("MoveFileW") - procMultiByteToWideChar = modkernel32.NewProc("MultiByteToWideChar") - procOpenEventW = modkernel32.NewProc("OpenEventW") - procOpenMutexW = modkernel32.NewProc("OpenMutexW") - procOpenProcess = modkernel32.NewProc("OpenProcess") - procOpenThread = modkernel32.NewProc("OpenThread") - procPostQueuedCompletionStatus = modkernel32.NewProc("PostQueuedCompletionStatus") - procProcess32FirstW = modkernel32.NewProc("Process32FirstW") - procProcess32NextW = modkernel32.NewProc("Process32NextW") - procProcessIdToSessionId = modkernel32.NewProc("ProcessIdToSessionId") - procPulseEvent = modkernel32.NewProc("PulseEvent") - procPurgeComm = modkernel32.NewProc("PurgeComm") - procQueryDosDeviceW = modkernel32.NewProc("QueryDosDeviceW") - procQueryFullProcessImageNameW = modkernel32.NewProc("QueryFullProcessImageNameW") - procQueryInformationJobObject = modkernel32.NewProc("QueryInformationJobObject") - procReadConsoleW = modkernel32.NewProc("ReadConsoleW") - procReadDirectoryChangesW = modkernel32.NewProc("ReadDirectoryChangesW") - procReadFile = modkernel32.NewProc("ReadFile") - procReadProcessMemory = modkernel32.NewProc("ReadProcessMemory") - procReleaseMutex = modkernel32.NewProc("ReleaseMutex") - procRemoveDirectoryW = modkernel32.NewProc("RemoveDirectoryW") - procRemoveDllDirectory = modkernel32.NewProc("RemoveDllDirectory") - procResetEvent = modkernel32.NewProc("ResetEvent") - procResizePseudoConsole = modkernel32.NewProc("ResizePseudoConsole") - procResumeThread = modkernel32.NewProc("ResumeThread") - procSetCommBreak = modkernel32.NewProc("SetCommBreak") - procSetCommMask = modkernel32.NewProc("SetCommMask") - procSetCommState = modkernel32.NewProc("SetCommState") - procSetCommTimeouts = modkernel32.NewProc("SetCommTimeouts") - procSetConsoleCursorPosition = modkernel32.NewProc("SetConsoleCursorPosition") - procSetConsoleMode = modkernel32.NewProc("SetConsoleMode") - procSetCurrentDirectoryW = modkernel32.NewProc("SetCurrentDirectoryW") - procSetDefaultDllDirectories = modkernel32.NewProc("SetDefaultDllDirectories") - procSetDllDirectoryW = modkernel32.NewProc("SetDllDirectoryW") - procSetEndOfFile = modkernel32.NewProc("SetEndOfFile") - procSetEnvironmentVariableW = modkernel32.NewProc("SetEnvironmentVariableW") - procSetErrorMode = modkernel32.NewProc("SetErrorMode") - procSetEvent = modkernel32.NewProc("SetEvent") - procSetFileAttributesW = modkernel32.NewProc("SetFileAttributesW") - procSetFileCompletionNotificationModes = modkernel32.NewProc("SetFileCompletionNotificationModes") - procSetFileInformationByHandle = modkernel32.NewProc("SetFileInformationByHandle") - procSetFilePointer = modkernel32.NewProc("SetFilePointer") - procSetFileTime = modkernel32.NewProc("SetFileTime") - procSetFileValidData = modkernel32.NewProc("SetFileValidData") - procSetHandleInformation = modkernel32.NewProc("SetHandleInformation") - procSetInformationJobObject = modkernel32.NewProc("SetInformationJobObject") - procSetNamedPipeHandleState = modkernel32.NewProc("SetNamedPipeHandleState") - procSetPriorityClass = modkernel32.NewProc("SetPriorityClass") - procSetProcessPriorityBoost = modkernel32.NewProc("SetProcessPriorityBoost") - procSetProcessShutdownParameters = modkernel32.NewProc("SetProcessShutdownParameters") - procSetProcessWorkingSetSizeEx = modkernel32.NewProc("SetProcessWorkingSetSizeEx") - procSetStdHandle = modkernel32.NewProc("SetStdHandle") - procSetVolumeLabelW = modkernel32.NewProc("SetVolumeLabelW") - procSetVolumeMountPointW = modkernel32.NewProc("SetVolumeMountPointW") - procSetupComm = modkernel32.NewProc("SetupComm") - procSizeofResource = modkernel32.NewProc("SizeofResource") - procSleepEx = modkernel32.NewProc("SleepEx") - procTerminateJobObject = modkernel32.NewProc("TerminateJobObject") - procTerminateProcess = modkernel32.NewProc("TerminateProcess") - procThread32First = modkernel32.NewProc("Thread32First") - procThread32Next = modkernel32.NewProc("Thread32Next") - procUnlockFileEx = modkernel32.NewProc("UnlockFileEx") - procUnmapViewOfFile = modkernel32.NewProc("UnmapViewOfFile") - procUpdateProcThreadAttribute = modkernel32.NewProc("UpdateProcThreadAttribute") - procVirtualAlloc = modkernel32.NewProc("VirtualAlloc") - procVirtualFree = modkernel32.NewProc("VirtualFree") - procVirtualLock = modkernel32.NewProc("VirtualLock") - procVirtualProtect = modkernel32.NewProc("VirtualProtect") - procVirtualProtectEx = modkernel32.NewProc("VirtualProtectEx") - procVirtualQuery = modkernel32.NewProc("VirtualQuery") - procVirtualQueryEx = modkernel32.NewProc("VirtualQueryEx") - procVirtualUnlock = modkernel32.NewProc("VirtualUnlock") - procWTSGetActiveConsoleSessionId = modkernel32.NewProc("WTSGetActiveConsoleSessionId") - procWaitCommEvent = modkernel32.NewProc("WaitCommEvent") - procWaitForMultipleObjects = modkernel32.NewProc("WaitForMultipleObjects") - procWaitForSingleObject = modkernel32.NewProc("WaitForSingleObject") - procWriteConsoleW = modkernel32.NewProc("WriteConsoleW") - procWriteFile = modkernel32.NewProc("WriteFile") - procWriteProcessMemory = modkernel32.NewProc("WriteProcessMemory") - procAcceptEx = modmswsock.NewProc("AcceptEx") - procGetAcceptExSockaddrs = modmswsock.NewProc("GetAcceptExSockaddrs") - procTransmitFile = modmswsock.NewProc("TransmitFile") - procNetApiBufferFree = modnetapi32.NewProc("NetApiBufferFree") - procNetGetJoinInformation = modnetapi32.NewProc("NetGetJoinInformation") - procNetUserGetInfo = modnetapi32.NewProc("NetUserGetInfo") - procNtCreateFile = modntdll.NewProc("NtCreateFile") - procNtCreateNamedPipeFile = modntdll.NewProc("NtCreateNamedPipeFile") - procNtQueryInformationProcess = modntdll.NewProc("NtQueryInformationProcess") - procNtQuerySystemInformation = modntdll.NewProc("NtQuerySystemInformation") - procNtSetInformationFile = modntdll.NewProc("NtSetInformationFile") - procNtSetInformationProcess = modntdll.NewProc("NtSetInformationProcess") - procNtSetSystemInformation = modntdll.NewProc("NtSetSystemInformation") - procRtlAddFunctionTable = modntdll.NewProc("RtlAddFunctionTable") - procRtlDefaultNpAcl = modntdll.NewProc("RtlDefaultNpAcl") - procRtlDeleteFunctionTable = modntdll.NewProc("RtlDeleteFunctionTable") - procRtlDosPathNameToNtPathName_U_WithStatus = modntdll.NewProc("RtlDosPathNameToNtPathName_U_WithStatus") - procRtlDosPathNameToRelativeNtPathName_U_WithStatus = modntdll.NewProc("RtlDosPathNameToRelativeNtPathName_U_WithStatus") - procRtlGetCurrentPeb = modntdll.NewProc("RtlGetCurrentPeb") - procRtlGetNtVersionNumbers = modntdll.NewProc("RtlGetNtVersionNumbers") - procRtlGetVersion = modntdll.NewProc("RtlGetVersion") - procRtlInitString = modntdll.NewProc("RtlInitString") - procRtlInitUnicodeString = modntdll.NewProc("RtlInitUnicodeString") - procRtlNtStatusToDosErrorNoTeb = modntdll.NewProc("RtlNtStatusToDosErrorNoTeb") - procCLSIDFromString = modole32.NewProc("CLSIDFromString") - procCoCreateGuid = modole32.NewProc("CoCreateGuid") - procCoGetObject = modole32.NewProc("CoGetObject") - procCoInitializeEx = modole32.NewProc("CoInitializeEx") - procCoTaskMemFree = modole32.NewProc("CoTaskMemFree") - procCoUninitialize = modole32.NewProc("CoUninitialize") - procStringFromGUID2 = modole32.NewProc("StringFromGUID2") - procEnumProcessModules = modpsapi.NewProc("EnumProcessModules") - procEnumProcessModulesEx = modpsapi.NewProc("EnumProcessModulesEx") - procEnumProcesses = modpsapi.NewProc("EnumProcesses") - procGetModuleBaseNameW = modpsapi.NewProc("GetModuleBaseNameW") - procGetModuleFileNameExW = modpsapi.NewProc("GetModuleFileNameExW") - procGetModuleInformation = modpsapi.NewProc("GetModuleInformation") - procQueryWorkingSetEx = modpsapi.NewProc("QueryWorkingSetEx") - procSubscribeServiceChangeNotifications = modsechost.NewProc("SubscribeServiceChangeNotifications") - procUnsubscribeServiceChangeNotifications = modsechost.NewProc("UnsubscribeServiceChangeNotifications") - procGetUserNameExW = modsecur32.NewProc("GetUserNameExW") - procTranslateNameW = modsecur32.NewProc("TranslateNameW") - procSetupDiBuildDriverInfoList = modsetupapi.NewProc("SetupDiBuildDriverInfoList") - procSetupDiCallClassInstaller = modsetupapi.NewProc("SetupDiCallClassInstaller") - procSetupDiCancelDriverInfoSearch = modsetupapi.NewProc("SetupDiCancelDriverInfoSearch") - procSetupDiClassGuidsFromNameExW = modsetupapi.NewProc("SetupDiClassGuidsFromNameExW") - procSetupDiClassNameFromGuidExW = modsetupapi.NewProc("SetupDiClassNameFromGuidExW") - procSetupDiCreateDeviceInfoListExW = modsetupapi.NewProc("SetupDiCreateDeviceInfoListExW") - procSetupDiCreateDeviceInfoW = modsetupapi.NewProc("SetupDiCreateDeviceInfoW") - procSetupDiDestroyDeviceInfoList = modsetupapi.NewProc("SetupDiDestroyDeviceInfoList") - procSetupDiDestroyDriverInfoList = modsetupapi.NewProc("SetupDiDestroyDriverInfoList") - procSetupDiEnumDeviceInfo = modsetupapi.NewProc("SetupDiEnumDeviceInfo") - procSetupDiEnumDriverInfoW = modsetupapi.NewProc("SetupDiEnumDriverInfoW") - procSetupDiGetClassDevsExW = modsetupapi.NewProc("SetupDiGetClassDevsExW") - procSetupDiGetClassInstallParamsW = modsetupapi.NewProc("SetupDiGetClassInstallParamsW") - procSetupDiGetDeviceInfoListDetailW = modsetupapi.NewProc("SetupDiGetDeviceInfoListDetailW") - procSetupDiGetDeviceInstallParamsW = modsetupapi.NewProc("SetupDiGetDeviceInstallParamsW") - procSetupDiGetDeviceInstanceIdW = modsetupapi.NewProc("SetupDiGetDeviceInstanceIdW") - procSetupDiGetDevicePropertyW = modsetupapi.NewProc("SetupDiGetDevicePropertyW") - procSetupDiGetDeviceRegistryPropertyW = modsetupapi.NewProc("SetupDiGetDeviceRegistryPropertyW") - procSetupDiGetDriverInfoDetailW = modsetupapi.NewProc("SetupDiGetDriverInfoDetailW") - procSetupDiGetSelectedDevice = modsetupapi.NewProc("SetupDiGetSelectedDevice") - procSetupDiGetSelectedDriverW = modsetupapi.NewProc("SetupDiGetSelectedDriverW") - procSetupDiOpenDevRegKey = modsetupapi.NewProc("SetupDiOpenDevRegKey") - procSetupDiSetClassInstallParamsW = modsetupapi.NewProc("SetupDiSetClassInstallParamsW") - procSetupDiSetDeviceInstallParamsW = modsetupapi.NewProc("SetupDiSetDeviceInstallParamsW") - procSetupDiSetDeviceRegistryPropertyW = modsetupapi.NewProc("SetupDiSetDeviceRegistryPropertyW") - procSetupDiSetSelectedDevice = modsetupapi.NewProc("SetupDiSetSelectedDevice") - procSetupDiSetSelectedDriverW = modsetupapi.NewProc("SetupDiSetSelectedDriverW") - procSetupUninstallOEMInfW = modsetupapi.NewProc("SetupUninstallOEMInfW") - procCommandLineToArgvW = modshell32.NewProc("CommandLineToArgvW") - procSHGetKnownFolderPath = modshell32.NewProc("SHGetKnownFolderPath") - procShellExecuteW = modshell32.NewProc("ShellExecuteW") - procEnumChildWindows = moduser32.NewProc("EnumChildWindows") - procEnumWindows = moduser32.NewProc("EnumWindows") - procExitWindowsEx = moduser32.NewProc("ExitWindowsEx") - procGetClassNameW = moduser32.NewProc("GetClassNameW") - procGetDesktopWindow = moduser32.NewProc("GetDesktopWindow") - procGetForegroundWindow = moduser32.NewProc("GetForegroundWindow") - procGetGUIThreadInfo = moduser32.NewProc("GetGUIThreadInfo") - procGetShellWindow = moduser32.NewProc("GetShellWindow") - procGetWindowThreadProcessId = moduser32.NewProc("GetWindowThreadProcessId") - procIsWindow = moduser32.NewProc("IsWindow") - procIsWindowUnicode = moduser32.NewProc("IsWindowUnicode") - procIsWindowVisible = moduser32.NewProc("IsWindowVisible") - procMessageBoxW = moduser32.NewProc("MessageBoxW") - procCreateEnvironmentBlock = moduserenv.NewProc("CreateEnvironmentBlock") - procDestroyEnvironmentBlock = moduserenv.NewProc("DestroyEnvironmentBlock") - procGetUserProfileDirectoryW = moduserenv.NewProc("GetUserProfileDirectoryW") - procGetFileVersionInfoSizeW = modversion.NewProc("GetFileVersionInfoSizeW") - procGetFileVersionInfoW = modversion.NewProc("GetFileVersionInfoW") - procVerQueryValueW = modversion.NewProc("VerQueryValueW") - proctimeBeginPeriod = modwinmm.NewProc("timeBeginPeriod") - proctimeEndPeriod = modwinmm.NewProc("timeEndPeriod") - procWinVerifyTrustEx = modwintrust.NewProc("WinVerifyTrustEx") - procFreeAddrInfoW = modws2_32.NewProc("FreeAddrInfoW") - procGetAddrInfoW = modws2_32.NewProc("GetAddrInfoW") - procWSACleanup = modws2_32.NewProc("WSACleanup") - procWSAEnumProtocolsW = modws2_32.NewProc("WSAEnumProtocolsW") - procWSAGetOverlappedResult = modws2_32.NewProc("WSAGetOverlappedResult") - procWSAIoctl = modws2_32.NewProc("WSAIoctl") - procWSALookupServiceBeginW = modws2_32.NewProc("WSALookupServiceBeginW") - procWSALookupServiceEnd = modws2_32.NewProc("WSALookupServiceEnd") - procWSALookupServiceNextW = modws2_32.NewProc("WSALookupServiceNextW") - procWSARecv = modws2_32.NewProc("WSARecv") - procWSARecvFrom = modws2_32.NewProc("WSARecvFrom") - procWSASend = modws2_32.NewProc("WSASend") - procWSASendTo = modws2_32.NewProc("WSASendTo") - procWSASocketW = modws2_32.NewProc("WSASocketW") - procWSAStartup = modws2_32.NewProc("WSAStartup") - procbind = modws2_32.NewProc("bind") - procclosesocket = modws2_32.NewProc("closesocket") - procconnect = modws2_32.NewProc("connect") - procgethostbyname = modws2_32.NewProc("gethostbyname") - procgetpeername = modws2_32.NewProc("getpeername") - procgetprotobyname = modws2_32.NewProc("getprotobyname") - procgetservbyname = modws2_32.NewProc("getservbyname") - procgetsockname = modws2_32.NewProc("getsockname") - procgetsockopt = modws2_32.NewProc("getsockopt") - proclisten = modws2_32.NewProc("listen") - procntohs = modws2_32.NewProc("ntohs") - procrecvfrom = modws2_32.NewProc("recvfrom") - procsendto = modws2_32.NewProc("sendto") - procsetsockopt = modws2_32.NewProc("setsockopt") - procshutdown = modws2_32.NewProc("shutdown") - procsocket = modws2_32.NewProc("socket") - procWTSEnumerateSessionsW = modwtsapi32.NewProc("WTSEnumerateSessionsW") - procWTSFreeMemory = modwtsapi32.NewProc("WTSFreeMemory") - procWTSQueryUserToken = modwtsapi32.NewProc("WTSQueryUserToken") + + procConvertStringSidToSidW = modadvapi32.NewProc("ConvertStringSidToSidW") + + procCopySid = modadvapi32.NewProc("CopySid") + + procCreateProcessAsUserW = modadvapi32.NewProc("CreateProcessAsUserW") + + procCreateServiceW = modadvapi32.NewProc("CreateServiceW") + + procCreateWellKnownSid = modadvapi32.NewProc("CreateWellKnownSid") + + procCryptAcquireContextW = modadvapi32.NewProc("CryptAcquireContextW") + + procCryptGenRandom = modadvapi32.NewProc("CryptGenRandom") + + procCryptReleaseContext = modadvapi32.NewProc("CryptReleaseContext") + + procDeleteService = modadvapi32.NewProc("DeleteService") + + procDeregisterEventSource = modadvapi32.NewProc("DeregisterEventSource") + + procDuplicateTokenEx = modadvapi32.NewProc("DuplicateTokenEx") + + procEnumDependentServicesW = modadvapi32.NewProc("EnumDependentServicesW") + + procEnumServicesStatusExW = modadvapi32.NewProc("EnumServicesStatusExW") + + procEqualSid = modadvapi32.NewProc("EqualSid") + + procFreeSid = modadvapi32.NewProc("FreeSid") + + procGetLengthSid = modadvapi32.NewProc("GetLengthSid") + + procGetNamedSecurityInfoW = modadvapi32.NewProc("GetNamedSecurityInfoW") + + procGetSecurityDescriptorControl = modadvapi32.NewProc("GetSecurityDescriptorControl") + + procGetSecurityDescriptorDacl = modadvapi32.NewProc("GetSecurityDescriptorDacl") + + procGetSecurityDescriptorGroup = modadvapi32.NewProc("GetSecurityDescriptorGroup") + + procGetSecurityDescriptorLength = modadvapi32.NewProc("GetSecurityDescriptorLength") + + procGetSecurityDescriptorOwner = modadvapi32.NewProc("GetSecurityDescriptorOwner") + + procGetSecurityDescriptorRMControl = modadvapi32.NewProc("GetSecurityDescriptorRMControl") + + procGetSecurityDescriptorSacl = modadvapi32.NewProc("GetSecurityDescriptorSacl") + + procGetSecurityInfo = modadvapi32.NewProc("GetSecurityInfo") + + procGetSidIdentifierAuthority = modadvapi32.NewProc("GetSidIdentifierAuthority") + + procGetSidSubAuthority = modadvapi32.NewProc("GetSidSubAuthority") + + procGetSidSubAuthorityCount = modadvapi32.NewProc("GetSidSubAuthorityCount") + + procGetTokenInformation = modadvapi32.NewProc("GetTokenInformation") + + procImpersonateSelf = modadvapi32.NewProc("ImpersonateSelf") + + procInitializeSecurityDescriptor = modadvapi32.NewProc("InitializeSecurityDescriptor") + + procInitiateSystemShutdownExW = modadvapi32.NewProc("InitiateSystemShutdownExW") + + procIsTokenRestricted = modadvapi32.NewProc("IsTokenRestricted") + + procIsValidSecurityDescriptor = modadvapi32.NewProc("IsValidSecurityDescriptor") + + procIsValidSid = modadvapi32.NewProc("IsValidSid") + + procIsWellKnownSid = modadvapi32.NewProc("IsWellKnownSid") + + procLookupAccountNameW = modadvapi32.NewProc("LookupAccountNameW") + + procLookupAccountSidW = modadvapi32.NewProc("LookupAccountSidW") + + procLookupPrivilegeValueW = modadvapi32.NewProc("LookupPrivilegeValueW") + + procMakeAbsoluteSD = modadvapi32.NewProc("MakeAbsoluteSD") + + procMakeSelfRelativeSD = modadvapi32.NewProc("MakeSelfRelativeSD") + + procNotifyServiceStatusChangeW = modadvapi32.NewProc("NotifyServiceStatusChangeW") + + procOpenProcessToken = modadvapi32.NewProc("OpenProcessToken") + + procOpenSCManagerW = modadvapi32.NewProc("OpenSCManagerW") + + procOpenServiceW = modadvapi32.NewProc("OpenServiceW") + + procOpenThreadToken = modadvapi32.NewProc("OpenThreadToken") + + procQueryServiceConfig2W = modadvapi32.NewProc("QueryServiceConfig2W") + + procQueryServiceConfigW = modadvapi32.NewProc("QueryServiceConfigW") + + procQueryServiceDynamicInformation = modadvapi32.NewProc("QueryServiceDynamicInformation") + + procQueryServiceLockStatusW = modadvapi32.NewProc("QueryServiceLockStatusW") + + procQueryServiceStatus = modadvapi32.NewProc("QueryServiceStatus") + + procQueryServiceStatusEx = modadvapi32.NewProc("QueryServiceStatusEx") + + procRegCloseKey = modadvapi32.NewProc("RegCloseKey") + + procRegEnumKeyExW = modadvapi32.NewProc("RegEnumKeyExW") + + procRegNotifyChangeKeyValue = modadvapi32.NewProc("RegNotifyChangeKeyValue") + + procRegOpenKeyExW = modadvapi32.NewProc("RegOpenKeyExW") + + procRegQueryInfoKeyW = modadvapi32.NewProc("RegQueryInfoKeyW") + + procRegQueryValueExW = modadvapi32.NewProc("RegQueryValueExW") + + procRegisterEventSourceW = modadvapi32.NewProc("RegisterEventSourceW") + + procRegisterServiceCtrlHandlerExW = modadvapi32.NewProc("RegisterServiceCtrlHandlerExW") + + procReportEventW = modadvapi32.NewProc("ReportEventW") + + procRevertToSelf = modadvapi32.NewProc("RevertToSelf") + + procSetEntriesInAclW = modadvapi32.NewProc("SetEntriesInAclW") + + procSetKernelObjectSecurity = modadvapi32.NewProc("SetKernelObjectSecurity") + + procSetNamedSecurityInfoW = modadvapi32.NewProc("SetNamedSecurityInfoW") + + procSetSecurityDescriptorControl = modadvapi32.NewProc("SetSecurityDescriptorControl") + + procSetSecurityDescriptorDacl = modadvapi32.NewProc("SetSecurityDescriptorDacl") + + procSetSecurityDescriptorGroup = modadvapi32.NewProc("SetSecurityDescriptorGroup") + + procSetSecurityDescriptorOwner = modadvapi32.NewProc("SetSecurityDescriptorOwner") + + procSetSecurityDescriptorRMControl = modadvapi32.NewProc("SetSecurityDescriptorRMControl") + + procSetSecurityDescriptorSacl = modadvapi32.NewProc("SetSecurityDescriptorSacl") + + procSetSecurityInfo = modadvapi32.NewProc("SetSecurityInfo") + + procSetServiceStatus = modadvapi32.NewProc("SetServiceStatus") + + procSetThreadToken = modadvapi32.NewProc("SetThreadToken") + + procSetTokenInformation = modadvapi32.NewProc("SetTokenInformation") + + procStartServiceCtrlDispatcherW = modadvapi32.NewProc("StartServiceCtrlDispatcherW") + + procStartServiceW = modadvapi32.NewProc("StartServiceW") + + procCertAddCertificateContextToStore = modcrypt32.NewProc("CertAddCertificateContextToStore") + + procCertCloseStore = modcrypt32.NewProc("CertCloseStore") + + procCertCreateCertificateContext = modcrypt32.NewProc("CertCreateCertificateContext") + + procCertDeleteCertificateFromStore = modcrypt32.NewProc("CertDeleteCertificateFromStore") + + procCertDuplicateCertificateContext = modcrypt32.NewProc("CertDuplicateCertificateContext") + + procCertEnumCertificatesInStore = modcrypt32.NewProc("CertEnumCertificatesInStore") + + procCertFindCertificateInStore = modcrypt32.NewProc("CertFindCertificateInStore") + + procCertFindChainInStore = modcrypt32.NewProc("CertFindChainInStore") + + procCertFindExtension = modcrypt32.NewProc("CertFindExtension") + + procCertFreeCertificateChain = modcrypt32.NewProc("CertFreeCertificateChain") + + procCertFreeCertificateContext = modcrypt32.NewProc("CertFreeCertificateContext") + + procCertGetCertificateChain = modcrypt32.NewProc("CertGetCertificateChain") + + procCertGetNameStringW = modcrypt32.NewProc("CertGetNameStringW") + + procCertOpenStore = modcrypt32.NewProc("CertOpenStore") + + procCertOpenSystemStoreW = modcrypt32.NewProc("CertOpenSystemStoreW") + + procCertVerifyCertificateChainPolicy = modcrypt32.NewProc("CertVerifyCertificateChainPolicy") + + procCryptAcquireCertificatePrivateKey = modcrypt32.NewProc("CryptAcquireCertificatePrivateKey") + + procCryptDecodeObject = modcrypt32.NewProc("CryptDecodeObject") + + procCryptProtectData = modcrypt32.NewProc("CryptProtectData") + + procCryptQueryObject = modcrypt32.NewProc("CryptQueryObject") + + procCryptUnprotectData = modcrypt32.NewProc("CryptUnprotectData") + + procPFXImportCertStore = modcrypt32.NewProc("PFXImportCertStore") + + procDnsNameCompare_W = moddnsapi.NewProc("DnsNameCompare_W") + + procDnsQuery_W = moddnsapi.NewProc("DnsQuery_W") + + procDnsRecordListFree = moddnsapi.NewProc("DnsRecordListFree") + + procDwmGetWindowAttribute = moddwmapi.NewProc("DwmGetWindowAttribute") + + procDwmSetWindowAttribute = moddwmapi.NewProc("DwmSetWindowAttribute") + + procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses") + + procGetAdaptersInfo = modiphlpapi.NewProc("GetAdaptersInfo") + + procGetBestInterfaceEx = modiphlpapi.NewProc("GetBestInterfaceEx") + + procGetIfEntry = modiphlpapi.NewProc("GetIfEntry") + + procAddDllDirectory = modkernel32.NewProc("AddDllDirectory") + + procAssignProcessToJobObject = modkernel32.NewProc("AssignProcessToJobObject") + + procCancelIo = modkernel32.NewProc("CancelIo") + + procCancelIoEx = modkernel32.NewProc("CancelIoEx") + + procClearCommBreak = modkernel32.NewProc("ClearCommBreak") + + procClearCommError = modkernel32.NewProc("ClearCommError") + + procCloseHandle = modkernel32.NewProc("CloseHandle") + + procClosePseudoConsole = modkernel32.NewProc("ClosePseudoConsole") + + procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe") + + procCreateDirectoryW = modkernel32.NewProc("CreateDirectoryW") + + procCreateEventExW = modkernel32.NewProc("CreateEventExW") + + procCreateEventW = modkernel32.NewProc("CreateEventW") + + procCreateFileMappingW = modkernel32.NewProc("CreateFileMappingW") + + procCreateFileW = modkernel32.NewProc("CreateFileW") + + procCreateHardLinkW = modkernel32.NewProc("CreateHardLinkW") + + procCreateIoCompletionPort = modkernel32.NewProc("CreateIoCompletionPort") + + procCreateJobObjectW = modkernel32.NewProc("CreateJobObjectW") + + procCreateMutexExW = modkernel32.NewProc("CreateMutexExW") + + procCreateMutexW = modkernel32.NewProc("CreateMutexW") + + procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW") + + procCreatePipe = modkernel32.NewProc("CreatePipe") + + procCreateProcessW = modkernel32.NewProc("CreateProcessW") + + procCreatePseudoConsole = modkernel32.NewProc("CreatePseudoConsole") + + procCreateSymbolicLinkW = modkernel32.NewProc("CreateSymbolicLinkW") + + procCreateToolhelp32Snapshot = modkernel32.NewProc("CreateToolhelp32Snapshot") + + procDefineDosDeviceW = modkernel32.NewProc("DefineDosDeviceW") + + procDeleteFileW = modkernel32.NewProc("DeleteFileW") + + procDeleteProcThreadAttributeList = modkernel32.NewProc("DeleteProcThreadAttributeList") + + procDeleteVolumeMountPointW = modkernel32.NewProc("DeleteVolumeMountPointW") + + procDeviceIoControl = modkernel32.NewProc("DeviceIoControl") + + procDisconnectNamedPipe = modkernel32.NewProc("DisconnectNamedPipe") + + procDuplicateHandle = modkernel32.NewProc("DuplicateHandle") + + procEscapeCommFunction = modkernel32.NewProc("EscapeCommFunction") + + procExitProcess = modkernel32.NewProc("ExitProcess") + + procExpandEnvironmentStringsW = modkernel32.NewProc("ExpandEnvironmentStringsW") + + procFindClose = modkernel32.NewProc("FindClose") + + procFindCloseChangeNotification = modkernel32.NewProc("FindCloseChangeNotification") + + procFindFirstChangeNotificationW = modkernel32.NewProc("FindFirstChangeNotificationW") + + procFindFirstFileW = modkernel32.NewProc("FindFirstFileW") + + procFindFirstVolumeMountPointW = modkernel32.NewProc("FindFirstVolumeMountPointW") + + procFindFirstVolumeW = modkernel32.NewProc("FindFirstVolumeW") + + procFindNextChangeNotification = modkernel32.NewProc("FindNextChangeNotification") + + procFindNextFileW = modkernel32.NewProc("FindNextFileW") + + procFindNextVolumeMountPointW = modkernel32.NewProc("FindNextVolumeMountPointW") + + procFindNextVolumeW = modkernel32.NewProc("FindNextVolumeW") + + procFindResourceW = modkernel32.NewProc("FindResourceW") + + procFindVolumeClose = modkernel32.NewProc("FindVolumeClose") + + procFindVolumeMountPointClose = modkernel32.NewProc("FindVolumeMountPointClose") + + procFlushFileBuffers = modkernel32.NewProc("FlushFileBuffers") + + procFlushViewOfFile = modkernel32.NewProc("FlushViewOfFile") + + procFormatMessageW = modkernel32.NewProc("FormatMessageW") + + procFreeEnvironmentStringsW = modkernel32.NewProc("FreeEnvironmentStringsW") + + procFreeLibrary = modkernel32.NewProc("FreeLibrary") + + procGenerateConsoleCtrlEvent = modkernel32.NewProc("GenerateConsoleCtrlEvent") + + procGetACP = modkernel32.NewProc("GetACP") + + procGetActiveProcessorCount = modkernel32.NewProc("GetActiveProcessorCount") + + procGetCommModemStatus = modkernel32.NewProc("GetCommModemStatus") + + procGetCommState = modkernel32.NewProc("GetCommState") + + procGetCommTimeouts = modkernel32.NewProc("GetCommTimeouts") + + procGetCommandLineW = modkernel32.NewProc("GetCommandLineW") + + procGetComputerNameExW = modkernel32.NewProc("GetComputerNameExW") + + procGetComputerNameW = modkernel32.NewProc("GetComputerNameW") + + procGetConsoleMode = modkernel32.NewProc("GetConsoleMode") + + procGetConsoleScreenBufferInfo = modkernel32.NewProc("GetConsoleScreenBufferInfo") + + procGetCurrentDirectoryW = modkernel32.NewProc("GetCurrentDirectoryW") + + procGetCurrentProcessId = modkernel32.NewProc("GetCurrentProcessId") + + procGetCurrentThreadId = modkernel32.NewProc("GetCurrentThreadId") + + procGetDiskFreeSpaceExW = modkernel32.NewProc("GetDiskFreeSpaceExW") + + procGetDriveTypeW = modkernel32.NewProc("GetDriveTypeW") + + procGetEnvironmentStringsW = modkernel32.NewProc("GetEnvironmentStringsW") + + procGetEnvironmentVariableW = modkernel32.NewProc("GetEnvironmentVariableW") + + procGetExitCodeProcess = modkernel32.NewProc("GetExitCodeProcess") + + procGetFileAttributesExW = modkernel32.NewProc("GetFileAttributesExW") + + procGetFileAttributesW = modkernel32.NewProc("GetFileAttributesW") + + procGetFileInformationByHandle = modkernel32.NewProc("GetFileInformationByHandle") + + procGetFileInformationByHandleEx = modkernel32.NewProc("GetFileInformationByHandleEx") + + procGetFileTime = modkernel32.NewProc("GetFileTime") + + procGetFileType = modkernel32.NewProc("GetFileType") + + procGetFinalPathNameByHandleW = modkernel32.NewProc("GetFinalPathNameByHandleW") + + procGetFullPathNameW = modkernel32.NewProc("GetFullPathNameW") + + procGetLargePageMinimum = modkernel32.NewProc("GetLargePageMinimum") + + procGetLastError = modkernel32.NewProc("GetLastError") + + procGetLogicalDriveStringsW = modkernel32.NewProc("GetLogicalDriveStringsW") + + procGetLogicalDrives = modkernel32.NewProc("GetLogicalDrives") + + procGetLongPathNameW = modkernel32.NewProc("GetLongPathNameW") + + procGetMaximumProcessorCount = modkernel32.NewProc("GetMaximumProcessorCount") + + procGetModuleFileNameW = modkernel32.NewProc("GetModuleFileNameW") + + procGetModuleHandleExW = modkernel32.NewProc("GetModuleHandleExW") + + procGetNamedPipeHandleStateW = modkernel32.NewProc("GetNamedPipeHandleStateW") + + procGetNamedPipeInfo = modkernel32.NewProc("GetNamedPipeInfo") + + procGetOverlappedResult = modkernel32.NewProc("GetOverlappedResult") + + procGetPriorityClass = modkernel32.NewProc("GetPriorityClass") + + procGetProcAddress = modkernel32.NewProc("GetProcAddress") + + procGetProcessId = modkernel32.NewProc("GetProcessId") + + procGetProcessPreferredUILanguages = modkernel32.NewProc("GetProcessPreferredUILanguages") + + procGetProcessShutdownParameters = modkernel32.NewProc("GetProcessShutdownParameters") + + procGetProcessTimes = modkernel32.NewProc("GetProcessTimes") + + procGetProcessWorkingSetSizeEx = modkernel32.NewProc("GetProcessWorkingSetSizeEx") + + procGetQueuedCompletionStatus = modkernel32.NewProc("GetQueuedCompletionStatus") + + procGetShortPathNameW = modkernel32.NewProc("GetShortPathNameW") + + procGetStartupInfoW = modkernel32.NewProc("GetStartupInfoW") + + procGetStdHandle = modkernel32.NewProc("GetStdHandle") + + procGetSystemDirectoryW = modkernel32.NewProc("GetSystemDirectoryW") + + procGetSystemPreferredUILanguages = modkernel32.NewProc("GetSystemPreferredUILanguages") + + procGetSystemTimeAsFileTime = modkernel32.NewProc("GetSystemTimeAsFileTime") + + procGetSystemTimePreciseAsFileTime = modkernel32.NewProc("GetSystemTimePreciseAsFileTime") + + procGetSystemWindowsDirectoryW = modkernel32.NewProc("GetSystemWindowsDirectoryW") + + procGetTempPathW = modkernel32.NewProc("GetTempPathW") + + procGetThreadPreferredUILanguages = modkernel32.NewProc("GetThreadPreferredUILanguages") + + procGetTickCount64 = modkernel32.NewProc("GetTickCount64") + + procGetTimeZoneInformation = modkernel32.NewProc("GetTimeZoneInformation") + + procGetUserPreferredUILanguages = modkernel32.NewProc("GetUserPreferredUILanguages") + + procGetVersion = modkernel32.NewProc("GetVersion") + + procGetVolumeInformationByHandleW = modkernel32.NewProc("GetVolumeInformationByHandleW") + + procGetVolumeInformationW = modkernel32.NewProc("GetVolumeInformationW") + + procGetVolumeNameForVolumeMountPointW = modkernel32.NewProc("GetVolumeNameForVolumeMountPointW") + + procGetVolumePathNameW = modkernel32.NewProc("GetVolumePathNameW") + + procGetVolumePathNamesForVolumeNameW = modkernel32.NewProc("GetVolumePathNamesForVolumeNameW") + + procGetWindowsDirectoryW = modkernel32.NewProc("GetWindowsDirectoryW") + + procInitializeProcThreadAttributeList = modkernel32.NewProc("InitializeProcThreadAttributeList") + + procIsWow64Process = modkernel32.NewProc("IsWow64Process") + + procIsWow64Process2 = modkernel32.NewProc("IsWow64Process2") + + procLoadLibraryExW = modkernel32.NewProc("LoadLibraryExW") + + procLoadLibraryW = modkernel32.NewProc("LoadLibraryW") + + procLoadResource = modkernel32.NewProc("LoadResource") + + procLocalAlloc = modkernel32.NewProc("LocalAlloc") + + procLocalFree = modkernel32.NewProc("LocalFree") + + procLockFileEx = modkernel32.NewProc("LockFileEx") + + procLockResource = modkernel32.NewProc("LockResource") + + procMapViewOfFile = modkernel32.NewProc("MapViewOfFile") + + procModule32FirstW = modkernel32.NewProc("Module32FirstW") + + procModule32NextW = modkernel32.NewProc("Module32NextW") + + procMoveFileExW = modkernel32.NewProc("MoveFileExW") + + procMoveFileW = modkernel32.NewProc("MoveFileW") + + procMultiByteToWideChar = modkernel32.NewProc("MultiByteToWideChar") + + procOpenEventW = modkernel32.NewProc("OpenEventW") + + procOpenMutexW = modkernel32.NewProc("OpenMutexW") + + procOpenProcess = modkernel32.NewProc("OpenProcess") + + procOpenThread = modkernel32.NewProc("OpenThread") + + procPostQueuedCompletionStatus = modkernel32.NewProc("PostQueuedCompletionStatus") + + procProcess32FirstW = modkernel32.NewProc("Process32FirstW") + + procProcess32NextW = modkernel32.NewProc("Process32NextW") + + procProcessIdToSessionId = modkernel32.NewProc("ProcessIdToSessionId") + + procPulseEvent = modkernel32.NewProc("PulseEvent") + + procPurgeComm = modkernel32.NewProc("PurgeComm") + + procQueryDosDeviceW = modkernel32.NewProc("QueryDosDeviceW") + + procQueryFullProcessImageNameW = modkernel32.NewProc("QueryFullProcessImageNameW") + + procQueryInformationJobObject = modkernel32.NewProc("QueryInformationJobObject") + + procReadConsoleW = modkernel32.NewProc("ReadConsoleW") + + procReadDirectoryChangesW = modkernel32.NewProc("ReadDirectoryChangesW") + + procReadFile = modkernel32.NewProc("ReadFile") + + procReadProcessMemory = modkernel32.NewProc("ReadProcessMemory") + + procReleaseMutex = modkernel32.NewProc("ReleaseMutex") + + procRemoveDirectoryW = modkernel32.NewProc("RemoveDirectoryW") + + procRemoveDllDirectory = modkernel32.NewProc("RemoveDllDirectory") + + procResetEvent = modkernel32.NewProc("ResetEvent") + + procResizePseudoConsole = modkernel32.NewProc("ResizePseudoConsole") + + procResumeThread = modkernel32.NewProc("ResumeThread") + + procSetCommBreak = modkernel32.NewProc("SetCommBreak") + + procSetCommMask = modkernel32.NewProc("SetCommMask") + + procSetCommState = modkernel32.NewProc("SetCommState") + + procSetCommTimeouts = modkernel32.NewProc("SetCommTimeouts") + + procSetConsoleCursorPosition = modkernel32.NewProc("SetConsoleCursorPosition") + + procSetConsoleMode = modkernel32.NewProc("SetConsoleMode") + + procSetCurrentDirectoryW = modkernel32.NewProc("SetCurrentDirectoryW") + + procSetDefaultDllDirectories = modkernel32.NewProc("SetDefaultDllDirectories") + + procSetDllDirectoryW = modkernel32.NewProc("SetDllDirectoryW") + + procSetEndOfFile = modkernel32.NewProc("SetEndOfFile") + + procSetEnvironmentVariableW = modkernel32.NewProc("SetEnvironmentVariableW") + + procSetErrorMode = modkernel32.NewProc("SetErrorMode") + + procSetEvent = modkernel32.NewProc("SetEvent") + + procSetFileAttributesW = modkernel32.NewProc("SetFileAttributesW") + + procSetFileCompletionNotificationModes = modkernel32.NewProc("SetFileCompletionNotificationModes") + + procSetFileInformationByHandle = modkernel32.NewProc("SetFileInformationByHandle") + + procSetFilePointer = modkernel32.NewProc("SetFilePointer") + + procSetFileTime = modkernel32.NewProc("SetFileTime") + + procSetFileValidData = modkernel32.NewProc("SetFileValidData") + + procSetHandleInformation = modkernel32.NewProc("SetHandleInformation") + + procSetInformationJobObject = modkernel32.NewProc("SetInformationJobObject") + + procSetNamedPipeHandleState = modkernel32.NewProc("SetNamedPipeHandleState") + + procSetPriorityClass = modkernel32.NewProc("SetPriorityClass") + + procSetProcessPriorityBoost = modkernel32.NewProc("SetProcessPriorityBoost") + + procSetProcessShutdownParameters = modkernel32.NewProc("SetProcessShutdownParameters") + + procSetProcessWorkingSetSizeEx = modkernel32.NewProc("SetProcessWorkingSetSizeEx") + + procSetStdHandle = modkernel32.NewProc("SetStdHandle") + + procSetVolumeLabelW = modkernel32.NewProc("SetVolumeLabelW") + + procSetVolumeMountPointW = modkernel32.NewProc("SetVolumeMountPointW") + + procSetupComm = modkernel32.NewProc("SetupComm") + + procSizeofResource = modkernel32.NewProc("SizeofResource") + + procSleepEx = modkernel32.NewProc("SleepEx") + + procTerminateJobObject = modkernel32.NewProc("TerminateJobObject") + + procTerminateProcess = modkernel32.NewProc("TerminateProcess") + + procThread32First = modkernel32.NewProc("Thread32First") + + procThread32Next = modkernel32.NewProc("Thread32Next") + + procUnlockFileEx = modkernel32.NewProc("UnlockFileEx") + + procUnmapViewOfFile = modkernel32.NewProc("UnmapViewOfFile") + + procUpdateProcThreadAttribute = modkernel32.NewProc("UpdateProcThreadAttribute") + + procVirtualAlloc = modkernel32.NewProc("VirtualAlloc") + + procVirtualFree = modkernel32.NewProc("VirtualFree") + + procVirtualLock = modkernel32.NewProc("VirtualLock") + + procVirtualProtect = modkernel32.NewProc("VirtualProtect") + + procVirtualProtectEx = modkernel32.NewProc("VirtualProtectEx") + + procVirtualQuery = modkernel32.NewProc("VirtualQuery") + + procVirtualQueryEx = modkernel32.NewProc("VirtualQueryEx") + + procVirtualUnlock = modkernel32.NewProc("VirtualUnlock") + + procWTSGetActiveConsoleSessionId = modkernel32.NewProc("WTSGetActiveConsoleSessionId") + + procWaitCommEvent = modkernel32.NewProc("WaitCommEvent") + + procWaitForMultipleObjects = modkernel32.NewProc("WaitForMultipleObjects") + + procWaitForSingleObject = modkernel32.NewProc("WaitForSingleObject") + + procWriteConsoleW = modkernel32.NewProc("WriteConsoleW") + + procWriteFile = modkernel32.NewProc("WriteFile") + + procWriteProcessMemory = modkernel32.NewProc("WriteProcessMemory") + + procAcceptEx = modmswsock.NewProc("AcceptEx") + + procGetAcceptExSockaddrs = modmswsock.NewProc("GetAcceptExSockaddrs") + + procTransmitFile = modmswsock.NewProc("TransmitFile") + + procNetApiBufferFree = modnetapi32.NewProc("NetApiBufferFree") + + procNetGetJoinInformation = modnetapi32.NewProc("NetGetJoinInformation") + + procNetUserGetInfo = modnetapi32.NewProc("NetUserGetInfo") + + procNtCreateFile = modntdll.NewProc("NtCreateFile") + + procNtCreateNamedPipeFile = modntdll.NewProc("NtCreateNamedPipeFile") + + procNtQueryInformationProcess = modntdll.NewProc("NtQueryInformationProcess") + + procNtQuerySystemInformation = modntdll.NewProc("NtQuerySystemInformation") + + procNtSetInformationFile = modntdll.NewProc("NtSetInformationFile") + + procNtSetInformationProcess = modntdll.NewProc("NtSetInformationProcess") + + procNtSetSystemInformation = modntdll.NewProc("NtSetSystemInformation") + + procRtlAddFunctionTable = modntdll.NewProc("RtlAddFunctionTable") + + procRtlDefaultNpAcl = modntdll.NewProc("RtlDefaultNpAcl") + + procRtlDeleteFunctionTable = modntdll.NewProc("RtlDeleteFunctionTable") + + procRtlDosPathNameToNtPathName_U_WithStatus = modntdll.NewProc("RtlDosPathNameToNtPathName_U_WithStatus") + + procRtlDosPathNameToRelativeNtPathName_U_WithStatus = modntdll.NewProc("RtlDosPathNameToRelativeNtPathName_U_WithStatus") + + procRtlGetCurrentPeb = modntdll.NewProc("RtlGetCurrentPeb") + + procRtlGetNtVersionNumbers = modntdll.NewProc("RtlGetNtVersionNumbers") + + procRtlGetVersion = modntdll.NewProc("RtlGetVersion") + + procRtlInitString = modntdll.NewProc("RtlInitString") + + procRtlInitUnicodeString = modntdll.NewProc("RtlInitUnicodeString") + + procRtlNtStatusToDosErrorNoTeb = modntdll.NewProc("RtlNtStatusToDosErrorNoTeb") + + procCLSIDFromString = modole32.NewProc("CLSIDFromString") + + procCoCreateGuid = modole32.NewProc("CoCreateGuid") + + procCoGetObject = modole32.NewProc("CoGetObject") + + procCoInitializeEx = modole32.NewProc("CoInitializeEx") + + procCoTaskMemFree = modole32.NewProc("CoTaskMemFree") + + procCoUninitialize = modole32.NewProc("CoUninitialize") + + procStringFromGUID2 = modole32.NewProc("StringFromGUID2") + + procEnumProcessModules = modpsapi.NewProc("EnumProcessModules") + + procEnumProcessModulesEx = modpsapi.NewProc("EnumProcessModulesEx") + + procEnumProcesses = modpsapi.NewProc("EnumProcesses") + + procGetModuleBaseNameW = modpsapi.NewProc("GetModuleBaseNameW") + + procGetModuleFileNameExW = modpsapi.NewProc("GetModuleFileNameExW") + + procGetModuleInformation = modpsapi.NewProc("GetModuleInformation") + + procQueryWorkingSetEx = modpsapi.NewProc("QueryWorkingSetEx") + + procSubscribeServiceChangeNotifications = modsechost.NewProc("SubscribeServiceChangeNotifications") + + procUnsubscribeServiceChangeNotifications = modsechost.NewProc("UnsubscribeServiceChangeNotifications") + + procGetUserNameExW = modsecur32.NewProc("GetUserNameExW") + + procTranslateNameW = modsecur32.NewProc("TranslateNameW") + + procSetupDiBuildDriverInfoList = modsetupapi.NewProc("SetupDiBuildDriverInfoList") + + procSetupDiCallClassInstaller = modsetupapi.NewProc("SetupDiCallClassInstaller") + + procSetupDiCancelDriverInfoSearch = modsetupapi.NewProc("SetupDiCancelDriverInfoSearch") + + procSetupDiClassGuidsFromNameExW = modsetupapi.NewProc("SetupDiClassGuidsFromNameExW") + + procSetupDiClassNameFromGuidExW = modsetupapi.NewProc("SetupDiClassNameFromGuidExW") + + procSetupDiCreateDeviceInfoListExW = modsetupapi.NewProc("SetupDiCreateDeviceInfoListExW") + + procSetupDiCreateDeviceInfoW = modsetupapi.NewProc("SetupDiCreateDeviceInfoW") + + procSetupDiDestroyDeviceInfoList = modsetupapi.NewProc("SetupDiDestroyDeviceInfoList") + + procSetupDiDestroyDriverInfoList = modsetupapi.NewProc("SetupDiDestroyDriverInfoList") + + procSetupDiEnumDeviceInfo = modsetupapi.NewProc("SetupDiEnumDeviceInfo") + + procSetupDiEnumDriverInfoW = modsetupapi.NewProc("SetupDiEnumDriverInfoW") + + procSetupDiGetClassDevsExW = modsetupapi.NewProc("SetupDiGetClassDevsExW") + + procSetupDiGetClassInstallParamsW = modsetupapi.NewProc("SetupDiGetClassInstallParamsW") + + procSetupDiGetDeviceInfoListDetailW = modsetupapi.NewProc("SetupDiGetDeviceInfoListDetailW") + + procSetupDiGetDeviceInstallParamsW = modsetupapi.NewProc("SetupDiGetDeviceInstallParamsW") + + procSetupDiGetDeviceInstanceIdW = modsetupapi.NewProc("SetupDiGetDeviceInstanceIdW") + + procSetupDiGetDevicePropertyW = modsetupapi.NewProc("SetupDiGetDevicePropertyW") + + procSetupDiGetDeviceRegistryPropertyW = modsetupapi.NewProc("SetupDiGetDeviceRegistryPropertyW") + + procSetupDiGetDriverInfoDetailW = modsetupapi.NewProc("SetupDiGetDriverInfoDetailW") + + procSetupDiGetSelectedDevice = modsetupapi.NewProc("SetupDiGetSelectedDevice") + + procSetupDiGetSelectedDriverW = modsetupapi.NewProc("SetupDiGetSelectedDriverW") + + procSetupDiOpenDevRegKey = modsetupapi.NewProc("SetupDiOpenDevRegKey") + + procSetupDiSetClassInstallParamsW = modsetupapi.NewProc("SetupDiSetClassInstallParamsW") + + procSetupDiSetDeviceInstallParamsW = modsetupapi.NewProc("SetupDiSetDeviceInstallParamsW") + + procSetupDiSetDeviceRegistryPropertyW = modsetupapi.NewProc("SetupDiSetDeviceRegistryPropertyW") + + procSetupDiSetSelectedDevice = modsetupapi.NewProc("SetupDiSetSelectedDevice") + + procSetupDiSetSelectedDriverW = modsetupapi.NewProc("SetupDiSetSelectedDriverW") + + procSetupUninstallOEMInfW = modsetupapi.NewProc("SetupUninstallOEMInfW") + + procCommandLineToArgvW = modshell32.NewProc("CommandLineToArgvW") + + procSHGetKnownFolderPath = modshell32.NewProc("SHGetKnownFolderPath") + + procShellExecuteW = modshell32.NewProc("ShellExecuteW") + + procEnumChildWindows = moduser32.NewProc("EnumChildWindows") + + procEnumWindows = moduser32.NewProc("EnumWindows") + + procExitWindowsEx = moduser32.NewProc("ExitWindowsEx") + + procGetClassNameW = moduser32.NewProc("GetClassNameW") + + procGetDesktopWindow = moduser32.NewProc("GetDesktopWindow") + + procGetForegroundWindow = moduser32.NewProc("GetForegroundWindow") + + procGetGUIThreadInfo = moduser32.NewProc("GetGUIThreadInfo") + + procGetShellWindow = moduser32.NewProc("GetShellWindow") + + procGetWindowThreadProcessId = moduser32.NewProc("GetWindowThreadProcessId") + + procIsWindow = moduser32.NewProc("IsWindow") + + procIsWindowUnicode = moduser32.NewProc("IsWindowUnicode") + + procIsWindowVisible = moduser32.NewProc("IsWindowVisible") + + procMessageBoxW = moduser32.NewProc("MessageBoxW") + + procCreateEnvironmentBlock = moduserenv.NewProc("CreateEnvironmentBlock") + + procDestroyEnvironmentBlock = moduserenv.NewProc("DestroyEnvironmentBlock") + + procGetUserProfileDirectoryW = moduserenv.NewProc("GetUserProfileDirectoryW") + + procGetFileVersionInfoSizeW = modversion.NewProc("GetFileVersionInfoSizeW") + + procGetFileVersionInfoW = modversion.NewProc("GetFileVersionInfoW") + + procVerQueryValueW = modversion.NewProc("VerQueryValueW") + + proctimeBeginPeriod = modwinmm.NewProc("timeBeginPeriod") + + proctimeEndPeriod = modwinmm.NewProc("timeEndPeriod") + + procWinVerifyTrustEx = modwintrust.NewProc("WinVerifyTrustEx") + + procFreeAddrInfoW = modws2_32.NewProc("FreeAddrInfoW") + + procGetAddrInfoW = modws2_32.NewProc("GetAddrInfoW") + + procWSACleanup = modws2_32.NewProc("WSACleanup") + + procWSAEnumProtocolsW = modws2_32.NewProc("WSAEnumProtocolsW") + + procWSAGetOverlappedResult = modws2_32.NewProc("WSAGetOverlappedResult") + + procWSAIoctl = modws2_32.NewProc("WSAIoctl") + + procWSALookupServiceBeginW = modws2_32.NewProc("WSALookupServiceBeginW") + + procWSALookupServiceEnd = modws2_32.NewProc("WSALookupServiceEnd") + + procWSALookupServiceNextW = modws2_32.NewProc("WSALookupServiceNextW") + + procWSARecv = modws2_32.NewProc("WSARecv") + + procWSARecvFrom = modws2_32.NewProc("WSARecvFrom") + + procWSASend = modws2_32.NewProc("WSASend") + + procWSASendTo = modws2_32.NewProc("WSASendTo") + + procWSASocketW = modws2_32.NewProc("WSASocketW") + + procWSAStartup = modws2_32.NewProc("WSAStartup") + + procbind = modws2_32.NewProc("bind") + + procclosesocket = modws2_32.NewProc("closesocket") + + procconnect = modws2_32.NewProc("connect") + + procgethostbyname = modws2_32.NewProc("gethostbyname") + + procgetpeername = modws2_32.NewProc("getpeername") + + procgetprotobyname = modws2_32.NewProc("getprotobyname") + + procgetservbyname = modws2_32.NewProc("getservbyname") + + procgetsockname = modws2_32.NewProc("getsockname") + + procgetsockopt = modws2_32.NewProc("getsockopt") + + proclisten = modws2_32.NewProc("listen") + + procntohs = modws2_32.NewProc("ntohs") + + procrecvfrom = modws2_32.NewProc("recvfrom") + + procsendto = modws2_32.NewProc("sendto") + + procsetsockopt = modws2_32.NewProc("setsockopt") + + procshutdown = modws2_32.NewProc("shutdown") + + procsocket = modws2_32.NewProc("socket") + + procWTSEnumerateSessionsW = modwtsapi32.NewProc("WTSEnumerateSessionsW") + + procWTSFreeMemory = modwtsapi32.NewProc("WTSFreeMemory") + + procWTSQueryUserToken = modwtsapi32.NewProc("WTSQueryUserToken") ) func cm_Get_DevNode_Status(status *uint32, problemNumber *uint32, devInst DEVINST, flags uint32) (ret CONFIGRET) { + r0, _, _ := syscall.Syscall6(procCM_Get_DevNode_Status.Addr(), 4, uintptr(unsafe.Pointer(status)), uintptr(unsafe.Pointer(problemNumber)), uintptr(devInst), uintptr(flags), 0, 0) + ret = CONFIGRET(r0) + return + } func cm_Get_Device_Interface_List(interfaceClass *GUID, deviceID *uint16, buffer *uint16, bufferLen uint32, flags uint32) (ret CONFIGRET) { + r0, _, _ := syscall.Syscall6(procCM_Get_Device_Interface_ListW.Addr(), 5, uintptr(unsafe.Pointer(interfaceClass)), uintptr(unsafe.Pointer(deviceID)), uintptr(unsafe.Pointer(buffer)), uintptr(bufferLen), uintptr(flags), 0) + ret = CONFIGRET(r0) + return + } func cm_Get_Device_Interface_List_Size(len *uint32, interfaceClass *GUID, deviceID *uint16, flags uint32) (ret CONFIGRET) { + r0, _, _ := syscall.Syscall6(procCM_Get_Device_Interface_List_SizeW.Addr(), 4, uintptr(unsafe.Pointer(len)), uintptr(unsafe.Pointer(interfaceClass)), uintptr(unsafe.Pointer(deviceID)), uintptr(flags), 0, 0) + ret = CONFIGRET(r0) + return + } func cm_MapCrToWin32Err(configRet CONFIGRET, defaultWin32Error Errno) (ret Errno) { + r0, _, _ := syscall.Syscall(procCM_MapCrToWin32Err.Addr(), 2, uintptr(configRet), uintptr(defaultWin32Error), 0) + ret = Errno(r0) + return + } func AdjustTokenGroups(token Token, resetToDefault bool, newstate *Tokengroups, buflen uint32, prevstate *Tokengroups, returnlen *uint32) (err error) { + var _p0 uint32 + if resetToDefault { + _p0 = 1 + } + r1, _, e1 := syscall.Syscall6(procAdjustTokenGroups.Addr(), 6, uintptr(token), uintptr(_p0), uintptr(unsafe.Pointer(newstate)), uintptr(buflen), uintptr(unsafe.Pointer(prevstate)), uintptr(unsafe.Pointer(returnlen))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func AdjustTokenPrivileges(token Token, disableAllPrivileges bool, newstate *Tokenprivileges, buflen uint32, prevstate *Tokenprivileges, returnlen *uint32) (err error) { + var _p0 uint32 + if disableAllPrivileges { + _p0 = 1 + } + r1, _, e1 := syscall.Syscall6(procAdjustTokenPrivileges.Addr(), 6, uintptr(token), uintptr(_p0), uintptr(unsafe.Pointer(newstate)), uintptr(buflen), uintptr(unsafe.Pointer(prevstate)), uintptr(unsafe.Pointer(returnlen))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func AllocateAndInitializeSid(identAuth *SidIdentifierAuthority, subAuth byte, subAuth0 uint32, subAuth1 uint32, subAuth2 uint32, subAuth3 uint32, subAuth4 uint32, subAuth5 uint32, subAuth6 uint32, subAuth7 uint32, sid **SID) (err error) { + r1, _, e1 := syscall.Syscall12(procAllocateAndInitializeSid.Addr(), 11, uintptr(unsafe.Pointer(identAuth)), uintptr(subAuth), uintptr(subAuth0), uintptr(subAuth1), uintptr(subAuth2), uintptr(subAuth3), uintptr(subAuth4), uintptr(subAuth5), uintptr(subAuth6), uintptr(subAuth7), uintptr(unsafe.Pointer(sid)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func buildSecurityDescriptor(owner *TRUSTEE, group *TRUSTEE, countAccessEntries uint32, accessEntries *EXPLICIT_ACCESS, countAuditEntries uint32, auditEntries *EXPLICIT_ACCESS, oldSecurityDescriptor *SECURITY_DESCRIPTOR, sizeNewSecurityDescriptor *uint32, newSecurityDescriptor **SECURITY_DESCRIPTOR) (ret error) { + r0, _, _ := syscall.Syscall9(procBuildSecurityDescriptorW.Addr(), 9, uintptr(unsafe.Pointer(owner)), uintptr(unsafe.Pointer(group)), uintptr(countAccessEntries), uintptr(unsafe.Pointer(accessEntries)), uintptr(countAuditEntries), uintptr(unsafe.Pointer(auditEntries)), uintptr(unsafe.Pointer(oldSecurityDescriptor)), uintptr(unsafe.Pointer(sizeNewSecurityDescriptor)), uintptr(unsafe.Pointer(newSecurityDescriptor))) + if r0 != 0 { + ret = syscall.Errno(r0) + } + return + } func ChangeServiceConfig2(service Handle, infoLevel uint32, info *byte) (err error) { + r1, _, e1 := syscall.Syscall(procChangeServiceConfig2W.Addr(), 3, uintptr(service), uintptr(infoLevel), uintptr(unsafe.Pointer(info))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func ChangeServiceConfig(service Handle, serviceType uint32, startType uint32, errorControl uint32, binaryPathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16, displayName *uint16) (err error) { + r1, _, e1 := syscall.Syscall12(procChangeServiceConfigW.Addr(), 11, uintptr(service), uintptr(serviceType), uintptr(startType), uintptr(errorControl), uintptr(unsafe.Pointer(binaryPathName)), uintptr(unsafe.Pointer(loadOrderGroup)), uintptr(unsafe.Pointer(tagId)), uintptr(unsafe.Pointer(dependencies)), uintptr(unsafe.Pointer(serviceStartName)), uintptr(unsafe.Pointer(password)), uintptr(unsafe.Pointer(displayName)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func checkTokenMembership(tokenHandle Token, sidToCheck *SID, isMember *int32) (err error) { + r1, _, e1 := syscall.Syscall(procCheckTokenMembership.Addr(), 3, uintptr(tokenHandle), uintptr(unsafe.Pointer(sidToCheck)), uintptr(unsafe.Pointer(isMember))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CloseServiceHandle(handle Handle) (err error) { + r1, _, e1 := syscall.Syscall(procCloseServiceHandle.Addr(), 1, uintptr(handle), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func ControlService(service Handle, control uint32, status *SERVICE_STATUS) (err error) { + r1, _, e1 := syscall.Syscall(procControlService.Addr(), 3, uintptr(service), uintptr(control), uintptr(unsafe.Pointer(status))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func convertSecurityDescriptorToStringSecurityDescriptor(sd *SECURITY_DESCRIPTOR, revision uint32, securityInformation SECURITY_INFORMATION, str **uint16, strLen *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procConvertSecurityDescriptorToStringSecurityDescriptorW.Addr(), 5, uintptr(unsafe.Pointer(sd)), uintptr(revision), uintptr(securityInformation), uintptr(unsafe.Pointer(str)), uintptr(unsafe.Pointer(strLen)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func ConvertSidToStringSid(sid *SID, stringSid **uint16) (err error) { + r1, _, e1 := syscall.Syscall(procConvertSidToStringSidW.Addr(), 2, uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(stringSid)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func convertStringSecurityDescriptorToSecurityDescriptor(str string, revision uint32, sd **SECURITY_DESCRIPTOR, size *uint32) (err error) { + var _p0 *uint16 + _p0, err = syscall.UTF16PtrFromString(str) + if err != nil { + return + } + return _convertStringSecurityDescriptorToSecurityDescriptor(_p0, revision, sd, size) + } func _convertStringSecurityDescriptorToSecurityDescriptor(str *uint16, revision uint32, sd **SECURITY_DESCRIPTOR, size *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procConvertStringSecurityDescriptorToSecurityDescriptorW.Addr(), 4, uintptr(unsafe.Pointer(str)), uintptr(revision), uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(size)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func ConvertStringSidToSid(stringSid *uint16, sid **SID) (err error) { + r1, _, e1 := syscall.Syscall(procConvertStringSidToSidW.Addr(), 2, uintptr(unsafe.Pointer(stringSid)), uintptr(unsafe.Pointer(sid)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CopySid(destSidLen uint32, destSid *SID, srcSid *SID) (err error) { + r1, _, e1 := syscall.Syscall(procCopySid.Addr(), 3, uintptr(destSidLen), uintptr(unsafe.Pointer(destSid)), uintptr(unsafe.Pointer(srcSid))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CreateProcessAsUser(token Token, appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error) { + var _p0 uint32 + if inheritHandles { + _p0 = 1 + } + r1, _, e1 := syscall.Syscall12(procCreateProcessAsUserW.Addr(), 11, uintptr(token), uintptr(unsafe.Pointer(appName)), uintptr(unsafe.Pointer(commandLine)), uintptr(unsafe.Pointer(procSecurity)), uintptr(unsafe.Pointer(threadSecurity)), uintptr(_p0), uintptr(creationFlags), uintptr(unsafe.Pointer(env)), uintptr(unsafe.Pointer(currentDir)), uintptr(unsafe.Pointer(startupInfo)), uintptr(unsafe.Pointer(outProcInfo)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CreateService(mgr Handle, serviceName *uint16, displayName *uint16, access uint32, srvType uint32, startType uint32, errCtl uint32, pathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall15(procCreateServiceW.Addr(), 13, uintptr(mgr), uintptr(unsafe.Pointer(serviceName)), uintptr(unsafe.Pointer(displayName)), uintptr(access), uintptr(srvType), uintptr(startType), uintptr(errCtl), uintptr(unsafe.Pointer(pathName)), uintptr(unsafe.Pointer(loadOrderGroup)), uintptr(unsafe.Pointer(tagId)), uintptr(unsafe.Pointer(dependencies)), uintptr(unsafe.Pointer(serviceStartName)), uintptr(unsafe.Pointer(password)), 0, 0) + handle = Handle(r0) + if handle == 0 { + err = errnoErr(e1) + } + return + } func createWellKnownSid(sidType WELL_KNOWN_SID_TYPE, domainSid *SID, sid *SID, sizeSid *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procCreateWellKnownSid.Addr(), 4, uintptr(sidType), uintptr(unsafe.Pointer(domainSid)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(sizeSid)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CryptAcquireContext(provhandle *Handle, container *uint16, provider *uint16, provtype uint32, flags uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procCryptAcquireContextW.Addr(), 5, uintptr(unsafe.Pointer(provhandle)), uintptr(unsafe.Pointer(container)), uintptr(unsafe.Pointer(provider)), uintptr(provtype), uintptr(flags), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CryptGenRandom(provhandle Handle, buflen uint32, buf *byte) (err error) { + r1, _, e1 := syscall.Syscall(procCryptGenRandom.Addr(), 3, uintptr(provhandle), uintptr(buflen), uintptr(unsafe.Pointer(buf))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CryptReleaseContext(provhandle Handle, flags uint32) (err error) { + r1, _, e1 := syscall.Syscall(procCryptReleaseContext.Addr(), 2, uintptr(provhandle), uintptr(flags), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func DeleteService(service Handle) (err error) { + r1, _, e1 := syscall.Syscall(procDeleteService.Addr(), 1, uintptr(service), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func DeregisterEventSource(handle Handle) (err error) { + r1, _, e1 := syscall.Syscall(procDeregisterEventSource.Addr(), 1, uintptr(handle), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func DuplicateTokenEx(existingToken Token, desiredAccess uint32, tokenAttributes *SecurityAttributes, impersonationLevel uint32, tokenType uint32, newToken *Token) (err error) { + r1, _, e1 := syscall.Syscall6(procDuplicateTokenEx.Addr(), 6, uintptr(existingToken), uintptr(desiredAccess), uintptr(unsafe.Pointer(tokenAttributes)), uintptr(impersonationLevel), uintptr(tokenType), uintptr(unsafe.Pointer(newToken))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func EnumDependentServices(service Handle, activityState uint32, services *ENUM_SERVICE_STATUS, buffSize uint32, bytesNeeded *uint32, servicesReturned *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procEnumDependentServicesW.Addr(), 6, uintptr(service), uintptr(activityState), uintptr(unsafe.Pointer(services)), uintptr(buffSize), uintptr(unsafe.Pointer(bytesNeeded)), uintptr(unsafe.Pointer(servicesReturned))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func EnumServicesStatusEx(mgr Handle, infoLevel uint32, serviceType uint32, serviceState uint32, services *byte, bufSize uint32, bytesNeeded *uint32, servicesReturned *uint32, resumeHandle *uint32, groupName *uint16) (err error) { + r1, _, e1 := syscall.Syscall12(procEnumServicesStatusExW.Addr(), 10, uintptr(mgr), uintptr(infoLevel), uintptr(serviceType), uintptr(serviceState), uintptr(unsafe.Pointer(services)), uintptr(bufSize), uintptr(unsafe.Pointer(bytesNeeded)), uintptr(unsafe.Pointer(servicesReturned)), uintptr(unsafe.Pointer(resumeHandle)), uintptr(unsafe.Pointer(groupName)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func EqualSid(sid1 *SID, sid2 *SID) (isEqual bool) { + r0, _, _ := syscall.Syscall(procEqualSid.Addr(), 2, uintptr(unsafe.Pointer(sid1)), uintptr(unsafe.Pointer(sid2)), 0) + isEqual = r0 != 0 + return + } func FreeSid(sid *SID) (err error) { + r1, _, e1 := syscall.Syscall(procFreeSid.Addr(), 1, uintptr(unsafe.Pointer(sid)), 0, 0) + if r1 != 0 { + err = errnoErr(e1) + } + return + } func GetLengthSid(sid *SID) (len uint32) { + r0, _, _ := syscall.Syscall(procGetLengthSid.Addr(), 1, uintptr(unsafe.Pointer(sid)), 0, 0) + len = uint32(r0) + return + } func getNamedSecurityInfo(objectName string, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner **SID, group **SID, dacl **ACL, sacl **ACL, sd **SECURITY_DESCRIPTOR) (ret error) { + var _p0 *uint16 + _p0, ret = syscall.UTF16PtrFromString(objectName) + if ret != nil { + return + } + return _getNamedSecurityInfo(_p0, objectType, securityInformation, owner, group, dacl, sacl, sd) + } func _getNamedSecurityInfo(objectName *uint16, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner **SID, group **SID, dacl **ACL, sacl **ACL, sd **SECURITY_DESCRIPTOR) (ret error) { + r0, _, _ := syscall.Syscall9(procGetNamedSecurityInfoW.Addr(), 8, uintptr(unsafe.Pointer(objectName)), uintptr(objectType), uintptr(securityInformation), uintptr(unsafe.Pointer(owner)), uintptr(unsafe.Pointer(group)), uintptr(unsafe.Pointer(dacl)), uintptr(unsafe.Pointer(sacl)), uintptr(unsafe.Pointer(sd)), 0) + if r0 != 0 { + ret = syscall.Errno(r0) + } + return + } func getSecurityDescriptorControl(sd *SECURITY_DESCRIPTOR, control *SECURITY_DESCRIPTOR_CONTROL, revision *uint32) (err error) { + r1, _, e1 := syscall.Syscall(procGetSecurityDescriptorControl.Addr(), 3, uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(control)), uintptr(unsafe.Pointer(revision))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func getSecurityDescriptorDacl(sd *SECURITY_DESCRIPTOR, daclPresent *bool, dacl **ACL, daclDefaulted *bool) (err error) { + var _p0 uint32 + if *daclPresent { + _p0 = 1 + } + var _p1 uint32 + if *daclDefaulted { + _p1 = 1 + } + r1, _, e1 := syscall.Syscall6(procGetSecurityDescriptorDacl.Addr(), 4, uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(&_p0)), uintptr(unsafe.Pointer(dacl)), uintptr(unsafe.Pointer(&_p1)), 0, 0) + *daclPresent = _p0 != 0 + *daclDefaulted = _p1 != 0 + if r1 == 0 { + err = errnoErr(e1) + } + return + } func getSecurityDescriptorGroup(sd *SECURITY_DESCRIPTOR, group **SID, groupDefaulted *bool) (err error) { + var _p0 uint32 + if *groupDefaulted { + _p0 = 1 + } + r1, _, e1 := syscall.Syscall(procGetSecurityDescriptorGroup.Addr(), 3, uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(group)), uintptr(unsafe.Pointer(&_p0))) + *groupDefaulted = _p0 != 0 + if r1 == 0 { + err = errnoErr(e1) + } + return + } func getSecurityDescriptorLength(sd *SECURITY_DESCRIPTOR) (len uint32) { + r0, _, _ := syscall.Syscall(procGetSecurityDescriptorLength.Addr(), 1, uintptr(unsafe.Pointer(sd)), 0, 0) + len = uint32(r0) + return + } func getSecurityDescriptorOwner(sd *SECURITY_DESCRIPTOR, owner **SID, ownerDefaulted *bool) (err error) { + var _p0 uint32 + if *ownerDefaulted { + _p0 = 1 + } + r1, _, e1 := syscall.Syscall(procGetSecurityDescriptorOwner.Addr(), 3, uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(owner)), uintptr(unsafe.Pointer(&_p0))) + *ownerDefaulted = _p0 != 0 + if r1 == 0 { + err = errnoErr(e1) + } + return + } func getSecurityDescriptorRMControl(sd *SECURITY_DESCRIPTOR, rmControl *uint8) (ret error) { + r0, _, _ := syscall.Syscall(procGetSecurityDescriptorRMControl.Addr(), 2, uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(rmControl)), 0) + if r0 != 0 { + ret = syscall.Errno(r0) + } + return + } func getSecurityDescriptorSacl(sd *SECURITY_DESCRIPTOR, saclPresent *bool, sacl **ACL, saclDefaulted *bool) (err error) { + var _p0 uint32 + if *saclPresent { + _p0 = 1 + } + var _p1 uint32 + if *saclDefaulted { + _p1 = 1 + } + r1, _, e1 := syscall.Syscall6(procGetSecurityDescriptorSacl.Addr(), 4, uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(&_p0)), uintptr(unsafe.Pointer(sacl)), uintptr(unsafe.Pointer(&_p1)), 0, 0) + *saclPresent = _p0 != 0 + *saclDefaulted = _p1 != 0 + if r1 == 0 { + err = errnoErr(e1) + } + return + } func getSecurityInfo(handle Handle, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner **SID, group **SID, dacl **ACL, sacl **ACL, sd **SECURITY_DESCRIPTOR) (ret error) { + r0, _, _ := syscall.Syscall9(procGetSecurityInfo.Addr(), 8, uintptr(handle), uintptr(objectType), uintptr(securityInformation), uintptr(unsafe.Pointer(owner)), uintptr(unsafe.Pointer(group)), uintptr(unsafe.Pointer(dacl)), uintptr(unsafe.Pointer(sacl)), uintptr(unsafe.Pointer(sd)), 0) + if r0 != 0 { + ret = syscall.Errno(r0) + } + return + } func getSidIdentifierAuthority(sid *SID) (authority *SidIdentifierAuthority) { + r0, _, _ := syscall.Syscall(procGetSidIdentifierAuthority.Addr(), 1, uintptr(unsafe.Pointer(sid)), 0, 0) + authority = (*SidIdentifierAuthority)(unsafe.Pointer(r0)) + return + } func getSidSubAuthority(sid *SID, index uint32) (subAuthority *uint32) { + r0, _, _ := syscall.Syscall(procGetSidSubAuthority.Addr(), 2, uintptr(unsafe.Pointer(sid)), uintptr(index), 0) + subAuthority = (*uint32)(unsafe.Pointer(r0)) + return + } func getSidSubAuthorityCount(sid *SID) (count *uint8) { + r0, _, _ := syscall.Syscall(procGetSidSubAuthorityCount.Addr(), 1, uintptr(unsafe.Pointer(sid)), 0, 0) + count = (*uint8)(unsafe.Pointer(r0)) + return + } func GetTokenInformation(token Token, infoClass uint32, info *byte, infoLen uint32, returnedLen *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procGetTokenInformation.Addr(), 5, uintptr(token), uintptr(infoClass), uintptr(unsafe.Pointer(info)), uintptr(infoLen), uintptr(unsafe.Pointer(returnedLen)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func ImpersonateSelf(impersonationlevel uint32) (err error) { + r1, _, e1 := syscall.Syscall(procImpersonateSelf.Addr(), 1, uintptr(impersonationlevel), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func initializeSecurityDescriptor(absoluteSD *SECURITY_DESCRIPTOR, revision uint32) (err error) { + r1, _, e1 := syscall.Syscall(procInitializeSecurityDescriptor.Addr(), 2, uintptr(unsafe.Pointer(absoluteSD)), uintptr(revision), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func InitiateSystemShutdownEx(machineName *uint16, message *uint16, timeout uint32, forceAppsClosed bool, rebootAfterShutdown bool, reason uint32) (err error) { + var _p0 uint32 + if forceAppsClosed { + _p0 = 1 + } + var _p1 uint32 + if rebootAfterShutdown { + _p1 = 1 + } + r1, _, e1 := syscall.Syscall6(procInitiateSystemShutdownExW.Addr(), 6, uintptr(unsafe.Pointer(machineName)), uintptr(unsafe.Pointer(message)), uintptr(timeout), uintptr(_p0), uintptr(_p1), uintptr(reason)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func isTokenRestricted(tokenHandle Token) (ret bool, err error) { + r0, _, e1 := syscall.Syscall(procIsTokenRestricted.Addr(), 1, uintptr(tokenHandle), 0, 0) + ret = r0 != 0 + if !ret { + err = errnoErr(e1) + } + return + } func isValidSecurityDescriptor(sd *SECURITY_DESCRIPTOR) (isValid bool) { + r0, _, _ := syscall.Syscall(procIsValidSecurityDescriptor.Addr(), 1, uintptr(unsafe.Pointer(sd)), 0, 0) + isValid = r0 != 0 + return + } func isValidSid(sid *SID) (isValid bool) { + r0, _, _ := syscall.Syscall(procIsValidSid.Addr(), 1, uintptr(unsafe.Pointer(sid)), 0, 0) + isValid = r0 != 0 + return + } func isWellKnownSid(sid *SID, sidType WELL_KNOWN_SID_TYPE) (isWellKnown bool) { + r0, _, _ := syscall.Syscall(procIsWellKnownSid.Addr(), 2, uintptr(unsafe.Pointer(sid)), uintptr(sidType), 0) + isWellKnown = r0 != 0 + return + } func LookupAccountName(systemName *uint16, accountName *uint16, sid *SID, sidLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) { + r1, _, e1 := syscall.Syscall9(procLookupAccountNameW.Addr(), 7, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(accountName)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(sidLen)), uintptr(unsafe.Pointer(refdDomainName)), uintptr(unsafe.Pointer(refdDomainNameLen)), uintptr(unsafe.Pointer(use)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func LookupAccountSid(systemName *uint16, sid *SID, name *uint16, nameLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) { + r1, _, e1 := syscall.Syscall9(procLookupAccountSidW.Addr(), 7, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(nameLen)), uintptr(unsafe.Pointer(refdDomainName)), uintptr(unsafe.Pointer(refdDomainNameLen)), uintptr(unsafe.Pointer(use)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func LookupPrivilegeValue(systemname *uint16, name *uint16, luid *LUID) (err error) { + r1, _, e1 := syscall.Syscall(procLookupPrivilegeValueW.Addr(), 3, uintptr(unsafe.Pointer(systemname)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(luid))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func makeAbsoluteSD(selfRelativeSD *SECURITY_DESCRIPTOR, absoluteSD *SECURITY_DESCRIPTOR, absoluteSDSize *uint32, dacl *ACL, daclSize *uint32, sacl *ACL, saclSize *uint32, owner *SID, ownerSize *uint32, group *SID, groupSize *uint32) (err error) { + r1, _, e1 := syscall.Syscall12(procMakeAbsoluteSD.Addr(), 11, uintptr(unsafe.Pointer(selfRelativeSD)), uintptr(unsafe.Pointer(absoluteSD)), uintptr(unsafe.Pointer(absoluteSDSize)), uintptr(unsafe.Pointer(dacl)), uintptr(unsafe.Pointer(daclSize)), uintptr(unsafe.Pointer(sacl)), uintptr(unsafe.Pointer(saclSize)), uintptr(unsafe.Pointer(owner)), uintptr(unsafe.Pointer(ownerSize)), uintptr(unsafe.Pointer(group)), uintptr(unsafe.Pointer(groupSize)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func makeSelfRelativeSD(absoluteSD *SECURITY_DESCRIPTOR, selfRelativeSD *SECURITY_DESCRIPTOR, selfRelativeSDSize *uint32) (err error) { + r1, _, e1 := syscall.Syscall(procMakeSelfRelativeSD.Addr(), 3, uintptr(unsafe.Pointer(absoluteSD)), uintptr(unsafe.Pointer(selfRelativeSD)), uintptr(unsafe.Pointer(selfRelativeSDSize))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func NotifyServiceStatusChange(service Handle, notifyMask uint32, notifier *SERVICE_NOTIFY) (ret error) { + r0, _, _ := syscall.Syscall(procNotifyServiceStatusChangeW.Addr(), 3, uintptr(service), uintptr(notifyMask), uintptr(unsafe.Pointer(notifier))) + if r0 != 0 { + ret = syscall.Errno(r0) + } + return + } func OpenProcessToken(process Handle, access uint32, token *Token) (err error) { + r1, _, e1 := syscall.Syscall(procOpenProcessToken.Addr(), 3, uintptr(process), uintptr(access), uintptr(unsafe.Pointer(token))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func OpenSCManager(machineName *uint16, databaseName *uint16, access uint32) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall(procOpenSCManagerW.Addr(), 3, uintptr(unsafe.Pointer(machineName)), uintptr(unsafe.Pointer(databaseName)), uintptr(access)) + handle = Handle(r0) + if handle == 0 { + err = errnoErr(e1) + } + return + } func OpenService(mgr Handle, serviceName *uint16, access uint32) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall(procOpenServiceW.Addr(), 3, uintptr(mgr), uintptr(unsafe.Pointer(serviceName)), uintptr(access)) + handle = Handle(r0) + if handle == 0 { + err = errnoErr(e1) + } + return + } func OpenThreadToken(thread Handle, access uint32, openAsSelf bool, token *Token) (err error) { + var _p0 uint32 + if openAsSelf { + _p0 = 1 + } + r1, _, e1 := syscall.Syscall6(procOpenThreadToken.Addr(), 4, uintptr(thread), uintptr(access), uintptr(_p0), uintptr(unsafe.Pointer(token)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func QueryServiceConfig2(service Handle, infoLevel uint32, buff *byte, buffSize uint32, bytesNeeded *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procQueryServiceConfig2W.Addr(), 5, uintptr(service), uintptr(infoLevel), uintptr(unsafe.Pointer(buff)), uintptr(buffSize), uintptr(unsafe.Pointer(bytesNeeded)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func QueryServiceConfig(service Handle, serviceConfig *QUERY_SERVICE_CONFIG, bufSize uint32, bytesNeeded *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procQueryServiceConfigW.Addr(), 4, uintptr(service), uintptr(unsafe.Pointer(serviceConfig)), uintptr(bufSize), uintptr(unsafe.Pointer(bytesNeeded)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func QueryServiceDynamicInformation(service Handle, infoLevel uint32, dynamicInfo unsafe.Pointer) (err error) { + err = procQueryServiceDynamicInformation.Find() + if err != nil { + return + } + r1, _, e1 := syscall.Syscall(procQueryServiceDynamicInformation.Addr(), 3, uintptr(service), uintptr(infoLevel), uintptr(dynamicInfo)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func QueryServiceLockStatus(mgr Handle, lockStatus *QUERY_SERVICE_LOCK_STATUS, bufSize uint32, bytesNeeded *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procQueryServiceLockStatusW.Addr(), 4, uintptr(mgr), uintptr(unsafe.Pointer(lockStatus)), uintptr(bufSize), uintptr(unsafe.Pointer(bytesNeeded)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func QueryServiceStatus(service Handle, status *SERVICE_STATUS) (err error) { + r1, _, e1 := syscall.Syscall(procQueryServiceStatus.Addr(), 2, uintptr(service), uintptr(unsafe.Pointer(status)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func QueryServiceStatusEx(service Handle, infoLevel uint32, buff *byte, buffSize uint32, bytesNeeded *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procQueryServiceStatusEx.Addr(), 5, uintptr(service), uintptr(infoLevel), uintptr(unsafe.Pointer(buff)), uintptr(buffSize), uintptr(unsafe.Pointer(bytesNeeded)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func RegCloseKey(key Handle) (regerrno error) { + r0, _, _ := syscall.Syscall(procRegCloseKey.Addr(), 1, uintptr(key), 0, 0) + if r0 != 0 { + regerrno = syscall.Errno(r0) + } + return + } func RegEnumKeyEx(key Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, class *uint16, classLen *uint32, lastWriteTime *Filetime) (regerrno error) { + r0, _, _ := syscall.Syscall9(procRegEnumKeyExW.Addr(), 8, uintptr(key), uintptr(index), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(nameLen)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(class)), uintptr(unsafe.Pointer(classLen)), uintptr(unsafe.Pointer(lastWriteTime)), 0) + if r0 != 0 { + regerrno = syscall.Errno(r0) + } + return + } func RegNotifyChangeKeyValue(key Handle, watchSubtree bool, notifyFilter uint32, event Handle, asynchronous bool) (regerrno error) { + var _p0 uint32 + if watchSubtree { + _p0 = 1 + } + var _p1 uint32 + if asynchronous { + _p1 = 1 + } + r0, _, _ := syscall.Syscall6(procRegNotifyChangeKeyValue.Addr(), 5, uintptr(key), uintptr(_p0), uintptr(notifyFilter), uintptr(event), uintptr(_p1), 0) + if r0 != 0 { + regerrno = syscall.Errno(r0) + } + return + } func RegOpenKeyEx(key Handle, subkey *uint16, options uint32, desiredAccess uint32, result *Handle) (regerrno error) { + r0, _, _ := syscall.Syscall6(procRegOpenKeyExW.Addr(), 5, uintptr(key), uintptr(unsafe.Pointer(subkey)), uintptr(options), uintptr(desiredAccess), uintptr(unsafe.Pointer(result)), 0) + if r0 != 0 { + regerrno = syscall.Errno(r0) + } + return + } func RegQueryInfoKey(key Handle, class *uint16, classLen *uint32, reserved *uint32, subkeysLen *uint32, maxSubkeyLen *uint32, maxClassLen *uint32, valuesLen *uint32, maxValueNameLen *uint32, maxValueLen *uint32, saLen *uint32, lastWriteTime *Filetime) (regerrno error) { + r0, _, _ := syscall.Syscall12(procRegQueryInfoKeyW.Addr(), 12, uintptr(key), uintptr(unsafe.Pointer(class)), uintptr(unsafe.Pointer(classLen)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(subkeysLen)), uintptr(unsafe.Pointer(maxSubkeyLen)), uintptr(unsafe.Pointer(maxClassLen)), uintptr(unsafe.Pointer(valuesLen)), uintptr(unsafe.Pointer(maxValueNameLen)), uintptr(unsafe.Pointer(maxValueLen)), uintptr(unsafe.Pointer(saLen)), uintptr(unsafe.Pointer(lastWriteTime))) + if r0 != 0 { + regerrno = syscall.Errno(r0) + } + return + } func RegQueryValueEx(key Handle, name *uint16, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) { + r0, _, _ := syscall.Syscall6(procRegQueryValueExW.Addr(), 6, uintptr(key), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(valtype)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(buflen))) + if r0 != 0 { + regerrno = syscall.Errno(r0) + } + return + } func RegisterEventSource(uncServerName *uint16, sourceName *uint16) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall(procRegisterEventSourceW.Addr(), 2, uintptr(unsafe.Pointer(uncServerName)), uintptr(unsafe.Pointer(sourceName)), 0) + handle = Handle(r0) + if handle == 0 { + err = errnoErr(e1) + } + return + } func RegisterServiceCtrlHandlerEx(serviceName *uint16, handlerProc uintptr, context uintptr) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall(procRegisterServiceCtrlHandlerExW.Addr(), 3, uintptr(unsafe.Pointer(serviceName)), uintptr(handlerProc), uintptr(context)) + handle = Handle(r0) + if handle == 0 { + err = errnoErr(e1) + } + return + } func ReportEvent(log Handle, etype uint16, category uint16, eventId uint32, usrSId uintptr, numStrings uint16, dataSize uint32, strings **uint16, rawData *byte) (err error) { + r1, _, e1 := syscall.Syscall9(procReportEventW.Addr(), 9, uintptr(log), uintptr(etype), uintptr(category), uintptr(eventId), uintptr(usrSId), uintptr(numStrings), uintptr(dataSize), uintptr(unsafe.Pointer(strings)), uintptr(unsafe.Pointer(rawData))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func RevertToSelf() (err error) { + r1, _, e1 := syscall.Syscall(procRevertToSelf.Addr(), 0, 0, 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setEntriesInAcl(countExplicitEntries uint32, explicitEntries *EXPLICIT_ACCESS, oldACL *ACL, newACL **ACL) (ret error) { + r0, _, _ := syscall.Syscall6(procSetEntriesInAclW.Addr(), 4, uintptr(countExplicitEntries), uintptr(unsafe.Pointer(explicitEntries)), uintptr(unsafe.Pointer(oldACL)), uintptr(unsafe.Pointer(newACL)), 0, 0) + if r0 != 0 { + ret = syscall.Errno(r0) + } + return + } func SetKernelObjectSecurity(handle Handle, securityInformation SECURITY_INFORMATION, securityDescriptor *SECURITY_DESCRIPTOR) (err error) { + r1, _, e1 := syscall.Syscall(procSetKernelObjectSecurity.Addr(), 3, uintptr(handle), uintptr(securityInformation), uintptr(unsafe.Pointer(securityDescriptor))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetNamedSecurityInfo(objectName string, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner *SID, group *SID, dacl *ACL, sacl *ACL) (ret error) { + var _p0 *uint16 + _p0, ret = syscall.UTF16PtrFromString(objectName) + if ret != nil { + return + } + return _SetNamedSecurityInfo(_p0, objectType, securityInformation, owner, group, dacl, sacl) + } func _SetNamedSecurityInfo(objectName *uint16, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner *SID, group *SID, dacl *ACL, sacl *ACL) (ret error) { + r0, _, _ := syscall.Syscall9(procSetNamedSecurityInfoW.Addr(), 7, uintptr(unsafe.Pointer(objectName)), uintptr(objectType), uintptr(securityInformation), uintptr(unsafe.Pointer(owner)), uintptr(unsafe.Pointer(group)), uintptr(unsafe.Pointer(dacl)), uintptr(unsafe.Pointer(sacl)), 0, 0) + if r0 != 0 { + ret = syscall.Errno(r0) + } + return + } func setSecurityDescriptorControl(sd *SECURITY_DESCRIPTOR, controlBitsOfInterest SECURITY_DESCRIPTOR_CONTROL, controlBitsToSet SECURITY_DESCRIPTOR_CONTROL) (err error) { + r1, _, e1 := syscall.Syscall(procSetSecurityDescriptorControl.Addr(), 3, uintptr(unsafe.Pointer(sd)), uintptr(controlBitsOfInterest), uintptr(controlBitsToSet)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setSecurityDescriptorDacl(sd *SECURITY_DESCRIPTOR, daclPresent bool, dacl *ACL, daclDefaulted bool) (err error) { + var _p0 uint32 + if daclPresent { + _p0 = 1 + } + var _p1 uint32 + if daclDefaulted { + _p1 = 1 + } + r1, _, e1 := syscall.Syscall6(procSetSecurityDescriptorDacl.Addr(), 4, uintptr(unsafe.Pointer(sd)), uintptr(_p0), uintptr(unsafe.Pointer(dacl)), uintptr(_p1), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setSecurityDescriptorGroup(sd *SECURITY_DESCRIPTOR, group *SID, groupDefaulted bool) (err error) { + var _p0 uint32 + if groupDefaulted { + _p0 = 1 + } + r1, _, e1 := syscall.Syscall(procSetSecurityDescriptorGroup.Addr(), 3, uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(group)), uintptr(_p0)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setSecurityDescriptorOwner(sd *SECURITY_DESCRIPTOR, owner *SID, ownerDefaulted bool) (err error) { + var _p0 uint32 + if ownerDefaulted { + _p0 = 1 + } + r1, _, e1 := syscall.Syscall(procSetSecurityDescriptorOwner.Addr(), 3, uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(owner)), uintptr(_p0)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setSecurityDescriptorRMControl(sd *SECURITY_DESCRIPTOR, rmControl *uint8) { + syscall.Syscall(procSetSecurityDescriptorRMControl.Addr(), 2, uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(rmControl)), 0) + return + } func setSecurityDescriptorSacl(sd *SECURITY_DESCRIPTOR, saclPresent bool, sacl *ACL, saclDefaulted bool) (err error) { + var _p0 uint32 + if saclPresent { + _p0 = 1 + } + var _p1 uint32 + if saclDefaulted { + _p1 = 1 + } + r1, _, e1 := syscall.Syscall6(procSetSecurityDescriptorSacl.Addr(), 4, uintptr(unsafe.Pointer(sd)), uintptr(_p0), uintptr(unsafe.Pointer(sacl)), uintptr(_p1), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetSecurityInfo(handle Handle, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner *SID, group *SID, dacl *ACL, sacl *ACL) (ret error) { + r0, _, _ := syscall.Syscall9(procSetSecurityInfo.Addr(), 7, uintptr(handle), uintptr(objectType), uintptr(securityInformation), uintptr(unsafe.Pointer(owner)), uintptr(unsafe.Pointer(group)), uintptr(unsafe.Pointer(dacl)), uintptr(unsafe.Pointer(sacl)), 0, 0) + if r0 != 0 { + ret = syscall.Errno(r0) + } + return + } func SetServiceStatus(service Handle, serviceStatus *SERVICE_STATUS) (err error) { + r1, _, e1 := syscall.Syscall(procSetServiceStatus.Addr(), 2, uintptr(service), uintptr(unsafe.Pointer(serviceStatus)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetThreadToken(thread *Handle, token Token) (err error) { + r1, _, e1 := syscall.Syscall(procSetThreadToken.Addr(), 2, uintptr(unsafe.Pointer(thread)), uintptr(token), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetTokenInformation(token Token, infoClass uint32, info *byte, infoLen uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procSetTokenInformation.Addr(), 4, uintptr(token), uintptr(infoClass), uintptr(unsafe.Pointer(info)), uintptr(infoLen), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func StartServiceCtrlDispatcher(serviceTable *SERVICE_TABLE_ENTRY) (err error) { + r1, _, e1 := syscall.Syscall(procStartServiceCtrlDispatcherW.Addr(), 1, uintptr(unsafe.Pointer(serviceTable)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func StartService(service Handle, numArgs uint32, argVectors **uint16) (err error) { + r1, _, e1 := syscall.Syscall(procStartServiceW.Addr(), 3, uintptr(service), uintptr(numArgs), uintptr(unsafe.Pointer(argVectors))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CertAddCertificateContextToStore(store Handle, certContext *CertContext, addDisposition uint32, storeContext **CertContext) (err error) { + r1, _, e1 := syscall.Syscall6(procCertAddCertificateContextToStore.Addr(), 4, uintptr(store), uintptr(unsafe.Pointer(certContext)), uintptr(addDisposition), uintptr(unsafe.Pointer(storeContext)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CertCloseStore(store Handle, flags uint32) (err error) { + r1, _, e1 := syscall.Syscall(procCertCloseStore.Addr(), 2, uintptr(store), uintptr(flags), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CertCreateCertificateContext(certEncodingType uint32, certEncoded *byte, encodedLen uint32) (context *CertContext, err error) { + r0, _, e1 := syscall.Syscall(procCertCreateCertificateContext.Addr(), 3, uintptr(certEncodingType), uintptr(unsafe.Pointer(certEncoded)), uintptr(encodedLen)) + context = (*CertContext)(unsafe.Pointer(r0)) + if context == nil { + err = errnoErr(e1) + } + return + } func CertDeleteCertificateFromStore(certContext *CertContext) (err error) { + r1, _, e1 := syscall.Syscall(procCertDeleteCertificateFromStore.Addr(), 1, uintptr(unsafe.Pointer(certContext)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CertDuplicateCertificateContext(certContext *CertContext) (dupContext *CertContext) { + r0, _, _ := syscall.Syscall(procCertDuplicateCertificateContext.Addr(), 1, uintptr(unsafe.Pointer(certContext)), 0, 0) + dupContext = (*CertContext)(unsafe.Pointer(r0)) + return + } func CertEnumCertificatesInStore(store Handle, prevContext *CertContext) (context *CertContext, err error) { + r0, _, e1 := syscall.Syscall(procCertEnumCertificatesInStore.Addr(), 2, uintptr(store), uintptr(unsafe.Pointer(prevContext)), 0) + context = (*CertContext)(unsafe.Pointer(r0)) + if context == nil { + err = errnoErr(e1) + } + return + } func CertFindCertificateInStore(store Handle, certEncodingType uint32, findFlags uint32, findType uint32, findPara unsafe.Pointer, prevCertContext *CertContext) (cert *CertContext, err error) { + r0, _, e1 := syscall.Syscall6(procCertFindCertificateInStore.Addr(), 6, uintptr(store), uintptr(certEncodingType), uintptr(findFlags), uintptr(findType), uintptr(findPara), uintptr(unsafe.Pointer(prevCertContext))) + cert = (*CertContext)(unsafe.Pointer(r0)) + if cert == nil { + err = errnoErr(e1) + } + return + } func CertFindChainInStore(store Handle, certEncodingType uint32, findFlags uint32, findType uint32, findPara unsafe.Pointer, prevChainContext *CertChainContext) (certchain *CertChainContext, err error) { + r0, _, e1 := syscall.Syscall6(procCertFindChainInStore.Addr(), 6, uintptr(store), uintptr(certEncodingType), uintptr(findFlags), uintptr(findType), uintptr(findPara), uintptr(unsafe.Pointer(prevChainContext))) + certchain = (*CertChainContext)(unsafe.Pointer(r0)) + if certchain == nil { + err = errnoErr(e1) + } + return + } func CertFindExtension(objId *byte, countExtensions uint32, extensions *CertExtension) (ret *CertExtension) { + r0, _, _ := syscall.Syscall(procCertFindExtension.Addr(), 3, uintptr(unsafe.Pointer(objId)), uintptr(countExtensions), uintptr(unsafe.Pointer(extensions))) + ret = (*CertExtension)(unsafe.Pointer(r0)) + return + } func CertFreeCertificateChain(ctx *CertChainContext) { + syscall.Syscall(procCertFreeCertificateChain.Addr(), 1, uintptr(unsafe.Pointer(ctx)), 0, 0) + return + } func CertFreeCertificateContext(ctx *CertContext) (err error) { + r1, _, e1 := syscall.Syscall(procCertFreeCertificateContext.Addr(), 1, uintptr(unsafe.Pointer(ctx)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CertGetCertificateChain(engine Handle, leaf *CertContext, time *Filetime, additionalStore Handle, para *CertChainPara, flags uint32, reserved uintptr, chainCtx **CertChainContext) (err error) { + r1, _, e1 := syscall.Syscall9(procCertGetCertificateChain.Addr(), 8, uintptr(engine), uintptr(unsafe.Pointer(leaf)), uintptr(unsafe.Pointer(time)), uintptr(additionalStore), uintptr(unsafe.Pointer(para)), uintptr(flags), uintptr(reserved), uintptr(unsafe.Pointer(chainCtx)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CertGetNameString(certContext *CertContext, nameType uint32, flags uint32, typePara unsafe.Pointer, name *uint16, size uint32) (chars uint32) { + r0, _, _ := syscall.Syscall6(procCertGetNameStringW.Addr(), 6, uintptr(unsafe.Pointer(certContext)), uintptr(nameType), uintptr(flags), uintptr(typePara), uintptr(unsafe.Pointer(name)), uintptr(size)) + chars = uint32(r0) + return + } func CertOpenStore(storeProvider uintptr, msgAndCertEncodingType uint32, cryptProv uintptr, flags uint32, para uintptr) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall6(procCertOpenStore.Addr(), 5, uintptr(storeProvider), uintptr(msgAndCertEncodingType), uintptr(cryptProv), uintptr(flags), uintptr(para), 0) + handle = Handle(r0) + if handle == 0 { + err = errnoErr(e1) + } + return + } func CertOpenSystemStore(hprov Handle, name *uint16) (store Handle, err error) { + r0, _, e1 := syscall.Syscall(procCertOpenSystemStoreW.Addr(), 2, uintptr(hprov), uintptr(unsafe.Pointer(name)), 0) + store = Handle(r0) + if store == 0 { + err = errnoErr(e1) + } + return + } func CertVerifyCertificateChainPolicy(policyOID uintptr, chain *CertChainContext, para *CertChainPolicyPara, status *CertChainPolicyStatus) (err error) { + r1, _, e1 := syscall.Syscall6(procCertVerifyCertificateChainPolicy.Addr(), 4, uintptr(policyOID), uintptr(unsafe.Pointer(chain)), uintptr(unsafe.Pointer(para)), uintptr(unsafe.Pointer(status)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CryptAcquireCertificatePrivateKey(cert *CertContext, flags uint32, parameters unsafe.Pointer, cryptProvOrNCryptKey *Handle, keySpec *uint32, callerFreeProvOrNCryptKey *bool) (err error) { + var _p0 uint32 + if *callerFreeProvOrNCryptKey { + _p0 = 1 + } + r1, _, e1 := syscall.Syscall6(procCryptAcquireCertificatePrivateKey.Addr(), 6, uintptr(unsafe.Pointer(cert)), uintptr(flags), uintptr(parameters), uintptr(unsafe.Pointer(cryptProvOrNCryptKey)), uintptr(unsafe.Pointer(keySpec)), uintptr(unsafe.Pointer(&_p0))) + *callerFreeProvOrNCryptKey = _p0 != 0 + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CryptDecodeObject(encodingType uint32, structType *byte, encodedBytes *byte, lenEncodedBytes uint32, flags uint32, decoded unsafe.Pointer, decodedLen *uint32) (err error) { + r1, _, e1 := syscall.Syscall9(procCryptDecodeObject.Addr(), 7, uintptr(encodingType), uintptr(unsafe.Pointer(structType)), uintptr(unsafe.Pointer(encodedBytes)), uintptr(lenEncodedBytes), uintptr(flags), uintptr(decoded), uintptr(unsafe.Pointer(decodedLen)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CryptProtectData(dataIn *DataBlob, name *uint16, optionalEntropy *DataBlob, reserved uintptr, promptStruct *CryptProtectPromptStruct, flags uint32, dataOut *DataBlob) (err error) { + r1, _, e1 := syscall.Syscall9(procCryptProtectData.Addr(), 7, uintptr(unsafe.Pointer(dataIn)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(optionalEntropy)), uintptr(reserved), uintptr(unsafe.Pointer(promptStruct)), uintptr(flags), uintptr(unsafe.Pointer(dataOut)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CryptQueryObject(objectType uint32, object unsafe.Pointer, expectedContentTypeFlags uint32, expectedFormatTypeFlags uint32, flags uint32, msgAndCertEncodingType *uint32, contentType *uint32, formatType *uint32, certStore *Handle, msg *Handle, context *unsafe.Pointer) (err error) { + r1, _, e1 := syscall.Syscall12(procCryptQueryObject.Addr(), 11, uintptr(objectType), uintptr(object), uintptr(expectedContentTypeFlags), uintptr(expectedFormatTypeFlags), uintptr(flags), uintptr(unsafe.Pointer(msgAndCertEncodingType)), uintptr(unsafe.Pointer(contentType)), uintptr(unsafe.Pointer(formatType)), uintptr(unsafe.Pointer(certStore)), uintptr(unsafe.Pointer(msg)), uintptr(unsafe.Pointer(context)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CryptUnprotectData(dataIn *DataBlob, name **uint16, optionalEntropy *DataBlob, reserved uintptr, promptStruct *CryptProtectPromptStruct, flags uint32, dataOut *DataBlob) (err error) { + r1, _, e1 := syscall.Syscall9(procCryptUnprotectData.Addr(), 7, uintptr(unsafe.Pointer(dataIn)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(optionalEntropy)), uintptr(reserved), uintptr(unsafe.Pointer(promptStruct)), uintptr(flags), uintptr(unsafe.Pointer(dataOut)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func PFXImportCertStore(pfx *CryptDataBlob, password *uint16, flags uint32) (store Handle, err error) { + r0, _, e1 := syscall.Syscall(procPFXImportCertStore.Addr(), 3, uintptr(unsafe.Pointer(pfx)), uintptr(unsafe.Pointer(password)), uintptr(flags)) + store = Handle(r0) + if store == 0 { + err = errnoErr(e1) + } + return + } func DnsNameCompare(name1 *uint16, name2 *uint16) (same bool) { + r0, _, _ := syscall.Syscall(procDnsNameCompare_W.Addr(), 2, uintptr(unsafe.Pointer(name1)), uintptr(unsafe.Pointer(name2)), 0) + same = r0 != 0 + return + } func DnsQuery(name string, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error) { + var _p0 *uint16 + _p0, status = syscall.UTF16PtrFromString(name) + if status != nil { + return + } + return _DnsQuery(_p0, qtype, options, extra, qrs, pr) + } func _DnsQuery(name *uint16, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error) { + r0, _, _ := syscall.Syscall6(procDnsQuery_W.Addr(), 6, uintptr(unsafe.Pointer(name)), uintptr(qtype), uintptr(options), uintptr(unsafe.Pointer(extra)), uintptr(unsafe.Pointer(qrs)), uintptr(unsafe.Pointer(pr))) + if r0 != 0 { + status = syscall.Errno(r0) + } + return + } func DnsRecordListFree(rl *DNSRecord, freetype uint32) { + syscall.Syscall(procDnsRecordListFree.Addr(), 2, uintptr(unsafe.Pointer(rl)), uintptr(freetype), 0) + return + } func DwmGetWindowAttribute(hwnd HWND, attribute uint32, value unsafe.Pointer, size uint32) (ret error) { + r0, _, _ := syscall.Syscall6(procDwmGetWindowAttribute.Addr(), 4, uintptr(hwnd), uintptr(attribute), uintptr(value), uintptr(size), 0, 0) + if r0 != 0 { + ret = syscall.Errno(r0) + } + return + } func DwmSetWindowAttribute(hwnd HWND, attribute uint32, value unsafe.Pointer, size uint32) (ret error) { + r0, _, _ := syscall.Syscall6(procDwmSetWindowAttribute.Addr(), 4, uintptr(hwnd), uintptr(attribute), uintptr(value), uintptr(size), 0, 0) + if r0 != 0 { + ret = syscall.Errno(r0) + } + return + } func GetAdaptersAddresses(family uint32, flags uint32, reserved uintptr, adapterAddresses *IpAdapterAddresses, sizePointer *uint32) (errcode error) { + r0, _, _ := syscall.Syscall6(procGetAdaptersAddresses.Addr(), 5, uintptr(family), uintptr(flags), uintptr(reserved), uintptr(unsafe.Pointer(adapterAddresses)), uintptr(unsafe.Pointer(sizePointer)), 0) + if r0 != 0 { + errcode = syscall.Errno(r0) + } + return + } func GetAdaptersInfo(ai *IpAdapterInfo, ol *uint32) (errcode error) { + r0, _, _ := syscall.Syscall(procGetAdaptersInfo.Addr(), 2, uintptr(unsafe.Pointer(ai)), uintptr(unsafe.Pointer(ol)), 0) + if r0 != 0 { + errcode = syscall.Errno(r0) + } + return + } func getBestInterfaceEx(sockaddr unsafe.Pointer, pdwBestIfIndex *uint32) (errcode error) { + r0, _, _ := syscall.Syscall(procGetBestInterfaceEx.Addr(), 2, uintptr(sockaddr), uintptr(unsafe.Pointer(pdwBestIfIndex)), 0) + if r0 != 0 { + errcode = syscall.Errno(r0) + } + return + } func GetIfEntry(pIfRow *MibIfRow) (errcode error) { + r0, _, _ := syscall.Syscall(procGetIfEntry.Addr(), 1, uintptr(unsafe.Pointer(pIfRow)), 0, 0) + if r0 != 0 { + errcode = syscall.Errno(r0) + } + return + } func AddDllDirectory(path *uint16) (cookie uintptr, err error) { + r0, _, e1 := syscall.Syscall(procAddDllDirectory.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0) + cookie = uintptr(r0) + if cookie == 0 { + err = errnoErr(e1) + } + return + } func AssignProcessToJobObject(job Handle, process Handle) (err error) { + r1, _, e1 := syscall.Syscall(procAssignProcessToJobObject.Addr(), 2, uintptr(job), uintptr(process), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CancelIo(s Handle) (err error) { + r1, _, e1 := syscall.Syscall(procCancelIo.Addr(), 1, uintptr(s), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CancelIoEx(s Handle, o *Overlapped) (err error) { + r1, _, e1 := syscall.Syscall(procCancelIoEx.Addr(), 2, uintptr(s), uintptr(unsafe.Pointer(o)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func ClearCommBreak(handle Handle) (err error) { + r1, _, e1 := syscall.Syscall(procClearCommBreak.Addr(), 1, uintptr(handle), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func ClearCommError(handle Handle, lpErrors *uint32, lpStat *ComStat) (err error) { + r1, _, e1 := syscall.Syscall(procClearCommError.Addr(), 3, uintptr(handle), uintptr(unsafe.Pointer(lpErrors)), uintptr(unsafe.Pointer(lpStat))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CloseHandle(handle Handle) (err error) { + r1, _, e1 := syscall.Syscall(procCloseHandle.Addr(), 1, uintptr(handle), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func ClosePseudoConsole(console Handle) { + syscall.Syscall(procClosePseudoConsole.Addr(), 1, uintptr(console), 0, 0) + return + } func ConnectNamedPipe(pipe Handle, overlapped *Overlapped) (err error) { + r1, _, e1 := syscall.Syscall(procConnectNamedPipe.Addr(), 2, uintptr(pipe), uintptr(unsafe.Pointer(overlapped)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CreateDirectory(path *uint16, sa *SecurityAttributes) (err error) { + r1, _, e1 := syscall.Syscall(procCreateDirectoryW.Addr(), 2, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(sa)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CreateEventEx(eventAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall6(procCreateEventExW.Addr(), 4, uintptr(unsafe.Pointer(eventAttrs)), uintptr(unsafe.Pointer(name)), uintptr(flags), uintptr(desiredAccess), 0, 0) + handle = Handle(r0) + if handle == 0 || e1 == ERROR_ALREADY_EXISTS { + err = errnoErr(e1) + } + return + } func CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall6(procCreateEventW.Addr(), 4, uintptr(unsafe.Pointer(eventAttrs)), uintptr(manualReset), uintptr(initialState), uintptr(unsafe.Pointer(name)), 0, 0) + handle = Handle(r0) + if handle == 0 || e1 == ERROR_ALREADY_EXISTS { + err = errnoErr(e1) + } + return + } func CreateFileMapping(fhandle Handle, sa *SecurityAttributes, prot uint32, maxSizeHigh uint32, maxSizeLow uint32, name *uint16) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall6(procCreateFileMappingW.Addr(), 6, uintptr(fhandle), uintptr(unsafe.Pointer(sa)), uintptr(prot), uintptr(maxSizeHigh), uintptr(maxSizeLow), uintptr(unsafe.Pointer(name))) + handle = Handle(r0) + if handle == 0 || e1 == ERROR_ALREADY_EXISTS { + err = errnoErr(e1) + } + return + } func CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile Handle) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall9(procCreateFileW.Addr(), 7, uintptr(unsafe.Pointer(name)), uintptr(access), uintptr(mode), uintptr(unsafe.Pointer(sa)), uintptr(createmode), uintptr(attrs), uintptr(templatefile), 0, 0) + handle = Handle(r0) + if handle == InvalidHandle { + err = errnoErr(e1) + } + return + } func CreateHardLink(filename *uint16, existingfilename *uint16, reserved uintptr) (err error) { + r1, _, e1 := syscall.Syscall(procCreateHardLinkW.Addr(), 3, uintptr(unsafe.Pointer(filename)), uintptr(unsafe.Pointer(existingfilename)), uintptr(reserved)) + if r1&0xff == 0 { + err = errnoErr(e1) + } + return + } func CreateIoCompletionPort(filehandle Handle, cphandle Handle, key uintptr, threadcnt uint32) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall6(procCreateIoCompletionPort.Addr(), 4, uintptr(filehandle), uintptr(cphandle), uintptr(key), uintptr(threadcnt), 0, 0) + handle = Handle(r0) + if handle == 0 { + err = errnoErr(e1) + } + return + } func CreateJobObject(jobAttr *SecurityAttributes, name *uint16) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall(procCreateJobObjectW.Addr(), 2, uintptr(unsafe.Pointer(jobAttr)), uintptr(unsafe.Pointer(name)), 0) + handle = Handle(r0) + if handle == 0 { + err = errnoErr(e1) + } + return + } func CreateMutexEx(mutexAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall6(procCreateMutexExW.Addr(), 4, uintptr(unsafe.Pointer(mutexAttrs)), uintptr(unsafe.Pointer(name)), uintptr(flags), uintptr(desiredAccess), 0, 0) + handle = Handle(r0) + if handle == 0 || e1 == ERROR_ALREADY_EXISTS { + err = errnoErr(e1) + } + return + } func CreateMutex(mutexAttrs *SecurityAttributes, initialOwner bool, name *uint16) (handle Handle, err error) { + var _p0 uint32 + if initialOwner { + _p0 = 1 + } + r0, _, e1 := syscall.Syscall(procCreateMutexW.Addr(), 3, uintptr(unsafe.Pointer(mutexAttrs)), uintptr(_p0), uintptr(unsafe.Pointer(name))) + handle = Handle(r0) + if handle == 0 || e1 == ERROR_ALREADY_EXISTS { + err = errnoErr(e1) + } + return + } func CreateNamedPipe(name *uint16, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *SecurityAttributes) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall9(procCreateNamedPipeW.Addr(), 8, uintptr(unsafe.Pointer(name)), uintptr(flags), uintptr(pipeMode), uintptr(maxInstances), uintptr(outSize), uintptr(inSize), uintptr(defaultTimeout), uintptr(unsafe.Pointer(sa)), 0) + handle = Handle(r0) + if handle == InvalidHandle { + err = errnoErr(e1) + } + return + } func CreatePipe(readhandle *Handle, writehandle *Handle, sa *SecurityAttributes, size uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procCreatePipe.Addr(), 4, uintptr(unsafe.Pointer(readhandle)), uintptr(unsafe.Pointer(writehandle)), uintptr(unsafe.Pointer(sa)), uintptr(size), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func CreateProcess(appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error) { + var _p0 uint32 + if inheritHandles { + _p0 = 1 + } + r1, _, e1 := syscall.Syscall12(procCreateProcessW.Addr(), 10, uintptr(unsafe.Pointer(appName)), uintptr(unsafe.Pointer(commandLine)), uintptr(unsafe.Pointer(procSecurity)), uintptr(unsafe.Pointer(threadSecurity)), uintptr(_p0), uintptr(creationFlags), uintptr(unsafe.Pointer(env)), uintptr(unsafe.Pointer(currentDir)), uintptr(unsafe.Pointer(startupInfo)), uintptr(unsafe.Pointer(outProcInfo)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func createPseudoConsole(size uint32, in Handle, out Handle, flags uint32, pconsole *Handle) (hr error) { + r0, _, _ := syscall.Syscall6(procCreatePseudoConsole.Addr(), 5, uintptr(size), uintptr(in), uintptr(out), uintptr(flags), uintptr(unsafe.Pointer(pconsole)), 0) + if r0 != 0 { + hr = syscall.Errno(r0) + } + return + } func CreateSymbolicLink(symlinkfilename *uint16, targetfilename *uint16, flags uint32) (err error) { + r1, _, e1 := syscall.Syscall(procCreateSymbolicLinkW.Addr(), 3, uintptr(unsafe.Pointer(symlinkfilename)), uintptr(unsafe.Pointer(targetfilename)), uintptr(flags)) + if r1&0xff == 0 { + err = errnoErr(e1) + } + return + } func CreateToolhelp32Snapshot(flags uint32, processId uint32) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall(procCreateToolhelp32Snapshot.Addr(), 2, uintptr(flags), uintptr(processId), 0) + handle = Handle(r0) + if handle == InvalidHandle { + err = errnoErr(e1) + } + return + } func DefineDosDevice(flags uint32, deviceName *uint16, targetPath *uint16) (err error) { + r1, _, e1 := syscall.Syscall(procDefineDosDeviceW.Addr(), 3, uintptr(flags), uintptr(unsafe.Pointer(deviceName)), uintptr(unsafe.Pointer(targetPath))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func DeleteFile(path *uint16) (err error) { + r1, _, e1 := syscall.Syscall(procDeleteFileW.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func deleteProcThreadAttributeList(attrlist *ProcThreadAttributeList) { + syscall.Syscall(procDeleteProcThreadAttributeList.Addr(), 1, uintptr(unsafe.Pointer(attrlist)), 0, 0) + return + } func DeleteVolumeMountPoint(volumeMountPoint *uint16) (err error) { + r1, _, e1 := syscall.Syscall(procDeleteVolumeMountPointW.Addr(), 1, uintptr(unsafe.Pointer(volumeMountPoint)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesReturned *uint32, overlapped *Overlapped) (err error) { + r1, _, e1 := syscall.Syscall9(procDeviceIoControl.Addr(), 8, uintptr(handle), uintptr(ioControlCode), uintptr(unsafe.Pointer(inBuffer)), uintptr(inBufferSize), uintptr(unsafe.Pointer(outBuffer)), uintptr(outBufferSize), uintptr(unsafe.Pointer(bytesReturned)), uintptr(unsafe.Pointer(overlapped)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func DisconnectNamedPipe(pipe Handle) (err error) { + r1, _, e1 := syscall.Syscall(procDisconnectNamedPipe.Addr(), 1, uintptr(pipe), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetProcessHandle Handle, lpTargetHandle *Handle, dwDesiredAccess uint32, bInheritHandle bool, dwOptions uint32) (err error) { + var _p0 uint32 + if bInheritHandle { + _p0 = 1 + } + r1, _, e1 := syscall.Syscall9(procDuplicateHandle.Addr(), 7, uintptr(hSourceProcessHandle), uintptr(hSourceHandle), uintptr(hTargetProcessHandle), uintptr(unsafe.Pointer(lpTargetHandle)), uintptr(dwDesiredAccess), uintptr(_p0), uintptr(dwOptions), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func EscapeCommFunction(handle Handle, dwFunc uint32) (err error) { + r1, _, e1 := syscall.Syscall(procEscapeCommFunction.Addr(), 2, uintptr(handle), uintptr(dwFunc), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func ExitProcess(exitcode uint32) { + syscall.Syscall(procExitProcess.Addr(), 1, uintptr(exitcode), 0, 0) + return + } func ExpandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error) { + r0, _, e1 := syscall.Syscall(procExpandEnvironmentStringsW.Addr(), 3, uintptr(unsafe.Pointer(src)), uintptr(unsafe.Pointer(dst)), uintptr(size)) + n = uint32(r0) + if n == 0 { + err = errnoErr(e1) + } + return + } func FindClose(handle Handle) (err error) { + r1, _, e1 := syscall.Syscall(procFindClose.Addr(), 1, uintptr(handle), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func FindCloseChangeNotification(handle Handle) (err error) { + r1, _, e1 := syscall.Syscall(procFindCloseChangeNotification.Addr(), 1, uintptr(handle), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func FindFirstChangeNotification(path string, watchSubtree bool, notifyFilter uint32) (handle Handle, err error) { + var _p0 *uint16 + _p0, err = syscall.UTF16PtrFromString(path) + if err != nil { + return + } + return _FindFirstChangeNotification(_p0, watchSubtree, notifyFilter) + } func _FindFirstChangeNotification(path *uint16, watchSubtree bool, notifyFilter uint32) (handle Handle, err error) { + var _p1 uint32 + if watchSubtree { + _p1 = 1 + } + r0, _, e1 := syscall.Syscall(procFindFirstChangeNotificationW.Addr(), 3, uintptr(unsafe.Pointer(path)), uintptr(_p1), uintptr(notifyFilter)) + handle = Handle(r0) + if handle == InvalidHandle { + err = errnoErr(e1) + } + return + } func findFirstFile1(name *uint16, data *win32finddata1) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall(procFindFirstFileW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(data)), 0) + handle = Handle(r0) + if handle == InvalidHandle { + err = errnoErr(e1) + } + return + } func FindFirstVolumeMountPoint(rootPathName *uint16, volumeMountPoint *uint16, bufferLength uint32) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall(procFindFirstVolumeMountPointW.Addr(), 3, uintptr(unsafe.Pointer(rootPathName)), uintptr(unsafe.Pointer(volumeMountPoint)), uintptr(bufferLength)) + handle = Handle(r0) + if handle == InvalidHandle { + err = errnoErr(e1) + } + return + } func FindFirstVolume(volumeName *uint16, bufferLength uint32) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall(procFindFirstVolumeW.Addr(), 2, uintptr(unsafe.Pointer(volumeName)), uintptr(bufferLength), 0) + handle = Handle(r0) + if handle == InvalidHandle { + err = errnoErr(e1) + } + return + } func FindNextChangeNotification(handle Handle) (err error) { + r1, _, e1 := syscall.Syscall(procFindNextChangeNotification.Addr(), 1, uintptr(handle), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func findNextFile1(handle Handle, data *win32finddata1) (err error) { + r1, _, e1 := syscall.Syscall(procFindNextFileW.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(data)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func FindNextVolumeMountPoint(findVolumeMountPoint Handle, volumeMountPoint *uint16, bufferLength uint32) (err error) { + r1, _, e1 := syscall.Syscall(procFindNextVolumeMountPointW.Addr(), 3, uintptr(findVolumeMountPoint), uintptr(unsafe.Pointer(volumeMountPoint)), uintptr(bufferLength)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func FindNextVolume(findVolume Handle, volumeName *uint16, bufferLength uint32) (err error) { + r1, _, e1 := syscall.Syscall(procFindNextVolumeW.Addr(), 3, uintptr(findVolume), uintptr(unsafe.Pointer(volumeName)), uintptr(bufferLength)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func findResource(module Handle, name uintptr, resType uintptr) (resInfo Handle, err error) { + r0, _, e1 := syscall.Syscall(procFindResourceW.Addr(), 3, uintptr(module), uintptr(name), uintptr(resType)) + resInfo = Handle(r0) + if resInfo == 0 { + err = errnoErr(e1) + } + return + } func FindVolumeClose(findVolume Handle) (err error) { + r1, _, e1 := syscall.Syscall(procFindVolumeClose.Addr(), 1, uintptr(findVolume), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func FindVolumeMountPointClose(findVolumeMountPoint Handle) (err error) { + r1, _, e1 := syscall.Syscall(procFindVolumeMountPointClose.Addr(), 1, uintptr(findVolumeMountPoint), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func FlushFileBuffers(handle Handle) (err error) { + r1, _, e1 := syscall.Syscall(procFlushFileBuffers.Addr(), 1, uintptr(handle), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func FlushViewOfFile(addr uintptr, length uintptr) (err error) { + r1, _, e1 := syscall.Syscall(procFlushViewOfFile.Addr(), 2, uintptr(addr), uintptr(length), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func FormatMessage(flags uint32, msgsrc uintptr, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) { + var _p0 *uint16 + if len(buf) > 0 { + _p0 = &buf[0] + } + r0, _, e1 := syscall.Syscall9(procFormatMessageW.Addr(), 7, uintptr(flags), uintptr(msgsrc), uintptr(msgid), uintptr(langid), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(unsafe.Pointer(args)), 0, 0) + n = uint32(r0) + if n == 0 { + err = errnoErr(e1) + } + return + } func FreeEnvironmentStrings(envs *uint16) (err error) { + r1, _, e1 := syscall.Syscall(procFreeEnvironmentStringsW.Addr(), 1, uintptr(unsafe.Pointer(envs)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func FreeLibrary(handle Handle) (err error) { + r1, _, e1 := syscall.Syscall(procFreeLibrary.Addr(), 1, uintptr(handle), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GenerateConsoleCtrlEvent(ctrlEvent uint32, processGroupID uint32) (err error) { + r1, _, e1 := syscall.Syscall(procGenerateConsoleCtrlEvent.Addr(), 2, uintptr(ctrlEvent), uintptr(processGroupID), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetACP() (acp uint32) { + r0, _, _ := syscall.Syscall(procGetACP.Addr(), 0, 0, 0, 0) + acp = uint32(r0) + return + } func GetActiveProcessorCount(groupNumber uint16) (ret uint32) { + r0, _, _ := syscall.Syscall(procGetActiveProcessorCount.Addr(), 1, uintptr(groupNumber), 0, 0) + ret = uint32(r0) + return + } func GetCommModemStatus(handle Handle, lpModemStat *uint32) (err error) { + r1, _, e1 := syscall.Syscall(procGetCommModemStatus.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(lpModemStat)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetCommState(handle Handle, lpDCB *DCB) (err error) { + r1, _, e1 := syscall.Syscall(procGetCommState.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(lpDCB)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error) { + r1, _, e1 := syscall.Syscall(procGetCommTimeouts.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(timeouts)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetCommandLine() (cmd *uint16) { + r0, _, _ := syscall.Syscall(procGetCommandLineW.Addr(), 0, 0, 0, 0) + cmd = (*uint16)(unsafe.Pointer(r0)) + return + } func GetComputerNameEx(nametype uint32, buf *uint16, n *uint32) (err error) { + r1, _, e1 := syscall.Syscall(procGetComputerNameExW.Addr(), 3, uintptr(nametype), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(n))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetComputerName(buf *uint16, n *uint32) (err error) { + r1, _, e1 := syscall.Syscall(procGetComputerNameW.Addr(), 2, uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(n)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetConsoleMode(console Handle, mode *uint32) (err error) { + r1, _, e1 := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(console), uintptr(unsafe.Pointer(mode)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetConsoleScreenBufferInfo(console Handle, info *ConsoleScreenBufferInfo) (err error) { + r1, _, e1 := syscall.Syscall(procGetConsoleScreenBufferInfo.Addr(), 2, uintptr(console), uintptr(unsafe.Pointer(info)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetCurrentDirectory(buflen uint32, buf *uint16) (n uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetCurrentDirectoryW.Addr(), 2, uintptr(buflen), uintptr(unsafe.Pointer(buf)), 0) + n = uint32(r0) + if n == 0 { + err = errnoErr(e1) + } + return + } func GetCurrentProcessId() (pid uint32) { + r0, _, _ := syscall.Syscall(procGetCurrentProcessId.Addr(), 0, 0, 0, 0) + pid = uint32(r0) + return + } func GetCurrentThreadId() (id uint32) { + r0, _, _ := syscall.Syscall(procGetCurrentThreadId.Addr(), 0, 0, 0, 0) + id = uint32(r0) + return + } func GetDiskFreeSpaceEx(directoryName *uint16, freeBytesAvailableToCaller *uint64, totalNumberOfBytes *uint64, totalNumberOfFreeBytes *uint64) (err error) { + r1, _, e1 := syscall.Syscall6(procGetDiskFreeSpaceExW.Addr(), 4, uintptr(unsafe.Pointer(directoryName)), uintptr(unsafe.Pointer(freeBytesAvailableToCaller)), uintptr(unsafe.Pointer(totalNumberOfBytes)), uintptr(unsafe.Pointer(totalNumberOfFreeBytes)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetDriveType(rootPathName *uint16) (driveType uint32) { + r0, _, _ := syscall.Syscall(procGetDriveTypeW.Addr(), 1, uintptr(unsafe.Pointer(rootPathName)), 0, 0) + driveType = uint32(r0) + return + } func GetEnvironmentStrings() (envs *uint16, err error) { + r0, _, e1 := syscall.Syscall(procGetEnvironmentStringsW.Addr(), 0, 0, 0, 0) + envs = (*uint16)(unsafe.Pointer(r0)) + if envs == nil { + err = errnoErr(e1) + } + return + } func GetEnvironmentVariable(name *uint16, buffer *uint16, size uint32) (n uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetEnvironmentVariableW.Addr(), 3, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(buffer)), uintptr(size)) + n = uint32(r0) + if n == 0 { + err = errnoErr(e1) + } + return + } func GetExitCodeProcess(handle Handle, exitcode *uint32) (err error) { + r1, _, e1 := syscall.Syscall(procGetExitCodeProcess.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(exitcode)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetFileAttributesEx(name *uint16, level uint32, info *byte) (err error) { + r1, _, e1 := syscall.Syscall(procGetFileAttributesExW.Addr(), 3, uintptr(unsafe.Pointer(name)), uintptr(level), uintptr(unsafe.Pointer(info))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetFileAttributes(name *uint16) (attrs uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetFileAttributesW.Addr(), 1, uintptr(unsafe.Pointer(name)), 0, 0) + attrs = uint32(r0) + if attrs == INVALID_FILE_ATTRIBUTES { + err = errnoErr(e1) + } + return + } func GetFileInformationByHandle(handle Handle, data *ByHandleFileInformation) (err error) { + r1, _, e1 := syscall.Syscall(procGetFileInformationByHandle.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(data)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetFileInformationByHandleEx(handle Handle, class uint32, outBuffer *byte, outBufferLen uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procGetFileInformationByHandleEx.Addr(), 4, uintptr(handle), uintptr(class), uintptr(unsafe.Pointer(outBuffer)), uintptr(outBufferLen), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error) { + r1, _, e1 := syscall.Syscall6(procGetFileTime.Addr(), 4, uintptr(handle), uintptr(unsafe.Pointer(ctime)), uintptr(unsafe.Pointer(atime)), uintptr(unsafe.Pointer(wtime)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetFileType(filehandle Handle) (n uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetFileType.Addr(), 1, uintptr(filehandle), 0, 0) + n = uint32(r0) + if n == 0 { + err = errnoErr(e1) + } + return + } func GetFinalPathNameByHandle(file Handle, filePath *uint16, filePathSize uint32, flags uint32) (n uint32, err error) { + r0, _, e1 := syscall.Syscall6(procGetFinalPathNameByHandleW.Addr(), 4, uintptr(file), uintptr(unsafe.Pointer(filePath)), uintptr(filePathSize), uintptr(flags), 0, 0) + n = uint32(r0) + if n == 0 { + err = errnoErr(e1) + } + return + } func GetFullPathName(path *uint16, buflen uint32, buf *uint16, fname **uint16) (n uint32, err error) { + r0, _, e1 := syscall.Syscall6(procGetFullPathNameW.Addr(), 4, uintptr(unsafe.Pointer(path)), uintptr(buflen), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(fname)), 0, 0) + n = uint32(r0) + if n == 0 { + err = errnoErr(e1) + } + return + } func GetLargePageMinimum() (size uintptr) { + r0, _, _ := syscall.Syscall(procGetLargePageMinimum.Addr(), 0, 0, 0, 0) + size = uintptr(r0) + return + } func GetLastError() (lasterr error) { + r0, _, _ := syscall.Syscall(procGetLastError.Addr(), 0, 0, 0, 0) + if r0 != 0 { + lasterr = syscall.Errno(r0) + } + return + } func GetLogicalDriveStrings(bufferLength uint32, buffer *uint16) (n uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetLogicalDriveStringsW.Addr(), 2, uintptr(bufferLength), uintptr(unsafe.Pointer(buffer)), 0) + n = uint32(r0) + if n == 0 { + err = errnoErr(e1) + } + return + } func GetLogicalDrives() (drivesBitMask uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetLogicalDrives.Addr(), 0, 0, 0, 0) + drivesBitMask = uint32(r0) + if drivesBitMask == 0 { + err = errnoErr(e1) + } + return + } func GetLongPathName(path *uint16, buf *uint16, buflen uint32) (n uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetLongPathNameW.Addr(), 3, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(buf)), uintptr(buflen)) + n = uint32(r0) + if n == 0 { + err = errnoErr(e1) + } + return + } func GetMaximumProcessorCount(groupNumber uint16) (ret uint32) { + r0, _, _ := syscall.Syscall(procGetMaximumProcessorCount.Addr(), 1, uintptr(groupNumber), 0, 0) + ret = uint32(r0) + return + } func GetModuleFileName(module Handle, filename *uint16, size uint32) (n uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetModuleFileNameW.Addr(), 3, uintptr(module), uintptr(unsafe.Pointer(filename)), uintptr(size)) + n = uint32(r0) + if n == 0 { + err = errnoErr(e1) + } + return + } func GetModuleHandleEx(flags uint32, moduleName *uint16, module *Handle) (err error) { + r1, _, e1 := syscall.Syscall(procGetModuleHandleExW.Addr(), 3, uintptr(flags), uintptr(unsafe.Pointer(moduleName)), uintptr(unsafe.Pointer(module))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetNamedPipeHandleState(pipe Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) { + r1, _, e1 := syscall.Syscall9(procGetNamedPipeHandleStateW.Addr(), 7, uintptr(pipe), uintptr(unsafe.Pointer(state)), uintptr(unsafe.Pointer(curInstances)), uintptr(unsafe.Pointer(maxCollectionCount)), uintptr(unsafe.Pointer(collectDataTimeout)), uintptr(unsafe.Pointer(userName)), uintptr(maxUserNameSize), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetNamedPipeInfo(pipe Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procGetNamedPipeInfo.Addr(), 5, uintptr(pipe), uintptr(unsafe.Pointer(flags)), uintptr(unsafe.Pointer(outSize)), uintptr(unsafe.Pointer(inSize)), uintptr(unsafe.Pointer(maxInstances)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetOverlappedResult(handle Handle, overlapped *Overlapped, done *uint32, wait bool) (err error) { + var _p0 uint32 + if wait { + _p0 = 1 + } + r1, _, e1 := syscall.Syscall6(procGetOverlappedResult.Addr(), 4, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(done)), uintptr(_p0), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetPriorityClass(process Handle) (ret uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetPriorityClass.Addr(), 1, uintptr(process), 0, 0) + ret = uint32(r0) + if ret == 0 { + err = errnoErr(e1) + } + return + } func GetProcAddress(module Handle, procname string) (proc uintptr, err error) { + var _p0 *byte + _p0, err = syscall.BytePtrFromString(procname) + if err != nil { + return + } + return _GetProcAddress(module, _p0) + } func _GetProcAddress(module Handle, procname *byte) (proc uintptr, err error) { + r0, _, e1 := syscall.Syscall(procGetProcAddress.Addr(), 2, uintptr(module), uintptr(unsafe.Pointer(procname)), 0) + proc = uintptr(r0) + if proc == 0 { + err = errnoErr(e1) + } + return + } func GetProcessId(process Handle) (id uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetProcessId.Addr(), 1, uintptr(process), 0, 0) + id = uint32(r0) + if id == 0 { + err = errnoErr(e1) + } + return + } func getProcessPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procGetProcessPreferredUILanguages.Addr(), 4, uintptr(flags), uintptr(unsafe.Pointer(numLanguages)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(bufSize)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetProcessShutdownParameters(level *uint32, flags *uint32) (err error) { + r1, _, e1 := syscall.Syscall(procGetProcessShutdownParameters.Addr(), 2, uintptr(unsafe.Pointer(level)), uintptr(unsafe.Pointer(flags)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetProcessTimes(handle Handle, creationTime *Filetime, exitTime *Filetime, kernelTime *Filetime, userTime *Filetime) (err error) { + r1, _, e1 := syscall.Syscall6(procGetProcessTimes.Addr(), 5, uintptr(handle), uintptr(unsafe.Pointer(creationTime)), uintptr(unsafe.Pointer(exitTime)), uintptr(unsafe.Pointer(kernelTime)), uintptr(unsafe.Pointer(userTime)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetProcessWorkingSetSizeEx(hProcess Handle, lpMinimumWorkingSetSize *uintptr, lpMaximumWorkingSetSize *uintptr, flags *uint32) { + syscall.Syscall6(procGetProcessWorkingSetSizeEx.Addr(), 4, uintptr(hProcess), uintptr(unsafe.Pointer(lpMinimumWorkingSetSize)), uintptr(unsafe.Pointer(lpMaximumWorkingSetSize)), uintptr(unsafe.Pointer(flags)), 0, 0) + return + } func GetQueuedCompletionStatus(cphandle Handle, qty *uint32, key *uintptr, overlapped **Overlapped, timeout uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procGetQueuedCompletionStatus.Addr(), 5, uintptr(cphandle), uintptr(unsafe.Pointer(qty)), uintptr(unsafe.Pointer(key)), uintptr(unsafe.Pointer(overlapped)), uintptr(timeout), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetShortPathName(longpath *uint16, shortpath *uint16, buflen uint32) (n uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetShortPathNameW.Addr(), 3, uintptr(unsafe.Pointer(longpath)), uintptr(unsafe.Pointer(shortpath)), uintptr(buflen)) + n = uint32(r0) + if n == 0 { + err = errnoErr(e1) + } + return + } func getStartupInfo(startupInfo *StartupInfo) { + syscall.Syscall(procGetStartupInfoW.Addr(), 1, uintptr(unsafe.Pointer(startupInfo)), 0, 0) + return + } func GetStdHandle(stdhandle uint32) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall(procGetStdHandle.Addr(), 1, uintptr(stdhandle), 0, 0) + handle = Handle(r0) + if handle == InvalidHandle { + err = errnoErr(e1) + } + return + } func getSystemDirectory(dir *uint16, dirLen uint32) (len uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetSystemDirectoryW.Addr(), 2, uintptr(unsafe.Pointer(dir)), uintptr(dirLen), 0) + len = uint32(r0) + if len == 0 { + err = errnoErr(e1) + } + return + } func getSystemPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procGetSystemPreferredUILanguages.Addr(), 4, uintptr(flags), uintptr(unsafe.Pointer(numLanguages)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(bufSize)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetSystemTimeAsFileTime(time *Filetime) { + syscall.Syscall(procGetSystemTimeAsFileTime.Addr(), 1, uintptr(unsafe.Pointer(time)), 0, 0) + return + } func GetSystemTimePreciseAsFileTime(time *Filetime) { + syscall.Syscall(procGetSystemTimePreciseAsFileTime.Addr(), 1, uintptr(unsafe.Pointer(time)), 0, 0) + return + } func getSystemWindowsDirectory(dir *uint16, dirLen uint32) (len uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetSystemWindowsDirectoryW.Addr(), 2, uintptr(unsafe.Pointer(dir)), uintptr(dirLen), 0) + len = uint32(r0) + if len == 0 { + err = errnoErr(e1) + } + return + } func GetTempPath(buflen uint32, buf *uint16) (n uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetTempPathW.Addr(), 2, uintptr(buflen), uintptr(unsafe.Pointer(buf)), 0) + n = uint32(r0) + if n == 0 { + err = errnoErr(e1) + } + return + } func getThreadPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procGetThreadPreferredUILanguages.Addr(), 4, uintptr(flags), uintptr(unsafe.Pointer(numLanguages)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(bufSize)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func getTickCount64() (ms uint64) { + r0, _, _ := syscall.Syscall(procGetTickCount64.Addr(), 0, 0, 0, 0) + ms = uint64(r0) + return + } func GetTimeZoneInformation(tzi *Timezoneinformation) (rc uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetTimeZoneInformation.Addr(), 1, uintptr(unsafe.Pointer(tzi)), 0, 0) + rc = uint32(r0) + if rc == 0xffffffff { + err = errnoErr(e1) + } + return + } func getUserPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procGetUserPreferredUILanguages.Addr(), 4, uintptr(flags), uintptr(unsafe.Pointer(numLanguages)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(bufSize)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetVersion() (ver uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetVersion.Addr(), 0, 0, 0, 0) + ver = uint32(r0) + if ver == 0 { + err = errnoErr(e1) + } + return + } func GetVolumeInformationByHandle(file Handle, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) { + r1, _, e1 := syscall.Syscall9(procGetVolumeInformationByHandleW.Addr(), 8, uintptr(file), uintptr(unsafe.Pointer(volumeNameBuffer)), uintptr(volumeNameSize), uintptr(unsafe.Pointer(volumeNameSerialNumber)), uintptr(unsafe.Pointer(maximumComponentLength)), uintptr(unsafe.Pointer(fileSystemFlags)), uintptr(unsafe.Pointer(fileSystemNameBuffer)), uintptr(fileSystemNameSize), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetVolumeInformation(rootPathName *uint16, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) { + r1, _, e1 := syscall.Syscall9(procGetVolumeInformationW.Addr(), 8, uintptr(unsafe.Pointer(rootPathName)), uintptr(unsafe.Pointer(volumeNameBuffer)), uintptr(volumeNameSize), uintptr(unsafe.Pointer(volumeNameSerialNumber)), uintptr(unsafe.Pointer(maximumComponentLength)), uintptr(unsafe.Pointer(fileSystemFlags)), uintptr(unsafe.Pointer(fileSystemNameBuffer)), uintptr(fileSystemNameSize), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetVolumeNameForVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16, bufferlength uint32) (err error) { + r1, _, e1 := syscall.Syscall(procGetVolumeNameForVolumeMountPointW.Addr(), 3, uintptr(unsafe.Pointer(volumeMountPoint)), uintptr(unsafe.Pointer(volumeName)), uintptr(bufferlength)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetVolumePathName(fileName *uint16, volumePathName *uint16, bufferLength uint32) (err error) { + r1, _, e1 := syscall.Syscall(procGetVolumePathNameW.Addr(), 3, uintptr(unsafe.Pointer(fileName)), uintptr(unsafe.Pointer(volumePathName)), uintptr(bufferLength)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetVolumePathNamesForVolumeName(volumeName *uint16, volumePathNames *uint16, bufferLength uint32, returnLength *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procGetVolumePathNamesForVolumeNameW.Addr(), 4, uintptr(unsafe.Pointer(volumeName)), uintptr(unsafe.Pointer(volumePathNames)), uintptr(bufferLength), uintptr(unsafe.Pointer(returnLength)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func getWindowsDirectory(dir *uint16, dirLen uint32) (len uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetWindowsDirectoryW.Addr(), 2, uintptr(unsafe.Pointer(dir)), uintptr(dirLen), 0) + len = uint32(r0) + if len == 0 { + err = errnoErr(e1) + } + return + } func initializeProcThreadAttributeList(attrlist *ProcThreadAttributeList, attrcount uint32, flags uint32, size *uintptr) (err error) { + r1, _, e1 := syscall.Syscall6(procInitializeProcThreadAttributeList.Addr(), 4, uintptr(unsafe.Pointer(attrlist)), uintptr(attrcount), uintptr(flags), uintptr(unsafe.Pointer(size)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func IsWow64Process(handle Handle, isWow64 *bool) (err error) { + var _p0 uint32 + if *isWow64 { + _p0 = 1 + } + r1, _, e1 := syscall.Syscall(procIsWow64Process.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(&_p0)), 0) + *isWow64 = _p0 != 0 + if r1 == 0 { + err = errnoErr(e1) + } + return + } func IsWow64Process2(handle Handle, processMachine *uint16, nativeMachine *uint16) (err error) { + err = procIsWow64Process2.Find() + if err != nil { + return + } + r1, _, e1 := syscall.Syscall(procIsWow64Process2.Addr(), 3, uintptr(handle), uintptr(unsafe.Pointer(processMachine)), uintptr(unsafe.Pointer(nativeMachine))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func LoadLibraryEx(libname string, zero Handle, flags uintptr) (handle Handle, err error) { + var _p0 *uint16 + _p0, err = syscall.UTF16PtrFromString(libname) + if err != nil { + return + } + return _LoadLibraryEx(_p0, zero, flags) + } func _LoadLibraryEx(libname *uint16, zero Handle, flags uintptr) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall(procLoadLibraryExW.Addr(), 3, uintptr(unsafe.Pointer(libname)), uintptr(zero), uintptr(flags)) + handle = Handle(r0) + if handle == 0 { + err = errnoErr(e1) + } + return + } func LoadLibrary(libname string) (handle Handle, err error) { + var _p0 *uint16 + _p0, err = syscall.UTF16PtrFromString(libname) + if err != nil { + return + } + return _LoadLibrary(_p0) + } func _LoadLibrary(libname *uint16) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall(procLoadLibraryW.Addr(), 1, uintptr(unsafe.Pointer(libname)), 0, 0) + handle = Handle(r0) + if handle == 0 { + err = errnoErr(e1) + } + return + } func LoadResource(module Handle, resInfo Handle) (resData Handle, err error) { + r0, _, e1 := syscall.Syscall(procLoadResource.Addr(), 2, uintptr(module), uintptr(resInfo), 0) + resData = Handle(r0) + if resData == 0 { + err = errnoErr(e1) + } + return + } func LocalAlloc(flags uint32, length uint32) (ptr uintptr, err error) { + r0, _, e1 := syscall.Syscall(procLocalAlloc.Addr(), 2, uintptr(flags), uintptr(length), 0) + ptr = uintptr(r0) + if ptr == 0 { + err = errnoErr(e1) + } + return + } func LocalFree(hmem Handle) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall(procLocalFree.Addr(), 1, uintptr(hmem), 0, 0) + handle = Handle(r0) + if handle != 0 { + err = errnoErr(e1) + } + return + } func LockFileEx(file Handle, flags uint32, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error) { + r1, _, e1 := syscall.Syscall6(procLockFileEx.Addr(), 6, uintptr(file), uintptr(flags), uintptr(reserved), uintptr(bytesLow), uintptr(bytesHigh), uintptr(unsafe.Pointer(overlapped))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func LockResource(resData Handle) (addr uintptr, err error) { + r0, _, e1 := syscall.Syscall(procLockResource.Addr(), 1, uintptr(resData), 0, 0) + addr = uintptr(r0) + if addr == 0 { + err = errnoErr(e1) + } + return + } func MapViewOfFile(handle Handle, access uint32, offsetHigh uint32, offsetLow uint32, length uintptr) (addr uintptr, err error) { + r0, _, e1 := syscall.Syscall6(procMapViewOfFile.Addr(), 5, uintptr(handle), uintptr(access), uintptr(offsetHigh), uintptr(offsetLow), uintptr(length), 0) + addr = uintptr(r0) + if addr == 0 { + err = errnoErr(e1) + } + return + } func Module32First(snapshot Handle, moduleEntry *ModuleEntry32) (err error) { + r1, _, e1 := syscall.Syscall(procModule32FirstW.Addr(), 2, uintptr(snapshot), uintptr(unsafe.Pointer(moduleEntry)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func Module32Next(snapshot Handle, moduleEntry *ModuleEntry32) (err error) { + r1, _, e1 := syscall.Syscall(procModule32NextW.Addr(), 2, uintptr(snapshot), uintptr(unsafe.Pointer(moduleEntry)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func MoveFileEx(from *uint16, to *uint16, flags uint32) (err error) { + r1, _, e1 := syscall.Syscall(procMoveFileExW.Addr(), 3, uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(to)), uintptr(flags)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func MoveFile(from *uint16, to *uint16) (err error) { + r1, _, e1 := syscall.Syscall(procMoveFileW.Addr(), 2, uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(to)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func MultiByteToWideChar(codePage uint32, dwFlags uint32, str *byte, nstr int32, wchar *uint16, nwchar int32) (nwrite int32, err error) { + r0, _, e1 := syscall.Syscall6(procMultiByteToWideChar.Addr(), 6, uintptr(codePage), uintptr(dwFlags), uintptr(unsafe.Pointer(str)), uintptr(nstr), uintptr(unsafe.Pointer(wchar)), uintptr(nwchar)) + nwrite = int32(r0) + if nwrite == 0 { + err = errnoErr(e1) + } + return + } func OpenEvent(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) { + var _p0 uint32 + if inheritHandle { + _p0 = 1 + } + r0, _, e1 := syscall.Syscall(procOpenEventW.Addr(), 3, uintptr(desiredAccess), uintptr(_p0), uintptr(unsafe.Pointer(name))) + handle = Handle(r0) + if handle == 0 { + err = errnoErr(e1) + } + return + } func OpenMutex(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) { + var _p0 uint32 + if inheritHandle { + _p0 = 1 + } + r0, _, e1 := syscall.Syscall(procOpenMutexW.Addr(), 3, uintptr(desiredAccess), uintptr(_p0), uintptr(unsafe.Pointer(name))) + handle = Handle(r0) + if handle == 0 { + err = errnoErr(e1) + } + return + } func OpenProcess(desiredAccess uint32, inheritHandle bool, processId uint32) (handle Handle, err error) { + var _p0 uint32 + if inheritHandle { + _p0 = 1 + } + r0, _, e1 := syscall.Syscall(procOpenProcess.Addr(), 3, uintptr(desiredAccess), uintptr(_p0), uintptr(processId)) + handle = Handle(r0) + if handle == 0 { + err = errnoErr(e1) + } + return + } func OpenThread(desiredAccess uint32, inheritHandle bool, threadId uint32) (handle Handle, err error) { + var _p0 uint32 + if inheritHandle { + _p0 = 1 + } + r0, _, e1 := syscall.Syscall(procOpenThread.Addr(), 3, uintptr(desiredAccess), uintptr(_p0), uintptr(threadId)) + handle = Handle(r0) + if handle == 0 { + err = errnoErr(e1) + } + return + } func PostQueuedCompletionStatus(cphandle Handle, qty uint32, key uintptr, overlapped *Overlapped) (err error) { + r1, _, e1 := syscall.Syscall6(procPostQueuedCompletionStatus.Addr(), 4, uintptr(cphandle), uintptr(qty), uintptr(key), uintptr(unsafe.Pointer(overlapped)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error) { + r1, _, e1 := syscall.Syscall(procProcess32FirstW.Addr(), 2, uintptr(snapshot), uintptr(unsafe.Pointer(procEntry)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error) { + r1, _, e1 := syscall.Syscall(procProcess32NextW.Addr(), 2, uintptr(snapshot), uintptr(unsafe.Pointer(procEntry)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func ProcessIdToSessionId(pid uint32, sessionid *uint32) (err error) { + r1, _, e1 := syscall.Syscall(procProcessIdToSessionId.Addr(), 2, uintptr(pid), uintptr(unsafe.Pointer(sessionid)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func PulseEvent(event Handle) (err error) { + r1, _, e1 := syscall.Syscall(procPulseEvent.Addr(), 1, uintptr(event), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func PurgeComm(handle Handle, dwFlags uint32) (err error) { + r1, _, e1 := syscall.Syscall(procPurgeComm.Addr(), 2, uintptr(handle), uintptr(dwFlags), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func QueryDosDevice(deviceName *uint16, targetPath *uint16, max uint32) (n uint32, err error) { + r0, _, e1 := syscall.Syscall(procQueryDosDeviceW.Addr(), 3, uintptr(unsafe.Pointer(deviceName)), uintptr(unsafe.Pointer(targetPath)), uintptr(max)) + n = uint32(r0) + if n == 0 { + err = errnoErr(e1) + } + return + } func QueryFullProcessImageName(proc Handle, flags uint32, exeName *uint16, size *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procQueryFullProcessImageNameW.Addr(), 4, uintptr(proc), uintptr(flags), uintptr(unsafe.Pointer(exeName)), uintptr(unsafe.Pointer(size)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func QueryInformationJobObject(job Handle, JobObjectInformationClass int32, JobObjectInformation uintptr, JobObjectInformationLength uint32, retlen *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procQueryInformationJobObject.Addr(), 5, uintptr(job), uintptr(JobObjectInformationClass), uintptr(JobObjectInformation), uintptr(JobObjectInformationLength), uintptr(unsafe.Pointer(retlen)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error) { + r1, _, e1 := syscall.Syscall6(procReadConsoleW.Addr(), 5, uintptr(console), uintptr(unsafe.Pointer(buf)), uintptr(toread), uintptr(unsafe.Pointer(read)), uintptr(unsafe.Pointer(inputControl)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func ReadDirectoryChanges(handle Handle, buf *byte, buflen uint32, watchSubTree bool, mask uint32, retlen *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) { + var _p0 uint32 + if watchSubTree { + _p0 = 1 + } + r1, _, e1 := syscall.Syscall9(procReadDirectoryChangesW.Addr(), 8, uintptr(handle), uintptr(unsafe.Pointer(buf)), uintptr(buflen), uintptr(_p0), uintptr(mask), uintptr(unsafe.Pointer(retlen)), uintptr(unsafe.Pointer(overlapped)), uintptr(completionRoutine), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func readFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) { + var _p0 *byte + if len(buf) > 0 { + _p0 = &buf[0] + } + r1, _, e1 := syscall.Syscall6(procReadFile.Addr(), 5, uintptr(handle), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(unsafe.Pointer(done)), uintptr(unsafe.Pointer(overlapped)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func ReadProcessMemory(process Handle, baseAddress uintptr, buffer *byte, size uintptr, numberOfBytesRead *uintptr) (err error) { + r1, _, e1 := syscall.Syscall6(procReadProcessMemory.Addr(), 5, uintptr(process), uintptr(baseAddress), uintptr(unsafe.Pointer(buffer)), uintptr(size), uintptr(unsafe.Pointer(numberOfBytesRead)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func ReleaseMutex(mutex Handle) (err error) { + r1, _, e1 := syscall.Syscall(procReleaseMutex.Addr(), 1, uintptr(mutex), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func RemoveDirectory(path *uint16) (err error) { + r1, _, e1 := syscall.Syscall(procRemoveDirectoryW.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func RemoveDllDirectory(cookie uintptr) (err error) { + r1, _, e1 := syscall.Syscall(procRemoveDllDirectory.Addr(), 1, uintptr(cookie), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func ResetEvent(event Handle) (err error) { + r1, _, e1 := syscall.Syscall(procResetEvent.Addr(), 1, uintptr(event), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func resizePseudoConsole(pconsole Handle, size uint32) (hr error) { + r0, _, _ := syscall.Syscall(procResizePseudoConsole.Addr(), 2, uintptr(pconsole), uintptr(size), 0) + if r0 != 0 { + hr = syscall.Errno(r0) + } + return + } func ResumeThread(thread Handle) (ret uint32, err error) { + r0, _, e1 := syscall.Syscall(procResumeThread.Addr(), 1, uintptr(thread), 0, 0) + ret = uint32(r0) + if ret == 0xffffffff { + err = errnoErr(e1) + } + return + } func SetCommBreak(handle Handle) (err error) { + r1, _, e1 := syscall.Syscall(procSetCommBreak.Addr(), 1, uintptr(handle), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetCommMask(handle Handle, dwEvtMask uint32) (err error) { + r1, _, e1 := syscall.Syscall(procSetCommMask.Addr(), 2, uintptr(handle), uintptr(dwEvtMask), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetCommState(handle Handle, lpDCB *DCB) (err error) { + r1, _, e1 := syscall.Syscall(procSetCommState.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(lpDCB)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error) { + r1, _, e1 := syscall.Syscall(procSetCommTimeouts.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(timeouts)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setConsoleCursorPosition(console Handle, position uint32) (err error) { + r1, _, e1 := syscall.Syscall(procSetConsoleCursorPosition.Addr(), 2, uintptr(console), uintptr(position), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetConsoleMode(console Handle, mode uint32) (err error) { + r1, _, e1 := syscall.Syscall(procSetConsoleMode.Addr(), 2, uintptr(console), uintptr(mode), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetCurrentDirectory(path *uint16) (err error) { + r1, _, e1 := syscall.Syscall(procSetCurrentDirectoryW.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetDefaultDllDirectories(directoryFlags uint32) (err error) { + r1, _, e1 := syscall.Syscall(procSetDefaultDllDirectories.Addr(), 1, uintptr(directoryFlags), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetDllDirectory(path string) (err error) { + var _p0 *uint16 + _p0, err = syscall.UTF16PtrFromString(path) + if err != nil { + return + } + return _SetDllDirectory(_p0) + } func _SetDllDirectory(path *uint16) (err error) { + r1, _, e1 := syscall.Syscall(procSetDllDirectoryW.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetEndOfFile(handle Handle) (err error) { + r1, _, e1 := syscall.Syscall(procSetEndOfFile.Addr(), 1, uintptr(handle), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetEnvironmentVariable(name *uint16, value *uint16) (err error) { + r1, _, e1 := syscall.Syscall(procSetEnvironmentVariableW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(value)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetErrorMode(mode uint32) (ret uint32) { + r0, _, _ := syscall.Syscall(procSetErrorMode.Addr(), 1, uintptr(mode), 0, 0) + ret = uint32(r0) + return + } func SetEvent(event Handle) (err error) { + r1, _, e1 := syscall.Syscall(procSetEvent.Addr(), 1, uintptr(event), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetFileAttributes(name *uint16, attrs uint32) (err error) { + r1, _, e1 := syscall.Syscall(procSetFileAttributesW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(attrs), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetFileCompletionNotificationModes(handle Handle, flags uint8) (err error) { + r1, _, e1 := syscall.Syscall(procSetFileCompletionNotificationModes.Addr(), 2, uintptr(handle), uintptr(flags), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetFileInformationByHandle(handle Handle, class uint32, inBuffer *byte, inBufferLen uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procSetFileInformationByHandle.Addr(), 4, uintptr(handle), uintptr(class), uintptr(unsafe.Pointer(inBuffer)), uintptr(inBufferLen), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetFilePointer(handle Handle, lowoffset int32, highoffsetptr *int32, whence uint32) (newlowoffset uint32, err error) { + r0, _, e1 := syscall.Syscall6(procSetFilePointer.Addr(), 4, uintptr(handle), uintptr(lowoffset), uintptr(unsafe.Pointer(highoffsetptr)), uintptr(whence), 0, 0) + newlowoffset = uint32(r0) + if newlowoffset == 0xffffffff { + err = errnoErr(e1) + } + return + } func SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error) { + r1, _, e1 := syscall.Syscall6(procSetFileTime.Addr(), 4, uintptr(handle), uintptr(unsafe.Pointer(ctime)), uintptr(unsafe.Pointer(atime)), uintptr(unsafe.Pointer(wtime)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetFileValidData(handle Handle, validDataLength int64) (err error) { + r1, _, e1 := syscall.Syscall(procSetFileValidData.Addr(), 2, uintptr(handle), uintptr(validDataLength), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error) { + r1, _, e1 := syscall.Syscall(procSetHandleInformation.Addr(), 3, uintptr(handle), uintptr(mask), uintptr(flags)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetInformationJobObject(job Handle, JobObjectInformationClass uint32, JobObjectInformation uintptr, JobObjectInformationLength uint32) (ret int, err error) { + r0, _, e1 := syscall.Syscall6(procSetInformationJobObject.Addr(), 4, uintptr(job), uintptr(JobObjectInformationClass), uintptr(JobObjectInformation), uintptr(JobObjectInformationLength), 0, 0) + ret = int(r0) + if ret == 0 { + err = errnoErr(e1) + } + return + } func SetNamedPipeHandleState(pipe Handle, state *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procSetNamedPipeHandleState.Addr(), 4, uintptr(pipe), uintptr(unsafe.Pointer(state)), uintptr(unsafe.Pointer(maxCollectionCount)), uintptr(unsafe.Pointer(collectDataTimeout)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetPriorityClass(process Handle, priorityClass uint32) (err error) { + r1, _, e1 := syscall.Syscall(procSetPriorityClass.Addr(), 2, uintptr(process), uintptr(priorityClass), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetProcessPriorityBoost(process Handle, disable bool) (err error) { + var _p0 uint32 + if disable { + _p0 = 1 + } + r1, _, e1 := syscall.Syscall(procSetProcessPriorityBoost.Addr(), 2, uintptr(process), uintptr(_p0), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetProcessShutdownParameters(level uint32, flags uint32) (err error) { + r1, _, e1 := syscall.Syscall(procSetProcessShutdownParameters.Addr(), 2, uintptr(level), uintptr(flags), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetProcessWorkingSetSizeEx(hProcess Handle, dwMinimumWorkingSetSize uintptr, dwMaximumWorkingSetSize uintptr, flags uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procSetProcessWorkingSetSizeEx.Addr(), 4, uintptr(hProcess), uintptr(dwMinimumWorkingSetSize), uintptr(dwMaximumWorkingSetSize), uintptr(flags), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetStdHandle(stdhandle uint32, handle Handle) (err error) { + r1, _, e1 := syscall.Syscall(procSetStdHandle.Addr(), 2, uintptr(stdhandle), uintptr(handle), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetVolumeLabel(rootPathName *uint16, volumeName *uint16) (err error) { + r1, _, e1 := syscall.Syscall(procSetVolumeLabelW.Addr(), 2, uintptr(unsafe.Pointer(rootPathName)), uintptr(unsafe.Pointer(volumeName)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16) (err error) { + r1, _, e1 := syscall.Syscall(procSetVolumeMountPointW.Addr(), 2, uintptr(unsafe.Pointer(volumeMountPoint)), uintptr(unsafe.Pointer(volumeName)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetupComm(handle Handle, dwInQueue uint32, dwOutQueue uint32) (err error) { + r1, _, e1 := syscall.Syscall(procSetupComm.Addr(), 3, uintptr(handle), uintptr(dwInQueue), uintptr(dwOutQueue)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SizeofResource(module Handle, resInfo Handle) (size uint32, err error) { + r0, _, e1 := syscall.Syscall(procSizeofResource.Addr(), 2, uintptr(module), uintptr(resInfo), 0) + size = uint32(r0) + if size == 0 { + err = errnoErr(e1) + } + return + } func SleepEx(milliseconds uint32, alertable bool) (ret uint32) { + var _p0 uint32 + if alertable { + _p0 = 1 + } + r0, _, _ := syscall.Syscall(procSleepEx.Addr(), 2, uintptr(milliseconds), uintptr(_p0), 0) + ret = uint32(r0) + return + } func TerminateJobObject(job Handle, exitCode uint32) (err error) { + r1, _, e1 := syscall.Syscall(procTerminateJobObject.Addr(), 2, uintptr(job), uintptr(exitCode), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func TerminateProcess(handle Handle, exitcode uint32) (err error) { + r1, _, e1 := syscall.Syscall(procTerminateProcess.Addr(), 2, uintptr(handle), uintptr(exitcode), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func Thread32First(snapshot Handle, threadEntry *ThreadEntry32) (err error) { + r1, _, e1 := syscall.Syscall(procThread32First.Addr(), 2, uintptr(snapshot), uintptr(unsafe.Pointer(threadEntry)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func Thread32Next(snapshot Handle, threadEntry *ThreadEntry32) (err error) { + r1, _, e1 := syscall.Syscall(procThread32Next.Addr(), 2, uintptr(snapshot), uintptr(unsafe.Pointer(threadEntry)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func UnlockFileEx(file Handle, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error) { + r1, _, e1 := syscall.Syscall6(procUnlockFileEx.Addr(), 5, uintptr(file), uintptr(reserved), uintptr(bytesLow), uintptr(bytesHigh), uintptr(unsafe.Pointer(overlapped)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func UnmapViewOfFile(addr uintptr) (err error) { + r1, _, e1 := syscall.Syscall(procUnmapViewOfFile.Addr(), 1, uintptr(addr), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func updateProcThreadAttribute(attrlist *ProcThreadAttributeList, flags uint32, attr uintptr, value unsafe.Pointer, size uintptr, prevvalue unsafe.Pointer, returnedsize *uintptr) (err error) { + r1, _, e1 := syscall.Syscall9(procUpdateProcThreadAttribute.Addr(), 7, uintptr(unsafe.Pointer(attrlist)), uintptr(flags), uintptr(attr), uintptr(value), uintptr(size), uintptr(prevvalue), uintptr(unsafe.Pointer(returnedsize)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func VirtualAlloc(address uintptr, size uintptr, alloctype uint32, protect uint32) (value uintptr, err error) { + r0, _, e1 := syscall.Syscall6(procVirtualAlloc.Addr(), 4, uintptr(address), uintptr(size), uintptr(alloctype), uintptr(protect), 0, 0) + value = uintptr(r0) + if value == 0 { + err = errnoErr(e1) + } + return + } func VirtualFree(address uintptr, size uintptr, freetype uint32) (err error) { + r1, _, e1 := syscall.Syscall(procVirtualFree.Addr(), 3, uintptr(address), uintptr(size), uintptr(freetype)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func VirtualLock(addr uintptr, length uintptr) (err error) { + r1, _, e1 := syscall.Syscall(procVirtualLock.Addr(), 2, uintptr(addr), uintptr(length), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func VirtualProtect(address uintptr, size uintptr, newprotect uint32, oldprotect *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procVirtualProtect.Addr(), 4, uintptr(address), uintptr(size), uintptr(newprotect), uintptr(unsafe.Pointer(oldprotect)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func VirtualProtectEx(process Handle, address uintptr, size uintptr, newProtect uint32, oldProtect *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procVirtualProtectEx.Addr(), 5, uintptr(process), uintptr(address), uintptr(size), uintptr(newProtect), uintptr(unsafe.Pointer(oldProtect)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func VirtualQuery(address uintptr, buffer *MemoryBasicInformation, length uintptr) (err error) { + r1, _, e1 := syscall.Syscall(procVirtualQuery.Addr(), 3, uintptr(address), uintptr(unsafe.Pointer(buffer)), uintptr(length)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func VirtualQueryEx(process Handle, address uintptr, buffer *MemoryBasicInformation, length uintptr) (err error) { + r1, _, e1 := syscall.Syscall6(procVirtualQueryEx.Addr(), 4, uintptr(process), uintptr(address), uintptr(unsafe.Pointer(buffer)), uintptr(length), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func VirtualUnlock(addr uintptr, length uintptr) (err error) { + r1, _, e1 := syscall.Syscall(procVirtualUnlock.Addr(), 2, uintptr(addr), uintptr(length), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func WTSGetActiveConsoleSessionId() (sessionID uint32) { + r0, _, _ := syscall.Syscall(procWTSGetActiveConsoleSessionId.Addr(), 0, 0, 0, 0) + sessionID = uint32(r0) + return + } func WaitCommEvent(handle Handle, lpEvtMask *uint32, lpOverlapped *Overlapped) (err error) { + r1, _, e1 := syscall.Syscall(procWaitCommEvent.Addr(), 3, uintptr(handle), uintptr(unsafe.Pointer(lpEvtMask)), uintptr(unsafe.Pointer(lpOverlapped))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func waitForMultipleObjects(count uint32, handles uintptr, waitAll bool, waitMilliseconds uint32) (event uint32, err error) { + var _p0 uint32 + if waitAll { + _p0 = 1 + } + r0, _, e1 := syscall.Syscall6(procWaitForMultipleObjects.Addr(), 4, uintptr(count), uintptr(handles), uintptr(_p0), uintptr(waitMilliseconds), 0, 0) + event = uint32(r0) + if event == 0xffffffff { + err = errnoErr(e1) + } + return + } func WaitForSingleObject(handle Handle, waitMilliseconds uint32) (event uint32, err error) { + r0, _, e1 := syscall.Syscall(procWaitForSingleObject.Addr(), 2, uintptr(handle), uintptr(waitMilliseconds), 0) + event = uint32(r0) + if event == 0xffffffff { + err = errnoErr(e1) + } + return + } func WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error) { + r1, _, e1 := syscall.Syscall6(procWriteConsoleW.Addr(), 5, uintptr(console), uintptr(unsafe.Pointer(buf)), uintptr(towrite), uintptr(unsafe.Pointer(written)), uintptr(unsafe.Pointer(reserved)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func writeFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) { + var _p0 *byte + if len(buf) > 0 { + _p0 = &buf[0] + } + r1, _, e1 := syscall.Syscall6(procWriteFile.Addr(), 5, uintptr(handle), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(unsafe.Pointer(done)), uintptr(unsafe.Pointer(overlapped)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func WriteProcessMemory(process Handle, baseAddress uintptr, buffer *byte, size uintptr, numberOfBytesWritten *uintptr) (err error) { + r1, _, e1 := syscall.Syscall6(procWriteProcessMemory.Addr(), 5, uintptr(process), uintptr(baseAddress), uintptr(unsafe.Pointer(buffer)), uintptr(size), uintptr(unsafe.Pointer(numberOfBytesWritten)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func AcceptEx(ls Handle, as Handle, buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, recvd *uint32, overlapped *Overlapped) (err error) { + r1, _, e1 := syscall.Syscall9(procAcceptEx.Addr(), 8, uintptr(ls), uintptr(as), uintptr(unsafe.Pointer(buf)), uintptr(rxdatalen), uintptr(laddrlen), uintptr(raddrlen), uintptr(unsafe.Pointer(recvd)), uintptr(unsafe.Pointer(overlapped)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetAcceptExSockaddrs(buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, lrsa **RawSockaddrAny, lrsalen *int32, rrsa **RawSockaddrAny, rrsalen *int32) { + syscall.Syscall9(procGetAcceptExSockaddrs.Addr(), 8, uintptr(unsafe.Pointer(buf)), uintptr(rxdatalen), uintptr(laddrlen), uintptr(raddrlen), uintptr(unsafe.Pointer(lrsa)), uintptr(unsafe.Pointer(lrsalen)), uintptr(unsafe.Pointer(rrsa)), uintptr(unsafe.Pointer(rrsalen)), 0) + return + } func TransmitFile(s Handle, handle Handle, bytesToWrite uint32, bytsPerSend uint32, overlapped *Overlapped, transmitFileBuf *TransmitFileBuffers, flags uint32) (err error) { + r1, _, e1 := syscall.Syscall9(procTransmitFile.Addr(), 7, uintptr(s), uintptr(handle), uintptr(bytesToWrite), uintptr(bytsPerSend), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(transmitFileBuf)), uintptr(flags), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func NetApiBufferFree(buf *byte) (neterr error) { + r0, _, _ := syscall.Syscall(procNetApiBufferFree.Addr(), 1, uintptr(unsafe.Pointer(buf)), 0, 0) + if r0 != 0 { + neterr = syscall.Errno(r0) + } + return + } func NetGetJoinInformation(server *uint16, name **uint16, bufType *uint32) (neterr error) { + r0, _, _ := syscall.Syscall(procNetGetJoinInformation.Addr(), 3, uintptr(unsafe.Pointer(server)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(bufType))) + if r0 != 0 { + neterr = syscall.Errno(r0) + } + return + } func NetUserGetInfo(serverName *uint16, userName *uint16, level uint32, buf **byte) (neterr error) { + r0, _, _ := syscall.Syscall6(procNetUserGetInfo.Addr(), 4, uintptr(unsafe.Pointer(serverName)), uintptr(unsafe.Pointer(userName)), uintptr(level), uintptr(unsafe.Pointer(buf)), 0, 0) + if r0 != 0 { + neterr = syscall.Errno(r0) + } + return + } func NtCreateFile(handle *Handle, access uint32, oa *OBJECT_ATTRIBUTES, iosb *IO_STATUS_BLOCK, allocationSize *int64, attributes uint32, share uint32, disposition uint32, options uint32, eabuffer uintptr, ealength uint32) (ntstatus error) { + r0, _, _ := syscall.Syscall12(procNtCreateFile.Addr(), 11, uintptr(unsafe.Pointer(handle)), uintptr(access), uintptr(unsafe.Pointer(oa)), uintptr(unsafe.Pointer(iosb)), uintptr(unsafe.Pointer(allocationSize)), uintptr(attributes), uintptr(share), uintptr(disposition), uintptr(options), uintptr(eabuffer), uintptr(ealength), 0) + if r0 != 0 { + ntstatus = NTStatus(r0) + } + return + } func NtCreateNamedPipeFile(pipe *Handle, access uint32, oa *OBJECT_ATTRIBUTES, iosb *IO_STATUS_BLOCK, share uint32, disposition uint32, options uint32, typ uint32, readMode uint32, completionMode uint32, maxInstances uint32, inboundQuota uint32, outputQuota uint32, timeout *int64) (ntstatus error) { + r0, _, _ := syscall.Syscall15(procNtCreateNamedPipeFile.Addr(), 14, uintptr(unsafe.Pointer(pipe)), uintptr(access), uintptr(unsafe.Pointer(oa)), uintptr(unsafe.Pointer(iosb)), uintptr(share), uintptr(disposition), uintptr(options), uintptr(typ), uintptr(readMode), uintptr(completionMode), uintptr(maxInstances), uintptr(inboundQuota), uintptr(outputQuota), uintptr(unsafe.Pointer(timeout)), 0) + if r0 != 0 { + ntstatus = NTStatus(r0) + } + return + } func NtQueryInformationProcess(proc Handle, procInfoClass int32, procInfo unsafe.Pointer, procInfoLen uint32, retLen *uint32) (ntstatus error) { + r0, _, _ := syscall.Syscall6(procNtQueryInformationProcess.Addr(), 5, uintptr(proc), uintptr(procInfoClass), uintptr(procInfo), uintptr(procInfoLen), uintptr(unsafe.Pointer(retLen)), 0) + if r0 != 0 { + ntstatus = NTStatus(r0) + } + return + } func NtQuerySystemInformation(sysInfoClass int32, sysInfo unsafe.Pointer, sysInfoLen uint32, retLen *uint32) (ntstatus error) { + r0, _, _ := syscall.Syscall6(procNtQuerySystemInformation.Addr(), 4, uintptr(sysInfoClass), uintptr(sysInfo), uintptr(sysInfoLen), uintptr(unsafe.Pointer(retLen)), 0, 0) + if r0 != 0 { + ntstatus = NTStatus(r0) + } + return + } func NtSetInformationFile(handle Handle, iosb *IO_STATUS_BLOCK, inBuffer *byte, inBufferLen uint32, class uint32) (ntstatus error) { + r0, _, _ := syscall.Syscall6(procNtSetInformationFile.Addr(), 5, uintptr(handle), uintptr(unsafe.Pointer(iosb)), uintptr(unsafe.Pointer(inBuffer)), uintptr(inBufferLen), uintptr(class), 0) + if r0 != 0 { + ntstatus = NTStatus(r0) + } + return + } func NtSetInformationProcess(proc Handle, procInfoClass int32, procInfo unsafe.Pointer, procInfoLen uint32) (ntstatus error) { + r0, _, _ := syscall.Syscall6(procNtSetInformationProcess.Addr(), 4, uintptr(proc), uintptr(procInfoClass), uintptr(procInfo), uintptr(procInfoLen), 0, 0) + if r0 != 0 { + ntstatus = NTStatus(r0) + } + return + } func NtSetSystemInformation(sysInfoClass int32, sysInfo unsafe.Pointer, sysInfoLen uint32) (ntstatus error) { + r0, _, _ := syscall.Syscall(procNtSetSystemInformation.Addr(), 3, uintptr(sysInfoClass), uintptr(sysInfo), uintptr(sysInfoLen)) + if r0 != 0 { + ntstatus = NTStatus(r0) + } + return + } func RtlAddFunctionTable(functionTable *RUNTIME_FUNCTION, entryCount uint32, baseAddress uintptr) (ret bool) { + r0, _, _ := syscall.Syscall(procRtlAddFunctionTable.Addr(), 3, uintptr(unsafe.Pointer(functionTable)), uintptr(entryCount), uintptr(baseAddress)) + ret = r0 != 0 + return + } func RtlDefaultNpAcl(acl **ACL) (ntstatus error) { + r0, _, _ := syscall.Syscall(procRtlDefaultNpAcl.Addr(), 1, uintptr(unsafe.Pointer(acl)), 0, 0) + if r0 != 0 { + ntstatus = NTStatus(r0) + } + return + } func RtlDeleteFunctionTable(functionTable *RUNTIME_FUNCTION) (ret bool) { + r0, _, _ := syscall.Syscall(procRtlDeleteFunctionTable.Addr(), 1, uintptr(unsafe.Pointer(functionTable)), 0, 0) + ret = r0 != 0 + return + } func RtlDosPathNameToNtPathName(dosName *uint16, ntName *NTUnicodeString, ntFileNamePart *uint16, relativeName *RTL_RELATIVE_NAME) (ntstatus error) { + r0, _, _ := syscall.Syscall6(procRtlDosPathNameToNtPathName_U_WithStatus.Addr(), 4, uintptr(unsafe.Pointer(dosName)), uintptr(unsafe.Pointer(ntName)), uintptr(unsafe.Pointer(ntFileNamePart)), uintptr(unsafe.Pointer(relativeName)), 0, 0) + if r0 != 0 { + ntstatus = NTStatus(r0) + } + return + } func RtlDosPathNameToRelativeNtPathName(dosName *uint16, ntName *NTUnicodeString, ntFileNamePart *uint16, relativeName *RTL_RELATIVE_NAME) (ntstatus error) { + r0, _, _ := syscall.Syscall6(procRtlDosPathNameToRelativeNtPathName_U_WithStatus.Addr(), 4, uintptr(unsafe.Pointer(dosName)), uintptr(unsafe.Pointer(ntName)), uintptr(unsafe.Pointer(ntFileNamePart)), uintptr(unsafe.Pointer(relativeName)), 0, 0) + if r0 != 0 { + ntstatus = NTStatus(r0) + } + return + } func RtlGetCurrentPeb() (peb *PEB) { + r0, _, _ := syscall.Syscall(procRtlGetCurrentPeb.Addr(), 0, 0, 0, 0) + peb = (*PEB)(unsafe.Pointer(r0)) + return + } func rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32) { + syscall.Syscall(procRtlGetNtVersionNumbers.Addr(), 3, uintptr(unsafe.Pointer(majorVersion)), uintptr(unsafe.Pointer(minorVersion)), uintptr(unsafe.Pointer(buildNumber))) + return + } func rtlGetVersion(info *OsVersionInfoEx) (ntstatus error) { + r0, _, _ := syscall.Syscall(procRtlGetVersion.Addr(), 1, uintptr(unsafe.Pointer(info)), 0, 0) + if r0 != 0 { + ntstatus = NTStatus(r0) + } + return + } func RtlInitString(destinationString *NTString, sourceString *byte) { + syscall.Syscall(procRtlInitString.Addr(), 2, uintptr(unsafe.Pointer(destinationString)), uintptr(unsafe.Pointer(sourceString)), 0) + return + } func RtlInitUnicodeString(destinationString *NTUnicodeString, sourceString *uint16) { + syscall.Syscall(procRtlInitUnicodeString.Addr(), 2, uintptr(unsafe.Pointer(destinationString)), uintptr(unsafe.Pointer(sourceString)), 0) + return + } func rtlNtStatusToDosErrorNoTeb(ntstatus NTStatus) (ret syscall.Errno) { + r0, _, _ := syscall.Syscall(procRtlNtStatusToDosErrorNoTeb.Addr(), 1, uintptr(ntstatus), 0, 0) + ret = syscall.Errno(r0) + return + } func clsidFromString(lpsz *uint16, pclsid *GUID) (ret error) { + r0, _, _ := syscall.Syscall(procCLSIDFromString.Addr(), 2, uintptr(unsafe.Pointer(lpsz)), uintptr(unsafe.Pointer(pclsid)), 0) + if r0 != 0 { + ret = syscall.Errno(r0) + } + return + } func coCreateGuid(pguid *GUID) (ret error) { + r0, _, _ := syscall.Syscall(procCoCreateGuid.Addr(), 1, uintptr(unsafe.Pointer(pguid)), 0, 0) + if r0 != 0 { + ret = syscall.Errno(r0) + } + return + } func CoGetObject(name *uint16, bindOpts *BIND_OPTS3, guid *GUID, functionTable **uintptr) (ret error) { + r0, _, _ := syscall.Syscall6(procCoGetObject.Addr(), 4, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(bindOpts)), uintptr(unsafe.Pointer(guid)), uintptr(unsafe.Pointer(functionTable)), 0, 0) + if r0 != 0 { + ret = syscall.Errno(r0) + } + return + } func CoInitializeEx(reserved uintptr, coInit uint32) (ret error) { + r0, _, _ := syscall.Syscall(procCoInitializeEx.Addr(), 2, uintptr(reserved), uintptr(coInit), 0) + if r0 != 0 { + ret = syscall.Errno(r0) + } + return + } func CoTaskMemFree(address unsafe.Pointer) { + syscall.Syscall(procCoTaskMemFree.Addr(), 1, uintptr(address), 0, 0) + return + } func CoUninitialize() { + syscall.Syscall(procCoUninitialize.Addr(), 0, 0, 0, 0) + return + } func stringFromGUID2(rguid *GUID, lpsz *uint16, cchMax int32) (chars int32) { + r0, _, _ := syscall.Syscall(procStringFromGUID2.Addr(), 3, uintptr(unsafe.Pointer(rguid)), uintptr(unsafe.Pointer(lpsz)), uintptr(cchMax)) + chars = int32(r0) + return + } func EnumProcessModules(process Handle, module *Handle, cb uint32, cbNeeded *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procEnumProcessModules.Addr(), 4, uintptr(process), uintptr(unsafe.Pointer(module)), uintptr(cb), uintptr(unsafe.Pointer(cbNeeded)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func EnumProcessModulesEx(process Handle, module *Handle, cb uint32, cbNeeded *uint32, filterFlag uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procEnumProcessModulesEx.Addr(), 5, uintptr(process), uintptr(unsafe.Pointer(module)), uintptr(cb), uintptr(unsafe.Pointer(cbNeeded)), uintptr(filterFlag), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func enumProcesses(processIds *uint32, nSize uint32, bytesReturned *uint32) (err error) { + r1, _, e1 := syscall.Syscall(procEnumProcesses.Addr(), 3, uintptr(unsafe.Pointer(processIds)), uintptr(nSize), uintptr(unsafe.Pointer(bytesReturned))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetModuleBaseName(process Handle, module Handle, baseName *uint16, size uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procGetModuleBaseNameW.Addr(), 4, uintptr(process), uintptr(module), uintptr(unsafe.Pointer(baseName)), uintptr(size), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetModuleFileNameEx(process Handle, module Handle, filename *uint16, size uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procGetModuleFileNameExW.Addr(), 4, uintptr(process), uintptr(module), uintptr(unsafe.Pointer(filename)), uintptr(size), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetModuleInformation(process Handle, module Handle, modinfo *ModuleInfo, cb uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procGetModuleInformation.Addr(), 4, uintptr(process), uintptr(module), uintptr(unsafe.Pointer(modinfo)), uintptr(cb), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func QueryWorkingSetEx(process Handle, pv uintptr, cb uint32) (err error) { + r1, _, e1 := syscall.Syscall(procQueryWorkingSetEx.Addr(), 3, uintptr(process), uintptr(pv), uintptr(cb)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SubscribeServiceChangeNotifications(service Handle, eventType uint32, callback uintptr, callbackCtx uintptr, subscription *uintptr) (ret error) { + ret = procSubscribeServiceChangeNotifications.Find() + if ret != nil { + return + } + r0, _, _ := syscall.Syscall6(procSubscribeServiceChangeNotifications.Addr(), 5, uintptr(service), uintptr(eventType), uintptr(callback), uintptr(callbackCtx), uintptr(unsafe.Pointer(subscription)), 0) + if r0 != 0 { + ret = syscall.Errno(r0) + } + return + } func UnsubscribeServiceChangeNotifications(subscription uintptr) (err error) { + err = procUnsubscribeServiceChangeNotifications.Find() + if err != nil { + return + } + syscall.Syscall(procUnsubscribeServiceChangeNotifications.Addr(), 1, uintptr(subscription), 0, 0) + return + } func GetUserNameEx(nameFormat uint32, nameBuffre *uint16, nSize *uint32) (err error) { + r1, _, e1 := syscall.Syscall(procGetUserNameExW.Addr(), 3, uintptr(nameFormat), uintptr(unsafe.Pointer(nameBuffre)), uintptr(unsafe.Pointer(nSize))) + if r1&0xff == 0 { + err = errnoErr(e1) + } + return + } func TranslateName(accName *uint16, accNameFormat uint32, desiredNameFormat uint32, translatedName *uint16, nSize *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procTranslateNameW.Addr(), 5, uintptr(unsafe.Pointer(accName)), uintptr(accNameFormat), uintptr(desiredNameFormat), uintptr(unsafe.Pointer(translatedName)), uintptr(unsafe.Pointer(nSize)), 0) + if r1&0xff == 0 { + err = errnoErr(e1) + } + return + } func SetupDiBuildDriverInfoList(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, driverType SPDIT) (err error) { + r1, _, e1 := syscall.Syscall(procSetupDiBuildDriverInfoList.Addr(), 3, uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(driverType)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetupDiCallClassInstaller(installFunction DI_FUNCTION, deviceInfoSet DevInfo, deviceInfoData *DevInfoData) (err error) { + r1, _, e1 := syscall.Syscall(procSetupDiCallClassInstaller.Addr(), 3, uintptr(installFunction), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetupDiCancelDriverInfoSearch(deviceInfoSet DevInfo) (err error) { + r1, _, e1 := syscall.Syscall(procSetupDiCancelDriverInfoSearch.Addr(), 1, uintptr(deviceInfoSet), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setupDiClassGuidsFromNameEx(className *uint16, classGuidList *GUID, classGuidListSize uint32, requiredSize *uint32, machineName *uint16, reserved uintptr) (err error) { + r1, _, e1 := syscall.Syscall6(procSetupDiClassGuidsFromNameExW.Addr(), 6, uintptr(unsafe.Pointer(className)), uintptr(unsafe.Pointer(classGuidList)), uintptr(classGuidListSize), uintptr(unsafe.Pointer(requiredSize)), uintptr(unsafe.Pointer(machineName)), uintptr(reserved)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setupDiClassNameFromGuidEx(classGUID *GUID, className *uint16, classNameSize uint32, requiredSize *uint32, machineName *uint16, reserved uintptr) (err error) { + r1, _, e1 := syscall.Syscall6(procSetupDiClassNameFromGuidExW.Addr(), 6, uintptr(unsafe.Pointer(classGUID)), uintptr(unsafe.Pointer(className)), uintptr(classNameSize), uintptr(unsafe.Pointer(requiredSize)), uintptr(unsafe.Pointer(machineName)), uintptr(reserved)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setupDiCreateDeviceInfoListEx(classGUID *GUID, hwndParent uintptr, machineName *uint16, reserved uintptr) (handle DevInfo, err error) { + r0, _, e1 := syscall.Syscall6(procSetupDiCreateDeviceInfoListExW.Addr(), 4, uintptr(unsafe.Pointer(classGUID)), uintptr(hwndParent), uintptr(unsafe.Pointer(machineName)), uintptr(reserved), 0, 0) + handle = DevInfo(r0) + if handle == DevInfo(InvalidHandle) { + err = errnoErr(e1) + } + return + } func setupDiCreateDeviceInfo(deviceInfoSet DevInfo, DeviceName *uint16, classGUID *GUID, DeviceDescription *uint16, hwndParent uintptr, CreationFlags DICD, deviceInfoData *DevInfoData) (err error) { + r1, _, e1 := syscall.Syscall9(procSetupDiCreateDeviceInfoW.Addr(), 7, uintptr(deviceInfoSet), uintptr(unsafe.Pointer(DeviceName)), uintptr(unsafe.Pointer(classGUID)), uintptr(unsafe.Pointer(DeviceDescription)), uintptr(hwndParent), uintptr(CreationFlags), uintptr(unsafe.Pointer(deviceInfoData)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetupDiDestroyDeviceInfoList(deviceInfoSet DevInfo) (err error) { + r1, _, e1 := syscall.Syscall(procSetupDiDestroyDeviceInfoList.Addr(), 1, uintptr(deviceInfoSet), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetupDiDestroyDriverInfoList(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, driverType SPDIT) (err error) { + r1, _, e1 := syscall.Syscall(procSetupDiDestroyDriverInfoList.Addr(), 3, uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(driverType)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setupDiEnumDeviceInfo(deviceInfoSet DevInfo, memberIndex uint32, deviceInfoData *DevInfoData) (err error) { + r1, _, e1 := syscall.Syscall(procSetupDiEnumDeviceInfo.Addr(), 3, uintptr(deviceInfoSet), uintptr(memberIndex), uintptr(unsafe.Pointer(deviceInfoData))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setupDiEnumDriverInfo(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, driverType SPDIT, memberIndex uint32, driverInfoData *DrvInfoData) (err error) { + r1, _, e1 := syscall.Syscall6(procSetupDiEnumDriverInfoW.Addr(), 5, uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(driverType), uintptr(memberIndex), uintptr(unsafe.Pointer(driverInfoData)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setupDiGetClassDevsEx(classGUID *GUID, Enumerator *uint16, hwndParent uintptr, Flags DIGCF, deviceInfoSet DevInfo, machineName *uint16, reserved uintptr) (handle DevInfo, err error) { + r0, _, e1 := syscall.Syscall9(procSetupDiGetClassDevsExW.Addr(), 7, uintptr(unsafe.Pointer(classGUID)), uintptr(unsafe.Pointer(Enumerator)), uintptr(hwndParent), uintptr(Flags), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(machineName)), uintptr(reserved), 0, 0) + handle = DevInfo(r0) + if handle == DevInfo(InvalidHandle) { + err = errnoErr(e1) + } + return + } func SetupDiGetClassInstallParams(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, classInstallParams *ClassInstallHeader, classInstallParamsSize uint32, requiredSize *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procSetupDiGetClassInstallParamsW.Addr(), 5, uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(unsafe.Pointer(classInstallParams)), uintptr(classInstallParamsSize), uintptr(unsafe.Pointer(requiredSize)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setupDiGetDeviceInfoListDetail(deviceInfoSet DevInfo, deviceInfoSetDetailData *DevInfoListDetailData) (err error) { + r1, _, e1 := syscall.Syscall(procSetupDiGetDeviceInfoListDetailW.Addr(), 2, uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoSetDetailData)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setupDiGetDeviceInstallParams(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, deviceInstallParams *DevInstallParams) (err error) { + r1, _, e1 := syscall.Syscall(procSetupDiGetDeviceInstallParamsW.Addr(), 3, uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(unsafe.Pointer(deviceInstallParams))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setupDiGetDeviceInstanceId(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, instanceId *uint16, instanceIdSize uint32, instanceIdRequiredSize *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procSetupDiGetDeviceInstanceIdW.Addr(), 5, uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(unsafe.Pointer(instanceId)), uintptr(instanceIdSize), uintptr(unsafe.Pointer(instanceIdRequiredSize)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setupDiGetDeviceProperty(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, propertyKey *DEVPROPKEY, propertyType *DEVPROPTYPE, propertyBuffer *byte, propertyBufferSize uint32, requiredSize *uint32, flags uint32) (err error) { + r1, _, e1 := syscall.Syscall9(procSetupDiGetDevicePropertyW.Addr(), 8, uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(unsafe.Pointer(propertyKey)), uintptr(unsafe.Pointer(propertyType)), uintptr(unsafe.Pointer(propertyBuffer)), uintptr(propertyBufferSize), uintptr(unsafe.Pointer(requiredSize)), uintptr(flags), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setupDiGetDeviceRegistryProperty(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, property SPDRP, propertyRegDataType *uint32, propertyBuffer *byte, propertyBufferSize uint32, requiredSize *uint32) (err error) { + r1, _, e1 := syscall.Syscall9(procSetupDiGetDeviceRegistryPropertyW.Addr(), 7, uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(property), uintptr(unsafe.Pointer(propertyRegDataType)), uintptr(unsafe.Pointer(propertyBuffer)), uintptr(propertyBufferSize), uintptr(unsafe.Pointer(requiredSize)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setupDiGetDriverInfoDetail(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, driverInfoData *DrvInfoData, driverInfoDetailData *DrvInfoDetailData, driverInfoDetailDataSize uint32, requiredSize *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procSetupDiGetDriverInfoDetailW.Addr(), 6, uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(unsafe.Pointer(driverInfoData)), uintptr(unsafe.Pointer(driverInfoDetailData)), uintptr(driverInfoDetailDataSize), uintptr(unsafe.Pointer(requiredSize))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setupDiGetSelectedDevice(deviceInfoSet DevInfo, deviceInfoData *DevInfoData) (err error) { + r1, _, e1 := syscall.Syscall(procSetupDiGetSelectedDevice.Addr(), 2, uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setupDiGetSelectedDriver(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, driverInfoData *DrvInfoData) (err error) { + r1, _, e1 := syscall.Syscall(procSetupDiGetSelectedDriverW.Addr(), 3, uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(unsafe.Pointer(driverInfoData))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetupDiOpenDevRegKey(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, Scope DICS_FLAG, HwProfile uint32, KeyType DIREG, samDesired uint32) (key Handle, err error) { + r0, _, e1 := syscall.Syscall6(procSetupDiOpenDevRegKey.Addr(), 6, uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(Scope), uintptr(HwProfile), uintptr(KeyType), uintptr(samDesired)) + key = Handle(r0) + if key == InvalidHandle { + err = errnoErr(e1) + } + return + } func SetupDiSetClassInstallParams(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, classInstallParams *ClassInstallHeader, classInstallParamsSize uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procSetupDiSetClassInstallParamsW.Addr(), 4, uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(unsafe.Pointer(classInstallParams)), uintptr(classInstallParamsSize), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetupDiSetDeviceInstallParams(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, deviceInstallParams *DevInstallParams) (err error) { + r1, _, e1 := syscall.Syscall(procSetupDiSetDeviceInstallParamsW.Addr(), 3, uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(unsafe.Pointer(deviceInstallParams))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setupDiSetDeviceRegistryProperty(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, property SPDRP, propertyBuffer *byte, propertyBufferSize uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procSetupDiSetDeviceRegistryPropertyW.Addr(), 5, uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(property), uintptr(unsafe.Pointer(propertyBuffer)), uintptr(propertyBufferSize), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetupDiSetSelectedDevice(deviceInfoSet DevInfo, deviceInfoData *DevInfoData) (err error) { + r1, _, e1 := syscall.Syscall(procSetupDiSetSelectedDevice.Addr(), 2, uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func SetupDiSetSelectedDriver(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, driverInfoData *DrvInfoData) (err error) { + r1, _, e1 := syscall.Syscall(procSetupDiSetSelectedDriverW.Addr(), 3, uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(unsafe.Pointer(driverInfoData))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func setupUninstallOEMInf(infFileName *uint16, flags SUOI, reserved uintptr) (err error) { + r1, _, e1 := syscall.Syscall(procSetupUninstallOEMInfW.Addr(), 3, uintptr(unsafe.Pointer(infFileName)), uintptr(flags), uintptr(reserved)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func commandLineToArgv(cmd *uint16, argc *int32) (argv **uint16, err error) { + r0, _, e1 := syscall.Syscall(procCommandLineToArgvW.Addr(), 2, uintptr(unsafe.Pointer(cmd)), uintptr(unsafe.Pointer(argc)), 0) + argv = (**uint16)(unsafe.Pointer(r0)) + if argv == nil { + err = errnoErr(e1) + } + return + } func shGetKnownFolderPath(id *KNOWNFOLDERID, flags uint32, token Token, path **uint16) (ret error) { + r0, _, _ := syscall.Syscall6(procSHGetKnownFolderPath.Addr(), 4, uintptr(unsafe.Pointer(id)), uintptr(flags), uintptr(token), uintptr(unsafe.Pointer(path)), 0, 0) + if r0 != 0 { + ret = syscall.Errno(r0) + } + return + } func ShellExecute(hwnd Handle, verb *uint16, file *uint16, args *uint16, cwd *uint16, showCmd int32) (err error) { + r1, _, e1 := syscall.Syscall6(procShellExecuteW.Addr(), 6, uintptr(hwnd), uintptr(unsafe.Pointer(verb)), uintptr(unsafe.Pointer(file)), uintptr(unsafe.Pointer(args)), uintptr(unsafe.Pointer(cwd)), uintptr(showCmd)) + if r1 <= 32 { + err = errnoErr(e1) + } + return + } func EnumChildWindows(hwnd HWND, enumFunc uintptr, param unsafe.Pointer) { + syscall.Syscall(procEnumChildWindows.Addr(), 3, uintptr(hwnd), uintptr(enumFunc), uintptr(param)) + return + } func EnumWindows(enumFunc uintptr, param unsafe.Pointer) (err error) { + r1, _, e1 := syscall.Syscall(procEnumWindows.Addr(), 2, uintptr(enumFunc), uintptr(param), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func ExitWindowsEx(flags uint32, reason uint32) (err error) { + r1, _, e1 := syscall.Syscall(procExitWindowsEx.Addr(), 2, uintptr(flags), uintptr(reason), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetClassName(hwnd HWND, className *uint16, maxCount int32) (copied int32, err error) { + r0, _, e1 := syscall.Syscall(procGetClassNameW.Addr(), 3, uintptr(hwnd), uintptr(unsafe.Pointer(className)), uintptr(maxCount)) + copied = int32(r0) + if copied == 0 { + err = errnoErr(e1) + } + return + } func GetDesktopWindow() (hwnd HWND) { + r0, _, _ := syscall.Syscall(procGetDesktopWindow.Addr(), 0, 0, 0, 0) + hwnd = HWND(r0) + return + } func GetForegroundWindow() (hwnd HWND) { + r0, _, _ := syscall.Syscall(procGetForegroundWindow.Addr(), 0, 0, 0, 0) + hwnd = HWND(r0) + return + } func GetGUIThreadInfo(thread uint32, info *GUIThreadInfo) (err error) { + r1, _, e1 := syscall.Syscall(procGetGUIThreadInfo.Addr(), 2, uintptr(thread), uintptr(unsafe.Pointer(info)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetShellWindow() (shellWindow HWND) { + r0, _, _ := syscall.Syscall(procGetShellWindow.Addr(), 0, 0, 0, 0) + shellWindow = HWND(r0) + return + } func GetWindowThreadProcessId(hwnd HWND, pid *uint32) (tid uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetWindowThreadProcessId.Addr(), 2, uintptr(hwnd), uintptr(unsafe.Pointer(pid)), 0) + tid = uint32(r0) + if tid == 0 { + err = errnoErr(e1) + } + return + } func IsWindow(hwnd HWND) (isWindow bool) { + r0, _, _ := syscall.Syscall(procIsWindow.Addr(), 1, uintptr(hwnd), 0, 0) + isWindow = r0 != 0 + return + } func IsWindowUnicode(hwnd HWND) (isUnicode bool) { + r0, _, _ := syscall.Syscall(procIsWindowUnicode.Addr(), 1, uintptr(hwnd), 0, 0) + isUnicode = r0 != 0 + return + } func IsWindowVisible(hwnd HWND) (isVisible bool) { + r0, _, _ := syscall.Syscall(procIsWindowVisible.Addr(), 1, uintptr(hwnd), 0, 0) + isVisible = r0 != 0 + return + } func MessageBox(hwnd HWND, text *uint16, caption *uint16, boxtype uint32) (ret int32, err error) { + r0, _, e1 := syscall.Syscall6(procMessageBoxW.Addr(), 4, uintptr(hwnd), uintptr(unsafe.Pointer(text)), uintptr(unsafe.Pointer(caption)), uintptr(boxtype), 0, 0) + ret = int32(r0) + if ret == 0 { + err = errnoErr(e1) + } + return + } func CreateEnvironmentBlock(block **uint16, token Token, inheritExisting bool) (err error) { + var _p0 uint32 + if inheritExisting { + _p0 = 1 + } + r1, _, e1 := syscall.Syscall(procCreateEnvironmentBlock.Addr(), 3, uintptr(unsafe.Pointer(block)), uintptr(token), uintptr(_p0)) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func DestroyEnvironmentBlock(block *uint16) (err error) { + r1, _, e1 := syscall.Syscall(procDestroyEnvironmentBlock.Addr(), 1, uintptr(unsafe.Pointer(block)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetUserProfileDirectory(t Token, dir *uint16, dirLen *uint32) (err error) { + r1, _, e1 := syscall.Syscall(procGetUserProfileDirectoryW.Addr(), 3, uintptr(t), uintptr(unsafe.Pointer(dir)), uintptr(unsafe.Pointer(dirLen))) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func GetFileVersionInfoSize(filename string, zeroHandle *Handle) (bufSize uint32, err error) { + var _p0 *uint16 + _p0, err = syscall.UTF16PtrFromString(filename) + if err != nil { + return + } + return _GetFileVersionInfoSize(_p0, zeroHandle) + } func _GetFileVersionInfoSize(filename *uint16, zeroHandle *Handle) (bufSize uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetFileVersionInfoSizeW.Addr(), 2, uintptr(unsafe.Pointer(filename)), uintptr(unsafe.Pointer(zeroHandle)), 0) + bufSize = uint32(r0) + if bufSize == 0 { + err = errnoErr(e1) + } + return + } func GetFileVersionInfo(filename string, handle uint32, bufSize uint32, buffer unsafe.Pointer) (err error) { + var _p0 *uint16 + _p0, err = syscall.UTF16PtrFromString(filename) + if err != nil { + return + } + return _GetFileVersionInfo(_p0, handle, bufSize, buffer) + } func _GetFileVersionInfo(filename *uint16, handle uint32, bufSize uint32, buffer unsafe.Pointer) (err error) { + r1, _, e1 := syscall.Syscall6(procGetFileVersionInfoW.Addr(), 4, uintptr(unsafe.Pointer(filename)), uintptr(handle), uintptr(bufSize), uintptr(buffer), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func VerQueryValue(block unsafe.Pointer, subBlock string, pointerToBufferPointer unsafe.Pointer, bufSize *uint32) (err error) { + var _p0 *uint16 + _p0, err = syscall.UTF16PtrFromString(subBlock) + if err != nil { + return + } + return _VerQueryValue(block, _p0, pointerToBufferPointer, bufSize) + } func _VerQueryValue(block unsafe.Pointer, subBlock *uint16, pointerToBufferPointer unsafe.Pointer, bufSize *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procVerQueryValueW.Addr(), 4, uintptr(block), uintptr(unsafe.Pointer(subBlock)), uintptr(pointerToBufferPointer), uintptr(unsafe.Pointer(bufSize)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func TimeBeginPeriod(period uint32) (err error) { + r1, _, e1 := syscall.Syscall(proctimeBeginPeriod.Addr(), 1, uintptr(period), 0, 0) + if r1 != 0 { + err = errnoErr(e1) + } + return + } func TimeEndPeriod(period uint32) (err error) { + r1, _, e1 := syscall.Syscall(proctimeEndPeriod.Addr(), 1, uintptr(period), 0, 0) + if r1 != 0 { + err = errnoErr(e1) + } + return + } func WinVerifyTrustEx(hwnd HWND, actionId *GUID, data *WinTrustData) (ret error) { + r0, _, _ := syscall.Syscall(procWinVerifyTrustEx.Addr(), 3, uintptr(hwnd), uintptr(unsafe.Pointer(actionId)), uintptr(unsafe.Pointer(data))) + if r0 != 0 { + ret = syscall.Errno(r0) + } + return + } func FreeAddrInfoW(addrinfo *AddrinfoW) { + syscall.Syscall(procFreeAddrInfoW.Addr(), 1, uintptr(unsafe.Pointer(addrinfo)), 0, 0) + return + } func GetAddrInfoW(nodename *uint16, servicename *uint16, hints *AddrinfoW, result **AddrinfoW) (sockerr error) { + r0, _, _ := syscall.Syscall6(procGetAddrInfoW.Addr(), 4, uintptr(unsafe.Pointer(nodename)), uintptr(unsafe.Pointer(servicename)), uintptr(unsafe.Pointer(hints)), uintptr(unsafe.Pointer(result)), 0, 0) + if r0 != 0 { + sockerr = syscall.Errno(r0) + } + return + } func WSACleanup() (err error) { + r1, _, e1 := syscall.Syscall(procWSACleanup.Addr(), 0, 0, 0, 0) + if r1 == socket_error { + err = errnoErr(e1) + } + return + } func WSAEnumProtocols(protocols *int32, protocolBuffer *WSAProtocolInfo, bufferLength *uint32) (n int32, err error) { + r0, _, e1 := syscall.Syscall(procWSAEnumProtocolsW.Addr(), 3, uintptr(unsafe.Pointer(protocols)), uintptr(unsafe.Pointer(protocolBuffer)), uintptr(unsafe.Pointer(bufferLength))) + n = int32(r0) + if n == -1 { + err = errnoErr(e1) + } + return + } func WSAGetOverlappedResult(h Handle, o *Overlapped, bytes *uint32, wait bool, flags *uint32) (err error) { + var _p0 uint32 + if wait { + _p0 = 1 + } + r1, _, e1 := syscall.Syscall6(procWSAGetOverlappedResult.Addr(), 5, uintptr(h), uintptr(unsafe.Pointer(o)), uintptr(unsafe.Pointer(bytes)), uintptr(_p0), uintptr(unsafe.Pointer(flags)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func WSAIoctl(s Handle, iocc uint32, inbuf *byte, cbif uint32, outbuf *byte, cbob uint32, cbbr *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) { + r1, _, e1 := syscall.Syscall9(procWSAIoctl.Addr(), 9, uintptr(s), uintptr(iocc), uintptr(unsafe.Pointer(inbuf)), uintptr(cbif), uintptr(unsafe.Pointer(outbuf)), uintptr(cbob), uintptr(unsafe.Pointer(cbbr)), uintptr(unsafe.Pointer(overlapped)), uintptr(completionRoutine)) + if r1 == socket_error { + err = errnoErr(e1) + } + return + } func WSALookupServiceBegin(querySet *WSAQUERYSET, flags uint32, handle *Handle) (err error) { + r1, _, e1 := syscall.Syscall(procWSALookupServiceBeginW.Addr(), 3, uintptr(unsafe.Pointer(querySet)), uintptr(flags), uintptr(unsafe.Pointer(handle))) + if r1 == socket_error { + err = errnoErr(e1) + } + return + } func WSALookupServiceEnd(handle Handle) (err error) { + r1, _, e1 := syscall.Syscall(procWSALookupServiceEnd.Addr(), 1, uintptr(handle), 0, 0) + if r1 == socket_error { + err = errnoErr(e1) + } + return + } func WSALookupServiceNext(handle Handle, flags uint32, size *int32, querySet *WSAQUERYSET) (err error) { + r1, _, e1 := syscall.Syscall6(procWSALookupServiceNextW.Addr(), 4, uintptr(handle), uintptr(flags), uintptr(unsafe.Pointer(size)), uintptr(unsafe.Pointer(querySet)), 0, 0) + if r1 == socket_error { + err = errnoErr(e1) + } + return + } func WSARecv(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, overlapped *Overlapped, croutine *byte) (err error) { + r1, _, e1 := syscall.Syscall9(procWSARecv.Addr(), 7, uintptr(s), uintptr(unsafe.Pointer(bufs)), uintptr(bufcnt), uintptr(unsafe.Pointer(recvd)), uintptr(unsafe.Pointer(flags)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)), 0, 0) + if r1 == socket_error { + err = errnoErr(e1) + } + return + } func WSARecvFrom(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, from *RawSockaddrAny, fromlen *int32, overlapped *Overlapped, croutine *byte) (err error) { + r1, _, e1 := syscall.Syscall9(procWSARecvFrom.Addr(), 9, uintptr(s), uintptr(unsafe.Pointer(bufs)), uintptr(bufcnt), uintptr(unsafe.Pointer(recvd)), uintptr(unsafe.Pointer(flags)), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine))) + if r1 == socket_error { + err = errnoErr(e1) + } + return + } func WSASend(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, overlapped *Overlapped, croutine *byte) (err error) { + r1, _, e1 := syscall.Syscall9(procWSASend.Addr(), 7, uintptr(s), uintptr(unsafe.Pointer(bufs)), uintptr(bufcnt), uintptr(unsafe.Pointer(sent)), uintptr(flags), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)), 0, 0) + if r1 == socket_error { + err = errnoErr(e1) + } + return + } func WSASendTo(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to *RawSockaddrAny, tolen int32, overlapped *Overlapped, croutine *byte) (err error) { + r1, _, e1 := syscall.Syscall9(procWSASendTo.Addr(), 9, uintptr(s), uintptr(unsafe.Pointer(bufs)), uintptr(bufcnt), uintptr(unsafe.Pointer(sent)), uintptr(flags), uintptr(unsafe.Pointer(to)), uintptr(tolen), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine))) + if r1 == socket_error { + err = errnoErr(e1) + } + return + } func WSASocket(af int32, typ int32, protocol int32, protoInfo *WSAProtocolInfo, group uint32, flags uint32) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall6(procWSASocketW.Addr(), 6, uintptr(af), uintptr(typ), uintptr(protocol), uintptr(unsafe.Pointer(protoInfo)), uintptr(group), uintptr(flags)) + handle = Handle(r0) + if handle == InvalidHandle { + err = errnoErr(e1) + } + return + } func WSAStartup(verreq uint32, data *WSAData) (sockerr error) { + r0, _, _ := syscall.Syscall(procWSAStartup.Addr(), 2, uintptr(verreq), uintptr(unsafe.Pointer(data)), 0) + if r0 != 0 { + sockerr = syscall.Errno(r0) + } + return + } func bind(s Handle, name unsafe.Pointer, namelen int32) (err error) { + r1, _, e1 := syscall.Syscall(procbind.Addr(), 3, uintptr(s), uintptr(name), uintptr(namelen)) + if r1 == socket_error { + err = errnoErr(e1) + } + return + } func Closesocket(s Handle) (err error) { + r1, _, e1 := syscall.Syscall(procclosesocket.Addr(), 1, uintptr(s), 0, 0) + if r1 == socket_error { + err = errnoErr(e1) + } + return + } func connect(s Handle, name unsafe.Pointer, namelen int32) (err error) { + r1, _, e1 := syscall.Syscall(procconnect.Addr(), 3, uintptr(s), uintptr(name), uintptr(namelen)) + if r1 == socket_error { + err = errnoErr(e1) + } + return + } func GetHostByName(name string) (h *Hostent, err error) { + var _p0 *byte + _p0, err = syscall.BytePtrFromString(name) + if err != nil { + return + } + return _GetHostByName(_p0) + } func _GetHostByName(name *byte) (h *Hostent, err error) { + r0, _, e1 := syscall.Syscall(procgethostbyname.Addr(), 1, uintptr(unsafe.Pointer(name)), 0, 0) + h = (*Hostent)(unsafe.Pointer(r0)) + if h == nil { + err = errnoErr(e1) + } + return + } func getpeername(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) { + r1, _, e1 := syscall.Syscall(procgetpeername.Addr(), 3, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if r1 == socket_error { + err = errnoErr(e1) + } + return + } func GetProtoByName(name string) (p *Protoent, err error) { + var _p0 *byte + _p0, err = syscall.BytePtrFromString(name) + if err != nil { + return + } + return _GetProtoByName(_p0) + } func _GetProtoByName(name *byte) (p *Protoent, err error) { + r0, _, e1 := syscall.Syscall(procgetprotobyname.Addr(), 1, uintptr(unsafe.Pointer(name)), 0, 0) + p = (*Protoent)(unsafe.Pointer(r0)) + if p == nil { + err = errnoErr(e1) + } + return + } func GetServByName(name string, proto string) (s *Servent, err error) { + var _p0 *byte + _p0, err = syscall.BytePtrFromString(name) + if err != nil { + return + } + var _p1 *byte + _p1, err = syscall.BytePtrFromString(proto) + if err != nil { + return + } + return _GetServByName(_p0, _p1) + } func _GetServByName(name *byte, proto *byte) (s *Servent, err error) { + r0, _, e1 := syscall.Syscall(procgetservbyname.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(proto)), 0) + s = (*Servent)(unsafe.Pointer(r0)) + if s == nil { + err = errnoErr(e1) + } + return + } func getsockname(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) { + r1, _, e1 := syscall.Syscall(procgetsockname.Addr(), 3, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if r1 == socket_error { + err = errnoErr(e1) + } + return + } func Getsockopt(s Handle, level int32, optname int32, optval *byte, optlen *int32) (err error) { + r1, _, e1 := syscall.Syscall6(procgetsockopt.Addr(), 5, uintptr(s), uintptr(level), uintptr(optname), uintptr(unsafe.Pointer(optval)), uintptr(unsafe.Pointer(optlen)), 0) + if r1 == socket_error { + err = errnoErr(e1) + } + return + } func listen(s Handle, backlog int32) (err error) { + r1, _, e1 := syscall.Syscall(proclisten.Addr(), 2, uintptr(s), uintptr(backlog), 0) + if r1 == socket_error { + err = errnoErr(e1) + } + return + } func Ntohs(netshort uint16) (u uint16) { + r0, _, _ := syscall.Syscall(procntohs.Addr(), 1, uintptr(netshort), 0, 0) + u = uint16(r0) + return + } func recvfrom(s Handle, buf []byte, flags int32, from *RawSockaddrAny, fromlen *int32) (n int32, err error) { + var _p0 *byte + if len(buf) > 0 { + _p0 = &buf[0] + } + r0, _, e1 := syscall.Syscall6(procrecvfrom.Addr(), 6, uintptr(s), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + n = int32(r0) + if n == -1 { + err = errnoErr(e1) + } + return + } func sendto(s Handle, buf []byte, flags int32, to unsafe.Pointer, tolen int32) (err error) { + var _p0 *byte + if len(buf) > 0 { + _p0 = &buf[0] + } + r1, _, e1 := syscall.Syscall6(procsendto.Addr(), 6, uintptr(s), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(tolen)) + if r1 == socket_error { + err = errnoErr(e1) + } + return + } func Setsockopt(s Handle, level int32, optname int32, optval *byte, optlen int32) (err error) { + r1, _, e1 := syscall.Syscall6(procsetsockopt.Addr(), 5, uintptr(s), uintptr(level), uintptr(optname), uintptr(unsafe.Pointer(optval)), uintptr(optlen), 0) + if r1 == socket_error { + err = errnoErr(e1) + } + return + } func shutdown(s Handle, how int32) (err error) { + r1, _, e1 := syscall.Syscall(procshutdown.Addr(), 2, uintptr(s), uintptr(how), 0) + if r1 == socket_error { + err = errnoErr(e1) + } + return + } func socket(af int32, typ int32, protocol int32) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall(procsocket.Addr(), 3, uintptr(af), uintptr(typ), uintptr(protocol)) + handle = Handle(r0) + if handle == InvalidHandle { + err = errnoErr(e1) + } + return + } func WTSEnumerateSessions(handle Handle, reserved uint32, version uint32, sessions **WTS_SESSION_INFO, count *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procWTSEnumerateSessionsW.Addr(), 5, uintptr(handle), uintptr(reserved), uintptr(version), uintptr(unsafe.Pointer(sessions)), uintptr(unsafe.Pointer(count)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } func WTSFreeMemory(ptr uintptr) { + syscall.Syscall(procWTSFreeMemory.Addr(), 1, uintptr(ptr), 0, 0) + return + } func WTSQueryUserToken(session uint32, token *Token) (err error) { + r1, _, e1 := syscall.Syscall(procWTSQueryUserToken.Addr(), 2, uintptr(session), uintptr(unsafe.Pointer(token)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return + } diff --git a/vendor/golang.org/x/text/secure/bidirule/bidirule.go b/vendor/golang.org/x/text/secure/bidirule/bidirule.go index e2b70f7..4e495b4 100644 --- a/vendor/golang.org/x/text/secure/bidirule/bidirule.go +++ b/vendor/golang.org/x/text/secure/bidirule/bidirule.go @@ -1,11 +1,17 @@ // Copyright 2016 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Package bidirule implements the Bidi Rule defined by RFC 5893. + // + // This package is under development. The API may change without notice and + // without preserving backward compatibility. + package bidirule import ( @@ -17,320 +23,574 @@ import ( ) // This file contains an implementation of RFC 5893: Right-to-Left Scripts for + // Internationalized Domain Names for Applications (IDNA) + // + // A label is an individual component of a domain name. Labels are usually + // shown separated by dots; for example, the domain name "www.example.com" is + // composed of three labels: "www", "example", and "com". + // + // An RTL label is a label that contains at least one character of class R, AL, + // or AN. An LTR label is any label that is not an RTL label. + // + // A "Bidi domain name" is a domain name that contains at least one RTL label. + // + // The following guarantees can be made based on the above: + // + // o In a domain name consisting of only labels that satisfy the rule, + // the requirements of Section 3 are satisfied. Note that even LTR + // labels and pure ASCII labels have to be tested. + // + // o In a domain name consisting of only LDH labels (as defined in the + // Definitions document [RFC5890]) and labels that satisfy the rule, + // the requirements of Section 3 are satisfied as long as a label + // that starts with an ASCII digit does not come after a + // right-to-left label. + // + // No guarantee is given for other combinations. // ErrInvalid indicates a label is invalid according to the Bidi Rule. + var ErrInvalid = errors.New("bidirule: failed Bidi Rule") type ruleState uint8 const ( ruleInitial ruleState = iota + ruleLTR + ruleLTRFinal + ruleRTL + ruleRTLFinal + ruleInvalid ) type ruleTransition struct { next ruleState + mask uint16 } var transitions = [...][2]ruleTransition{ + // [2.1] The first character must be a character with Bidi property L, R, or + // AL. If it has the R or AL property, it is an RTL label; if it has the L + // property, it is an LTR label. + ruleInitial: { + {ruleLTRFinal, 1 << bidi.L}, + {ruleRTLFinal, 1< 0 bytes returned + // before considering the error". + if r.src0 != r.src1 || r.err != nil { + r.dst0 = 0 + r.dst1, n, err = r.t.Transform(r.dst, r.src[r.src0:r.src1], r.err == io.EOF) + r.src0 += n switch { + case err == nil: + if r.src0 != r.src1 { + r.err = errInconsistentByteCount + } + // The Transform call was successful; we are complete if we + // cannot read more bytes into src. + r.transformComplete = r.err != nil + continue + case err == ErrShortDst && (r.dst1 != 0 || n != 0): + // Make room in dst by copying out, and try again. + continue + case err == ErrShortSrc && r.src1-r.src0 != len(r.src) && r.err == nil: + // Read more bytes into src via the code below, and try again. + default: + r.transformComplete = true + // The reader error (r.err) takes precedence over the + // transformer error (err) unless r.err is nil or io.EOF. + if r.err == nil || r.err == io.EOF { + r.err = err + } + continue + } + } // Move any untransformed source bytes to the start of the buffer + // and read more bytes. + if r.src0 != 0 { + r.src0, r.src1 = 0, copy(r.src, r.src[r.src0:r.src1]) + } + n, r.err = r.r.Read(r.src[r.src1:]) + r.src1 += n + } + } // TODO: implement ReadByte (and ReadRune??). // Writer wraps another io.Writer by transforming the bytes read. + // The user needs to call Close to flush unwritten bytes that may + // be buffered. + type Writer struct { - w io.Writer - t Transformer + w io.Writer + + t Transformer + dst []byte // src[:n] contains bytes that have not yet passed through t. + src []byte - n int + + n int } // NewWriter returns a new Writer that wraps w by transforming the bytes written + // via t. It calls Reset on t. + func NewWriter(w io.Writer, t Transformer) *Writer { + t.Reset() + return &Writer{ - w: w, - t: t, + + w: w, + + t: t, + dst: make([]byte, defaultBufSize), + src: make([]byte, defaultBufSize), } + } // Write implements the io.Writer interface. If there are not enough + // bytes available to complete a Transform, the bytes will be buffered + // for the next write. Call Close to convert the remaining bytes. + func (w *Writer) Write(data []byte) (n int, err error) { + src := data + if w.n > 0 { + // Append bytes from data to the last remainder. + // TODO: limit the amount copied on first try. + n = copy(w.src[w.n:], data) + w.n += n + src = w.src[:w.n] + } + for { + nDst, nSrc, err := w.t.Transform(w.dst, src, false) + if _, werr := w.w.Write(w.dst[:nDst]); werr != nil { + return n, werr + } + src = src[nSrc:] + if w.n == 0 { + n += nSrc + } else if len(src) <= n { + // Enough bytes from w.src have been consumed. We make src point + // to data instead to reduce the copying. + w.n = 0 + n -= len(src) + src = data[n:] + if n < len(data) && (err == nil || err == ErrShortSrc) { + continue + } + } + switch err { + case ErrShortDst: + // This error is okay as long as we are making progress. + if nDst > 0 || nSrc > 0 { + continue + } + case ErrShortSrc: + if len(src) < len(w.src) { + m := copy(w.src, src) + // If w.n > 0, bytes from data were already copied to w.src and n + // was already set to the number of bytes consumed. + if w.n == 0 { + n += m + } + w.n = m + err = nil + } else if nDst > 0 || nSrc > 0 { + // Not enough buffer to store the remainder. Keep processing as + // long as there is progress. Without this case, transforms that + // require a lookahead larger than the buffer may result in an + // error. This is not something one may expect to be common in + // practice, but it may occur when buffers are set to small + // sizes during testing. + continue + } + case nil: + if w.n > 0 { + err = errInconsistentByteCount + } + } + return n, err + } + } // Close implements the io.Closer interface. + func (w *Writer) Close() error { + src := w.src[:w.n] + for { + nDst, nSrc, err := w.t.Transform(w.dst, src, true) + if _, werr := w.w.Write(w.dst[:nDst]); werr != nil { + return werr + } + if err != ErrShortDst { + return err + } + src = src[nSrc:] + } + } type nop struct{ NopResetter } func (nop) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { + n := copy(dst, src) + if n < len(src) { + err = ErrShortDst + } + return n, n, err + } func (nop) Span(src []byte, atEOF bool) (n int, err error) { + return len(src), nil + } type discard struct{ NopResetter } func (discard) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { + return 0, len(src), nil + } var ( + // Discard is a Transformer for which all Transform calls succeed + // by consuming all bytes and writing nothing. + Discard Transformer = discard{} // Nop is a SpanningTransformer that copies src to dst. + Nop SpanningTransformer = nop{} ) // chain is a sequence of links. A chain with N Transformers has N+1 links and + // N+1 buffers. Of those N+1 buffers, the first and last are the src and dst + // buffers given to chain.Transform and the middle N-1 buffers are intermediate + // buffers owned by the chain. The i'th link transforms bytes from the i'th + // buffer chain.link[i].b at read offset chain.link[i].p to the i+1'th buffer + // chain.link[i+1].b at write offset chain.link[i+1].n, for i in [0, N). + type chain struct { link []link - err error + + err error + // errStart is the index at which the error occurred plus 1. Processing + // errStart at this level at the next call to Transform. As long as + // errStart > 0, chain will not consume any more source bytes. + errStart int } func (c *chain) fatalError(errIndex int, err error) { + if i := errIndex + 1; i > c.errStart { + c.errStart = i + c.err = err + } + } type link struct { t Transformer + // b[p:n] holds the bytes to be transformed by t. + b []byte + p int + n int } func (l *link) src() []byte { + return l.b[l.p:l.n] + } func (l *link) dst() []byte { + return l.b[l.n:] + } // Chain returns a Transformer that applies t in sequence. + func Chain(t ...Transformer) Transformer { + if len(t) == 0 { + return nop{} + } + c := &chain{link: make([]link, len(t)+1)} + for i, tt := range t { + c.link[i].t = tt + } + // Allocate intermediate buffers. + b := make([][defaultBufSize]byte, len(t)-1) + for i := range b { + c.link[i+1].b = b[i][:] + } + return c + } // Reset resets the state of Chain. It calls Reset on all the Transformers. + func (c *chain) Reset() { + for i, l := range c.link { + if l.t != nil { + l.t.Reset() + } + c.link[i].p, c.link[i].n = 0, 0 + } + } // TODO: make chain use Span (is going to be fun to implement!) // Transform applies the transformers of c in sequence. + func (c *chain) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { + // Set up src and dst in the chain. + srcL := &c.link[0] + dstL := &c.link[len(c.link)-1] + srcL.b, srcL.p, srcL.n = src, 0, len(src) + dstL.b, dstL.n = dst, 0 + var lastFull, needProgress bool // for detecting progress // i is the index of the next Transformer to apply, for i in [low, high]. + // low is the lowest index for which c.link[low] may still produce bytes. + // high is the highest index for which c.link[high] has a Transformer. + // The error returned by Transform determines whether to increase or + // decrease i. We try to completely fill a buffer before converting it. + for low, i, high := c.errStart, c.errStart, len(c.link)-2; low <= i && i <= high; { + in, out := &c.link[i], &c.link[i+1] + nDst, nSrc, err0 := in.t.Transform(out.dst(), in.src(), atEOF && low == i) + out.n += nDst + in.p += nSrc + if i > 0 && in.p == in.n { + in.p, in.n = 0, 0 + } + needProgress, lastFull = lastFull, false + switch err0 { + case ErrShortDst: + // Process the destination buffer next. Return if we are already + // at the high index. + if i == high { + return dstL.n, srcL.p, ErrShortDst + } + if out.n != 0 { + i++ + // If the Transformer at the next index is not able to process any + // source bytes there is nothing that can be done to make progress + // and the bytes will remain unprocessed. lastFull is used to + // detect this and break out of the loop with a fatal error. + lastFull = true + continue + } + // The destination buffer was too small, but is completely empty. + // Return a fatal error as this transformation can never complete. + c.fatalError(i, errShortInternal) + case ErrShortSrc: + if i == 0 { + // Save ErrShortSrc in err. All other errors take precedence. + err = ErrShortSrc + break + } + // Source bytes were depleted before filling up the destination buffer. + // Verify we made some progress, move the remaining bytes to the errStart + // and try to get more source bytes. + if needProgress && nSrc == 0 || in.n-in.p == len(in.b) { + // There were not enough source bytes to proceed while the source + // buffer cannot hold any more bytes. Return a fatal error as this + // transformation can never complete. + c.fatalError(i, errShortInternal) + break + } + // in.b is an internal buffer and we can make progress. + in.p, in.n = 0, copy(in.b, in.src()) + fallthrough + case nil: + // if i == low, we have depleted the bytes at index i or any lower levels. + // In that case we increase low and i. In all other cases we decrease i to + // fetch more bytes before proceeding to the next index. + if i > low { + i-- + continue + } + default: + c.fatalError(i, err0) + } + // Exhausted level low or fatal error: increase low and continue + // to process the bytes accepted so far. + i++ + low = i + } // If c.errStart > 0, this means we found a fatal error. We will clear + // all upstream buffers. At this point, no more progress can be made + // downstream, as Transform would have bailed while handling ErrShortDst. + if c.errStart > 0 { + for i := 1; i < c.errStart; i++ { + c.link[i].p, c.link[i].n = 0, 0 + } + err, c.errStart, c.err = c.err, 0, nil + } + return dstL.n, srcL.p, err + } // Deprecated: Use runes.Remove instead. + func RemoveFunc(f func(r rune) bool) Transformer { + return removeF(f) + } type removeF func(r rune) bool @@ -503,207 +885,373 @@ type removeF func(r rune) bool func (removeF) Reset() {} // Transform implements the Transformer interface. + func (t removeF) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { + for r, sz := rune(0), 0; len(src) > 0; src = src[sz:] { if r = rune(src[0]); r < utf8.RuneSelf { + sz = 1 + } else { + r, sz = utf8.DecodeRune(src) if sz == 1 { + // Invalid rune. + if !atEOF && !utf8.FullRune(src) { + err = ErrShortSrc + break + } + // We replace illegal bytes with RuneError. Not doing so might + // otherwise turn a sequence of invalid UTF-8 into valid UTF-8. + // The resulting byte sequence may subsequently contain runes + // for which t(r) is true that were passed unnoticed. + if !t(r) { + if nDst+3 > len(dst) { + err = ErrShortDst + break + } + nDst += copy(dst[nDst:], "\uFFFD") + } + nSrc++ + continue + } + } if !t(r) { + if nDst+sz > len(dst) { + err = ErrShortDst + break + } + nDst += copy(dst[nDst:], src[:sz]) + } + nSrc += sz + } + return + } // grow returns a new []byte that is longer than b, and copies the first n bytes + // of b to the start of the new slice. + func grow(b []byte, n int) []byte { + m := len(b) + if m <= 32 { + m = 64 + } else if m <= 256 { + m *= 2 + } else { + m += m >> 1 + } + buf := make([]byte, m) + copy(buf, b[:n]) + return buf + } const initialBufSize = 128 // String returns a string with the result of converting s[:n] using t, where + // n <= len(s). If err == nil, n will be len(s). It calls Reset on t. + func String(t Transformer, s string) (result string, n int, err error) { + t.Reset() + if s == "" { + // Fast path for the common case for empty input. Results in about a + // 86% reduction of running time for BenchmarkStringLowerEmpty. + if _, _, err := t.Transform(nil, nil, true); err == nil { + return "", 0, nil + } + } // Allocate only once. Note that both dst and src escape when passed to + // Transform. + buf := [2 * initialBufSize]byte{} + dst := buf[:initialBufSize:initialBufSize] + src := buf[initialBufSize : 2*initialBufSize] // The input string s is transformed in multiple chunks (starting with a + // chunk size of initialBufSize). nDst and nSrc are per-chunk (or + // per-Transform-call) indexes, pDst and pSrc are overall indexes. + nDst, nSrc := 0, 0 + pDst, pSrc := 0, 0 // pPrefix is the length of a common prefix: the first pPrefix bytes of the + // result will equal the first pPrefix bytes of s. It is not guaranteed to + // be the largest such value, but if pPrefix, len(result) and len(s) are + // all equal after the final transform (i.e. calling Transform with atEOF + // being true returned nil error) then we don't need to allocate a new + // result string. + pPrefix := 0 + for { + // Invariant: pDst == pPrefix && pSrc == pPrefix. n := copy(src, s[pSrc:]) + nDst, nSrc, err = t.Transform(dst, src[:n], pSrc+n == len(s)) + pDst += nDst + pSrc += nSrc // TODO: let transformers implement an optional Spanner interface, akin + // to norm's QuickSpan. This would even allow us to avoid any allocation. + if !bytes.Equal(dst[:nDst], src[:nSrc]) { + break + } + pPrefix = pSrc + if err == ErrShortDst { + // A buffer can only be short if a transformer modifies its input. + break + } else if err == ErrShortSrc { + if nSrc == 0 { + // No progress was made. + break + } + // Equal so far and !atEOF, so continue checking. + } else if err != nil || pPrefix == len(s) { + return string(s[:pPrefix]), pPrefix, err + } + } + // Post-condition: pDst == pPrefix + nDst && pSrc == pPrefix + nSrc. // We have transformed the first pSrc bytes of the input s to become pDst + // transformed bytes. Those transformed bytes are discontiguous: the first + // pPrefix of them equal s[:pPrefix] and the last nDst of them equal + // dst[:nDst]. We copy them around, into a new dst buffer if necessary, so + // that they become one contiguous slice: dst[:pDst]. + if pPrefix != 0 { + newDst := dst + if pDst > len(newDst) { + newDst = make([]byte, len(s)+nDst-nSrc) + } + copy(newDst[pPrefix:pDst], dst[:nDst]) + copy(newDst[:pPrefix], s[:pPrefix]) + dst = newDst + } // Prevent duplicate Transform calls with atEOF being true at the end of + // the input. Also return if we have an unrecoverable error. + if (err == nil && pSrc == len(s)) || + (err != nil && err != ErrShortDst && err != ErrShortSrc) { + return string(dst[:pDst]), pSrc, err + } // Transform the remaining input, growing dst and src buffers as necessary. + for { + n := copy(src, s[pSrc:]) + atEOF := pSrc+n == len(s) + nDst, nSrc, err := t.Transform(dst[pDst:], src[:n], atEOF) + pDst += nDst + pSrc += nSrc // If we got ErrShortDst or ErrShortSrc, do not grow as long as we can + // make progress. This may avoid excessive allocations. + if err == ErrShortDst { + if nDst == 0 { + dst = grow(dst, pDst) + } + } else if err == ErrShortSrc { + if atEOF { + return string(dst[:pDst]), pSrc, err + } + if nSrc == 0 { + src = grow(src, 0) + } + } else if err != nil || pSrc == len(s) { + return string(dst[:pDst]), pSrc, err + } + } + } // Bytes returns a new byte slice with the result of converting b[:n] using t, + // where n <= len(b). If err == nil, n will be len(b). It calls Reset on t. + func Bytes(t Transformer, b []byte) (result []byte, n int, err error) { + return doAppend(t, 0, make([]byte, len(b)), b) + } // Append appends the result of converting src[:n] using t to dst, where + // n <= len(src), If err == nil, n will be len(src). It calls Reset on t. + func Append(t Transformer, dst, src []byte) (result []byte, n int, err error) { + if len(dst) == cap(dst) { + n := len(src) + len(dst) // It is okay for this to be 0. + b := make([]byte, n) + dst = b[:copy(b, dst)] + } + return doAppend(t, len(dst), dst[:cap(dst)], src) + } func doAppend(t Transformer, pDst int, dst, src []byte) (result []byte, n int, err error) { + t.Reset() + pSrc := 0 + for { + nDst, nSrc, err := t.Transform(dst[pDst:], src[pSrc:], true) + pDst += nDst + pSrc += nSrc + if err != ErrShortDst { + return dst[:pDst], pSrc, err + } // Grow the destination buffer, but do not grow as long as we can make + // progress. This may avoid excessive allocations. + if nDst == 0 { + dst = grow(dst, pDst) + } + } + } diff --git a/vendor/golang.org/x/text/unicode/bidi/bracket.go b/vendor/golang.org/x/text/unicode/bidi/bracket.go index 1853939..ba798ac 100644 --- a/vendor/golang.org/x/text/unicode/bidi/bracket.go +++ b/vendor/golang.org/x/text/unicode/bidi/bracket.go @@ -1,5 +1,7 @@ // Copyright 2015 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package bidi @@ -11,325 +13,577 @@ import ( ) // This file contains a port of the reference implementation of the + // Bidi Parentheses Algorithm: + // https://www.unicode.org/Public/PROGRAMS/BidiReferenceJava/BidiPBAReference.java + // + // The implementation in this file covers definitions BD14-BD16 and rule N0 + // of UAX#9. + // + // Some preprocessing is done for each rune before data is passed to this + // algorithm: + // - opening and closing brackets are identified + // - a bracket pair type, like '(' and ')' is assigned a unique identifier that + // is identical for the opening and closing bracket. It is left to do these + // mappings. + // - The BPA algorithm requires that bracket characters that are canonical + // equivalents of each other be able to be substituted for each other. + // It is the responsibility of the caller to do this canonicalization. + // + // In implementing BD16, this implementation departs slightly from the "logical" + // algorithm defined in UAX#9. In particular, the stack referenced there + // supports operations that go beyond a "basic" stack. An equivalent + // implementation based on a linked list is used here. // Bidi_Paired_Bracket_Type + // BD14. An opening paired bracket is a character whose + // Bidi_Paired_Bracket_Type property value is Open. + // + // BD15. A closing paired bracket is a character whose + // Bidi_Paired_Bracket_Type property value is Close. + type bracketType byte const ( bpNone bracketType = iota + bpOpen + bpClose ) // bracketPair holds a pair of index values for opening and closing bracket + // location of a bracket pair. + type bracketPair struct { opener int + closer int } func (b *bracketPair) String() string { + return fmt.Sprintf("(%v, %v)", b.opener, b.closer) + } // bracketPairs is a slice of bracketPairs with a sort.Interface implementation. + type bracketPairs []bracketPair -func (b bracketPairs) Len() int { return len(b) } -func (b bracketPairs) Swap(i, j int) { b[i], b[j] = b[j], b[i] } +func (b bracketPairs) Len() int { return len(b) } + +func (b bracketPairs) Swap(i, j int) { b[i], b[j] = b[j], b[i] } + func (b bracketPairs) Less(i, j int) bool { return b[i].opener < b[j].opener } // resolvePairedBrackets runs the paired bracket part of the UBA algorithm. + // + // For each rune, it takes the indexes into the original string, the class the + // bracket type (in pairTypes) and the bracket identifier (pairValues). It also + // takes the direction type for the start-of-sentence and the embedding level. + // + // The identifiers for bracket types are the rune of the canonicalized opening + // bracket for brackets (open or close) or 0 for runes that are not brackets. + func resolvePairedBrackets(s *isolatingRunSequence) { + p := bracketPairer{ - sos: s.sos, - openers: list.New(), + + sos: s.sos, + + openers: list.New(), + codesIsolatedRun: s.types, - indexes: s.indexes, + + indexes: s.indexes, } + dirEmbed := L + if s.level&1 != 0 { + dirEmbed = R + } + p.locateBrackets(s.p.pairTypes, s.p.pairValues) + p.resolveBrackets(dirEmbed, s.p.initialTypes) + } type bracketPairer struct { sos Class // direction corresponding to start of sequence // The following is a restatement of BD 16 using non-algorithmic language. + // + // A bracket pair is a pair of characters consisting of an opening + // paired bracket and a closing paired bracket such that the + // Bidi_Paired_Bracket property value of the former equals the latter, + // subject to the following constraints. + // - both characters of a pair occur in the same isolating run sequence + // - the closing character of a pair follows the opening character + // - any bracket character can belong at most to one pair, the earliest possible one + // - any bracket character not part of a pair is treated like an ordinary character + // - pairs may nest properly, but their spans may not overlap otherwise // Bracket characters with canonical decompositions are supposed to be + // treated as if they had been normalized, to allow normalized and non- + // normalized text to give the same result. In this implementation that step + // is pushed out to the caller. The caller has to ensure that the pairValue + // slices contain the rune of the opening bracket after normalization for + // any opening or closing bracket. openers *list.List // list of positions for opening brackets // bracket pair positions sorted by location of opening bracket + pairPositions bracketPairs codesIsolatedRun []Class // directional bidi codes for an isolated run - indexes []int // array of index values into the original string + + indexes []int // array of index values into the original string } // matchOpener reports whether characters at given positions form a matching + // bracket pair. + func (p *bracketPairer) matchOpener(pairValues []rune, opener, closer int) bool { + return pairValues[p.indexes[opener]] == pairValues[p.indexes[closer]] + } const maxPairingDepth = 63 // locateBrackets locates matching bracket pairs according to BD16. + // + // This implementation uses a linked list instead of a stack, because, while + // elements are added at the front (like a push) they are not generally removed + // in atomic 'pop' operations, reducing the benefit of the stack archetype. + func (p *bracketPairer) locateBrackets(pairTypes []bracketType, pairValues []rune) { + // traverse the run + // do that explicitly (not in a for-each) so we can record position + for i, index := range p.indexes { // look at the bracket type for each character + if pairTypes[index] == bpNone || p.codesIsolatedRun[i] != ON { + // continue scanning + continue + } + switch pairTypes[index] { + case bpOpen: + // check if maximum pairing depth reached + if p.openers.Len() == maxPairingDepth { + p.openers.Init() + return + } + // remember opener location, most recent first + p.openers.PushFront(i) case bpClose: + // see if there is a match + count := 0 + for elem := p.openers.Front(); elem != nil; elem = elem.Next() { + count++ + opener := elem.Value.(int) + if p.matchOpener(pairValues, opener, i) { + // if the opener matches, add nested pair to the ordered list + p.pairPositions = append(p.pairPositions, bracketPair{opener, i}) + // remove up to and including matched opener + for ; count > 0; count-- { + p.openers.Remove(p.openers.Front()) + } + break + } + } + sort.Sort(p.pairPositions) + // if we get here, the closing bracket matched no openers + // and gets ignored + } + } + } // Bracket pairs within an isolating run sequence are processed as units so + // that both the opening and the closing paired bracket in a pair resolve to + // the same direction. + // + // N0. Process bracket pairs in an isolating run sequence sequentially in + // the logical order of the text positions of the opening paired brackets + // using the logic given below. Within this scope, bidirectional types EN + // and AN are treated as R. + // + // Identify the bracket pairs in the current isolating run sequence + // according to BD16. For each bracket-pair element in the list of pairs of + // text positions: + // + // a Inspect the bidirectional types of the characters enclosed within the + // bracket pair. + // + // b If any strong type (either L or R) matching the embedding direction is + // found, set the type for both brackets in the pair to match the embedding + // direction. + // + // o [ e ] o -> o e e e o + // + // o [ o e ] -> o e o e e + // + // o [ NI e ] -> o e NI e e + // + // c Otherwise, if a strong type (opposite the embedding direction) is + // found, test for adjacent strong types as follows: 1 First, check + // backwards before the opening paired bracket until the first strong type + // (L, R, or sos) is found. If that first preceding strong type is opposite + // the embedding direction, then set the type for both brackets in the pair + // to that type. 2 Otherwise, set the type for both brackets in the pair to + // the embedding direction. + // + // o [ o ] e -> o o o o e + // + // o [ o NI ] o -> o o o NI o o + // + // e [ o ] o -> e e o e o + // + // e [ o ] e -> e e o e e + // + // e ( o [ o ] NI ) e -> e e o o o o NI e e + // + // d Otherwise, do not set the type for the current bracket pair. Note that + // if the enclosed text contains no strong types the paired brackets will + // both resolve to the same level when resolved individually using rules N1 + // and N2. + // + // e ( NI ) o -> e ( NI ) o // getStrongTypeN0 maps character's directional code to strong type as required + // by rule N0. + // + // TODO: have separate type for "strong" directionality. + func (p *bracketPairer) getStrongTypeN0(index int) Class { + switch p.codesIsolatedRun[index] { + // in the scope of N0, number types are treated as R + case EN, AN, AL, R: + return R + case L: + return L + default: + return ON + } + } // classifyPairContent reports the strong types contained inside a Bracket Pair, + // assuming the given embedding direction. + // + // It returns ON if no strong type is found. If a single strong type is found, + // it returns this type. Otherwise it returns the embedding direction. + // + // TODO: use separate type for "strong" directionality. + func (p *bracketPairer) classifyPairContent(loc bracketPair, dirEmbed Class) Class { + dirOpposite := ON + for i := loc.opener + 1; i < loc.closer; i++ { + dir := p.getStrongTypeN0(i) + if dir == ON { + continue + } + if dir == dirEmbed { + return dir // type matching embedding direction found + } + dirOpposite = dir + } + // return ON if no strong type found, or class opposite to dirEmbed + return dirOpposite + } // classBeforePair determines which strong types are present before a Bracket + // Pair. Return R or L if strong type found, otherwise ON. + func (p *bracketPairer) classBeforePair(loc bracketPair) Class { + for i := loc.opener - 1; i >= 0; i-- { + if dir := p.getStrongTypeN0(i); dir != ON { + return dir + } + } + // no strong types found, return sos + return p.sos + } // assignBracketType implements rule N0 for a single bracket pair. + func (p *bracketPairer) assignBracketType(loc bracketPair, dirEmbed Class, initialTypes []Class) { + // rule "N0, a", inspect contents of pair + dirPair := p.classifyPairContent(loc, dirEmbed) // dirPair is now L, R, or N (no strong type found) // the following logical tests are performed out of order compared to + // the statement of the rules but yield the same results + if dirPair == ON { + return // case "d" - nothing to do + } if dirPair != dirEmbed { + // case "c": strong type found, opposite - check before (c.1) + dirPair = p.classBeforePair(loc) + if dirPair == dirEmbed || dirPair == ON { + // no strong opposite type found before - use embedding (c.2) + dirPair = dirEmbed + } + } + // else: case "b", strong type found matching embedding, + // no explicit action needed, as dirPair is already set to embedding + // direction // set the bracket types to the type found + p.setBracketsToType(loc, dirPair, initialTypes) + } func (p *bracketPairer) setBracketsToType(loc bracketPair, dirPair Class, initialTypes []Class) { + p.codesIsolatedRun[loc.opener] = dirPair + p.codesIsolatedRun[loc.closer] = dirPair for i := loc.opener + 1; i < loc.closer; i++ { + index := p.indexes[i] + if initialTypes[index] != NSM { + break + } + p.codesIsolatedRun[i] = dirPair + } for i := loc.closer + 1; i < len(p.indexes); i++ { + index := p.indexes[i] + if initialTypes[index] != NSM { + break + } + p.codesIsolatedRun[i] = dirPair + } + } // resolveBrackets implements rule N0 for a list of pairs. + func (p *bracketPairer) resolveBrackets(dirEmbed Class, initialTypes []Class) { + for _, loc := range p.pairPositions { + p.assignBracketType(loc, dirEmbed, initialTypes) + } + } diff --git a/vendor/golang.org/x/text/unicode/bidi/core.go b/vendor/golang.org/x/text/unicode/bidi/core.go index 9d2ae54..a53800d 100644 --- a/vendor/golang.org/x/text/unicode/bidi/core.go +++ b/vendor/golang.org/x/text/unicode/bidi/core.go @@ -1,5 +1,7 @@ // Copyright 2015 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package bidi @@ -10,408 +12,706 @@ import ( ) // This implementation is a port based on the reference implementation found at: + // https://www.unicode.org/Public/PROGRAMS/BidiReferenceJava/ + // + // described in Unicode Bidirectional Algorithm (UAX #9). + // + // Input: + // There are two levels of input to the algorithm, since clients may prefer to + // supply some information from out-of-band sources rather than relying on the + // default behavior. + // + // - Bidi class array + // - Bidi class array, with externally supplied base line direction + // + // Output: + // Output is separated into several stages: + // + // - levels array over entire paragraph + // - reordering array over entire paragraph + // - levels array over line + // - reordering array over line + // + // Note that for conformance to the Unicode Bidirectional Algorithm, + // implementations are only required to generate correct reordering and + // character directionality (odd or even levels) over a line. Generating + // identical level arrays over a line is not required. Bidi explicit format + // codes (LRE, RLE, LRO, RLO, PDF) and BN can be assigned arbitrary levels and + // positions as long as the rest of the input is properly reordered. + // + // As the algorithm is defined to operate on a single paragraph at a time, this + // implementation is written to handle single paragraphs. Thus rule P1 is + // presumed by this implementation-- the data provided to the implementation is + // assumed to be a single paragraph, and either contains no 'B' codes, or a + // single 'B' code at the end of the input. 'B' is allowed as input to + // illustrate how the algorithm assigns it a level. + // + // Also note that rules L3 and L4 depend on the rendering engine that uses the + // result of the bidi algorithm. This implementation assumes that the rendering + // engine expects combining marks in visual order (e.g. to the left of their + // base character in RTL runs) and that it adjusts the glyphs used to render + // mirrored characters that are in RTL runs so that they render appropriately. // level is the embedding level of a character. Even embedding levels indicate + // left-to-right order and odd levels indicate right-to-left order. The special + // level of -1 is reserved for undefined order. + type level int8 const implicitLevel level = -1 // in returns if x is equal to any of the values in set. + func (c Class) in(set ...Class) bool { + for _, s := range set { + if c == s { + return true + } + } + return false + } // A paragraph contains the state of a paragraph. + type paragraph struct { initialTypes []Class // Arrays of properties needed for paired bracket evaluation in N0 - pairTypes []bracketType // paired Bracket types for paragraph - pairValues []rune // rune for opening bracket or pbOpen and pbClose; 0 for pbNone + + pairTypes []bracketType // paired Bracket types for paragraph + + pairValues []rune // rune for opening bracket or pbOpen and pbClose; 0 for pbNone embeddingLevel level // default: = implicitLevel; // at the paragraph levels - resultTypes []Class + + resultTypes []Class + resultLevels []level // Index of matching PDI for isolate initiator characters. For other + // characters, the value of matchingPDI will be set to -1. For isolate + // initiators with no matching PDI, matchingPDI will be set to the length of + // the input string. + matchingPDI []int // Index of matching isolate initiator for PDI characters. For other + // characters, and for PDIs with no matching isolate initiator, the value of + // matchingIsolateInitiator will be set to -1. + matchingIsolateInitiator []int } // newParagraph initializes a paragraph. The user needs to supply a few arrays + // corresponding to the preprocessed text input. The types correspond to the + // Unicode BiDi classes for each rune. pairTypes indicates the bracket type for + // each rune. pairValues provides a unique bracket class identifier for each + // rune (suggested is the rune of the open bracket for opening and matching + // close brackets, after normalization). The embedding levels are optional, but + // may be supplied to encode embedding levels of styled text. + func newParagraph(types []Class, pairTypes []bracketType, pairValues []rune, levels level) (*paragraph, error) { + var err error + if err = validateTypes(types); err != nil { + return nil, err + } + if err = validatePbTypes(pairTypes); err != nil { + return nil, err + } + if err = validatePbValues(pairValues, pairTypes); err != nil { + return nil, err + } + if err = validateParagraphEmbeddingLevel(levels); err != nil { + return nil, err + } p := ¶graph{ - initialTypes: append([]Class(nil), types...), + + initialTypes: append([]Class(nil), types...), + embeddingLevel: levels, - pairTypes: pairTypes, + pairTypes: pairTypes, + pairValues: pairValues, resultTypes: append([]Class(nil), types...), } + p.run() + return p, nil + } func (p *paragraph) Len() int { return len(p.initialTypes) } // The algorithm. Does not include line-based processing (Rules L1, L2). + // These are applied later in the line-based phase of the algorithm. + func (p *paragraph) run() { + p.determineMatchingIsolates() // 1) determining the paragraph level + // Rule P1 is the requirement for entering this algorithm. + // Rules P2, P3. + // If no externally supplied paragraph embedding level, use default. + if p.embeddingLevel == implicitLevel { + p.embeddingLevel = p.determineParagraphEmbeddingLevel(0, p.Len()) + } // Initialize result levels to paragraph embedding level. + p.resultLevels = make([]level, p.Len()) + setLevels(p.resultLevels, p.embeddingLevel) // 2) Explicit levels and directions + // Rules X1-X8. + p.determineExplicitEmbeddingLevels() // Rule X9. + // We do not remove the embeddings, the overrides, the PDFs, and the BNs + // from the string explicitly. But they are not copied into isolating run + // sequences when they are created, so they are removed for all + // practical purposes. // Rule X10. + // Run remainder of algorithm one isolating run sequence at a time + for _, seq := range p.determineIsolatingRunSequences() { + // 3) resolving weak types + // Rules W1-W7. + seq.resolveWeakTypes() // 4a) resolving paired brackets + // Rule N0 + resolvePairedBrackets(seq) // 4b) resolving neutral types + // Rules N1-N3. + seq.resolveNeutralTypes() // 5) resolving implicit embedding levels + // Rules I1, I2. + seq.resolveImplicitLevels() // Apply the computed levels and types + seq.applyLevelsAndTypes() + } // Assign appropriate levels to 'hide' LREs, RLEs, LROs, RLOs, PDFs, and + // BNs. This is for convenience, so the resulting level array will have + // a value for every character. + p.assignLevelsToCharactersRemovedByX9() + } // determineMatchingIsolates determines the matching PDI for each isolate + // initiator and vice versa. + // + // Definition BD9. + // + // At the end of this function: + // + // - The member variable matchingPDI is set to point to the index of the + // matching PDI character for each isolate initiator character. If there is + // no matching PDI, it is set to the length of the input text. For other + // characters, it is set to -1. + // - The member variable matchingIsolateInitiator is set to point to the + // index of the matching isolate initiator character for each PDI character. + // If there is no matching isolate initiator, or the character is not a PDI, + // it is set to -1. + func (p *paragraph) determineMatchingIsolates() { + p.matchingPDI = make([]int, p.Len()) + p.matchingIsolateInitiator = make([]int, p.Len()) for i := range p.matchingIsolateInitiator { + p.matchingIsolateInitiator[i] = -1 + } for i := range p.matchingPDI { + p.matchingPDI[i] = -1 if t := p.resultTypes[i]; t.in(LRI, RLI, FSI) { + depthCounter := 1 + for j := i + 1; j < p.Len(); j++ { + if u := p.resultTypes[j]; u.in(LRI, RLI, FSI) { + depthCounter++ + } else if u == PDI { + if depthCounter--; depthCounter == 0 { + p.matchingPDI[i] = j + p.matchingIsolateInitiator[j] = i + break + } + } + } + if p.matchingPDI[i] == -1 { + p.matchingPDI[i] = p.Len() + } + } + } + } // determineParagraphEmbeddingLevel reports the resolved paragraph direction of + // the substring limited by the given range [start, end). + // + // Determines the paragraph level based on rules P2, P3. This is also used + // in rule X5c to find if an FSI should resolve to LRI or RLI. + func (p *paragraph) determineParagraphEmbeddingLevel(start, end int) level { + var strongType Class = unknownClass // Rule P2. + for i := start; i < end; i++ { + if t := p.resultTypes[i]; t.in(L, AL, R) { + strongType = t + break + } else if t.in(FSI, LRI, RLI) { + i = p.matchingPDI[i] // skip over to the matching PDI + if i > end { + log.Panic("assert (i <= end)") + } + } + } + // Rule P3. + switch strongType { + case unknownClass: // none found + // default embedding level when no strong types found is 0. + return 0 + case L: + return 0 + default: // AL, R + return 1 + } + } const maxDepth = 125 // This stack will store the embedding levels and override and isolated + // statuses + type directionalStatusStack struct { - stackCounter int + stackCounter int + embeddingLevelStack [maxDepth + 1]level + overrideStatusStack [maxDepth + 1]Class - isolateStatusStack [maxDepth + 1]bool + + isolateStatusStack [maxDepth + 1]bool } -func (s *directionalStatusStack) empty() { s.stackCounter = 0 } -func (s *directionalStatusStack) pop() { s.stackCounter-- } +func (s *directionalStatusStack) empty() { s.stackCounter = 0 } + +func (s *directionalStatusStack) pop() { s.stackCounter-- } + func (s *directionalStatusStack) depth() int { return s.stackCounter } func (s *directionalStatusStack) push(level level, overrideStatus Class, isolateStatus bool) { + s.embeddingLevelStack[s.stackCounter] = level + s.overrideStatusStack[s.stackCounter] = overrideStatus + s.isolateStatusStack[s.stackCounter] = isolateStatus + s.stackCounter++ + } func (s *directionalStatusStack) lastEmbeddingLevel() level { + return s.embeddingLevelStack[s.stackCounter-1] + } func (s *directionalStatusStack) lastDirectionalOverrideStatus() Class { + return s.overrideStatusStack[s.stackCounter-1] + } func (s *directionalStatusStack) lastDirectionalIsolateStatus() bool { + return s.isolateStatusStack[s.stackCounter-1] + } // Determine explicit levels using rules X1 - X8 + func (p *paragraph) determineExplicitEmbeddingLevels() { + var stack directionalStatusStack + var overflowIsolateCount, overflowEmbeddingCount, validIsolateCount int // Rule X1. + stack.push(p.embeddingLevel, ON, false) for i, t := range p.resultTypes { + // Rules X2, X3, X4, X5, X5a, X5b, X5c + switch t { + case RLE, LRE, RLO, LRO, RLI, LRI, FSI: + isIsolate := t.in(RLI, LRI, FSI) + isRTL := t.in(RLE, RLO, RLI) // override if this is an FSI that resolves to RLI + if t == FSI { + isRTL = (p.determineParagraphEmbeddingLevel(i+1, p.matchingPDI[i]) == 1) + } + if isIsolate { + p.resultLevels[i] = stack.lastEmbeddingLevel() + if stack.lastDirectionalOverrideStatus() != ON { + p.resultTypes[i] = stack.lastDirectionalOverrideStatus() + } + } var newLevel level + if isRTL { + // least greater odd + newLevel = (stack.lastEmbeddingLevel() + 1) | 1 + } else { + // least greater even + newLevel = (stack.lastEmbeddingLevel() + 2) &^ 1 + } if newLevel <= maxDepth && overflowIsolateCount == 0 && overflowEmbeddingCount == 0 { + if isIsolate { + validIsolateCount++ + } + // Push new embedding level, override status, and isolated + // status. + // No check for valid stack counter, since the level check + // suffices. + switch t { + case LRO: + stack.push(newLevel, L, isIsolate) + case RLO: + stack.push(newLevel, R, isIsolate) + default: + stack.push(newLevel, ON, isIsolate) + } + // Not really part of the spec + if !isIsolate { + p.resultLevels[i] = newLevel + } + } else { + // This is an invalid explicit formatting character, + // so apply the "Otherwise" part of rules X2-X5b. + if isIsolate { + overflowIsolateCount++ + } else { // !isIsolate + if overflowIsolateCount == 0 { + overflowEmbeddingCount++ + } + } + } // Rule X6a + case PDI: + if overflowIsolateCount > 0 { + overflowIsolateCount-- + } else if validIsolateCount == 0 { + // do nothing + } else { + overflowEmbeddingCount = 0 + for !stack.lastDirectionalIsolateStatus() { + stack.pop() + } + stack.pop() + validIsolateCount-- + } + p.resultLevels[i] = stack.lastEmbeddingLevel() // Rule X7 + case PDF: + // Not really part of the spec + p.resultLevels[i] = stack.lastEmbeddingLevel() if overflowIsolateCount > 0 { + // do nothing + } else if overflowEmbeddingCount > 0 { + overflowEmbeddingCount-- + } else if !stack.lastDirectionalIsolateStatus() && stack.depth() >= 2 { + stack.pop() + } case B: // paragraph separator. + // Rule X8. // These values are reset for clarity, in this implementation B + // can only occur as the last code in the array. + stack.empty() + overflowIsolateCount = 0 + overflowEmbeddingCount = 0 + validIsolateCount = 0 + p.resultLevels[i] = p.embeddingLevel default: + p.resultLevels[i] = stack.lastEmbeddingLevel() + if stack.lastDirectionalOverrideStatus() != ON { + p.resultTypes[i] = stack.lastDirectionalOverrideStatus() + } + } + } + } type isolatingRunSequence struct { @@ -419,369 +719,654 @@ type isolatingRunSequence struct { indexes []int // indexes to the original string - types []Class // type of each character using the index + types []Class // type of each character using the index + resolvedLevels []level // resolved levels after application of rules - level level - sos, eos Class + + level level + + sos, eos Class } func (i *isolatingRunSequence) Len() int { return len(i.indexes) } func maxLevel(a, b level) level { + if a > b { + return a + } + return b + } // Rule X10, second bullet: Determine the start-of-sequence (sos) and end-of-sequence (eos) types, + // either L or R, for each isolating run sequence. + func (p *paragraph) isolatingRunSequence(indexes []int) *isolatingRunSequence { + length := len(indexes) + types := make([]Class, length) + for i, x := range indexes { + types[i] = p.resultTypes[x] + } // assign level, sos and eos + prevChar := indexes[0] - 1 + for prevChar >= 0 && isRemovedByX9(p.initialTypes[prevChar]) { + prevChar-- + } + prevLevel := p.embeddingLevel + if prevChar >= 0 { + prevLevel = p.resultLevels[prevChar] + } var succLevel level + lastType := types[length-1] + if lastType.in(LRI, RLI, FSI) { + succLevel = p.embeddingLevel + } else { + // the first character after the end of run sequence + limit := indexes[length-1] + 1 + for ; limit < p.Len() && isRemovedByX9(p.initialTypes[limit]); limit++ { } + succLevel = p.embeddingLevel + if limit < p.Len() { + succLevel = p.resultLevels[limit] + } + } + level := p.resultLevels[indexes[0]] + return &isolatingRunSequence{ - p: p, + + p: p, + indexes: indexes, - types: types, - level: level, - sos: typeForLevel(maxLevel(prevLevel, level)), - eos: typeForLevel(maxLevel(succLevel, level)), + + types: types, + + level: level, + + sos: typeForLevel(maxLevel(prevLevel, level)), + + eos: typeForLevel(maxLevel(succLevel, level)), } + } // Resolving weak types Rules W1-W7. + // + // Note that some weak types (EN, AN) remain after this processing is + // complete. + func (s *isolatingRunSequence) resolveWeakTypes() { // on entry, only these types remain + s.assertOnly(L, R, AL, EN, ES, ET, AN, CS, B, S, WS, ON, NSM, LRI, RLI, FSI, PDI) // Rule W1. + // Changes all NSMs. + precedingCharacterType := s.sos + for i, t := range s.types { + if t == NSM { + s.types[i] = precedingCharacterType + } else { + // if t.in(LRI, RLI, FSI, PDI) { + // precedingCharacterType = ON + // } + precedingCharacterType = t + } + } // Rule W2. + // EN does not change at the start of the run, because sos != AL. + for i, t := range s.types { + if t == EN { + for j := i - 1; j >= 0; j-- { + if t := s.types[j]; t.in(L, R, AL) { + if t == AL { + s.types[i] = AN + } + break + } + } + } + } // Rule W3. + for i, t := range s.types { + if t == AL { + s.types[i] = R + } + } // Rule W4. + // Since there must be values on both sides for this rule to have an + // effect, the scan skips the first and last value. + // + // Although the scan proceeds left to right, and changes the type + // values in a way that would appear to affect the computations + // later in the scan, there is actually no problem. A change in the + // current value can only affect the value to its immediate right, + // and only affect it if it is ES or CS. But the current value can + // only change if the value to its right is not ES or CS. Thus + // either the current value will not change, or its change will have + // no effect on the remainder of the analysis. for i := 1; i < s.Len()-1; i++ { + t := s.types[i] + if t == ES || t == CS { + prevSepType := s.types[i-1] + succSepType := s.types[i+1] + if prevSepType == EN && succSepType == EN { + s.types[i] = EN + } else if s.types[i] == CS && prevSepType == AN && succSepType == AN { + s.types[i] = AN + } + } + } // Rule W5. + for i, t := range s.types { + if t == ET { + // locate end of sequence + runStart := i + runEnd := s.findRunLimit(runStart, ET) // check values at ends of sequence + t := s.sos + if runStart > 0 { + t = s.types[runStart-1] + } + if t != EN { + t = s.eos + if runEnd < len(s.types) { + t = s.types[runEnd] + } + } + if t == EN { + setTypes(s.types[runStart:runEnd], EN) + } + // continue at end of sequence + i = runEnd + } + } // Rule W6. + for i, t := range s.types { + if t.in(ES, ET, CS) { + s.types[i] = ON + } + } // Rule W7. + for i, t := range s.types { + if t == EN { + // set default if we reach start of run + prevStrongType := s.sos + for j := i - 1; j >= 0; j-- { + t = s.types[j] + if t == L || t == R { // AL's have been changed to R + prevStrongType = t + break + } + } + if prevStrongType == L { + s.types[i] = L + } + } + } + } // 6) resolving neutral types Rules N1-N2. + func (s *isolatingRunSequence) resolveNeutralTypes() { // on entry, only these types can be in resultTypes + s.assertOnly(L, R, EN, AN, B, S, WS, ON, RLI, LRI, FSI, PDI) for i, t := range s.types { + switch t { + case WS, ON, B, S, RLI, LRI, FSI, PDI: + // find bounds of run of neutrals + runStart := i + runEnd := s.findRunLimit(runStart, B, S, WS, ON, RLI, LRI, FSI, PDI) // determine effective types at ends of run + var leadType, trailType Class // Note that the character found can only be L, R, AN, or + // EN. + if runStart == 0 { + leadType = s.sos + } else { + leadType = s.types[runStart-1] + if leadType.in(AN, EN) { + leadType = R + } + } + if runEnd == len(s.types) { + trailType = s.eos + } else { + trailType = s.types[runEnd] + if trailType.in(AN, EN) { + trailType = R + } + } var resolvedType Class + if leadType == trailType { + // Rule N1. + resolvedType = leadType + } else { + // Rule N2. + // Notice the embedding level of the run is used, not + // the paragraph embedding level. + resolvedType = typeForLevel(s.level) + } setTypes(s.types[runStart:runEnd], resolvedType) // skip over run of (former) neutrals + i = runEnd + } + } + } func setLevels(levels []level, newLevel level) { + for i := range levels { + levels[i] = newLevel + } + } func setTypes(types []Class, newType Class) { + for i := range types { + types[i] = newType + } + } // 7) resolving implicit embedding levels Rules I1, I2. + func (s *isolatingRunSequence) resolveImplicitLevels() { // on entry, only these types can be in resultTypes + s.assertOnly(L, R, EN, AN) s.resolvedLevels = make([]level, len(s.types)) + setLevels(s.resolvedLevels, s.level) if (s.level & 1) == 0 { // even level + for i, t := range s.types { + // Rule I1. + if t == L { + // no change + } else if t == R { + s.resolvedLevels[i] += 1 + } else { // t == AN || t == EN + s.resolvedLevels[i] += 2 + } + } + } else { // odd level + for i, t := range s.types { + // Rule I2. + if t == R { + // no change + } else { // t == L || t == AN || t == EN + s.resolvedLevels[i] += 1 + } + } + } + } // Applies the levels and types resolved in rules W1-I2 to the + // resultLevels array. + func (s *isolatingRunSequence) applyLevelsAndTypes() { + for i, x := range s.indexes { + s.p.resultTypes[x] = s.types[i] + s.p.resultLevels[x] = s.resolvedLevels[i] + } + } // Return the limit of the run consisting only of the types in validSet + // starting at index. This checks the value at index, and will return + // index if that value is not in validSet. + func (s *isolatingRunSequence) findRunLimit(index int, validSet ...Class) int { + loop: + for ; index < len(s.types); index++ { + t := s.types[index] + for _, valid := range validSet { + if t == valid { + continue loop + } + } + return index // didn't find a match in validSet + } + return len(s.types) + } // Algorithm validation. Assert that all values in types are in the + // provided set. + func (s *isolatingRunSequence) assertOnly(codes ...Class) { + loop: + for i, t := range s.types { + for _, c := range codes { + if t == c { + continue loop + } + } + log.Panicf("invalid bidi code %v present in assertOnly at position %d", t, s.indexes[i]) + } + } // determineLevelRuns returns an array of level runs. Each level run is + // described as an array of indexes into the input string. + // + // Determines the level runs. Rule X9 will be applied in determining the + // runs, in the way that makes sure the characters that are supposed to be + // removed are not included in the runs. + func (p *paragraph) determineLevelRuns() [][]int { + run := []int{} + allRuns := [][]int{} + currentLevel := implicitLevel for i := range p.initialTypes { + if !isRemovedByX9(p.initialTypes[i]) { + if p.resultLevels[i] != currentLevel { + // we just encountered a new run; wrap up last run + if currentLevel >= 0 { // only wrap it up if there was a run + allRuns = append(allRuns, run) + run = nil + } + // Start new run + currentLevel = p.resultLevels[i] + } + run = append(run, i) + } + } + // Wrap up the final run, if any + if len(run) > 0 { + allRuns = append(allRuns, run) + } + return allRuns + } // Definition BD13. Determine isolating run sequences. + func (p *paragraph) determineIsolatingRunSequences() []*isolatingRunSequence { + levelRuns := p.determineLevelRuns() // Compute the run that each character belongs to + runForCharacter := make([]int, p.Len()) + for i, run := range levelRuns { + for _, index := range run { + runForCharacter[index] = i + } + } sequences := []*isolatingRunSequence{} @@ -789,75 +1374,135 @@ func (p *paragraph) determineIsolatingRunSequences() []*isolatingRunSequence { var currentRunSequence []int for _, run := range levelRuns { + first := run[0] + if p.initialTypes[first] != PDI || p.matchingIsolateInitiator[first] == -1 { + currentRunSequence = nil + // int run = i; + for { + // Copy this level run into currentRunSequence + currentRunSequence = append(currentRunSequence, run...) last := currentRunSequence[len(currentRunSequence)-1] + lastT := p.initialTypes[last] + if lastT.in(LRI, RLI, FSI) && p.matchingPDI[last] != p.Len() { + run = levelRuns[runForCharacter[p.matchingPDI[last]]] + } else { + break + } + } + sequences = append(sequences, p.isolatingRunSequence(currentRunSequence)) + } + } + return sequences + } // Assign level information to characters removed by rule X9. This is for + // ease of relating the level information to the original input data. Note + // that the levels assigned to these codes are arbitrary, they're chosen so + // as to avoid breaking level runs. + func (p *paragraph) assignLevelsToCharactersRemovedByX9() { + for i, t := range p.initialTypes { + if t.in(LRE, RLE, LRO, RLO, PDF, BN) { + p.resultTypes[i] = t + p.resultLevels[i] = -1 + } + } + // now propagate forward the levels information (could have + // propagated backward, the main thing is not to introduce a level + // break where one doesn't already exist). if p.resultLevels[0] == -1 { + p.resultLevels[0] = p.embeddingLevel + } + for i := 1; i < len(p.initialTypes); i++ { + if p.resultLevels[i] == -1 { + p.resultLevels[i] = p.resultLevels[i-1] + } + } + // Embedding information is for informational purposes only so need not be + // adjusted. + } // + // Output + // // getLevels computes levels array breaking lines at offsets in linebreaks. + // Rule L1. + // + // The linebreaks array must include at least one value. The values must be + // in strictly increasing order (no duplicates) between 1 and the length of + // the text, inclusive. The last value must be the length of the text. + func (p *paragraph) getLevels(linebreaks []int) []level { + // Note that since the previous processing has removed all + // P, S, and WS values from resultTypes, the values referred to + // in these rules are the initial types, before any processing + // has been applied (including processing of overrides). + // + // This example implementation has reinserted explicit format codes + // and BN, in order that the levels array correspond to the + // initial text. Their final placement is not normative. + // These codes are treated like WS in this implementation, + // so they don't interrupt sequences of WS. validateLineBreaks(linebreaks, p.Len()) @@ -865,207 +1510,369 @@ func (p *paragraph) getLevels(linebreaks []int) []level { result := append([]level(nil), p.resultLevels...) // don't worry about linebreaks since if there is a break within + // a series of WS values preceding S, the linebreak itself + // causes the reset. + for i, t := range p.initialTypes { + if t.in(B, S) { + // Rule L1, clauses one and two. + result[i] = p.embeddingLevel // Rule L1, clause three. + for j := i - 1; j >= 0; j-- { + if isWhitespace(p.initialTypes[j]) { // including format codes + result[j] = p.embeddingLevel + } else { + break + } + } + } + } // Rule L1, clause four. + start := 0 + for _, limit := range linebreaks { + for j := limit - 1; j >= start; j-- { + if isWhitespace(p.initialTypes[j]) { // including format codes + result[j] = p.embeddingLevel + } else { + break + } + } + start = limit + } return result + } // getReordering returns the reordering of lines from a visual index to a + // logical index for line breaks at the given offsets. + // + // Lines are concatenated from left to right. So for example, the fifth + // character from the left on the third line is + // + // getReordering(linebreaks)[linebreaks[1] + 4] + // + // (linebreaks[1] is the position after the last character of the second + // line, which is also the index of the first character on the third line, + // and adding four gets the fifth character from the left). + // + // The linebreaks array must include at least one value. The values must be + // in strictly increasing order (no duplicates) between 1 and the length of + // the text, inclusive. The last value must be the length of the text. + func (p *paragraph) getReordering(linebreaks []int) []int { + validateLineBreaks(linebreaks, p.Len()) return computeMultilineReordering(p.getLevels(linebreaks), linebreaks) + } // Return multiline reordering array for a given level array. Reordering + // does not occur across a line break. + func computeMultilineReordering(levels []level, linebreaks []int) []int { + result := make([]int, len(levels)) start := 0 + for _, limit := range linebreaks { + tempLevels := make([]level, limit-start) + copy(tempLevels, levels[start:]) for j, order := range computeReordering(tempLevels) { + result[start+j] = order + start + } + start = limit + } + return result + } // Return reordering array for a given level array. This reorders a single + // line. The reordering is a visual to logical map. For example, the + // leftmost char is string.charAt(order[0]). Rule L2. + func computeReordering(levels []level) []int { + result := make([]int, len(levels)) + // initialize order + for i := range result { + result[i] = i + } // locate highest level found on line. + // Note the rules say text, but no reordering across line bounds is + // performed, so this is sufficient. + highestLevel := level(0) + lowestOddLevel := level(maxDepth + 2) + for _, level := range levels { + if level > highestLevel { + highestLevel = level + } + if level&1 != 0 && level < lowestOddLevel { + lowestOddLevel = level + } + } for level := highestLevel; level >= lowestOddLevel; level-- { + for i := 0; i < len(levels); i++ { + if levels[i] >= level { + // find range of text at or above this level + start := i + limit := i + 1 + for limit < len(levels) && levels[limit] >= level { + limit++ + } for j, k := start, limit-1; j < k; j, k = j+1, k-1 { + result[j], result[k] = result[k], result[j] + } + // skip to end of level run + i = limit + } + } + } return result + } // isWhitespace reports whether the type is considered a whitespace type for the + // line break rules. + func isWhitespace(c Class) bool { + switch c { + case LRE, RLE, LRO, RLO, PDF, LRI, RLI, FSI, PDI, BN, WS: + return true + } + return false + } // isRemovedByX9 reports whether the type is one of the types removed in X9. + func isRemovedByX9(c Class) bool { + switch c { + case LRE, RLE, LRO, RLO, PDF, BN: + return true + } + return false + } // typeForLevel reports the strong type (L or R) corresponding to the level. + func typeForLevel(level level) Class { + if (level & 0x1) == 0 { + return L + } + return R + } func validateTypes(types []Class) error { + if len(types) == 0 { + return fmt.Errorf("types is null") + } + for i, t := range types[:len(types)-1] { + if t == B { + return fmt.Errorf("B type before end of paragraph at index: %d", i) + } + } + return nil + } func validateParagraphEmbeddingLevel(embeddingLevel level) error { + if embeddingLevel != implicitLevel && + embeddingLevel != 0 && + embeddingLevel != 1 { + return fmt.Errorf("illegal paragraph embedding level: %d", embeddingLevel) + } + return nil + } func validateLineBreaks(linebreaks []int, textLength int) error { + prev := 0 + for i, next := range linebreaks { + if next <= prev { + return fmt.Errorf("bad linebreak: %d at index: %d", next, i) + } + prev = next + } + if prev != textLength { + return fmt.Errorf("last linebreak was %d, want %d", prev, textLength) + } + return nil + } func validatePbTypes(pairTypes []bracketType) error { + if len(pairTypes) == 0 { + return fmt.Errorf("pairTypes is null") + } + for i, pt := range pairTypes { + switch pt { + case bpNone, bpOpen, bpClose: + default: + return fmt.Errorf("illegal pairType value at %d: %v", i, pairTypes[i]) + } + } + return nil + } func validatePbValues(pairValues []rune, pairTypes []bracketType) error { + if pairValues == nil { + return fmt.Errorf("pairValues is null") + } + if len(pairTypes) != len(pairValues) { + return fmt.Errorf("pairTypes is different length from pairValues") + } + return nil + } diff --git a/vendor/golang.org/x/text/unicode/norm/iter.go b/vendor/golang.org/x/text/unicode/norm/iter.go index 417c6b2..5108203 100644 --- a/vendor/golang.org/x/text/unicode/norm/iter.go +++ b/vendor/golang.org/x/text/unicode/norm/iter.go @@ -1,5 +1,7 @@ // Copyright 2011 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package norm @@ -10,449 +12,848 @@ import ( ) // MaxSegmentSize is the maximum size of a byte buffer needed to consider any + // sequence of starter and non-starter runes for the purpose of normalization. + const MaxSegmentSize = maxByteBufferSize // An Iter iterates over a string or byte slice, while normalizing it + // to a given Form. + type Iter struct { - rb reorderBuffer - buf [maxByteBufferSize]byte - info Properties // first character saved from previous iteration - next iterFunc // implementation of next depends on form + rb reorderBuffer + + buf [maxByteBufferSize]byte + + info Properties // first character saved from previous iteration + + next iterFunc // implementation of next depends on form + asciiF iterFunc - p int // current position in input source + p int // current position in input source + multiSeg []byte // remainder of multi-segment decomposition + } type iterFunc func(*Iter) []byte // Init initializes i to iterate over src after normalizing it to Form f. + func (i *Iter) Init(f Form, src []byte) { + i.p = 0 + if len(src) == 0 { + i.setDone() + i.rb.nsrc = 0 + return + } + i.multiSeg = nil + i.rb.init(f, src) + i.next = i.rb.f.nextMain + i.asciiF = nextASCIIBytes + i.info = i.rb.f.info(i.rb.src, i.p) + i.rb.ss.first(i.info) + } // InitString initializes i to iterate over src after normalizing it to Form f. + func (i *Iter) InitString(f Form, src string) { + i.p = 0 + if len(src) == 0 { + i.setDone() + i.rb.nsrc = 0 + return + } + i.multiSeg = nil + i.rb.initString(f, src) + i.next = i.rb.f.nextMain + i.asciiF = nextASCIIString + i.info = i.rb.f.info(i.rb.src, i.p) + i.rb.ss.first(i.info) + } // Seek sets the segment to be returned by the next call to Next to start + // at position p. It is the responsibility of the caller to set p to the + // start of a segment. + func (i *Iter) Seek(offset int64, whence int) (int64, error) { + var abs int64 + switch whence { + case 0: + abs = offset + case 1: + abs = int64(i.p) + offset + case 2: + abs = int64(i.rb.nsrc) + offset + default: + return 0, fmt.Errorf("norm: invalid whence") + } + if abs < 0 { + return 0, fmt.Errorf("norm: negative position") + } + if int(abs) >= i.rb.nsrc { + i.setDone() + return int64(i.p), nil + } + i.p = int(abs) + i.multiSeg = nil + i.next = i.rb.f.nextMain + i.info = i.rb.f.info(i.rb.src, i.p) + i.rb.ss.first(i.info) + return abs, nil + } // returnSlice returns a slice of the underlying input type as a byte slice. + // If the underlying is of type []byte, it will simply return a slice. + // If the underlying is of type string, it will copy the slice to the buffer + // and return that. + func (i *Iter) returnSlice(a, b int) []byte { + if i.rb.src.bytes == nil { + return i.buf[:copy(i.buf[:], i.rb.src.str[a:b])] + } + return i.rb.src.bytes[a:b] + } // Pos returns the byte position at which the next call to Next will commence processing. + func (i *Iter) Pos() int { + return i.p + } func (i *Iter) setDone() { + i.next = nextDone + i.p = i.rb.nsrc + } // Done returns true if there is no more input to process. + func (i *Iter) Done() bool { + return i.p >= i.rb.nsrc + } // Next returns f(i.input[i.Pos():n]), where n is a boundary of i.input. + // For any input a and b for which f(a) == f(b), subsequent calls + // to Next will return the same segments. + // Modifying runes are grouped together with the preceding starter, if such a starter exists. + // Although not guaranteed, n will typically be the smallest possible n. + func (i *Iter) Next() []byte { + return i.next(i) + } func nextASCIIBytes(i *Iter) []byte { + p := i.p + 1 + if p >= i.rb.nsrc { + p0 := i.p + i.setDone() + return i.rb.src.bytes[p0:p] + } + if i.rb.src.bytes[p] < utf8.RuneSelf { + p0 := i.p + i.p = p + return i.rb.src.bytes[p0:p] + } + i.info = i.rb.f.info(i.rb.src, i.p) + i.next = i.rb.f.nextMain + return i.next(i) + } func nextASCIIString(i *Iter) []byte { + p := i.p + 1 + if p >= i.rb.nsrc { + i.buf[0] = i.rb.src.str[i.p] + i.setDone() + return i.buf[:1] + } + if i.rb.src.str[p] < utf8.RuneSelf { + i.buf[0] = i.rb.src.str[i.p] + i.p = p + return i.buf[:1] + } + i.info = i.rb.f.info(i.rb.src, i.p) + i.next = i.rb.f.nextMain + return i.next(i) + } func nextHangul(i *Iter) []byte { + p := i.p + next := p + hangulUTF8Size + if next >= i.rb.nsrc { + i.setDone() + } else if i.rb.src.hangul(next) == 0 { + i.rb.ss.next(i.info) + i.info = i.rb.f.info(i.rb.src, i.p) + i.next = i.rb.f.nextMain + return i.next(i) + } + i.p = next + return i.buf[:decomposeHangul(i.buf[:], i.rb.src.hangul(p))] + } func nextDone(i *Iter) []byte { + return nil + } // nextMulti is used for iterating over multi-segment decompositions + // for decomposing normal forms. + func nextMulti(i *Iter) []byte { + j := 0 + d := i.multiSeg + // skip first rune + for j = 1; j < len(d) && !utf8.RuneStart(d[j]); j++ { + } + for j < len(d) { + info := i.rb.f.info(input{bytes: d}, j) + if info.BoundaryBefore() { + i.multiSeg = d[j:] + return d[:j] + } + j += int(info.size) + } + // treat last segment as normal decomposition + i.next = i.rb.f.nextMain + return i.next(i) + } // nextMultiNorm is used for iterating over multi-segment decompositions + // for composing normal forms. + func nextMultiNorm(i *Iter) []byte { + j := 0 + d := i.multiSeg + for j < len(d) { + info := i.rb.f.info(input{bytes: d}, j) + if info.BoundaryBefore() { + i.rb.compose() + seg := i.buf[:i.rb.flushCopy(i.buf[:])] + i.rb.insertUnsafe(input{bytes: d}, j, info) + i.multiSeg = d[j+int(info.size):] + return seg + } + i.rb.insertUnsafe(input{bytes: d}, j, info) + j += int(info.size) + } + i.multiSeg = nil + i.next = nextComposed + return doNormComposed(i) + } // nextDecomposed is the implementation of Next for forms NFD and NFKD. + func nextDecomposed(i *Iter) (next []byte) { + outp := 0 + inCopyStart, outCopyStart := i.p, 0 + for { + if sz := int(i.info.size); sz <= 1 { + i.rb.ss = 0 + p := i.p + i.p++ // ASCII or illegal byte. Either way, advance by 1. + if i.p >= i.rb.nsrc { + i.setDone() + return i.returnSlice(p, i.p) + } else if i.rb.src._byte(i.p) < utf8.RuneSelf { + i.next = i.asciiF + return i.returnSlice(p, i.p) + } + outp++ + } else if d := i.info.Decomposition(); d != nil { + // Note: If leading CCC != 0, then len(d) == 2 and last is also non-zero. + // Case 1: there is a leftover to copy. In this case the decomposition + // must begin with a modifier and should always be appended. + // Case 2: no leftover. Simply return d if followed by a ccc == 0 value. + p := outp + len(d) + if outp > 0 { + i.rb.src.copySlice(i.buf[outCopyStart:], inCopyStart, i.p) + // TODO: this condition should not be possible, but we leave it + // in for defensive purposes. + if p > len(i.buf) { + return i.buf[:outp] + } + } else if i.info.multiSegment() { + // outp must be 0 as multi-segment decompositions always + // start a new segment. + if i.multiSeg == nil { + i.multiSeg = d + i.next = nextMulti + return nextMulti(i) + } + // We are in the last segment. Treat as normal decomposition. + d = i.multiSeg + i.multiSeg = nil + p = len(d) + } + prevCC := i.info.tccc + if i.p += sz; i.p >= i.rb.nsrc { + i.setDone() + i.info = Properties{} // Force BoundaryBefore to succeed. + } else { + i.info = i.rb.f.info(i.rb.src, i.p) + } + switch i.rb.ss.next(i.info) { + case ssOverflow: + i.next = nextCGJDecompose + fallthrough + case ssStarter: + if outp > 0 { + copy(i.buf[outp:], d) + return i.buf[:p] + } + return d + } + copy(i.buf[outp:], d) + outp = p + inCopyStart, outCopyStart = i.p, outp + if i.info.ccc < prevCC { + goto doNorm + } + continue + } else if r := i.rb.src.hangul(i.p); r != 0 { + outp = decomposeHangul(i.buf[:], r) + i.p += hangulUTF8Size + inCopyStart, outCopyStart = i.p, outp + if i.p >= i.rb.nsrc { + i.setDone() + break + } else if i.rb.src.hangul(i.p) != 0 { + i.next = nextHangul + return i.buf[:outp] + } + } else { + p := outp + sz + if p > len(i.buf) { + break + } + outp = p + i.p += sz + } + if i.p >= i.rb.nsrc { + i.setDone() + break + } + prevCC := i.info.tccc + i.info = i.rb.f.info(i.rb.src, i.p) + if v := i.rb.ss.next(i.info); v == ssStarter { + break + } else if v == ssOverflow { + i.next = nextCGJDecompose + break + } + if i.info.ccc < prevCC { + goto doNorm + } + } + if outCopyStart == 0 { + return i.returnSlice(inCopyStart, i.p) + } else if inCopyStart < i.p { + i.rb.src.copySlice(i.buf[outCopyStart:], inCopyStart, i.p) + } + return i.buf[:outp] + doNorm: + // Insert what we have decomposed so far in the reorderBuffer. + // As we will only reorder, there will always be enough room. + i.rb.src.copySlice(i.buf[outCopyStart:], inCopyStart, i.p) + i.rb.insertDecomposed(i.buf[0:outp]) + return doNormDecomposed(i) + } func doNormDecomposed(i *Iter) []byte { + for { + i.rb.insertUnsafe(i.rb.src, i.p, i.info) + if i.p += int(i.info.size); i.p >= i.rb.nsrc { + i.setDone() + break + } + i.info = i.rb.f.info(i.rb.src, i.p) + if i.info.ccc == 0 { + break + } + if s := i.rb.ss.next(i.info); s == ssOverflow { + i.next = nextCGJDecompose + break + } + } + // new segment or too many combining characters: exit normalization + return i.buf[:i.rb.flushCopy(i.buf[:])] + } func nextCGJDecompose(i *Iter) []byte { + i.rb.ss = 0 + i.rb.insertCGJ() + i.next = nextDecomposed + i.rb.ss.first(i.info) + buf := doNormDecomposed(i) + return buf + } // nextComposed is the implementation of Next for forms NFC and NFKC. + func nextComposed(i *Iter) []byte { + outp, startp := 0, i.p + var prevCC uint8 + for { + if !i.info.isYesC() { + goto doNorm + } + prevCC = i.info.tccc + sz := int(i.info.size) + if sz == 0 { + sz = 1 // illegal rune: copy byte-by-byte + } + p := outp + sz + if p > len(i.buf) { + break + } + outp = p + i.p += sz + if i.p >= i.rb.nsrc { + i.setDone() + break + } else if i.rb.src._byte(i.p) < utf8.RuneSelf { + i.rb.ss = 0 + i.next = i.asciiF + break + } + i.info = i.rb.f.info(i.rb.src, i.p) + if v := i.rb.ss.next(i.info); v == ssStarter { + break + } else if v == ssOverflow { + i.next = nextCGJCompose + break + } + if i.info.ccc < prevCC { + goto doNorm + } + } + return i.returnSlice(startp, i.p) + doNorm: + // reset to start position + i.p = startp + i.info = i.rb.f.info(i.rb.src, i.p) + i.rb.ss.first(i.info) + if i.info.multiSegment() { + d := i.info.Decomposition() + info := i.rb.f.info(input{bytes: d}, 0) + i.rb.insertUnsafe(input{bytes: d}, 0, info) + i.multiSeg = d[int(info.size):] + i.next = nextMultiNorm + return nextMultiNorm(i) + } + i.rb.ss.first(i.info) + i.rb.insertUnsafe(i.rb.src, i.p, i.info) + return doNormComposed(i) + } func doNormComposed(i *Iter) []byte { + // First rune should already be inserted. + for { + if i.p += int(i.info.size); i.p >= i.rb.nsrc { + i.setDone() + break + } + i.info = i.rb.f.info(i.rb.src, i.p) + if s := i.rb.ss.next(i.info); s == ssStarter { + break + } else if s == ssOverflow { + i.next = nextCGJCompose + break + } + i.rb.insertUnsafe(i.rb.src, i.p, i.info) + } + i.rb.compose() + seg := i.buf[:i.rb.flushCopy(i.buf[:])] + return seg + } func nextCGJCompose(i *Iter) []byte { + i.rb.ss = 0 // instead of first + i.rb.insertCGJ() + i.next = nextComposed + // Note that we treat any rune with nLeadingNonStarters > 0 as a non-starter, + // even if they are not. This is particularly dubious for U+FF9E and UFF9A. + // If we ever change that, insert a check here. + i.rb.ss.first(i.info) + i.rb.insertUnsafe(i.rb.src, i.p, i.info) + return doNormComposed(i) + } diff --git a/vendor/golang.org/x/text/unicode/norm/normalize.go b/vendor/golang.org/x/text/unicode/norm/normalize.go index 4747ad0..a89ef65 100644 --- a/vendor/golang.org/x/text/unicode/norm/normalize.go +++ b/vendor/golang.org/x/text/unicode/norm/normalize.go @@ -1,12 +1,17 @@ // Copyright 2011 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Note: the file data_test.go that is generated should not be checked in. + //go:generate go run maketables.go triegen.go + //go:generate go test -tags test // Package norm contains types and functions for normalizing Unicode strings. + package norm // import "golang.org/x/text/unicode/norm" import ( @@ -16,595 +21,1125 @@ import ( ) // A Form denotes a canonical representation of Unicode code points. + // The Unicode-defined normalization and equivalence forms are: + // + // NFC Unicode Normalization Form C + // NFD Unicode Normalization Form D + // NFKC Unicode Normalization Form KC + // NFKD Unicode Normalization Form KD + // + // For a Form f, this documentation uses the notation f(x) to mean + // the bytes or string x converted to the given form. + // A position n in x is called a boundary if conversion to the form can + // proceed independently on both sides: + // + // f(x) == append(f(x[0:n]), f(x[n:])...) + // + // References: https://unicode.org/reports/tr15/ and + // https://unicode.org/notes/tn5/. + type Form int const ( NFC Form = iota + NFD + NFKC + NFKD ) // Bytes returns f(b). May return b if f(b) = b. + func (f Form) Bytes(b []byte) []byte { + src := inputBytes(b) + ft := formTable[f] + n, ok := ft.quickSpan(src, 0, len(b), true) + if ok { + return b + } + out := make([]byte, n, len(b)) + copy(out, b[0:n]) + rb := reorderBuffer{f: *ft, src: src, nsrc: len(b), out: out, flushF: appendFlush} + return doAppendInner(&rb, n) + } // String returns f(s). + func (f Form) String(s string) string { + src := inputString(s) + ft := formTable[f] + n, ok := ft.quickSpan(src, 0, len(s), true) + if ok { + return s + } + out := make([]byte, n, len(s)) + copy(out, s[0:n]) + rb := reorderBuffer{f: *ft, src: src, nsrc: len(s), out: out, flushF: appendFlush} + return string(doAppendInner(&rb, n)) + } // IsNormal returns true if b == f(b). + func (f Form) IsNormal(b []byte) bool { + src := inputBytes(b) + ft := formTable[f] + bp, ok := ft.quickSpan(src, 0, len(b), true) + if ok { + return true + } + rb := reorderBuffer{f: *ft, src: src, nsrc: len(b)} + rb.setFlusher(nil, cmpNormalBytes) + for bp < len(b) { + rb.out = b[bp:] + if bp = decomposeSegment(&rb, bp, true); bp < 0 { + return false + } + bp, _ = rb.f.quickSpan(rb.src, bp, len(b), true) + } + return true + } func cmpNormalBytes(rb *reorderBuffer) bool { + b := rb.out + for i := 0; i < rb.nrune; i++ { + info := rb.rune[i] + if int(info.size) > len(b) { + return false + } + p := info.pos + pe := p + info.size + for ; p < pe; p++ { + if b[0] != rb.byte[p] { + return false + } + b = b[1:] + } + } + return true + } // IsNormalString returns true if s == f(s). + func (f Form) IsNormalString(s string) bool { + src := inputString(s) + ft := formTable[f] + bp, ok := ft.quickSpan(src, 0, len(s), true) + if ok { + return true + } + rb := reorderBuffer{f: *ft, src: src, nsrc: len(s)} + rb.setFlusher(nil, func(rb *reorderBuffer) bool { + for i := 0; i < rb.nrune; i++ { + info := rb.rune[i] + if bp+int(info.size) > len(s) { + return false + } + p := info.pos + pe := p + info.size + for ; p < pe; p++ { + if s[bp] != rb.byte[p] { + return false + } + bp++ + } + } + return true + }) + for bp < len(s) { + if bp = decomposeSegment(&rb, bp, true); bp < 0 { + return false + } + bp, _ = rb.f.quickSpan(rb.src, bp, len(s), true) + } + return true + } // patchTail fixes a case where a rune may be incorrectly normalized + // if it is followed by illegal continuation bytes. It returns the + // patched buffer and whether the decomposition is still in progress. + func patchTail(rb *reorderBuffer) bool { + info, p := lastRuneStart(&rb.f, rb.out) + if p == -1 || info.size == 0 { + return true + } + end := p + int(info.size) + extra := len(rb.out) - end + if extra > 0 { + // Potentially allocating memory. However, this only + // happens with ill-formed UTF-8. + x := make([]byte, 0) + x = append(x, rb.out[len(rb.out)-extra:]...) + rb.out = rb.out[:end] + decomposeToLastBoundary(rb) + rb.doFlush() + rb.out = append(rb.out, x...) + return false + } + buf := rb.out[p:] + rb.out = rb.out[:p] + decomposeToLastBoundary(rb) + if s := rb.ss.next(info); s == ssStarter { + rb.doFlush() + rb.ss.first(info) + } else if s == ssOverflow { + rb.doFlush() + rb.insertCGJ() + rb.ss = 0 + } + rb.insertUnsafe(inputBytes(buf), 0, info) + return true + } func appendQuick(rb *reorderBuffer, i int) int { + if rb.nsrc == i { + return i + } + end, _ := rb.f.quickSpan(rb.src, i, rb.nsrc, true) + rb.out = rb.src.appendSlice(rb.out, i, end) + return end + } // Append returns f(append(out, b...)). + // The buffer out must be nil, empty, or equal to f(out). + func (f Form) Append(out []byte, src ...byte) []byte { + return f.doAppend(out, inputBytes(src), len(src)) + } func (f Form) doAppend(out []byte, src input, n int) []byte { + if n == 0 { + return out + } + ft := formTable[f] + // Attempt to do a quickSpan first so we can avoid initializing the reorderBuffer. + if len(out) == 0 { + p, _ := ft.quickSpan(src, 0, n, true) + out = src.appendSlice(out, 0, p) + if p == n { + return out + } + rb := reorderBuffer{f: *ft, src: src, nsrc: n, out: out, flushF: appendFlush} + return doAppendInner(&rb, p) + } + rb := reorderBuffer{f: *ft, src: src, nsrc: n} + return doAppend(&rb, out, 0) + } func doAppend(rb *reorderBuffer, out []byte, p int) []byte { + rb.setFlusher(out, appendFlush) + src, n := rb.src, rb.nsrc + doMerge := len(out) > 0 + if q := src.skipContinuationBytes(p); q > p { + // Move leading non-starters to destination. + rb.out = src.appendSlice(rb.out, p, q) + p = q + doMerge = patchTail(rb) + } + fd := &rb.f + if doMerge { + var info Properties + if p < n { + info = fd.info(src, p) + if !info.BoundaryBefore() || info.nLeadingNonStarters() > 0 { + if p == 0 { + decomposeToLastBoundary(rb) + } + p = decomposeSegment(rb, p, true) + } + } + if info.size == 0 { + rb.doFlush() + // Append incomplete UTF-8 encoding. + return src.appendSlice(rb.out, p, n) + } + if rb.nrune > 0 { + return doAppendInner(rb, p) + } + } + p = appendQuick(rb, p) + return doAppendInner(rb, p) + } func doAppendInner(rb *reorderBuffer, p int) []byte { + for n := rb.nsrc; p < n; { + p = decomposeSegment(rb, p, true) + p = appendQuick(rb, p) + } + return rb.out + } // AppendString returns f(append(out, []byte(s))). + // The buffer out must be nil, empty, or equal to f(out). + func (f Form) AppendString(out []byte, src string) []byte { + return f.doAppend(out, inputString(src), len(src)) + } // QuickSpan returns a boundary n such that b[0:n] == f(b[0:n]). + // It is not guaranteed to return the largest such n. + func (f Form) QuickSpan(b []byte) int { + n, _ := formTable[f].quickSpan(inputBytes(b), 0, len(b), true) + return n + } // Span implements transform.SpanningTransformer. It returns a boundary n such + // that b[0:n] == f(b[0:n]). It is not guaranteed to return the largest such n. + func (f Form) Span(b []byte, atEOF bool) (n int, err error) { + n, ok := formTable[f].quickSpan(inputBytes(b), 0, len(b), atEOF) + if n < len(b) { + if !ok { + err = transform.ErrEndOfSpan + } else { + err = transform.ErrShortSrc + } + } + return n, err + } // SpanString returns a boundary n such that s[0:n] == f(s[0:n]). + // It is not guaranteed to return the largest such n. + func (f Form) SpanString(s string, atEOF bool) (n int, err error) { + n, ok := formTable[f].quickSpan(inputString(s), 0, len(s), atEOF) + if n < len(s) { + if !ok { + err = transform.ErrEndOfSpan + } else { + err = transform.ErrShortSrc + } + } + return n, err + } // quickSpan returns a boundary n such that src[0:n] == f(src[0:n]) and + // whether any non-normalized parts were found. If atEOF is false, n will + // not point past the last segment if this segment might be become + // non-normalized by appending other runes. + func (f *formInfo) quickSpan(src input, i, end int, atEOF bool) (n int, ok bool) { + var lastCC uint8 + ss := streamSafe(0) + lastSegStart := i + for n = end; i < n; { + if j := src.skipASCII(i, n); i != j { + i = j + lastSegStart = i - 1 + lastCC = 0 + ss = 0 + continue + } + info := f.info(src, i) + if info.size == 0 { + if atEOF { + // include incomplete runes + return n, true + } + return lastSegStart, true + } + // This block needs to be before the next, because it is possible to + // have an overflow for runes that are starters (e.g. with U+FF9E). + switch ss.next(info) { + case ssStarter: + lastSegStart = i + case ssOverflow: + return lastSegStart, false + case ssSuccess: + if lastCC > info.ccc { + return lastSegStart, false + } + } + if f.composing { + if !info.isYesC() { + break + } + } else { + if !info.isYesD() { + break + } + } + lastCC = info.ccc + i += int(info.size) + } + if i == n { + if !atEOF { + n = lastSegStart + } + return n, true + } + return lastSegStart, false + } // QuickSpanString returns a boundary n such that s[0:n] == f(s[0:n]). + // It is not guaranteed to return the largest such n. + func (f Form) QuickSpanString(s string) int { + n, _ := formTable[f].quickSpan(inputString(s), 0, len(s), true) + return n + } // FirstBoundary returns the position i of the first boundary in b + // or -1 if b contains no boundary. + func (f Form) FirstBoundary(b []byte) int { + return f.firstBoundary(inputBytes(b), len(b)) + } func (f Form) firstBoundary(src input, nsrc int) int { + i := src.skipContinuationBytes(0) + if i >= nsrc { + return -1 + } + fd := formTable[f] + ss := streamSafe(0) + // We should call ss.first here, but we can't as the first rune is + // skipped already. This means FirstBoundary can't really determine + // CGJ insertion points correctly. Luckily it doesn't have to. + for { + info := fd.info(src, i) + if info.size == 0 { + return -1 + } + if s := ss.next(info); s != ssSuccess { + return i + } + i += int(info.size) + if i >= nsrc { + if !info.BoundaryAfter() && !ss.isMax() { + return -1 + } + return nsrc + } + } + } // FirstBoundaryInString returns the position i of the first boundary in s + // or -1 if s contains no boundary. + func (f Form) FirstBoundaryInString(s string) int { + return f.firstBoundary(inputString(s), len(s)) + } // NextBoundary reports the index of the boundary between the first and next + // segment in b or -1 if atEOF is false and there are not enough bytes to + // determine this boundary. + func (f Form) NextBoundary(b []byte, atEOF bool) int { + return f.nextBoundary(inputBytes(b), len(b), atEOF) + } // NextBoundaryInString reports the index of the boundary between the first and + // next segment in b or -1 if atEOF is false and there are not enough bytes to + // determine this boundary. + func (f Form) NextBoundaryInString(s string, atEOF bool) int { + return f.nextBoundary(inputString(s), len(s), atEOF) + } func (f Form) nextBoundary(src input, nsrc int, atEOF bool) int { + if nsrc == 0 { + if atEOF { + return 0 + } + return -1 + } + fd := formTable[f] + info := fd.info(src, 0) + if info.size == 0 { + if atEOF { + return 1 + } + return -1 + } + ss := streamSafe(0) + ss.first(info) for i := int(info.size); i < nsrc; i += int(info.size) { + info = fd.info(src, i) + if info.size == 0 { + if atEOF { + return i + } + return -1 + } + // TODO: Using streamSafe to determine the boundary isn't the same as + // using BoundaryBefore. Determine which should be used. + if s := ss.next(info); s != ssSuccess { + return i + } + } + if !atEOF && !info.BoundaryAfter() && !ss.isMax() { + return -1 + } + return nsrc + } // LastBoundary returns the position i of the last boundary in b + // or -1 if b contains no boundary. + func (f Form) LastBoundary(b []byte) int { + return lastBoundary(formTable[f], b) + } func lastBoundary(fd *formInfo, b []byte) int { + i := len(b) + info, p := lastRuneStart(fd, b) + if p == -1 { + return -1 + } + if info.size == 0 { // ends with incomplete rune + if p == 0 { // starts with incomplete rune + return -1 + } + i = p + info, p = lastRuneStart(fd, b[:i]) + if p == -1 { // incomplete UTF-8 encoding or non-starter bytes without a starter + return i + } + } + if p+int(info.size) != i { // trailing non-starter bytes: illegal UTF-8 + return i + } + if info.BoundaryAfter() { + return i + } + ss := streamSafe(0) + v := ss.backwards(info) + for i = p; i >= 0 && v != ssStarter; i = p { + info, p = lastRuneStart(fd, b[:i]) + if v = ss.backwards(info); v == ssOverflow { + break + } + if p+int(info.size) != i { + if p == -1 { // no boundary found + return -1 + } + return i // boundary after an illegal UTF-8 encoding + } + } + return i + } // decomposeSegment scans the first segment in src into rb. It inserts 0x034f + // (Grapheme Joiner) when it encounters a sequence of more than 30 non-starters + // and returns the number of bytes consumed from src or iShortDst or iShortSrc. + func decomposeSegment(rb *reorderBuffer, sp int, atEOF bool) int { + // Force one character to be consumed. + info := rb.f.info(rb.src, sp) + if info.size == 0 { + return 0 + } + if s := rb.ss.next(info); s == ssStarter { + // TODO: this could be removed if we don't support merging. + if rb.nrune > 0 { + goto end + } + } else if s == ssOverflow { + rb.insertCGJ() + goto end + } + if err := rb.insertFlush(rb.src, sp, info); err != iSuccess { + return int(err) + } + for { + sp += int(info.size) + if sp >= rb.nsrc { + if !atEOF && !info.BoundaryAfter() { + return int(iShortSrc) + } + break + } + info = rb.f.info(rb.src, sp) + if info.size == 0 { + if !atEOF { + return int(iShortSrc) + } + break + } + if s := rb.ss.next(info); s == ssStarter { + break + } else if s == ssOverflow { + rb.insertCGJ() + break + } + if err := rb.insertFlush(rb.src, sp, info); err != iSuccess { + return int(err) + } + } + end: + if !rb.doFlush() { + return int(iShortDst) + } + return sp + } // lastRuneStart returns the runeInfo and position of the last + // rune in buf or the zero runeInfo and -1 if no rune was found. + func lastRuneStart(fd *formInfo, buf []byte) (Properties, int) { + p := len(buf) - 1 + for ; p >= 0 && !utf8.RuneStart(buf[p]); p-- { + } + if p < 0 { + return Properties{}, -1 + } + return fd.info(inputBytes(buf), p), p + } // decomposeToLastBoundary finds an open segment at the end of the buffer + // and scans it into rb. Returns the buffer minus the last segment. + func decomposeToLastBoundary(rb *reorderBuffer) { + fd := &rb.f + info, i := lastRuneStart(fd, rb.out) + if int(info.size) != len(rb.out)-i { + // illegal trailing continuation bytes + return + } + if info.BoundaryAfter() { + return + } + var add [maxNonStarters + 1]Properties // stores runeInfo in reverse order + padd := 0 + ss := streamSafe(0) + p := len(rb.out) + for { + add[padd] = info + v := ss.backwards(info) + if v == ssOverflow { + // Note that if we have an overflow, it the string we are appending to + // is not correctly normalized. In this case the behavior is undefined. + break + } + padd++ + p -= int(info.size) + if v == ssStarter || p < 0 { + break + } + info, i = lastRuneStart(fd, rb.out[:p]) + if int(info.size) != p-i { + break + } + } + rb.ss = ss + // Copy bytes for insertion as we may need to overwrite rb.out. + var buf [maxBufferSize * utf8.UTFMax]byte + cp := buf[:copy(buf[:], rb.out[p:])] + rb.out = rb.out[:p] + for padd--; padd >= 0; padd-- { + info = add[padd] + rb.insertUnsafe(inputBytes(cp), 0, info) + cp = cp[info.size:] + } + } diff --git a/vendor/golang.org/x/text/unicode/norm/transform.go b/vendor/golang.org/x/text/unicode/norm/transform.go index a1d366a..c5863fe 100644 --- a/vendor/golang.org/x/text/unicode/norm/transform.go +++ b/vendor/golang.org/x/text/unicode/norm/transform.go @@ -1,5 +1,7 @@ // Copyright 2013 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package norm @@ -11,78 +13,141 @@ import ( ) // Reset implements the Reset method of the transform.Transformer interface. + func (Form) Reset() {} // Transform implements the Transform method of the transform.Transformer + // interface. It may need to write segments of up to MaxSegmentSize at once. + // Users should either catch ErrShortDst and allow dst to grow or have dst be at + // least of size MaxTransformChunkSize to be guaranteed of progress. + func (f Form) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { + // Cap the maximum number of src bytes to check. + b := src + eof := atEOF + if ns := len(dst); ns < len(b) { + err = transform.ErrShortDst + eof = false + b = b[:ns] + } + i, ok := formTable[f].quickSpan(inputBytes(b), 0, len(b), eof) + n := copy(dst, b[:i]) + if !ok { + nDst, nSrc, err = f.transform(dst[n:], src[n:], atEOF) + return nDst + n, nSrc + n, err + } if err == nil && n < len(src) && !atEOF { + err = transform.ErrShortSrc + } + return n, n, err + } func flushTransform(rb *reorderBuffer) bool { + // Write out (must fully fit in dst, or else it is an ErrShortDst). + if len(rb.out) < rb.nrune*utf8.UTFMax { + return false + } + rb.out = rb.out[rb.flushCopy(rb.out):] + return true + } var errs = []error{nil, transform.ErrShortDst, transform.ErrShortSrc} // transform implements the transform.Transformer interface. It is only called + // when quickSpan does not pass for a given string. + func (f Form) transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { + // TODO: get rid of reorderBuffer. See CL 23460044. + rb := reorderBuffer{} + rb.init(f, src) + for { + // Load segment into reorder buffer. + rb.setFlusher(dst[nDst:], flushTransform) + end := decomposeSegment(&rb, nSrc, atEOF) + if end < 0 { + return nDst, nSrc, errs[-end] + } + nDst = len(dst) - len(rb.out) + nSrc = end // Next quickSpan. + end = rb.nsrc + eof := atEOF + if n := nSrc + len(dst) - nDst; n < end { + err = transform.ErrShortDst + end = n + eof = false + } + end, ok := rb.f.quickSpan(rb.src, nSrc, end, eof) + n := copy(dst[nDst:], rb.src.bytes[nSrc:end]) + nSrc += n + nDst += n + if ok { + if err == nil && n < rb.nsrc && !atEOF { + err = transform.ErrShortSrc + } + return nDst, nSrc, err + } + } + } diff --git a/vendor/golang.org/x/time/rate/rate.go b/vendor/golang.org/x/time/rate/rate.go index 8f6c7f4..dbf4d80 100644 --- a/vendor/golang.org/x/time/rate/rate.go +++ b/vendor/golang.org/x/time/rate/rate.go @@ -1,8 +1,11 @@ // Copyright 2015 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Package rate provides a rate limiter. + package rate import ( @@ -14,417 +17,727 @@ import ( ) // Limit defines the maximum frequency of some events. + // Limit is represented as number of events per second. + // A zero Limit allows no events. + type Limit float64 // Inf is the infinite rate limit; it allows all events (even if burst is zero). + const Inf = Limit(math.MaxFloat64) // Every converts a minimum time interval between events to a Limit. + func Every(interval time.Duration) Limit { + if interval <= 0 { + return Inf + } + return 1 / Limit(interval.Seconds()) + } // A Limiter controls how frequently events are allowed to happen. + // It implements a "token bucket" of size b, initially full and refilled + // at rate r tokens per second. + // Informally, in any large enough time interval, the Limiter limits the + // rate to r tokens per second, with a maximum burst size of b events. + // As a special case, if r == Inf (the infinite rate), b is ignored. + // See https://en.wikipedia.org/wiki/Token_bucket for more about token buckets. + // + // The zero value is a valid Limiter, but it will reject all events. + // Use NewLimiter to create non-zero Limiters. + // + // Limiter has three main methods, Allow, Reserve, and Wait. + // Most callers should use Wait. + // + // Each of the three methods consumes a single token. + // They differ in their behavior when no token is available. + // If no token is available, Allow returns false. + // If no token is available, Reserve returns a reservation for a future token + // and the amount of time the caller must wait before using it. + // If no token is available, Wait blocks until one can be obtained + // or its associated context.Context is canceled. + // + // The methods AllowN, ReserveN, and WaitN consume n tokens. + // + // Limiter is safe for simultaneous use by multiple goroutines. + type Limiter struct { - mu sync.Mutex - limit Limit - burst int + mu sync.Mutex + + limit Limit + + burst int + tokens float64 + // last is the last time the limiter's tokens field was updated + last time.Time + // lastEvent is the latest time of a rate-limited event (past or future) + lastEvent time.Time } // Limit returns the maximum overall event rate. + func (lim *Limiter) Limit() Limit { + lim.mu.Lock() + defer lim.mu.Unlock() + return lim.limit + } // Burst returns the maximum burst size. Burst is the maximum number of tokens + // that can be consumed in a single call to Allow, Reserve, or Wait, so higher + // Burst values allow more events to happen at once. + // A zero Burst allows no events, unless limit == Inf. + func (lim *Limiter) Burst() int { + lim.mu.Lock() + defer lim.mu.Unlock() + return lim.burst + } // TokensAt returns the number of tokens available at time t. + func (lim *Limiter) TokensAt(t time.Time) float64 { + lim.mu.Lock() + _, tokens := lim.advance(t) // does not mutate lim + lim.mu.Unlock() + return tokens + } // Tokens returns the number of tokens available now. + func (lim *Limiter) Tokens() float64 { + return lim.TokensAt(time.Now()) + } // NewLimiter returns a new Limiter that allows events up to rate r and permits + // bursts of at most b tokens. + func NewLimiter(r Limit, b int) *Limiter { + return &Limiter{ + limit: r, + burst: b, } + } // Allow reports whether an event may happen now. + func (lim *Limiter) Allow() bool { + return lim.AllowN(time.Now(), 1) + } // AllowN reports whether n events may happen at time t. + // Use this method if you intend to drop / skip events that exceed the rate limit. + // Otherwise use Reserve or Wait. + func (lim *Limiter) AllowN(t time.Time, n int) bool { + return lim.reserveN(t, n, 0).ok + } // A Reservation holds information about events that are permitted by a Limiter to happen after a delay. + // A Reservation may be canceled, which may enable the Limiter to permit additional events. + type Reservation struct { - ok bool - lim *Limiter - tokens int + ok bool + + lim *Limiter + + tokens int + timeToAct time.Time + // This is the Limit at reservation time, it can change later. + limit Limit } // OK returns whether the limiter can provide the requested number of tokens + // within the maximum wait time. If OK is false, Delay returns InfDuration, and + // Cancel does nothing. + func (r *Reservation) OK() bool { + return r.ok + } // Delay is shorthand for DelayFrom(time.Now()). + func (r *Reservation) Delay() time.Duration { + return r.DelayFrom(time.Now()) + } // InfDuration is the duration returned by Delay when a Reservation is not OK. + const InfDuration = time.Duration(math.MaxInt64) // DelayFrom returns the duration for which the reservation holder must wait + // before taking the reserved action. Zero duration means act immediately. + // InfDuration means the limiter cannot grant the tokens requested in this + // Reservation within the maximum wait time. + func (r *Reservation) DelayFrom(t time.Time) time.Duration { + if !r.ok { + return InfDuration + } + delay := r.timeToAct.Sub(t) + if delay < 0 { + return 0 + } + return delay + } // Cancel is shorthand for CancelAt(time.Now()). + func (r *Reservation) Cancel() { + r.CancelAt(time.Now()) + } // CancelAt indicates that the reservation holder will not perform the reserved action + // and reverses the effects of this Reservation on the rate limit as much as possible, + // considering that other reservations may have already been made. + func (r *Reservation) CancelAt(t time.Time) { + if !r.ok { + return + } r.lim.mu.Lock() + defer r.lim.mu.Unlock() if r.lim.limit == Inf || r.tokens == 0 || r.timeToAct.Before(t) { + return + } // calculate tokens to restore + // The duration between lim.lastEvent and r.timeToAct tells us how many tokens were reserved + // after r was obtained. These tokens should not be restored. + restoreTokens := float64(r.tokens) - r.limit.tokensFromDuration(r.lim.lastEvent.Sub(r.timeToAct)) + if restoreTokens <= 0 { + return + } + // advance time to now + t, tokens := r.lim.advance(t) + // calculate new number of tokens + tokens += restoreTokens + if burst := float64(r.lim.burst); tokens > burst { + tokens = burst + } + // update state + r.lim.last = t + r.lim.tokens = tokens + if r.timeToAct == r.lim.lastEvent { + prevEvent := r.timeToAct.Add(r.limit.durationFromTokens(float64(-r.tokens))) + if !prevEvent.Before(t) { + r.lim.lastEvent = prevEvent + } + } + } // Reserve is shorthand for ReserveN(time.Now(), 1). + func (lim *Limiter) Reserve() *Reservation { + return lim.ReserveN(time.Now(), 1) + } // ReserveN returns a Reservation that indicates how long the caller must wait before n events happen. + // The Limiter takes this Reservation into account when allowing future events. + // The returned Reservation’s OK() method returns false if n exceeds the Limiter's burst size. + // Usage example: + // + // r := lim.ReserveN(time.Now(), 1) + // if !r.OK() { + // // Not allowed to act! Did you remember to set lim.burst to be > 0 ? + // return + // } + // time.Sleep(r.Delay()) + // Act() + // + // Use this method if you wish to wait and slow down in accordance with the rate limit without dropping events. + // If you need to respect a deadline or cancel the delay, use Wait instead. + // To drop or skip events exceeding rate limit, use Allow instead. + func (lim *Limiter) ReserveN(t time.Time, n int) *Reservation { + r := lim.reserveN(t, n, InfDuration) + return &r + } // Wait is shorthand for WaitN(ctx, 1). + func (lim *Limiter) Wait(ctx context.Context) (err error) { + return lim.WaitN(ctx, 1) + } // WaitN blocks until lim permits n events to happen. + // It returns an error if n exceeds the Limiter's burst size, the Context is + // canceled, or the expected wait time exceeds the Context's Deadline. + // The burst limit is ignored if the rate limit is Inf. + func (lim *Limiter) WaitN(ctx context.Context, n int) (err error) { + // The test code calls lim.wait with a fake timer generator. + // This is the real timer generator. + newTimer := func(d time.Duration) (<-chan time.Time, func() bool, func()) { + timer := time.NewTimer(d) + return timer.C, timer.Stop, func() {} + } return lim.wait(ctx, n, time.Now(), newTimer) + } // wait is the internal implementation of WaitN. + func (lim *Limiter) wait(ctx context.Context, n int, t time.Time, newTimer func(d time.Duration) (<-chan time.Time, func() bool, func())) error { + lim.mu.Lock() + burst := lim.burst + limit := lim.limit + lim.mu.Unlock() if n > burst && limit != Inf { + return fmt.Errorf("rate: Wait(n=%d) exceeds limiter's burst %d", n, burst) + } + // Check if ctx is already cancelled + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + // Determine wait limit + waitLimit := InfDuration + if deadline, ok := ctx.Deadline(); ok { + waitLimit = deadline.Sub(t) + } + // Reserve + r := lim.reserveN(t, n, waitLimit) + if !r.ok { + return fmt.Errorf("rate: Wait(n=%d) would exceed context deadline", n) + } + // Wait if necessary + delay := r.DelayFrom(t) + if delay == 0 { + return nil + } + ch, stop, advance := newTimer(delay) + defer stop() + advance() // only has an effect when testing + select { + case <-ch: + // We can proceed. + return nil + case <-ctx.Done(): + // Context was canceled before we could proceed. Cancel the + // reservation, which may permit other events to proceed sooner. + r.Cancel() + return ctx.Err() + } + } // SetLimit is shorthand for SetLimitAt(time.Now(), newLimit). + func (lim *Limiter) SetLimit(newLimit Limit) { + lim.SetLimitAt(time.Now(), newLimit) + } // SetLimitAt sets a new Limit for the limiter. The new Limit, and Burst, may be violated + // or underutilized by those which reserved (using Reserve or Wait) but did not yet act + // before SetLimitAt was called. + func (lim *Limiter) SetLimitAt(t time.Time, newLimit Limit) { + lim.mu.Lock() + defer lim.mu.Unlock() t, tokens := lim.advance(t) lim.last = t + lim.tokens = tokens + lim.limit = newLimit + } // SetBurst is shorthand for SetBurstAt(time.Now(), newBurst). + func (lim *Limiter) SetBurst(newBurst int) { + lim.SetBurstAt(time.Now(), newBurst) + } // SetBurstAt sets a new burst size for the limiter. + func (lim *Limiter) SetBurstAt(t time.Time, newBurst int) { + lim.mu.Lock() + defer lim.mu.Unlock() t, tokens := lim.advance(t) lim.last = t + lim.tokens = tokens + lim.burst = newBurst + } // reserveN is a helper method for AllowN, ReserveN, and WaitN. + // maxFutureReserve specifies the maximum reservation wait duration allowed. + // reserveN returns Reservation, not *Reservation, to avoid allocation in AllowN and WaitN. + func (lim *Limiter) reserveN(t time.Time, n int, maxFutureReserve time.Duration) Reservation { + lim.mu.Lock() + defer lim.mu.Unlock() if lim.limit == Inf { + return Reservation{ - ok: true, - lim: lim, - tokens: n, + + ok: true, + + lim: lim, + + tokens: n, + timeToAct: t, } + } else if lim.limit == 0 { + var ok bool + if lim.burst >= n { + ok = true + lim.burst -= n + } + return Reservation{ - ok: ok, - lim: lim, - tokens: lim.burst, + + ok: ok, + + lim: lim, + + tokens: lim.burst, + timeToAct: t, } + } t, tokens := lim.advance(t) // Calculate the remaining number of tokens resulting from the request. + tokens -= float64(n) // Calculate the wait duration + var waitDuration time.Duration + if tokens < 0 { + waitDuration = lim.limit.durationFromTokens(-tokens) + } // Decide result + ok := n <= lim.burst && waitDuration <= maxFutureReserve // Prepare reservation + r := Reservation{ - ok: ok, - lim: lim, + + ok: ok, + + lim: lim, + limit: lim.limit, } + if ok { + r.tokens = n + r.timeToAct = t.Add(waitDuration) // Update state + lim.last = t + lim.tokens = tokens + lim.lastEvent = r.timeToAct + } return r + } // advance calculates and returns an updated state for lim resulting from the passage of time. + // lim is not changed. + // advance requires that lim.mu is held. + func (lim *Limiter) advance(t time.Time) (newT time.Time, newTokens float64) { + last := lim.last + if t.Before(last) { + last = t + } // Calculate the new number of tokens, due to time that passed. + elapsed := t.Sub(last) + delta := lim.limit.tokensFromDuration(elapsed) + tokens := lim.tokens + delta + if burst := float64(lim.burst); tokens > burst { + tokens = burst + } + return t, tokens + } // durationFromTokens is a unit conversion function from the number of tokens to the duration + // of time it takes to accumulate them at a rate of limit tokens per second. + func (limit Limit) durationFromTokens(tokens float64) time.Duration { + if limit <= 0 { + return InfDuration + } + seconds := tokens / float64(limit) + return time.Duration(float64(time.Second) * seconds) + } // tokensFromDuration is a unit conversion function from a time duration to the number of tokens + // which could be accumulated during that duration at a rate of limit tokens per second. + func (limit Limit) tokensFromDuration(d time.Duration) float64 { + if limit <= 0 { + return 0 + } + return d.Seconds() * float64(limit) + } diff --git a/vendor/golang.org/x/time/rate/sometimes.go b/vendor/golang.org/x/time/rate/sometimes.go index 6ba99dd..a5a16c6 100644 --- a/vendor/golang.org/x/time/rate/sometimes.go +++ b/vendor/golang.org/x/time/rate/sometimes.go @@ -1,5 +1,7 @@ // Copyright 2022 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package rate @@ -10,58 +12,108 @@ import ( ) // Sometimes will perform an action occasionally. The First, Every, and + // Interval fields govern the behavior of Do, which performs the action. + // A zero Sometimes value will perform an action exactly once. + // + // # Example: logging with rate limiting + // + // var sometimes = rate.Sometimes{First: 3, Interval: 10*time.Second} + // func Spammy() { + // sometimes.Do(func() { log.Info("here I am!") }) + // } + type Sometimes struct { - First int // if non-zero, the first N calls to Do will run f. - Every int // if non-zero, every Nth call to Do will run f. + First int // if non-zero, the first N calls to Do will run f. + + Every int // if non-zero, every Nth call to Do will run f. + Interval time.Duration // if non-zero and Interval has elapsed since f's last run, Do will run f. - mu sync.Mutex - count int // number of Do calls - last time.Time // last time f was run + mu sync.Mutex + + count int // number of Do calls + + last time.Time // last time f was run + } // Do runs the function f as allowed by First, Every, and Interval. + // + // The model is a union (not intersection) of filters. The first call to Do + // always runs f. Subsequent calls to Do run f if allowed by First or Every or + // Interval. + // + // A non-zero First:N causes the first N Do(f) calls to run f. + // + // A non-zero Every:M causes every Mth Do(f) call, starting with the first, to + // run f. + // + // A non-zero Interval causes Do(f) to run f if Interval has elapsed since + // Do last ran f. + // + // Specifying multiple filters produces the union of these execution streams. + // For example, specifying both First:N and Every:M causes the first N Do(f) + // calls and every Mth Do(f) call, starting with the first, to run f. See + // Examples for more. + // + // If Do is called multiple times simultaneously, the calls will block and run + // serially. Therefore, Do is intended for lightweight operations. + // + // Because a call to Do may block until f returns, if f causes Do to be called, + // it will deadlock. + func (s *Sometimes) Do(f func()) { + s.mu.Lock() + defer s.mu.Unlock() + if s.count == 0 || + (s.First > 0 && s.count < s.First) || + (s.Every > 0 && s.count%s.Every == 0) || + (s.Interval > 0 && time.Since(s.last) >= s.Interval) { + f() + s.last = time.Now() + } + s.count++ + } diff --git a/vendor/golang.org/x/tools/go/ast/astutil/enclosing.go b/vendor/golang.org/x/tools/go/ast/astutil/enclosing.go index 2c4c4e2..dd0f993 100644 --- a/vendor/golang.org/x/tools/go/ast/astutil/enclosing.go +++ b/vendor/golang.org/x/tools/go/ast/astutil/enclosing.go @@ -1,5 +1,7 @@ // Copyright 2013 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package astutil @@ -14,621 +16,1073 @@ import ( ) // PathEnclosingInterval returns the node that encloses the source + // interval [start, end), and all its ancestors up to the AST root. + // + // The definition of "enclosing" used by this function considers + // additional whitespace abutting a node to be enclosed by it. + // In this example: + // + // z := x + y // add them + // <-A-> + // <----B-----> + // + // the ast.BinaryExpr(+) node is considered to enclose interval B + // even though its [Pos()..End()) is actually only interval A. + // This behaviour makes user interfaces more tolerant of imperfect + // input. + // + // This function treats tokens as nodes, though they are not included + // in the result. e.g. PathEnclosingInterval("+") returns the + // enclosing ast.BinaryExpr("x + y"). + // + // If start==end, the 1-char interval following start is used instead. + // + // The 'exact' result is true if the interval contains only path[0] + // and perhaps some adjacent whitespace. It is false if the interval + // overlaps multiple children of path[0], or if it contains only + // interior whitespace of path[0]. + // In this example: + // + // z := x + y // add them + // <--C--> <---E--> + // ^ + // D + // + // intervals C, D and E are inexact. C is contained by the + // z-assignment statement, because it spans three of its children (:=, + // x, +). So too is the 1-char interval D, because it contains only + // interior whitespace of the assignment. E is considered interior + // whitespace of the BlockStmt containing the assignment. + // + // The resulting path is never empty; it always contains at least the + // 'root' *ast.File. Ideally PathEnclosingInterval would reject + // intervals that lie wholly or partially outside the range of the + // file, but unfortunately ast.File records only the token.Pos of + // the 'package' keyword, but not of the start of the file itself. + func PathEnclosingInterval(root *ast.File, start, end token.Pos) (path []ast.Node, exact bool) { + // fmt.Printf("EnclosingInterval %d %d\n", start, end) // debugging // Precondition: node.[Pos..End) and adjoining whitespace contain [start, end). + var visit func(node ast.Node) bool + visit = func(node ast.Node) bool { + path = append(path, node) nodePos := node.Pos() + nodeEnd := node.End() // fmt.Printf("visit(%T, %d, %d)\n", node, nodePos, nodeEnd) // debugging // Intersect [start, end) with interval of node. + if start < nodePos { + start = nodePos + } + if end > nodeEnd { + end = nodeEnd + } // Find sole child that contains [start, end). + children := childrenOf(node) + l := len(children) + for i, child := range children { + // [childPos, childEnd) is unaugmented interval of child. + childPos := child.Pos() + childEnd := child.End() // [augPos, augEnd) is whitespace-augmented interval of child. + augPos := childPos + augEnd := childEnd + if i > 0 { + augPos = children[i-1].End() // start of preceding whitespace + } + if i < l-1 { + nextChildPos := children[i+1].Pos() + // Does [start, end) lie between child and next child? + if start >= augEnd && end <= nextChildPos { + return false // inexact match + } + augEnd = nextChildPos // end of following whitespace + } // fmt.Printf("\tchild %d: [%d..%d)\tcontains interval [%d..%d)?\n", + // i, augPos, augEnd, start, end) // debugging // Does augmented child strictly contain [start, end)? + if augPos <= start && end <= augEnd { + _, isToken := child.(tokenNode) + return isToken || visit(child) + } // Does [start, end) overlap multiple children? + // i.e. left-augmented child contains start + // but LR-augmented child does not contain end. + if start < childEnd && end > augEnd { + break + } + } // No single child contained [start, end), + // so node is the result. Is it exact? // (It's tempting to put this condition before the + // child loop, but it gives the wrong result in the + // case where a node (e.g. ExprStmt) and its sole + // child have equal intervals.) + if start == nodePos && end == nodeEnd { + return true // exact match + } return false // inexact: overlaps multiple children + } // Ensure [start,end) is nondecreasing. + if start > end { + start, end = end, start + } if start < root.End() && end > root.Pos() { + if start == end { + end = start + 1 // empty interval => interval of size 1 + } + exact = visit(root) // Reverse the path: + for i, l := 0, len(path); i < l/2; i++ { + path[i], path[l-1-i] = path[l-1-i], path[i] + } + } else { + // Selection lies within whitespace preceding the + // first (or following the last) declaration in the file. + // The result nonetheless always includes the ast.File. + path = append(path, root) + } return + } // tokenNode is a dummy implementation of ast.Node for a single token. + // They are used transiently by PathEnclosingInterval but never escape + // this package. + type tokenNode struct { pos token.Pos + end token.Pos } func (n tokenNode) Pos() token.Pos { + return n.pos + } func (n tokenNode) End() token.Pos { + return n.end + } func tok(pos token.Pos, len int) ast.Node { + return tokenNode{pos, pos + token.Pos(len)} + } // childrenOf returns the direct non-nil children of ast.Node n. + // It may include fake ast.Node implementations for bare tokens. + // it is not safe to call (e.g.) ast.Walk on such nodes. + func childrenOf(n ast.Node) []ast.Node { + var children []ast.Node // First add nodes for all true subtrees. + ast.Inspect(n, func(node ast.Node) bool { + if node == n { // push n + return true // recur + } + if node != nil { // push child + children = append(children, node) + } + return false // no recursion + }) // Then add fake Nodes for bare tokens. + switch n := n.(type) { + case *ast.ArrayType: + children = append(children, + tok(n.Lbrack, len("[")), + tok(n.Elt.End(), len("]"))) case *ast.AssignStmt: + children = append(children, + tok(n.TokPos, len(n.Tok.String()))) case *ast.BasicLit: + children = append(children, + tok(n.ValuePos, len(n.Value))) case *ast.BinaryExpr: + children = append(children, tok(n.OpPos, len(n.Op.String()))) case *ast.BlockStmt: + children = append(children, + tok(n.Lbrace, len("{")), + tok(n.Rbrace, len("}"))) case *ast.BranchStmt: + children = append(children, + tok(n.TokPos, len(n.Tok.String()))) case *ast.CallExpr: + children = append(children, + tok(n.Lparen, len("(")), + tok(n.Rparen, len(")"))) + if n.Ellipsis != 0 { + children = append(children, tok(n.Ellipsis, len("..."))) + } case *ast.CaseClause: + if n.List == nil { + children = append(children, + tok(n.Case, len("default"))) + } else { + children = append(children, + tok(n.Case, len("case"))) + } + children = append(children, tok(n.Colon, len(":"))) case *ast.ChanType: + switch n.Dir { + case ast.RECV: + children = append(children, tok(n.Begin, len("<-chan"))) + case ast.SEND: + children = append(children, tok(n.Begin, len("chan<-"))) + case ast.RECV | ast.SEND: + children = append(children, tok(n.Begin, len("chan"))) + } case *ast.CommClause: + if n.Comm == nil { + children = append(children, + tok(n.Case, len("default"))) + } else { + children = append(children, + tok(n.Case, len("case"))) + } + children = append(children, tok(n.Colon, len(":"))) case *ast.Comment: + // nop case *ast.CommentGroup: + // nop case *ast.CompositeLit: + children = append(children, + tok(n.Lbrace, len("{")), + tok(n.Rbrace, len("{"))) case *ast.DeclStmt: + // nop case *ast.DeferStmt: + children = append(children, + tok(n.Defer, len("defer"))) case *ast.Ellipsis: + children = append(children, + tok(n.Ellipsis, len("..."))) case *ast.EmptyStmt: + // nop case *ast.ExprStmt: + // nop case *ast.Field: + // TODO(adonovan): Field.{Doc,Comment,Tag}? case *ast.FieldList: + children = append(children, + tok(n.Opening, len("(")), // or len("[") + tok(n.Closing, len(")"))) // or len("]") case *ast.File: + // TODO test: Doc + children = append(children, + tok(n.Package, len("package"))) case *ast.ForStmt: + children = append(children, + tok(n.For, len("for"))) case *ast.FuncDecl: + // TODO(adonovan): FuncDecl.Comment? // Uniquely, FuncDecl breaks the invariant that + // preorder traversal yields tokens in lexical order: + // in fact, FuncDecl.Recv precedes FuncDecl.Type.Func. + // + // As a workaround, we inline the case for FuncType + // here and order things correctly. + // + children = nil // discard ast.Walk(FuncDecl) info subtrees + children = append(children, tok(n.Type.Func, len("func"))) + if n.Recv != nil { + children = append(children, n.Recv) + } + children = append(children, n.Name) + if tparams := n.Type.TypeParams; tparams != nil { + children = append(children, tparams) + } + if n.Type.Params != nil { + children = append(children, n.Type.Params) + } + if n.Type.Results != nil { + children = append(children, n.Type.Results) + } + if n.Body != nil { + children = append(children, n.Body) + } case *ast.FuncLit: + // nop case *ast.FuncType: + if n.Func != 0 { + children = append(children, + tok(n.Func, len("func"))) + } case *ast.GenDecl: + children = append(children, + tok(n.TokPos, len(n.Tok.String()))) + if n.Lparen != 0 { + children = append(children, + tok(n.Lparen, len("(")), + tok(n.Rparen, len(")"))) + } case *ast.GoStmt: + children = append(children, + tok(n.Go, len("go"))) case *ast.Ident: + children = append(children, + tok(n.NamePos, len(n.Name))) case *ast.IfStmt: + children = append(children, + tok(n.If, len("if"))) case *ast.ImportSpec: + // TODO(adonovan): ImportSpec.{Doc,EndPos}? case *ast.IncDecStmt: + children = append(children, + tok(n.TokPos, len(n.Tok.String()))) case *ast.IndexExpr: + children = append(children, + tok(n.Lbrack, len("[")), + tok(n.Rbrack, len("]"))) case *ast.IndexListExpr: + children = append(children, + tok(n.Lbrack, len("[")), + tok(n.Rbrack, len("]"))) case *ast.InterfaceType: + children = append(children, + tok(n.Interface, len("interface"))) case *ast.KeyValueExpr: + children = append(children, + tok(n.Colon, len(":"))) case *ast.LabeledStmt: + children = append(children, + tok(n.Colon, len(":"))) case *ast.MapType: + children = append(children, + tok(n.Map, len("map"))) case *ast.ParenExpr: + children = append(children, + tok(n.Lparen, len("(")), + tok(n.Rparen, len(")"))) case *ast.RangeStmt: + children = append(children, + tok(n.For, len("for")), + tok(n.TokPos, len(n.Tok.String()))) case *ast.ReturnStmt: + children = append(children, + tok(n.Return, len("return"))) case *ast.SelectStmt: + children = append(children, + tok(n.Select, len("select"))) case *ast.SelectorExpr: + // nop case *ast.SendStmt: + children = append(children, + tok(n.Arrow, len("<-"))) case *ast.SliceExpr: + children = append(children, + tok(n.Lbrack, len("[")), + tok(n.Rbrack, len("]"))) case *ast.StarExpr: + children = append(children, tok(n.Star, len("*"))) case *ast.StructType: + children = append(children, tok(n.Struct, len("struct"))) case *ast.SwitchStmt: + children = append(children, tok(n.Switch, len("switch"))) case *ast.TypeAssertExpr: + children = append(children, + tok(n.Lparen-1, len(".")), + tok(n.Lparen, len("(")), + tok(n.Rparen, len(")"))) case *ast.TypeSpec: + // TODO(adonovan): TypeSpec.{Doc,Comment}? case *ast.TypeSwitchStmt: + children = append(children, tok(n.Switch, len("switch"))) case *ast.UnaryExpr: + children = append(children, tok(n.OpPos, len(n.Op.String()))) case *ast.ValueSpec: + // TODO(adonovan): ValueSpec.{Doc,Comment}? case *ast.BadDecl, *ast.BadExpr, *ast.BadStmt: + // nop + } // TODO(adonovan): opt: merge the logic of ast.Inspect() into + // the switch above so we can make interleaved callbacks for + // both Nodes and Tokens in the right order and avoid the need + // to sort. + sort.Sort(byPos(children)) return children + } type byPos []ast.Node func (sl byPos) Len() int { + return len(sl) + } + func (sl byPos) Less(i, j int) bool { + return sl[i].Pos() < sl[j].Pos() + } + func (sl byPos) Swap(i, j int) { + sl[i], sl[j] = sl[j], sl[i] + } // NodeDescription returns a description of the concrete type of n suitable + // for a user interface. + // + // TODO(adonovan): in some cases (e.g. Field, FieldList, Ident, + // StarExpr) we could be much more specific given the path to the AST + // root. Perhaps we should do that. + func NodeDescription(n ast.Node) string { + switch n := n.(type) { + case *ast.ArrayType: + return "array type" + case *ast.AssignStmt: + return "assignment" + case *ast.BadDecl: + return "bad declaration" + case *ast.BadExpr: + return "bad expression" + case *ast.BadStmt: + return "bad statement" + case *ast.BasicLit: + return "basic literal" + case *ast.BinaryExpr: + return fmt.Sprintf("binary %s operation", n.Op) + case *ast.BlockStmt: + return "block" + case *ast.BranchStmt: + switch n.Tok { + case token.BREAK: + return "break statement" + case token.CONTINUE: + return "continue statement" + case token.GOTO: + return "goto statement" + case token.FALLTHROUGH: + return "fall-through statement" + } + case *ast.CallExpr: + if len(n.Args) == 1 && !n.Ellipsis.IsValid() { + return "function call (or conversion)" + } + return "function call" + case *ast.CaseClause: + return "case clause" + case *ast.ChanType: + return "channel type" + case *ast.CommClause: + return "communication clause" + case *ast.Comment: + return "comment" + case *ast.CommentGroup: + return "comment group" + case *ast.CompositeLit: + return "composite literal" + case *ast.DeclStmt: + return NodeDescription(n.Decl) + " statement" + case *ast.DeferStmt: + return "defer statement" + case *ast.Ellipsis: + return "ellipsis" + case *ast.EmptyStmt: + return "empty statement" + case *ast.ExprStmt: + return "expression statement" + case *ast.Field: + // Can be any of these: + // struct {x, y int} -- struct field(s) + // struct {T} -- anon struct field + // interface {I} -- interface embedding + // interface {f()} -- interface method + // func (A) func(B) C -- receiver, param(s), result(s) + return "field/method/parameter" + case *ast.FieldList: + return "field/method/parameter list" + case *ast.File: + return "source file" + case *ast.ForStmt: + return "for loop" + case *ast.FuncDecl: + return "function declaration" + case *ast.FuncLit: + return "function literal" + case *ast.FuncType: + return "function type" + case *ast.GenDecl: + switch n.Tok { + case token.IMPORT: + return "import declaration" + case token.CONST: + return "constant declaration" + case token.TYPE: + return "type declaration" + case token.VAR: + return "variable declaration" + } + case *ast.GoStmt: + return "go statement" + case *ast.Ident: + return "identifier" + case *ast.IfStmt: + return "if statement" + case *ast.ImportSpec: + return "import specification" + case *ast.IncDecStmt: + if n.Tok == token.INC { + return "increment statement" + } + return "decrement statement" + case *ast.IndexExpr: + return "index expression" + case *ast.IndexListExpr: + return "index list expression" + case *ast.InterfaceType: + return "interface type" + case *ast.KeyValueExpr: + return "key/value association" + case *ast.LabeledStmt: + return "statement label" + case *ast.MapType: + return "map type" + case *ast.Package: + return "package" + case *ast.ParenExpr: + return "parenthesized " + NodeDescription(n.X) + case *ast.RangeStmt: + return "range loop" + case *ast.ReturnStmt: + return "return statement" + case *ast.SelectStmt: + return "select statement" + case *ast.SelectorExpr: + return "selector" + case *ast.SendStmt: + return "channel send" + case *ast.SliceExpr: + return "slice expression" + case *ast.StarExpr: + return "*-operation" // load/store expr or pointer type + case *ast.StructType: + return "struct type" + case *ast.SwitchStmt: + return "switch statement" + case *ast.TypeAssertExpr: + return "type assertion" + case *ast.TypeSpec: + return "type specification" + case *ast.TypeSwitchStmt: + return "type switch" + case *ast.UnaryExpr: + return fmt.Sprintf("unary %s operation", n.Op) + case *ast.ValueSpec: + return "value specification" } + panic(fmt.Sprintf("unexpected node type: %T", n)) + } diff --git a/vendor/golang.org/x/tools/go/ast/astutil/imports.go b/vendor/golang.org/x/tools/go/ast/astutil/imports.go index 18d1adb..f7a699f 100644 --- a/vendor/golang.org/x/tools/go/ast/astutil/imports.go +++ b/vendor/golang.org/x/tools/go/ast/astutil/imports.go @@ -1,8 +1,11 @@ // Copyright 2013 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Package astutil contains common utilities for working with the Go AST. + package astutil // import "golang.org/x/tools/go/ast/astutil" import ( @@ -14,472 +17,844 @@ import ( ) // AddImport adds the import path to the file f, if absent. + func AddImport(fset *token.FileSet, f *ast.File, path string) (added bool) { + return AddNamedImport(fset, f, "", path) + } // AddNamedImport adds the import with the given name and path to the file f, if absent. + // If name is not empty, it is used to rename the import. + // + // For example, calling + // + // AddNamedImport(fset, f, "pathpkg", "path") + // + // adds + // + // import pathpkg "path" + func AddNamedImport(fset *token.FileSet, f *ast.File, name, path string) (added bool) { + if imports(f, name, path) { + return false + } newImport := &ast.ImportSpec{ + Path: &ast.BasicLit{ - Kind: token.STRING, + + Kind: token.STRING, + Value: strconv.Quote(path), }, } + if name != "" { + newImport.Name = &ast.Ident{Name: name} + } // Find an import decl to add to. + // The goal is to find an existing import + // whose import path has the longest shared + // prefix with path. + var ( - bestMatch = -1 // length of longest shared prefix - lastImport = -1 // index in f.Decls of the file's final import decl - impDecl *ast.GenDecl // import decl containing the best match - impIndex = -1 // spec index in impDecl containing the best match + bestMatch = -1 // length of longest shared prefix + + lastImport = -1 // index in f.Decls of the file's final import decl + + impDecl *ast.GenDecl // import decl containing the best match + + impIndex = -1 // spec index in impDecl containing the best match isThirdPartyPath = isThirdParty(path) ) + for i, decl := range f.Decls { + gen, ok := decl.(*ast.GenDecl) + if ok && gen.Tok == token.IMPORT { + lastImport = i + // Do not add to import "C", to avoid disrupting the + // association with its doc comment, breaking cgo. + if declImports(gen, "C") { + continue + } // Match an empty import decl if that's all that is available. + if len(gen.Specs) == 0 && bestMatch == -1 { + impDecl = gen + } // Compute longest shared prefix with imports in this group and find best + // matched import spec. + // 1. Always prefer import spec with longest shared prefix. + // 2. While match length is 0, + // - for stdlib package: prefer first import spec. + // - for third party package: prefer first third party import spec. + // We cannot use last import spec as best match for third party package + // because grouped imports are usually placed last by goimports -local + // flag. + // See issue #19190. + seenAnyThirdParty := false + for j, spec := range gen.Specs { + impspec := spec.(*ast.ImportSpec) + p := importPath(impspec) + n := matchLen(p, path) + if n > bestMatch || (bestMatch == 0 && !seenAnyThirdParty && isThirdPartyPath) { + bestMatch = n + impDecl = gen + impIndex = j + } + seenAnyThirdParty = seenAnyThirdParty || isThirdParty(p) + } + } + } // If no import decl found, add one after the last import. + if impDecl == nil { + impDecl = &ast.GenDecl{ + Tok: token.IMPORT, } + if lastImport >= 0 { + impDecl.TokPos = f.Decls[lastImport].End() + } else { + // There are no existing imports. + // Our new import, preceded by a blank line, goes after the package declaration + // and after the comment, if any, that starts on the same line as the + // package declaration. + impDecl.TokPos = f.Package file := fset.File(f.Package) + pkgLine := file.Line(f.Package) + for _, c := range f.Comments { + if file.Line(c.Pos()) > pkgLine { + break + } + // +2 for a blank line + impDecl.TokPos = c.End() + 2 + } + } + f.Decls = append(f.Decls, nil) + copy(f.Decls[lastImport+2:], f.Decls[lastImport+1:]) + f.Decls[lastImport+1] = impDecl + } // Insert new import at insertAt. + insertAt := 0 + if impIndex >= 0 { + // insert after the found import + insertAt = impIndex + 1 + } + impDecl.Specs = append(impDecl.Specs, nil) + copy(impDecl.Specs[insertAt+1:], impDecl.Specs[insertAt:]) + impDecl.Specs[insertAt] = newImport + pos := impDecl.Pos() + if insertAt > 0 { + // If there is a comment after an existing import, preserve the comment + // position by adding the new import after the comment. + if spec, ok := impDecl.Specs[insertAt-1].(*ast.ImportSpec); ok && spec.Comment != nil { + pos = spec.Comment.End() + } else { + // Assign same position as the previous import, + // so that the sorter sees it as being in the same block. + pos = impDecl.Specs[insertAt-1].Pos() + } + } + if newImport.Name != nil { + newImport.Name.NamePos = pos + } + newImport.Path.ValuePos = pos + newImport.EndPos = pos // Clean up parens. impDecl contains at least one spec. + if len(impDecl.Specs) == 1 { + // Remove unneeded parens. + impDecl.Lparen = token.NoPos + } else if !impDecl.Lparen.IsValid() { + // impDecl needs parens added. + impDecl.Lparen = impDecl.Specs[0].Pos() + } f.Imports = append(f.Imports, newImport) if len(f.Decls) <= 1 { + return true + } // Merge all the import declarations into the first one. + var first *ast.GenDecl + for i := 0; i < len(f.Decls); i++ { + decl := f.Decls[i] + gen, ok := decl.(*ast.GenDecl) + if !ok || gen.Tok != token.IMPORT || declImports(gen, "C") { + continue + } + if first == nil { + first = gen + continue // Don't touch the first one. + } + // We now know there is more than one package in this import + // declaration. Ensure that it ends up parenthesized. + first.Lparen = first.Pos() + // Move the imports of the other import declaration to the first one. + for _, spec := range gen.Specs { + spec.(*ast.ImportSpec).Path.ValuePos = first.Pos() + first.Specs = append(first.Specs, spec) + } + f.Decls = append(f.Decls[:i], f.Decls[i+1:]...) + i-- + } return true + } func isThirdParty(importPath string) bool { + // Third party package import path usually contains "." (".com", ".org", ...) + // This logic is taken from golang.org/x/tools/imports package. + return strings.Contains(importPath, ".") + } // DeleteImport deletes the import path from the file f, if present. + // If there are duplicate import declarations, all matching ones are deleted. + func DeleteImport(fset *token.FileSet, f *ast.File, path string) (deleted bool) { + return DeleteNamedImport(fset, f, "", path) + } // DeleteNamedImport deletes the import with the given name and path from the file f, if present. + // If there are duplicate import declarations, all matching ones are deleted. + func DeleteNamedImport(fset *token.FileSet, f *ast.File, name, path string) (deleted bool) { + var delspecs []*ast.ImportSpec + var delcomments []*ast.CommentGroup // Find the import nodes that import path, if any. + for i := 0; i < len(f.Decls); i++ { + decl := f.Decls[i] + gen, ok := decl.(*ast.GenDecl) + if !ok || gen.Tok != token.IMPORT { + continue + } + for j := 0; j < len(gen.Specs); j++ { + spec := gen.Specs[j] + impspec := spec.(*ast.ImportSpec) + if importName(impspec) != name || importPath(impspec) != path { + continue + } // We found an import spec that imports path. + // Delete it. + delspecs = append(delspecs, impspec) + deleted = true + copy(gen.Specs[j:], gen.Specs[j+1:]) + gen.Specs = gen.Specs[:len(gen.Specs)-1] // If this was the last import spec in this decl, + // delete the decl, too. + if len(gen.Specs) == 0 { + copy(f.Decls[i:], f.Decls[i+1:]) + f.Decls = f.Decls[:len(f.Decls)-1] + i-- + break + } else if len(gen.Specs) == 1 { + if impspec.Doc != nil { + delcomments = append(delcomments, impspec.Doc) + } + if impspec.Comment != nil { + delcomments = append(delcomments, impspec.Comment) + } + for _, cg := range f.Comments { + // Found comment on the same line as the import spec. + if cg.End() < impspec.Pos() && fset.Position(cg.End()).Line == fset.Position(impspec.Pos()).Line { + delcomments = append(delcomments, cg) + break + } + } spec := gen.Specs[0].(*ast.ImportSpec) // Move the documentation right after the import decl. + if spec.Doc != nil { + for fset.Position(gen.TokPos).Line+1 < fset.Position(spec.Doc.Pos()).Line { + fset.File(gen.TokPos).MergeLine(fset.Position(gen.TokPos).Line) + } + } + for _, cg := range f.Comments { + if cg.End() < spec.Pos() && fset.Position(cg.End()).Line == fset.Position(spec.Pos()).Line { + for fset.Position(gen.TokPos).Line+1 < fset.Position(spec.Pos()).Line { + fset.File(gen.TokPos).MergeLine(fset.Position(gen.TokPos).Line) + } + break + } + } + } + if j > 0 { + lastImpspec := gen.Specs[j-1].(*ast.ImportSpec) + lastLine := fset.PositionFor(lastImpspec.Path.ValuePos, false).Line + line := fset.PositionFor(impspec.Path.ValuePos, false).Line // We deleted an entry but now there may be + // a blank line-sized hole where the import was. + if line-lastLine > 1 || !gen.Rparen.IsValid() { + // There was a blank line immediately preceding the deleted import, + // so there's no need to close the hole. The right parenthesis is + // invalid after AddImport to an import statement without parenthesis. + // Do nothing. + } else if line != fset.File(gen.Rparen).LineCount() { + // There was no blank line. Close the hole. + fset.File(gen.Rparen).MergeLine(line) + } + } + j-- + } + } // Delete imports from f.Imports. + for i := 0; i < len(f.Imports); i++ { + imp := f.Imports[i] + for j, del := range delspecs { + if imp == del { + copy(f.Imports[i:], f.Imports[i+1:]) + f.Imports = f.Imports[:len(f.Imports)-1] + copy(delspecs[j:], delspecs[j+1:]) + delspecs = delspecs[:len(delspecs)-1] + i-- + break + } + } + } // Delete comments from f.Comments. + for i := 0; i < len(f.Comments); i++ { + cg := f.Comments[i] + for j, del := range delcomments { + if cg == del { + copy(f.Comments[i:], f.Comments[i+1:]) + f.Comments = f.Comments[:len(f.Comments)-1] + copy(delcomments[j:], delcomments[j+1:]) + delcomments = delcomments[:len(delcomments)-1] + i-- + break + } + } + } if len(delspecs) > 0 { + panic(fmt.Sprintf("deleted specs from Decls but not Imports: %v", delspecs)) + } return + } // RewriteImport rewrites any import of path oldPath to path newPath. + func RewriteImport(fset *token.FileSet, f *ast.File, oldPath, newPath string) (rewrote bool) { + for _, imp := range f.Imports { + if importPath(imp) == oldPath { + rewrote = true + // record old End, because the default is to compute + // it using the length of imp.Path.Value. + imp.EndPos = imp.End() + imp.Path.Value = strconv.Quote(newPath) + } + } + return + } // UsesImport reports whether a given import is used. + func UsesImport(f *ast.File, path string) (used bool) { + spec := importSpec(f, path) + if spec == nil { + return + } name := spec.Name.String() + switch name { + case "": + // If the package name is not explicitly specified, + // make an educated guess. This is not guaranteed to be correct. + lastSlash := strings.LastIndex(path, "/") + if lastSlash == -1 { + name = path + } else { + name = path[lastSlash+1:] + } + case "_", ".": + // Not sure if this import is used - err on the side of caution. + return true + } ast.Walk(visitFn(func(n ast.Node) { + sel, ok := n.(*ast.SelectorExpr) + if ok && isTopName(sel.X, name) { + used = true + } + }), f) return + } type visitFn func(node ast.Node) func (fn visitFn) Visit(node ast.Node) ast.Visitor { + fn(node) + return fn + } // imports reports whether f has an import with the specified name and path. + func imports(f *ast.File, name, path string) bool { + for _, s := range f.Imports { + if importName(s) == name && importPath(s) == path { + return true + } + } + return false + } // importSpec returns the import spec if f imports path, + // or nil otherwise. + func importSpec(f *ast.File, path string) *ast.ImportSpec { + for _, s := range f.Imports { + if importPath(s) == path { + return s + } + } + return nil + } // importName returns the name of s, + // or "" if the import is not named. + func importName(s *ast.ImportSpec) string { + if s.Name == nil { + return "" + } + return s.Name.Name + } // importPath returns the unquoted import path of s, + // or "" if the path is not properly quoted. + func importPath(s *ast.ImportSpec) string { + t, err := strconv.Unquote(s.Path.Value) + if err != nil { + return "" + } + return t + } // declImports reports whether gen contains an import of path. + func declImports(gen *ast.GenDecl, path string) bool { + if gen.Tok != token.IMPORT { + return false + } + for _, spec := range gen.Specs { + impspec := spec.(*ast.ImportSpec) + if importPath(impspec) == path { + return true + } + } + return false + } // matchLen returns the length of the longest path segment prefix shared by x and y. + func matchLen(x, y string) int { + n := 0 + for i := 0; i < len(x) && i < len(y) && x[i] == y[i]; i++ { + if x[i] == '/' { + n++ + } + } + return n + } // isTopName returns true if n is a top-level unresolved identifier with the given name. + func isTopName(n ast.Expr, name string) bool { + id, ok := n.(*ast.Ident) + return ok && id.Name == name && id.Obj == nil + } // Imports returns the file imports grouped by paragraph. + func Imports(fset *token.FileSet, f *ast.File) [][]*ast.ImportSpec { + var groups [][]*ast.ImportSpec for _, decl := range f.Decls { + genDecl, ok := decl.(*ast.GenDecl) + if !ok || genDecl.Tok != token.IMPORT { + break + } group := []*ast.ImportSpec{} var lastLine int + for _, spec := range genDecl.Specs { + importSpec := spec.(*ast.ImportSpec) + pos := importSpec.Path.ValuePos + line := fset.Position(pos).Line + if lastLine > 0 && pos > 0 && line-lastLine > 1 { + groups = append(groups, group) + group = []*ast.ImportSpec{} + } + group = append(group, importSpec) + lastLine = line + } + groups = append(groups, group) + } return groups + } diff --git a/vendor/golang.org/x/tools/go/ast/astutil/rewrite.go b/vendor/golang.org/x/tools/go/ast/astutil/rewrite.go index 58934f7..ef2dd11 100644 --- a/vendor/golang.org/x/tools/go/ast/astutil/rewrite.go +++ b/vendor/golang.org/x/tools/go/ast/astutil/rewrite.go @@ -1,5 +1,7 @@ // Copyright 2017 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package astutil @@ -12,475 +14,781 @@ import ( ) // An ApplyFunc is invoked by Apply for each node n, even if n is nil, + // before and/or after the node's children, using a Cursor describing + // the current node and providing operations on it. + // + // The return value of ApplyFunc controls the syntax tree traversal. + // See Apply for details. + type ApplyFunc func(*Cursor) bool // Apply traverses a syntax tree recursively, starting with root, + // and calling pre and post for each node as described below. + // Apply returns the syntax tree, possibly modified. + // + // If pre is not nil, it is called for each node before the node's + // children are traversed (pre-order). If pre returns false, no + // children are traversed, and post is not called for that node. + // + // If post is not nil, and a prior call of pre didn't return false, + // post is called for each node after its children are traversed + // (post-order). If post returns false, traversal is terminated and + // Apply returns immediately. + // + // Only fields that refer to AST nodes are considered children; + // i.e., token.Pos, Scopes, Objects, and fields of basic types + // (strings, etc.) are ignored. + // + // Children are traversed in the order in which they appear in the + // respective node's struct definition. A package's files are + // traversed in the filenames' alphabetical order. + func Apply(root ast.Node, pre, post ApplyFunc) (result ast.Node) { + parent := &struct{ ast.Node }{root} + defer func() { + if r := recover(); r != nil && r != abort { + panic(r) + } + result = parent.Node + }() + a := &application{pre: pre, post: post} + a.apply(parent, "Node", nil, root) + return + } var abort = new(int) // singleton, to signal termination of Apply // A Cursor describes a node encountered during Apply. + // Information about the node and its parent is available + // from the Node, Parent, Name, and Index methods. + // + // If p is a variable of type and value of the current parent node + // c.Parent(), and f is the field identifier with name c.Name(), + // the following invariants hold: + // + // p.f == c.Node() if c.Index() < 0 + // p.f[c.Index()] == c.Node() if c.Index() >= 0 + // + // The methods Replace, Delete, InsertBefore, and InsertAfter + // can be used to change the AST without disrupting Apply. + type Cursor struct { parent ast.Node - name string - iter *iterator // valid if non-nil - node ast.Node + + name string + + iter *iterator // valid if non-nil + + node ast.Node } // Node returns the current Node. + func (c *Cursor) Node() ast.Node { return c.node } // Parent returns the parent of the current Node. + func (c *Cursor) Parent() ast.Node { return c.parent } // Name returns the name of the parent Node field that contains the current Node. + // If the parent is a *ast.Package and the current Node is a *ast.File, Name returns + // the filename for the current Node. + func (c *Cursor) Name() string { return c.name } // Index reports the index >= 0 of the current Node in the slice of Nodes that + // contains it, or a value < 0 if the current Node is not part of a slice. + // The index of the current node changes if InsertBefore is called while + // processing the current node. + func (c *Cursor) Index() int { + if c.iter != nil { + return c.iter.index + } + return -1 + } // field returns the current node's parent field value. + func (c *Cursor) field() reflect.Value { + return reflect.Indirect(reflect.ValueOf(c.parent)).FieldByName(c.name) + } // Replace replaces the current Node with n. + // The replacement node is not walked by Apply. + func (c *Cursor) Replace(n ast.Node) { + if _, ok := c.node.(*ast.File); ok { + file, ok := n.(*ast.File) + if !ok { + panic("attempt to replace *ast.File with non-*ast.File") + } + c.parent.(*ast.Package).Files[c.name] = file + return + } v := c.field() + if i := c.Index(); i >= 0 { + v = v.Index(i) + } + v.Set(reflect.ValueOf(n)) + } // Delete deletes the current Node from its containing slice. + // If the current Node is not part of a slice, Delete panics. + // As a special case, if the current node is a package file, + // Delete removes it from the package's Files map. + func (c *Cursor) Delete() { + if _, ok := c.node.(*ast.File); ok { + delete(c.parent.(*ast.Package).Files, c.name) + return + } i := c.Index() + if i < 0 { + panic("Delete node not contained in slice") + } + v := c.field() + l := v.Len() + reflect.Copy(v.Slice(i, l), v.Slice(i+1, l)) + v.Index(l - 1).Set(reflect.Zero(v.Type().Elem())) + v.SetLen(l - 1) + c.iter.step-- + } // InsertAfter inserts n after the current Node in its containing slice. + // If the current Node is not part of a slice, InsertAfter panics. + // Apply does not walk n. + func (c *Cursor) InsertAfter(n ast.Node) { + i := c.Index() + if i < 0 { + panic("InsertAfter node not contained in slice") + } + v := c.field() + v.Set(reflect.Append(v, reflect.Zero(v.Type().Elem()))) + l := v.Len() + reflect.Copy(v.Slice(i+2, l), v.Slice(i+1, l)) + v.Index(i + 1).Set(reflect.ValueOf(n)) + c.iter.step++ + } // InsertBefore inserts n before the current Node in its containing slice. + // If the current Node is not part of a slice, InsertBefore panics. + // Apply will not walk n. + func (c *Cursor) InsertBefore(n ast.Node) { + i := c.Index() + if i < 0 { + panic("InsertBefore node not contained in slice") + } + v := c.field() + v.Set(reflect.Append(v, reflect.Zero(v.Type().Elem()))) + l := v.Len() + reflect.Copy(v.Slice(i+1, l), v.Slice(i, l)) + v.Index(i).Set(reflect.ValueOf(n)) + c.iter.index++ + } // application carries all the shared data so we can pass it around cheaply. + type application struct { pre, post ApplyFunc - cursor Cursor - iter iterator + + cursor Cursor + + iter iterator } func (a *application) apply(parent ast.Node, name string, iter *iterator, n ast.Node) { + // convert typed nil into untyped nil + if v := reflect.ValueOf(n); v.Kind() == reflect.Ptr && v.IsNil() { + n = nil + } // avoid heap-allocating a new cursor for each apply call; reuse a.cursor instead + saved := a.cursor + a.cursor.parent = parent + a.cursor.name = name + a.cursor.iter = iter + a.cursor.node = n if a.pre != nil && !a.pre(&a.cursor) { + a.cursor = saved + return + } // walk children + // (the order of the cases matches the order of the corresponding node types in go/ast) + switch n := n.(type) { + case nil: + // nothing to do // Comments and fields + case *ast.Comment: + // nothing to do case *ast.CommentGroup: + if n != nil { + a.applyList(n, "List") + } case *ast.Field: + a.apply(n, "Doc", nil, n.Doc) + a.applyList(n, "Names") + a.apply(n, "Type", nil, n.Type) + a.apply(n, "Tag", nil, n.Tag) + a.apply(n, "Comment", nil, n.Comment) case *ast.FieldList: + a.applyList(n, "List") // Expressions + case *ast.BadExpr, *ast.Ident, *ast.BasicLit: + // nothing to do case *ast.Ellipsis: + a.apply(n, "Elt", nil, n.Elt) case *ast.FuncLit: + a.apply(n, "Type", nil, n.Type) + a.apply(n, "Body", nil, n.Body) case *ast.CompositeLit: + a.apply(n, "Type", nil, n.Type) + a.applyList(n, "Elts") case *ast.ParenExpr: + a.apply(n, "X", nil, n.X) case *ast.SelectorExpr: + a.apply(n, "X", nil, n.X) + a.apply(n, "Sel", nil, n.Sel) case *ast.IndexExpr: + a.apply(n, "X", nil, n.X) + a.apply(n, "Index", nil, n.Index) case *ast.IndexListExpr: + a.apply(n, "X", nil, n.X) + a.applyList(n, "Indices") case *ast.SliceExpr: + a.apply(n, "X", nil, n.X) + a.apply(n, "Low", nil, n.Low) + a.apply(n, "High", nil, n.High) + a.apply(n, "Max", nil, n.Max) case *ast.TypeAssertExpr: + a.apply(n, "X", nil, n.X) + a.apply(n, "Type", nil, n.Type) case *ast.CallExpr: + a.apply(n, "Fun", nil, n.Fun) + a.applyList(n, "Args") case *ast.StarExpr: + a.apply(n, "X", nil, n.X) case *ast.UnaryExpr: + a.apply(n, "X", nil, n.X) case *ast.BinaryExpr: + a.apply(n, "X", nil, n.X) + a.apply(n, "Y", nil, n.Y) case *ast.KeyValueExpr: + a.apply(n, "Key", nil, n.Key) + a.apply(n, "Value", nil, n.Value) // Types + case *ast.ArrayType: + a.apply(n, "Len", nil, n.Len) + a.apply(n, "Elt", nil, n.Elt) case *ast.StructType: + a.apply(n, "Fields", nil, n.Fields) case *ast.FuncType: + if tparams := n.TypeParams; tparams != nil { + a.apply(n, "TypeParams", nil, tparams) + } + a.apply(n, "Params", nil, n.Params) + a.apply(n, "Results", nil, n.Results) case *ast.InterfaceType: + a.apply(n, "Methods", nil, n.Methods) case *ast.MapType: + a.apply(n, "Key", nil, n.Key) + a.apply(n, "Value", nil, n.Value) case *ast.ChanType: + a.apply(n, "Value", nil, n.Value) // Statements + case *ast.BadStmt: + // nothing to do case *ast.DeclStmt: + a.apply(n, "Decl", nil, n.Decl) case *ast.EmptyStmt: + // nothing to do case *ast.LabeledStmt: + a.apply(n, "Label", nil, n.Label) + a.apply(n, "Stmt", nil, n.Stmt) case *ast.ExprStmt: + a.apply(n, "X", nil, n.X) case *ast.SendStmt: + a.apply(n, "Chan", nil, n.Chan) + a.apply(n, "Value", nil, n.Value) case *ast.IncDecStmt: + a.apply(n, "X", nil, n.X) case *ast.AssignStmt: + a.applyList(n, "Lhs") + a.applyList(n, "Rhs") case *ast.GoStmt: + a.apply(n, "Call", nil, n.Call) case *ast.DeferStmt: + a.apply(n, "Call", nil, n.Call) case *ast.ReturnStmt: + a.applyList(n, "Results") case *ast.BranchStmt: + a.apply(n, "Label", nil, n.Label) case *ast.BlockStmt: + a.applyList(n, "List") case *ast.IfStmt: + a.apply(n, "Init", nil, n.Init) + a.apply(n, "Cond", nil, n.Cond) + a.apply(n, "Body", nil, n.Body) + a.apply(n, "Else", nil, n.Else) case *ast.CaseClause: + a.applyList(n, "List") + a.applyList(n, "Body") case *ast.SwitchStmt: + a.apply(n, "Init", nil, n.Init) + a.apply(n, "Tag", nil, n.Tag) + a.apply(n, "Body", nil, n.Body) case *ast.TypeSwitchStmt: + a.apply(n, "Init", nil, n.Init) + a.apply(n, "Assign", nil, n.Assign) + a.apply(n, "Body", nil, n.Body) case *ast.CommClause: + a.apply(n, "Comm", nil, n.Comm) + a.applyList(n, "Body") case *ast.SelectStmt: + a.apply(n, "Body", nil, n.Body) case *ast.ForStmt: + a.apply(n, "Init", nil, n.Init) + a.apply(n, "Cond", nil, n.Cond) + a.apply(n, "Post", nil, n.Post) + a.apply(n, "Body", nil, n.Body) case *ast.RangeStmt: + a.apply(n, "Key", nil, n.Key) + a.apply(n, "Value", nil, n.Value) + a.apply(n, "X", nil, n.X) + a.apply(n, "Body", nil, n.Body) // Declarations + case *ast.ImportSpec: + a.apply(n, "Doc", nil, n.Doc) + a.apply(n, "Name", nil, n.Name) + a.apply(n, "Path", nil, n.Path) + a.apply(n, "Comment", nil, n.Comment) case *ast.ValueSpec: + a.apply(n, "Doc", nil, n.Doc) + a.applyList(n, "Names") + a.apply(n, "Type", nil, n.Type) + a.applyList(n, "Values") + a.apply(n, "Comment", nil, n.Comment) case *ast.TypeSpec: + a.apply(n, "Doc", nil, n.Doc) + a.apply(n, "Name", nil, n.Name) + if tparams := n.TypeParams; tparams != nil { + a.apply(n, "TypeParams", nil, tparams) + } + a.apply(n, "Type", nil, n.Type) + a.apply(n, "Comment", nil, n.Comment) case *ast.BadDecl: + // nothing to do case *ast.GenDecl: + a.apply(n, "Doc", nil, n.Doc) + a.applyList(n, "Specs") case *ast.FuncDecl: + a.apply(n, "Doc", nil, n.Doc) + a.apply(n, "Recv", nil, n.Recv) + a.apply(n, "Name", nil, n.Name) + a.apply(n, "Type", nil, n.Type) + a.apply(n, "Body", nil, n.Body) // Files and packages + case *ast.File: + a.apply(n, "Doc", nil, n.Doc) + a.apply(n, "Name", nil, n.Name) + a.applyList(n, "Decls") + // Don't walk n.Comments; they have either been walked already if + // they are Doc comments, or they can be easily walked explicitly. case *ast.Package: + // collect and sort names for reproducible behavior + var names []string + for name := range n.Files { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + a.apply(n, name, nil, n.Files[name]) + } default: + panic(fmt.Sprintf("Apply: unexpected node type %T", n)) + } if a.post != nil && !a.post(&a.cursor) { + panic(abort) + } a.cursor = saved + } // An iterator controls iteration over a slice of nodes. + type iterator struct { index, step int } func (a *application) applyList(parent ast.Node, name string) { + // avoid heap-allocating a new iterator for each applyList call; reuse a.iter instead + saved := a.iter + a.iter.index = 0 + for { + // must reload parent.name each time, since cursor modifications might change it + v := reflect.Indirect(reflect.ValueOf(parent)).FieldByName(name) + if a.iter.index >= v.Len() { + break + } // element x may be nil in a bad AST - be cautious + var x ast.Node + if e := v.Index(a.iter.index); e.IsValid() { + x = e.Interface().(ast.Node) + } a.iter.step = 1 + a.apply(parent, name, &a.iter, x) + a.iter.index += a.iter.step + } + a.iter = saved + } diff --git a/vendor/golang.org/x/tools/go/buildutil/allpackages.go b/vendor/golang.org/x/tools/go/buildutil/allpackages.go index dfb8cd6..2d8c690 100644 --- a/vendor/golang.org/x/tools/go/buildutil/allpackages.go +++ b/vendor/golang.org/x/tools/go/buildutil/allpackages.go @@ -1,12 +1,19 @@ // Copyright 2014 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Package buildutil provides utilities related to the go/build + // package in the standard library. + // + // All I/O is done via the build.Context file system interface, which must + // be concurrency-safe. + package buildutil // import "golang.org/x/tools/go/buildutil" import ( @@ -19,177 +26,312 @@ import ( ) // AllPackages returns the package path of each Go package in any source + // directory of the specified build context (e.g. $GOROOT or an element + // of $GOPATH). Errors are ignored. The results are sorted. + // All package paths are canonical, and thus may contain "/vendor/". + // + // The result may include import paths for directories that contain no + // *.go files, such as "archive" (in $GOROOT/src). + // + // All I/O is done via the build.Context file system interface, + // which must be concurrency-safe. + func AllPackages(ctxt *build.Context) []string { + var list []string + ForEachPackage(ctxt, func(pkg string, _ error) { + list = append(list, pkg) + }) + sort.Strings(list) + return list + } // ForEachPackage calls the found function with the package path of + // each Go package it finds in any source directory of the specified + // build context (e.g. $GOROOT or an element of $GOPATH). + // All package paths are canonical, and thus may contain "/vendor/". + // + // If the package directory exists but could not be read, the second + // argument to the found function provides the error. + // + // All I/O is done via the build.Context file system interface, + // which must be concurrency-safe. + func ForEachPackage(ctxt *build.Context, found func(importPath string, err error)) { + ch := make(chan item) var wg sync.WaitGroup + for _, root := range ctxt.SrcDirs() { + root := root + wg.Add(1) + go func() { + allPackages(ctxt, root, ch) + wg.Done() + }() + } + go func() { + wg.Wait() + close(ch) + }() // All calls to found occur in the caller's goroutine. + for i := range ch { + found(i.importPath, i.err) + } + } type item struct { importPath string - err error // (optional) + + err error // (optional) + } // We use a process-wide counting semaphore to limit + // the number of parallel calls to ReadDir. + var ioLimit = make(chan bool, 20) func allPackages(ctxt *build.Context, root string, ch chan<- item) { + root = filepath.Clean(root) + string(os.PathSeparator) var wg sync.WaitGroup var walkDir func(dir string) + walkDir = func(dir string) { + // Avoid .foo, _foo, and testdata directory trees. + base := filepath.Base(dir) + if base == "" || base[0] == '.' || base[0] == '_' || base == "testdata" { + return + } pkg := filepath.ToSlash(strings.TrimPrefix(dir, root)) // Prune search if we encounter any of these import paths. + switch pkg { + case "builtin": + return + } ioLimit <- true + files, err := ReadDir(ctxt, dir) + <-ioLimit + if pkg != "" || err != nil { + ch <- item{pkg, err} + } + for _, fi := range files { + fi := fi + if fi.IsDir() { + wg.Add(1) + go func() { + walkDir(filepath.Join(dir, fi.Name())) + wg.Done() + }() + } + } + } walkDir(root) + wg.Wait() + } // ExpandPatterns returns the set of packages matched by patterns, + // which may have the following forms: + // + // golang.org/x/tools/cmd/guru # a single package + // golang.org/x/tools/... # all packages beneath dir + // ... # the entire workspace. + // + // Order is significant: a pattern preceded by '-' removes matching + // packages from the set. For example, these patterns match all encoding + // packages except encoding/xml: + // + // encoding/... -encoding/xml + // + // A trailing slash in a pattern is ignored. (Path components of Go + // package names are separated by slash, not the platform's path separator.) + func ExpandPatterns(ctxt *build.Context, patterns []string) map[string]bool { + // TODO(adonovan): support other features of 'go list': + // - "std"/"cmd"/"all" meta-packages + // - "..." not at the end of a pattern + // - relative patterns using "./" or "../" prefix pkgs := make(map[string]bool) + doPkg := func(pkg string, neg bool) { + if neg { + delete(pkgs, pkg) + } else { + pkgs[pkg] = true + } + } // Scan entire workspace if wildcards are present. + // TODO(adonovan): opt: scan only the necessary subtrees of the workspace. + var all []string + for _, arg := range patterns { + if strings.HasSuffix(arg, "...") { + all = AllPackages(ctxt) + break + } + } for _, arg := range patterns { + if arg == "" { + continue + } neg := arg[0] == '-' + if neg { + arg = arg[1:] + } if arg == "..." { + // ... matches all packages + for _, pkg := range all { + doPkg(pkg, neg) + } + } else if dir := strings.TrimSuffix(arg, "/..."); dir != arg { + // dir/... matches all packages beneath dir + for _, pkg := range all { + if strings.HasPrefix(pkg, dir) && + (len(pkg) == len(dir) || pkg[len(dir)] == '/') { + doPkg(pkg, neg) + } + } + } else { + // single package + doPkg(strings.TrimSuffix(arg, "/"), neg) + } + } return pkgs + } diff --git a/vendor/golang.org/x/tools/go/buildutil/fakecontext.go b/vendor/golang.org/x/tools/go/buildutil/fakecontext.go index 763d188..9c4f6e4 100644 --- a/vendor/golang.org/x/tools/go/buildutil/fakecontext.go +++ b/vendor/golang.org/x/tools/go/buildutil/fakecontext.go @@ -1,5 +1,7 @@ // Copyright 2015 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package buildutil @@ -17,95 +19,173 @@ import ( ) // FakeContext returns a build.Context for the fake file tree specified + // by pkgs, which maps package import paths to a mapping from file base + // names to contents. + // + // The fake Context has a GOROOT of "/go" and no GOPATH, and overrides + // the necessary file access methods to read from memory instead of the + // real file system. + // + // Unlike a real file tree, the fake one has only two levels---packages + // and files---so ReadDir("/go/src/") returns all packages under + // /go/src/ including, for instance, "math" and "math/big". + // ReadDir("/go/src/math/big") would return all the files in the + // "math/big" package. + func FakeContext(pkgs map[string]map[string]string) *build.Context { + clean := func(filename string) string { + f := path.Clean(filepath.ToSlash(filename)) + // Removing "/go/src" while respecting segment + // boundaries has this unfortunate corner case: + if f == "/go/src" { + return "" + } + return strings.TrimPrefix(f, "/go/src/") + } ctxt := build.Default // copy + ctxt.GOROOT = "/go" + ctxt.GOPATH = "" + ctxt.Compiler = "gc" + ctxt.IsDir = func(dir string) bool { + dir = clean(dir) + if dir == "" { + return true // needed by (*build.Context).SrcDirs + } + return pkgs[dir] != nil + } + ctxt.ReadDir = func(dir string) ([]os.FileInfo, error) { + dir = clean(dir) + var fis []os.FileInfo + if dir == "" { + // enumerate packages + for importPath := range pkgs { + fis = append(fis, fakeDirInfo(importPath)) + } + } else { + // enumerate files of package + for basename := range pkgs[dir] { + fis = append(fis, fakeFileInfo(basename)) + } + } + sort.Sort(byName(fis)) + return fis, nil + } + ctxt.OpenFile = func(filename string) (io.ReadCloser, error) { + filename = clean(filename) + dir, base := path.Split(filename) + content, ok := pkgs[path.Clean(dir)][base] + if !ok { + return nil, fmt.Errorf("file not found: %s", filename) + } + return io.NopCloser(strings.NewReader(content)), nil + } + ctxt.IsAbsPath = func(path string) bool { + path = filepath.ToSlash(path) + // Don't rely on the default (filepath.Path) since on + // Windows, it reports virtual paths as non-absolute. + return strings.HasPrefix(path, "/") + } + return &ctxt + } type byName []os.FileInfo -func (s byName) Len() int { return len(s) } -func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s byName) Len() int { return len(s) } + +func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] } + func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() } type fakeFileInfo string -func (fi fakeFileInfo) Name() string { return string(fi) } -func (fakeFileInfo) Sys() interface{} { return nil } +func (fi fakeFileInfo) Name() string { return string(fi) } + +func (fakeFileInfo) Sys() interface{} { return nil } + func (fakeFileInfo) ModTime() time.Time { return time.Time{} } -func (fakeFileInfo) IsDir() bool { return false } -func (fakeFileInfo) Size() int64 { return 0 } -func (fakeFileInfo) Mode() os.FileMode { return 0644 } + +func (fakeFileInfo) IsDir() bool { return false } + +func (fakeFileInfo) Size() int64 { return 0 } + +func (fakeFileInfo) Mode() os.FileMode { return 0644 } type fakeDirInfo string -func (fd fakeDirInfo) Name() string { return string(fd) } -func (fakeDirInfo) Sys() interface{} { return nil } +func (fd fakeDirInfo) Name() string { return string(fd) } + +func (fakeDirInfo) Sys() interface{} { return nil } + func (fakeDirInfo) ModTime() time.Time { return time.Time{} } -func (fakeDirInfo) IsDir() bool { return true } -func (fakeDirInfo) Size() int64 { return 0 } -func (fakeDirInfo) Mode() os.FileMode { return 0755 } + +func (fakeDirInfo) IsDir() bool { return true } + +func (fakeDirInfo) Size() int64 { return 0 } + +func (fakeDirInfo) Mode() os.FileMode { return 0755 } diff --git a/vendor/golang.org/x/tools/go/buildutil/overlay.go b/vendor/golang.org/x/tools/go/buildutil/overlay.go index 7e37165..972096f 100644 --- a/vendor/golang.org/x/tools/go/buildutil/overlay.go +++ b/vendor/golang.org/x/tools/go/buildutil/overlay.go @@ -1,5 +1,7 @@ // Copyright 2016 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package buildutil @@ -16,86 +18,153 @@ import ( ) // OverlayContext overlays a build.Context with additional files from + // a map. Files in the map take precedence over other files. + // + // In addition to plain string comparison, two file names are + // considered equal if their base names match and their directory + // components point at the same directory on the file system. That is, + // symbolic links are followed for directories, but not files. + // + // A common use case for OverlayContext is to allow editors to pass in + // a set of unsaved, modified files. + // + // Currently, only the Context.OpenFile function will respect the + // overlay. This may change in the future. + func OverlayContext(orig *build.Context, overlay map[string][]byte) *build.Context { + // TODO(dominikh): Implement IsDir, HasSubdir and ReadDir rc := func(data []byte) (io.ReadCloser, error) { + return io.NopCloser(bytes.NewBuffer(data)), nil + } copy := *orig // make a copy + ctxt := © + ctxt.OpenFile = func(path string) (io.ReadCloser, error) { + // Fast path: names match exactly. + if content, ok := overlay[path]; ok { + return rc(content) + } // Slow path: check for same file under a different + // alias, perhaps due to a symbolic link. + for filename, content := range overlay { + if sameFile(path, filename) { + return rc(content) + } + } return OpenFile(orig, path) + } + return ctxt + } // ParseOverlayArchive parses an archive containing Go files and their + // contents. The result is intended to be used with OverlayContext. + // + // # Archive format + // + // The archive consists of a series of files. Each file consists of a + // name, a decimal file size and the file contents, separated by + // newlines. No newline follows after the file contents. + func ParseOverlayArchive(archive io.Reader) (map[string][]byte, error) { + overlay := make(map[string][]byte) + r := bufio.NewReader(archive) + for { + // Read file name. + filename, err := r.ReadString('\n') + if err != nil { + if err == io.EOF { + break // OK + } + return nil, fmt.Errorf("reading archive file name: %v", err) + } + filename = filepath.Clean(strings.TrimSpace(filename)) // Read file size. + sz, err := r.ReadString('\n') + if err != nil { + return nil, fmt.Errorf("reading size of archive file %s: %v", filename, err) + } + sz = strings.TrimSpace(sz) + size, err := strconv.ParseUint(sz, 10, 32) + if err != nil { + return nil, fmt.Errorf("parsing size of archive file %s: %v", filename, err) + } // Read file content. + content := make([]byte, size) + if _, err := io.ReadFull(r, content); err != nil { + return nil, fmt.Errorf("reading archive file %s: %v", filename, err) + } + overlay[filename] = content + } return overlay, nil + } diff --git a/vendor/golang.org/x/tools/go/buildutil/tags.go b/vendor/golang.org/x/tools/go/buildutil/tags.go index 32c8d14..721719d 100644 --- a/vendor/golang.org/x/tools/go/buildutil/tags.go +++ b/vendor/golang.org/x/tools/go/buildutil/tags.go @@ -1,12 +1,17 @@ // Copyright 2015 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package buildutil // This duplicated logic must be kept in sync with that from go build: + // $GOROOT/src/cmd/go/internal/work/build.go (tagsFlag.Set) + // $GOROOT/src/cmd/go/internal/base/flag.go (StringsFlag.Set) + // $GOROOT/src/cmd/internal/quoted/quoted.go (isSpaceByte, Split) import ( @@ -15,86 +20,155 @@ import ( ) const TagsFlagDoc = "a list of `build tags` to consider satisfied during the build. " + + "For more information about build tags, see the description of " + + "build constraints in the documentation for the go/build package" // TagsFlag is an implementation of the flag.Value and flag.Getter interfaces that parses + // a flag value the same as go build's -tags flag and populates a []string slice. + // + // See $GOROOT/src/go/build/doc.go for description of build tags. + // See $GOROOT/src/cmd/go/doc.go for description of 'go build -tags' flag. + // + // Example: + // + // flag.Var((*buildutil.TagsFlag)(&build.Default.BuildTags), "tags", buildutil.TagsFlagDoc) + type TagsFlag []string func (v *TagsFlag) Set(s string) error { + // See $GOROOT/src/cmd/go/internal/work/build.go (tagsFlag.Set) + // For compatibility with Go 1.12 and earlier, allow "-tags='a b c'" or even just "-tags='a'". + if strings.Contains(s, " ") || strings.Contains(s, "'") { + var err error + *v, err = splitQuotedFields(s) + if *v == nil { + *v = []string{} + } + return err + } // Starting in Go 1.13, the -tags flag is a comma-separated list of build tags. + *v = []string{} + for _, s := range strings.Split(s, ",") { + if s != "" { + *v = append(*v, s) + } + } + return nil + } func (v *TagsFlag) Get() interface{} { return *v } func splitQuotedFields(s string) ([]string, error) { + // See $GOROOT/src/cmd/internal/quoted/quoted.go (Split) + // This must remain in sync with that logic. + var f []string + for len(s) > 0 { + for len(s) > 0 && isSpaceByte(s[0]) { + s = s[1:] + } + if len(s) == 0 { + break + } + // Accepted quoted string. No unescaping inside. + if s[0] == '"' || s[0] == '\'' { + quote := s[0] + s = s[1:] + i := 0 + for i < len(s) && s[i] != quote { + i++ + } + if i >= len(s) { + return nil, fmt.Errorf("unterminated %c string", quote) + } + f = append(f, s[:i]) + s = s[i+1:] + continue + } + i := 0 + for i < len(s) && !isSpaceByte(s[i]) { + i++ + } + f = append(f, s[:i]) + s = s[i:] + } + return f, nil + } func (v *TagsFlag) String() string { + return "" + } func isSpaceByte(c byte) bool { + // See $GOROOT/src/cmd/internal/quoted/quoted.go (isSpaceByte, Split) + // This list must remain in sync with that. + return c == ' ' || c == '\t' || c == '\n' || c == '\r' + } diff --git a/vendor/golang.org/x/tools/go/buildutil/util.go b/vendor/golang.org/x/tools/go/buildutil/util.go index bee6390..1a69cfb 100644 --- a/vendor/golang.org/x/tools/go/buildutil/util.go +++ b/vendor/golang.org/x/tools/go/buildutil/util.go @@ -1,5 +1,7 @@ // Copyright 2014 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package buildutil @@ -19,61 +21,107 @@ import ( ) // ParseFile behaves like parser.ParseFile, + // but uses the build context's file system interface, if any. + // + // If file is not absolute (as defined by IsAbsPath), the (dir, file) + // components are joined using JoinPath; dir must be absolute. + // + // The displayPath function, if provided, is used to transform the + // filename that will be attached to the ASTs. + // + // TODO(adonovan): call this from go/loader.parseFiles when the tree thaws. + func ParseFile(fset *token.FileSet, ctxt *build.Context, displayPath func(string) string, dir string, file string, mode parser.Mode) (*ast.File, error) { + if !IsAbsPath(ctxt, file) { + file = JoinPath(ctxt, dir, file) + } + rd, err := OpenFile(ctxt, file) + if err != nil { + return nil, err + } + defer rd.Close() // ignore error + if displayPath != nil { + file = displayPath(file) + } + return parser.ParseFile(fset, file, rd, mode) + } // ContainingPackage returns the package containing filename. + // + // If filename is not absolute, it is interpreted relative to working directory dir. + // All I/O is via the build context's file system interface, if any. + // + // The '...Files []string' fields of the resulting build.Package are not + // populated (build.FindOnly mode). + func ContainingPackage(ctxt *build.Context, dir, filename string) (*build.Package, error) { + if !IsAbsPath(ctxt, filename) { + filename = JoinPath(ctxt, dir, filename) + } // We must not assume the file tree uses + // "/" always, + // `\` always, + // or os.PathSeparator (which varies by platform), + // but to make any progress, we are forced to assume that + // paths will not use `\` unless the PathSeparator + // is also `\`, thus we can rely on filepath.ToSlash for some sanity. dirSlash := path.Dir(filepath.ToSlash(filename)) + "/" // We assume that no source root (GOPATH[i] or GOROOT) contains any other. + for _, srcdir := range ctxt.SrcDirs() { + srcdirSlash := filepath.ToSlash(srcdir) + "/" + if importPath, ok := HasSubdir(ctxt, srcdirSlash, dirSlash); ok { + return ctxt.Import(importPath, dir, build.FindOnly) + } + } return nil, fmt.Errorf("can't find package containing %s", filename) + } // -- Effective methods of file system interface ------------------------- @@ -81,129 +129,227 @@ func ContainingPackage(ctxt *build.Context, dir, filename string) (*build.Packag // (go/build.Context defines these as methods, but does not export them.) // HasSubdir calls ctxt.HasSubdir (if not nil) or else uses + // the local file system to answer the question. + func HasSubdir(ctxt *build.Context, root, dir string) (rel string, ok bool) { + if f := ctxt.HasSubdir; f != nil { + return f(root, dir) + } // Try using paths we received. + if rel, ok = hasSubdir(root, dir); ok { + return + } // Try expanding symlinks and comparing + // expanded against unexpanded and + // expanded against expanded. + rootSym, _ := filepath.EvalSymlinks(root) + dirSym, _ := filepath.EvalSymlinks(dir) if rel, ok = hasSubdir(rootSym, dir); ok { + return + } + if rel, ok = hasSubdir(root, dirSym); ok { + return + } + return hasSubdir(rootSym, dirSym) + } func hasSubdir(root, dir string) (rel string, ok bool) { + const sep = string(filepath.Separator) + root = filepath.Clean(root) + if !strings.HasSuffix(root, sep) { + root += sep + } dir = filepath.Clean(dir) + if !strings.HasPrefix(dir, root) { + return "", false + } return filepath.ToSlash(dir[len(root):]), true + } // FileExists returns true if the specified file exists, + // using the build context's file system interface. + func FileExists(ctxt *build.Context, path string) bool { + if ctxt.OpenFile != nil { + r, err := ctxt.OpenFile(path) + if err != nil { + return false + } + r.Close() // ignore error + return true + } + _, err := os.Stat(path) + return err == nil + } // OpenFile behaves like os.Open, + // but uses the build context's file system interface, if any. + func OpenFile(ctxt *build.Context, path string) (io.ReadCloser, error) { + if ctxt.OpenFile != nil { + return ctxt.OpenFile(path) + } + return os.Open(path) + } // IsAbsPath behaves like filepath.IsAbs, + // but uses the build context's file system interface, if any. + func IsAbsPath(ctxt *build.Context, path string) bool { + if ctxt.IsAbsPath != nil { + return ctxt.IsAbsPath(path) + } + return filepath.IsAbs(path) + } // JoinPath behaves like filepath.Join, + // but uses the build context's file system interface, if any. + func JoinPath(ctxt *build.Context, path ...string) string { + if ctxt.JoinPath != nil { + return ctxt.JoinPath(path...) + } + return filepath.Join(path...) + } // IsDir behaves like os.Stat plus IsDir, + // but uses the build context's file system interface, if any. + func IsDir(ctxt *build.Context, path string) bool { + if ctxt.IsDir != nil { + return ctxt.IsDir(path) + } + fi, err := os.Stat(path) + return err == nil && fi.IsDir() + } // ReadDir behaves like ioutil.ReadDir, + // but uses the build context's file system interface, if any. + func ReadDir(ctxt *build.Context, path string) ([]os.FileInfo, error) { + if ctxt.ReadDir != nil { + return ctxt.ReadDir(path) + } + return ioutil.ReadDir(path) + } // SplitPathList behaves like filepath.SplitList, + // but uses the build context's file system interface, if any. + func SplitPathList(ctxt *build.Context, s string) []string { + if ctxt.SplitPathList != nil { + return ctxt.SplitPathList(s) + } + return filepath.SplitList(s) + } // sameFile returns true if x and y have the same basename and denote + // the same file. + func sameFile(x, y string) bool { + if path.Clean(x) == path.Clean(y) { + return true + } + if filepath.Base(x) == filepath.Base(y) { // (optimisation) + if xi, err := os.Stat(x); err == nil { + if yi, err := os.Stat(y); err == nil { + return os.SameFile(xi, yi) + } + } + } + return false + } diff --git a/vendor/golang.org/x/tools/go/internal/cgo/cgo.go b/vendor/golang.org/x/tools/go/internal/cgo/cgo.go index 697974b..e59a28d 100644 --- a/vendor/golang.org/x/tools/go/internal/cgo/cgo.go +++ b/vendor/golang.org/x/tools/go/internal/cgo/cgo.go @@ -1,52 +1,99 @@ // Copyright 2013 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. // Package cgo handles cgo preprocessing of files containing `import "C"`. + // + // DESIGN + // + // The approach taken is to run the cgo processor on the package's + // CgoFiles and parse the output, faking the filenames of the + // resulting ASTs so that the synthetic file containing the C types is + // called "C" (e.g. "~/go/src/net/C") and the preprocessed files + // have their original names (e.g. "~/go/src/net/cgo_unix.go"), + // not the names of the actual temporary files. + // + // The advantage of this approach is its fidelity to 'go build'. The + // downside is that the token.Position.Offset for each AST node is + // incorrect, being an offset within the temporary file. Line numbers + // should still be correct because of the //line comments. + // + // The logic of this file is mostly plundered from the 'go build' + // tool, which also invokes the cgo preprocessor. + // + // + // REJECTED ALTERNATIVE + // + // An alternative approach that we explored is to extend go/types' + // Importer mechanism to provide the identity of the importing package + // so that each time `import "C"` appears it resolves to a different + // synthetic package containing just the objects needed in that case. + // The loader would invoke cgo but parse only the cgo_types.go file + // defining the package-level objects, discarding the other files + // resulting from preprocessing. + // + // The benefit of this approach would have been that source-level + // syntax information would correspond exactly to the original cgo + // file, with no preprocessing involved, making source tools like + // godoc, guru, and eg happy. However, the approach was rejected + // due to the additional complexity it would impose on go/types. (It + // made for a beautiful demo, though.) + // + // cgo files, despite their *.go extension, are not legal Go source + // files per the specification since they may refer to unexported + // members of package "C" such as C.int. Also, a function such as + // C.getpwent has in effect two types, one matching its C type and one + // which additionally returns (errno C.int). The cgo preprocessor + // uses name mangling to distinguish these two functions in the + // processed code, but go/types would need to duplicate this logic in + // its handling of function calls, analogous to the treatment of map + // lookups in which y=m[k] and y,ok=m[k] are both legal. package cgo @@ -66,154 +113,272 @@ import ( ) // ProcessFiles invokes the cgo preprocessor on bp.CgoFiles, parses + // the output and returns the resulting ASTs. + func ProcessFiles(bp *build.Package, fset *token.FileSet, DisplayPath func(path string) string, mode parser.Mode) ([]*ast.File, error) { + tmpdir, err := os.MkdirTemp("", strings.Replace(bp.ImportPath, "/", "_", -1)+"_C") + if err != nil { + return nil, err + } + defer os.RemoveAll(tmpdir) pkgdir := bp.Dir + if DisplayPath != nil { + pkgdir = DisplayPath(pkgdir) + } cgoFiles, cgoDisplayFiles, err := Run(bp, pkgdir, tmpdir, false) + if err != nil { + return nil, err + } + var files []*ast.File + for i := range cgoFiles { + rd, err := os.Open(cgoFiles[i]) + if err != nil { + return nil, err + } + display := filepath.Join(bp.Dir, cgoDisplayFiles[i]) + f, err := parser.ParseFile(fset, display, rd, mode) + rd.Close() + if err != nil { + return nil, err + } + files = append(files, f) + } + return files, nil + } var cgoRe = regexp.MustCompile(`[/\\:]`) // Run invokes the cgo preprocessor on bp.CgoFiles and returns two + // lists of files: the resulting processed files (in temporary + // directory tmpdir) and the corresponding names of the unprocessed files. + // + // Run is adapted from (*builder).cgo in + // $GOROOT/src/cmd/go/build.go, but these features are unsupported: + // Objective C, CGOPKGPATH, CGO_FLAGS. + // + // If useabs is set to true, absolute paths of the bp.CgoFiles will be passed in + // to the cgo preprocessor. This in turn will set the // line comments + // referring to those files to use absolute paths. This is needed for + // go/packages using the legacy go list support so it is able to find + // the original files. + func Run(bp *build.Package, pkgdir, tmpdir string, useabs bool) (files, displayFiles []string, err error) { + cgoCPPFLAGS, _, _, _ := cflags(bp, true) + _, cgoexeCFLAGS, _, _ := cflags(bp, false) if len(bp.CgoPkgConfig) > 0 { + pcCFLAGS, err := pkgConfigFlags(bp) + if err != nil { + return nil, nil, err + } + cgoCPPFLAGS = append(cgoCPPFLAGS, pcCFLAGS...) + } // Allows including _cgo_export.h from .[ch] files in the package. + cgoCPPFLAGS = append(cgoCPPFLAGS, "-I", tmpdir) // _cgo_gotypes.go (displayed "C") contains the type definitions. + files = append(files, filepath.Join(tmpdir, "_cgo_gotypes.go")) + displayFiles = append(displayFiles, "C") + for _, fn := range bp.CgoFiles { + // "foo.cgo1.go" (displayed "foo.go") is the processed Go source. + f := cgoRe.ReplaceAllString(fn[:len(fn)-len("go")], "_") + files = append(files, filepath.Join(tmpdir, f+"cgo1.go")) + displayFiles = append(displayFiles, fn) + } var cgoflags []string + if bp.Goroot && bp.ImportPath == "runtime/cgo" { + cgoflags = append(cgoflags, "-import_runtime_cgo=false") + } + if bp.Goroot && bp.ImportPath == "runtime/race" || bp.ImportPath == "runtime/cgo" { + cgoflags = append(cgoflags, "-import_syscall=false") + } var cgoFiles []string = bp.CgoFiles + if useabs { + cgoFiles = make([]string, len(bp.CgoFiles)) + for i := range cgoFiles { + cgoFiles[i] = filepath.Join(pkgdir, bp.CgoFiles[i]) + } + } args := stringList( + "go", "tool", "cgo", "-objdir", tmpdir, cgoflags, "--", + cgoCPPFLAGS, cgoexeCFLAGS, cgoFiles, ) + if false { + log.Printf("Running cgo for package %q: %s (dir=%s)", bp.ImportPath, args, pkgdir) + } + cmd := exec.Command(args[0], args[1:]...) + cmd.Dir = pkgdir + cmd.Env = append(os.Environ(), "PWD="+pkgdir) + cmd.Stdout = os.Stderr + cmd.Stderr = os.Stderr + if err := cmd.Run(); err != nil { + return nil, nil, fmt.Errorf("cgo failed: %s: %s", args, err) + } return files, displayFiles, nil + } // -- unmodified from 'go build' --------------------------------------- // Return the flags to use when invoking the C or C++ compilers, or cgo. + func cflags(p *build.Package, def bool) (cppflags, cflags, cxxflags, ldflags []string) { + var defaults string + if def { + defaults = "-g -O2" + } cppflags = stringList(envList("CGO_CPPFLAGS", ""), p.CgoCPPFLAGS) + cflags = stringList(envList("CGO_CFLAGS", defaults), p.CgoCFLAGS) + cxxflags = stringList(envList("CGO_CXXFLAGS", defaults), p.CgoCXXFLAGS) + ldflags = stringList(envList("CGO_LDFLAGS", defaults), p.CgoLDFLAGS) + return + } // envList returns the value of the given environment variable broken + // into fields, using the default value when the variable is empty. + func envList(key, def string) []string { + v := os.Getenv(key) + if v == "" { + v = def + } + return strings.Fields(v) + } // stringList's arguments should be a sequence of string or []string values. + // stringList flattens them into a single []string. + func stringList(args ...interface{}) []string { + var x []string + for _, arg := range args { + switch arg := arg.(type) { + case []string: + x = append(x, arg...) + case string: + x = append(x, arg) + default: + panic("stringList: invalid argument") + } + } + return x + } diff --git a/vendor/golang.org/x/tools/go/internal/cgo/cgo_pkgconfig.go b/vendor/golang.org/x/tools/go/internal/cgo/cgo_pkgconfig.go index 2455be5..e4c8f08 100644 --- a/vendor/golang.org/x/tools/go/internal/cgo/cgo_pkgconfig.go +++ b/vendor/golang.org/x/tools/go/internal/cgo/cgo_pkgconfig.go @@ -1,5 +1,7 @@ // Copyright 2013 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package cgo @@ -13,30 +15,55 @@ import ( ) // pkgConfig runs pkg-config with the specified arguments and returns the flags it prints. + func pkgConfig(mode string, pkgs []string) (flags []string, err error) { + cmd := exec.Command("pkg-config", append([]string{mode}, pkgs...)...) + out, err := cmd.Output() + if err != nil { + s := fmt.Sprintf("%s failed: %v", strings.Join(cmd.Args, " "), err) + if len(out) > 0 { + s = fmt.Sprintf("%s: %s", s, out) + } + if err, ok := err.(*exec.ExitError); ok && len(err.Stderr) > 0 { + s = fmt.Sprintf("%s\nstderr:\n%s", s, err.Stderr) + } + return nil, errors.New(s) + } + if len(out) > 0 { + flags = strings.Fields(string(out)) + } + return + } // pkgConfigFlags calls pkg-config if needed and returns the cflags + // needed to build the package. + func pkgConfigFlags(p *build.Package) (cflags []string, err error) { + if len(p.CgoPkgConfig) == 0 { + return nil, nil + } + return pkgConfig("--cflags", p.CgoPkgConfig) + } diff --git a/vendor/golang.org/x/tools/go/loader/loader.go b/vendor/golang.org/x/tools/go/loader/loader.go index 013c0f5..49e271d 100644 --- a/vendor/golang.org/x/tools/go/loader/loader.go +++ b/vendor/golang.org/x/tools/go/loader/loader.go @@ -1,5 +1,7 @@ // Copyright 2013 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package loader @@ -31,474 +33,823 @@ var ignoreVendor build.ImportMode const trace = false // show timing info for type-checking // Config specifies the configuration for loading a whole program from + // Go source code. + // The zero value for Config is a ready-to-use default configuration. + type Config struct { + // Fset is the file set for the parser to use when loading the + // program. If nil, it may be lazily initialized by any + // method of Config. + Fset *token.FileSet // ParserMode specifies the mode to be used by the parser when + // loading source packages. + ParserMode parser.Mode // TypeChecker contains options relating to the type checker. + // + // The supplied IgnoreFuncBodies is not used; the effective + // value comes from the TypeCheckFuncBodies func below. + // The supplied Import function is not used either. + TypeChecker types.Config // TypeCheckFuncBodies is a predicate over package paths. + // A package for which the predicate is false will + // have its package-level declarations type checked, but not + // its function bodies; this can be used to quickly load + // dependencies from source. If nil, all func bodies are type + // checked. + TypeCheckFuncBodies func(path string) bool // If Build is non-nil, it is used to locate source packages. + // Otherwise &build.Default is used. + // + // By default, cgo is invoked to preprocess Go files that + // import the fake package "C". This behaviour can be + // disabled by setting CGO_ENABLED=0 in the environment prior + // to startup, or by setting Build.CgoEnabled=false. + Build *build.Context // The current directory, used for resolving relative package + // references such as "./go/loader". If empty, os.Getwd will be + // used instead. + Cwd string // If DisplayPath is non-nil, it is used to transform each + // file name obtained from Build.Import(). This can be used + // to prevent a virtualized build.Config's file names from + // leaking into the user interface. + DisplayPath func(path string) string // If AllowErrors is true, Load will return a Program even + // if some of the its packages contained I/O, parser or type + // errors; such errors are accessible via PackageInfo.Errors. If + // false, Load will fail if any package had an error. + AllowErrors bool // CreatePkgs specifies a list of non-importable initial + // packages to create. The resulting packages will appear in + // the corresponding elements of the Program.Created slice. + CreatePkgs []PkgSpec // ImportPkgs specifies a set of initial packages to load. + // The map keys are package paths. + // + // The map value indicates whether to load tests. If true, Load + // will add and type-check two lists of files to the package: + // non-test files followed by in-package *_test.go files. In + // addition, it will append the external test package (if any) + // to Program.Created. + ImportPkgs map[string]bool // FindPackage is called during Load to create the build.Package + // for a given import path from a given directory. + // If FindPackage is nil, (*build.Context).Import is used. + // A client may use this hook to adapt to a proprietary build + // system that does not follow the "go build" layout + // conventions, for example. + // + // It must be safe to call concurrently from multiple goroutines. + FindPackage func(ctxt *build.Context, importPath, fromDir string, mode build.ImportMode) (*build.Package, error) // AfterTypeCheck is called immediately after a list of files + // has been type-checked and appended to info.Files. + // + // This optional hook function is the earliest opportunity for + // the client to observe the output of the type checker, + // which may be useful to reduce analysis latency when loading + // a large program. + // + // The function is permitted to modify info.Info, for instance + // to clear data structures that are no longer needed, which can + // dramatically reduce peak memory consumption. + // + // The function may be called twice for the same PackageInfo: + // once for the files of the package and again for the + // in-package test files. + // + // It must be safe to call concurrently from multiple goroutines. + AfterTypeCheck func(info *PackageInfo, files []*ast.File) } // A PkgSpec specifies a non-importable package to be created by Load. + // Files are processed first, but typically only one of Files and + // Filenames is provided. The path needn't be globally unique. + // + // For vendoring purposes, the package's directory is the one that + // contains the first file. + type PkgSpec struct { - Path string // package path ("" => use package declaration) - Files []*ast.File // ASTs of already-parsed files - Filenames []string // names of files to be parsed + Path string // package path ("" => use package declaration) + + Files []*ast.File // ASTs of already-parsed files + + Filenames []string // names of files to be parsed + } // A Program is a Go program loaded from source as specified by a Config. + type Program struct { Fset *token.FileSet // the file set for this program // Created[i] contains the initial package whose ASTs or + // filenames were supplied by Config.CreatePkgs[i], followed by + // the external test package, if any, of each package in + // Config.ImportPkgs ordered by ImportPath. + // + // NOTE: these files must not import "C". Cgo preprocessing is + // only performed on imported packages, not ad hoc packages. + // + // TODO(adonovan): we need to copy and adapt the logic of + // goFilesPackage (from $GOROOT/src/cmd/go/build.go) and make + // Config.Import and Config.Create methods return the same kind + // of entity, essentially a build.Package. + // Perhaps we can even reuse that type directly. + Created []*PackageInfo // Imported contains the initially imported packages, + // as specified by Config.ImportPkgs. + Imported map[string]*PackageInfo // AllPackages contains the PackageInfo of every package + // encountered by Load: all initial packages and all + // dependencies, including incomplete ones. + AllPackages map[*types.Package]*PackageInfo // importMap is the canonical mapping of package paths to + // packages. It contains all Imported initial packages, but not + // Created ones, and all imported dependencies. + importMap map[string]*types.Package } // PackageInfo holds the ASTs and facts derived by the type-checker -// for a single package. -// -// Not mutated once exposed via the API. -type PackageInfo struct { - Pkg *types.Package - Importable bool // true if 'import "Pkg.Path()"' would resolve to this - TransitivelyErrorFree bool // true if Pkg and all its dependencies are free of errors - Files []*ast.File // syntax trees for the package's files - Errors []error // non-nil if the package had errors - types.Info // type-checker deductions. - dir string // package directory - checker *types.Checker // transient type-checker state +// for a single package. + +// + +// Not mutated once exposed via the API. + +type PackageInfo struct { + Pkg *types.Package + + Importable bool // true if 'import "Pkg.Path()"' would resolve to this + + TransitivelyErrorFree bool // true if Pkg and all its dependencies are free of errors + + Files []*ast.File // syntax trees for the package's files + + Errors []error // non-nil if the package had errors + + types.Info // type-checker deductions. + + dir string // package directory + + checker *types.Checker // transient type-checker state + errorFunc func(error) } func (info *PackageInfo) String() string { return info.Pkg.Path() } func (info *PackageInfo) appendError(err error) { + if info.errorFunc != nil { + info.errorFunc(err) + } else { + fmt.Fprintln(os.Stderr, err) + } + info.Errors = append(info.Errors, err) + } func (conf *Config) fset() *token.FileSet { + if conf.Fset == nil { + conf.Fset = token.NewFileSet() + } + return conf.Fset + } // ParseFile is a convenience function (intended for testing) that invokes + // the parser using the Config's FileSet, which is initialized if nil. + // + // src specifies the parser input as a string, []byte, or io.Reader, and + // filename is its apparent name. If src is nil, the contents of + // filename are read from the file system. + func (conf *Config) ParseFile(filename string, src interface{}) (*ast.File, error) { + // TODO(adonovan): use conf.build() etc like parseFiles does. + return parser.ParseFile(conf.fset(), filename, src, conf.ParserMode) + } // FromArgsUsage is a partial usage message that applications calling + // FromArgs may wish to include in their -help output. + const FromArgsUsage = ` + is a list of arguments denoting a set of initial packages. + It may take one of two forms: + + 1. A list of *.go source files. + + All of the specified files are loaded, parsed and type-checked + as a single package. All the files must belong to the same directory. + + 2. A list of import paths, each denoting a package. + + The package's directory is found relative to the $GOROOT and + $GOPATH using similar logic to 'go build', and the *.go files in + that directory are loaded, parsed and type-checked as a single + package. + + In addition, all *_test.go files in the directory are then loaded + and parsed. Those files whose package declaration equals that of + the non-*_test.go files are included in the primary package. Test + files whose package declaration ends with "_test" are type-checked + as another package, the 'external' test package, so that a single + import path may denote two packages. (Whether this behaviour is + enabled is tool-specific, and may depend on additional flags.) + + A '--' argument terminates the list of packages. + ` // FromArgs interprets args as a set of initial packages to load from + // source and updates the configuration. It returns the list of + // unconsumed arguments. + // + // It is intended for use in command-line interfaces that require a + // set of initial packages to be specified; see FromArgsUsage message + // for details. + // + // Only superficial errors are reported at this stage; errors dependent + // on I/O are detected during Load. + func (conf *Config) FromArgs(args []string, xtest bool) ([]string, error) { + var rest []string + for i, arg := range args { + if arg == "--" { + rest = args[i+1:] + args = args[:i] + break // consume "--" and return the remaining args + } + } if len(args) > 0 && strings.HasSuffix(args[0], ".go") { + // Assume args is a list of a *.go files + // denoting a single ad hoc package. + for _, arg := range args { + if !strings.HasSuffix(arg, ".go") { + return nil, fmt.Errorf("named files must be .go files: %s", arg) + } + } + conf.CreateFromFilenames("", args...) + } else { + // Assume args are directories each denoting a + // package and (perhaps) an external test, iff xtest. + for _, arg := range args { + if xtest { + conf.ImportWithTests(arg) + } else { + conf.Import(arg) + } + } + } return rest, nil + } // CreateFromFilenames is a convenience function that adds + // a conf.CreatePkgs entry to create a package of the specified *.go + // files. + func (conf *Config) CreateFromFilenames(path string, filenames ...string) { + conf.CreatePkgs = append(conf.CreatePkgs, PkgSpec{Path: path, Filenames: filenames}) + } // CreateFromFiles is a convenience function that adds a conf.CreatePkgs + // entry to create package of the specified path and parsed files. + func (conf *Config) CreateFromFiles(path string, files ...*ast.File) { + conf.CreatePkgs = append(conf.CreatePkgs, PkgSpec{Path: path, Files: files}) + } // ImportWithTests is a convenience function that adds path to + // ImportPkgs, the set of initial source packages located relative to + // $GOPATH. The package will be augmented by any *_test.go files in + // its directory that contain a "package x" (not "package x_test") + // declaration. + // + // In addition, if any *_test.go files contain a "package x_test" + // declaration, an additional package comprising just those files will + // be added to CreatePkgs. + func (conf *Config) ImportWithTests(path string) { conf.addImport(path, true) } // Import is a convenience function that adds path to ImportPkgs, the + // set of initial packages that will be imported from source. + func (conf *Config) Import(path string) { conf.addImport(path, false) } func (conf *Config) addImport(path string, tests bool) { + if path == "C" { + return // ignore; not a real package + } + if conf.ImportPkgs == nil { + conf.ImportPkgs = make(map[string]bool) + } + conf.ImportPkgs[path] = conf.ImportPkgs[path] || tests + } // PathEnclosingInterval returns the PackageInfo and ast.Node that + // contain source interval [start, end), and all the node's ancestors + // up to the AST root. It searches all ast.Files of all packages in prog. + // exact is defined as for astutil.PathEnclosingInterval. + // + // The zero value is returned if not found. + func (prog *Program) PathEnclosingInterval(start, end token.Pos) (pkg *PackageInfo, path []ast.Node, exact bool) { + for _, info := range prog.AllPackages { + for _, f := range info.Files { + if f.Pos() == token.NoPos { + // This can happen if the parser saw + // too many errors and bailed out. + // (Use parser.AllErrors to prevent that.) + continue + } + if !tokenFileContainsPos(prog.Fset.File(f.Pos()), start) { + continue + } + if path, exact := astutil.PathEnclosingInterval(f, start, end); path != nil { + return info, path, exact + } + } + } + return nil, nil, false + } // InitialPackages returns a new slice containing the set of initial + // packages (Created + Imported) in unspecified order. + func (prog *Program) InitialPackages() []*PackageInfo { + infos := make([]*PackageInfo, 0, len(prog.Created)+len(prog.Imported)) + infos = append(infos, prog.Created...) + for _, info := range prog.Imported { + infos = append(infos, info) + } + return infos + } // Package returns the ASTs and results of type checking for the + // specified package. + func (prog *Program) Package(path string) *PackageInfo { + if info, ok := prog.AllPackages[prog.importMap[path]]; ok { + return info + } + for _, info := range prog.Created { + if path == info.Pkg.Path() { + return info + } + } + return nil + } // ---------- Implementation ---------- // importer holds the working state of the algorithm. + type importer struct { - conf *Config // the client configuration + conf *Config // the client configuration + start time.Time // for logging progMu sync.Mutex // guards prog - prog *Program // the resulting program + + prog *Program // the resulting program // findpkg is a memoization of FindPackage. - findpkgMu sync.Mutex // guards findpkg - findpkg map[findpkgKey]*findpkgValue - importedMu sync.Mutex // guards imported - imported map[string]*importInfo // all imported packages (incl. failures) by import path + findpkgMu sync.Mutex // guards findpkg + + findpkg map[findpkgKey]*findpkgValue + + importedMu sync.Mutex // guards imported + + imported map[string]*importInfo // all imported packages (incl. failures) by import path // import dependency graph: graph[x][y] => x imports y + // + // Since non-importable packages cannot be cyclic, we ignore + // their imports, thus we only need the subgraph over importable + // packages. Nodes are identified by their import paths. + graphMu sync.Mutex - graph map[string]map[string]bool + + graph map[string]map[string]bool } type findpkgKey struct { importPath string - fromDir string - mode build.ImportMode + + fromDir string + + mode build.ImportMode } type findpkgValue struct { ready chan struct{} // closed to broadcast readiness - bp *build.Package - err error + + bp *build.Package + + err error } // importInfo tracks the success or failure of a single import. + // + // Upon completion, exactly one of info and err is non-nil: + // info on successful creation of a package, err otherwise. + // A successful package may still contain type errors. + type importInfo struct { - path string // import path - info *PackageInfo // results of typechecking (including errors) + path string // import path + + info *PackageInfo // results of typechecking (including errors) + complete chan struct{} // closed to broadcast that info is set. + } // awaitCompletion blocks until ii is complete, + // i.e. the info field is safe to inspect. + func (ii *importInfo) awaitCompletion() { + <-ii.complete // wait for close + } // Complete marks ii as complete. + // Its info and err fields will not be subsequently updated. + func (ii *importInfo) Complete(info *PackageInfo) { + if info == nil { + panic("info == nil") + } + ii.info = info + close(ii.complete) + } type importError struct { path string // import path - err error // reason for failure to create a package + + err error // reason for failure to create a package + } // Load creates the initial packages specified by conf.{Create,Import}Pkgs, + // loading their dependencies packages as needed. + // + // On success, Load returns a Program containing a PackageInfo for + // each package. On failure, it returns an error. + // + // If AllowErrors is true, Load will return a Program even if some + // packages contained I/O, parser or type errors, or if dependencies + // were missing. (Such errors are accessible via PackageInfo.Errors. If + // false, Load will fail if any package had an error. + // + // It is an error if no packages were loaded. + func (conf *Config) Load() (*Program, error) { + // Create a simple default error handler for parse/type errors. + if conf.TypeChecker.Error == nil { + conf.TypeChecker.Error = func(e error) { fmt.Fprintln(os.Stderr, e) } + } // Set default working directory for relative package references. + if conf.Cwd == "" { + var err error + conf.Cwd, err = os.Getwd() + if err != nil { + return nil, err + } + } // Install default FindPackage hook using go/build logic. + if conf.FindPackage == nil { + conf.FindPackage = (*build.Context).Import + } prog := &Program{ - Fset: conf.fset(), - Imported: make(map[string]*PackageInfo), - importMap: make(map[string]*types.Package), + + Fset: conf.fset(), + + Imported: make(map[string]*PackageInfo), + + importMap: make(map[string]*types.Package), + AllPackages: make(map[*types.Package]*PackageInfo), } imp := importer{ - conf: conf, - prog: prog, - findpkg: make(map[findpkgKey]*findpkgValue), + + conf: conf, + + prog: prog, + + findpkg: make(map[findpkgKey]*findpkgValue), + imported: make(map[string]*importInfo), - start: time.Now(), - graph: make(map[string]map[string]bool), + + start: time.Now(), + + graph: make(map[string]map[string]bool), } // -- loading proper (concurrent phase) -------------------------------- @@ -506,560 +857,991 @@ func (conf *Config) Load() (*Program, error) { var errpkgs []string // packages that contained errors // Load the initially imported packages and their dependencies, + // in parallel. + // No vendor check on packages imported from the command line. + infos, importErrors := imp.importAll("", conf.Cwd, conf.ImportPkgs, ignoreVendor) + for _, ie := range importErrors { + conf.TypeChecker.Error(ie.err) // failed to create package + errpkgs = append(errpkgs, ie.path) + } + for _, info := range infos { + prog.Imported[info.Pkg.Path()] = info + } // Augment the designated initial packages by their tests. + // Dependencies are loaded in parallel. + var xtestPkgs []*build.Package + for importPath, augment := range conf.ImportPkgs { + if !augment { + continue + } // No vendor check on packages imported from command line. + bp, err := imp.findPackage(importPath, conf.Cwd, ignoreVendor) + if err != nil { + // Package not found, or can't even parse package declaration. + // Already reported by previous loop; ignore it. + continue + } // Needs external test package? + if len(bp.XTestGoFiles) > 0 { + xtestPkgs = append(xtestPkgs, bp) + } // Consult the cache using the canonical package path. + path := bp.ImportPath + imp.importedMu.Lock() // (unnecessary, we're sequential here) + ii, ok := imp.imported[path] + // Paranoid checks added due to issue #11012. + if !ok { + // Unreachable. + // The previous loop called importAll and thus + // startLoad for each path in ImportPkgs, which + // populates imp.imported[path] with a non-zero value. + panic(fmt.Sprintf("imported[%q] not found", path)) + } + if ii == nil { + // Unreachable. + // The ii values in this loop are the same as in + // the previous loop, which enforced the invariant + // that at least one of ii.err and ii.info is non-nil. + panic(fmt.Sprintf("imported[%q] == nil", path)) + } + if ii.info == nil { + // Unreachable. + // awaitCompletion has the postcondition + // ii.info != nil. + panic(fmt.Sprintf("imported[%q].info = nil", path)) + } + info := ii.info + imp.importedMu.Unlock() // Parse the in-package test files. + files, errs := imp.conf.parsePackageFiles(bp, 't') + for _, err := range errs { + info.appendError(err) + } // The test files augmenting package P cannot be imported, + // but may import packages that import P, + // so we must disable the cycle check. + imp.addFiles(info, files, false) + } createPkg := func(path, dir string, files []*ast.File, errs []error) { + info := imp.newPackageInfo(path, dir) + for _, err := range errs { + info.appendError(err) + } // Ad hoc packages are non-importable, + // so no cycle check is needed. + // addFiles loads dependencies in parallel. + imp.addFiles(info, files, false) + prog.Created = append(prog.Created, info) + } // Create packages specified by conf.CreatePkgs. + for _, cp := range conf.CreatePkgs { + files, errs := parseFiles(conf.fset(), conf.build(), nil, conf.Cwd, cp.Filenames, conf.ParserMode) + files = append(files, cp.Files...) path := cp.Path + if path == "" { + if len(files) > 0 { + path = files[0].Name.Name + } else { + path = "(unnamed)" + } + } dir := conf.Cwd + if len(files) > 0 && files[0].Pos().IsValid() { + dir = filepath.Dir(conf.fset().File(files[0].Pos()).Name()) + } + createPkg(path, dir, files, errs) + } // Create external test packages. + sort.Sort(byImportPath(xtestPkgs)) + for _, bp := range xtestPkgs { + files, errs := imp.conf.parsePackageFiles(bp, 'x') + createPkg(bp.ImportPath+"_test", bp.Dir, files, errs) + } // -- finishing up (sequential) ---------------------------------------- if len(prog.Imported)+len(prog.Created) == 0 { + return nil, errors.New("no initial packages were loaded") + } // Create infos for indirectly imported packages. + // e.g. incomplete packages without syntax, loaded from export data. + for _, obj := range prog.importMap { + info := prog.AllPackages[obj] + if info == nil { + prog.AllPackages[obj] = &PackageInfo{Pkg: obj, Importable: true} + } else { + // finished + info.checker = nil + info.errorFunc = nil + } + } if !conf.AllowErrors { + // Report errors in indirectly imported packages. + for _, info := range prog.AllPackages { + if len(info.Errors) > 0 { + errpkgs = append(errpkgs, info.Pkg.Path()) + } + } + if errpkgs != nil { + var more string + if len(errpkgs) > 3 { + more = fmt.Sprintf(" and %d more", len(errpkgs)-3) + errpkgs = errpkgs[:3] + } + return nil, fmt.Errorf("couldn't load packages due to errors: %s%s", + strings.Join(errpkgs, ", "), more) + } + } markErrorFreePackages(prog.AllPackages) return prog, nil + } type byImportPath []*build.Package -func (b byImportPath) Len() int { return len(b) } +func (b byImportPath) Len() int { return len(b) } + func (b byImportPath) Less(i, j int) bool { return b[i].ImportPath < b[j].ImportPath } -func (b byImportPath) Swap(i, j int) { b[i], b[j] = b[j], b[i] } + +func (b byImportPath) Swap(i, j int) { b[i], b[j] = b[j], b[i] } // markErrorFreePackages sets the TransitivelyErrorFree flag on all + // applicable packages. + func markErrorFreePackages(allPackages map[*types.Package]*PackageInfo) { + // Build the transpose of the import graph. + importedBy := make(map[*types.Package]map[*types.Package]bool) + for P := range allPackages { + for _, Q := range P.Imports() { + clients, ok := importedBy[Q] + if !ok { + clients = make(map[*types.Package]bool) + importedBy[Q] = clients + } + clients[P] = true + } + } // Find all packages reachable from some error package. + reachable := make(map[*types.Package]bool) + var visit func(*types.Package) + visit = func(p *types.Package) { + if !reachable[p] { + reachable[p] = true + for q := range importedBy[p] { + visit(q) + } + } + } + for _, info := range allPackages { + if len(info.Errors) > 0 { + visit(info.Pkg) + } + } // Mark the others as "transitively error-free". + for _, info := range allPackages { + if !reachable[info.Pkg] { + info.TransitivelyErrorFree = true + } + } + } // build returns the effective build context. + func (conf *Config) build() *build.Context { + if conf.Build != nil { + return conf.Build + } + return &build.Default + } // parsePackageFiles enumerates the files belonging to package path, + // then loads, parses and returns them, plus a list of I/O or parse + // errors that were encountered. + // + // 'which' indicates which files to include: + // + // 'g': include non-test *.go source files (GoFiles + processed CgoFiles) + // 't': include in-package *_test.go source files (TestGoFiles) + // 'x': include external *_test.go source files. (XTestGoFiles) + func (conf *Config) parsePackageFiles(bp *build.Package, which rune) ([]*ast.File, []error) { + if bp.ImportPath == "unsafe" { + return nil, nil + } + var filenames []string + switch which { + case 'g': + filenames = bp.GoFiles + case 't': + filenames = bp.TestGoFiles + case 'x': + filenames = bp.XTestGoFiles + default: + panic(which) + } files, errs := parseFiles(conf.fset(), conf.build(), conf.DisplayPath, bp.Dir, filenames, conf.ParserMode) // Preprocess CgoFiles and parse the outputs (sequentially). + if which == 'g' && bp.CgoFiles != nil { + cgofiles, err := cgo.ProcessFiles(bp, conf.fset(), conf.DisplayPath, conf.ParserMode) + if err != nil { + errs = append(errs, err) + } else { + files = append(files, cgofiles...) + } + } return files, errs + } // doImport imports the package denoted by path. + // It implements the types.Importer signature. + // + // It returns an error if a package could not be created + // (e.g. go/build or parse error), but type errors are reported via + // the types.Config.Error callback (the first of which is also saved + // in the package's PackageInfo). + // + // Idempotent. + func (imp *importer) doImport(from *PackageInfo, to string) (*types.Package, error) { + if to == "C" { + // This should be unreachable, but ad hoc packages are + // not currently subject to cgo preprocessing. + // See https://golang.org/issue/11627. + return nil, fmt.Errorf(`the loader doesn't cgo-process ad hoc packages like %q; see Go issue 11627`, + from.Pkg.Path()) + } bp, err := imp.findPackage(to, from.dir, 0) + if err != nil { + return nil, err + } // The standard unsafe package is handled specially, + // and has no PackageInfo. + if bp.ImportPath == "unsafe" { + return types.Unsafe, nil + } // Look for the package in the cache using its canonical path. + path := bp.ImportPath + imp.importedMu.Lock() + ii := imp.imported[path] + imp.importedMu.Unlock() + if ii == nil { + panic("internal error: unexpected import: " + path) + } + if ii.info != nil { + return ii.info.Pkg, nil + } // Import of incomplete package: this indicates a cycle. + fromPath := from.Pkg.Path() + if cycle := imp.findPath(path, fromPath); cycle != nil { + // Normalize cycle: start from alphabetically largest node. + pos, start := -1, "" + for i, s := range cycle { + if pos < 0 || s > start { + pos, start = i, s + } + } + cycle = append(cycle, cycle[:pos]...)[pos:] // rotate cycle to start from largest - cycle = append(cycle, cycle[0]) // add start node to end to show cycliness + + cycle = append(cycle, cycle[0]) // add start node to end to show cycliness + return nil, fmt.Errorf("import cycle: %s", strings.Join(cycle, " -> ")) + } panic("internal error: import of incomplete (yet acyclic) package: " + fromPath) + } // findPackage locates the package denoted by the importPath in the + // specified directory. + func (imp *importer) findPackage(importPath, fromDir string, mode build.ImportMode) (*build.Package, error) { + // We use a non-blocking duplicate-suppressing cache (gopl.io §9.7) + // to avoid holding the lock around FindPackage. + key := findpkgKey{importPath, fromDir, mode} + imp.findpkgMu.Lock() + v, ok := imp.findpkg[key] + if ok { + // cache hit + imp.findpkgMu.Unlock() <-v.ready // wait for entry to become ready + } else { + // Cache miss: this goroutine becomes responsible for + // populating the map entry and broadcasting its readiness. + v = &findpkgValue{ready: make(chan struct{})} + imp.findpkg[key] = v + imp.findpkgMu.Unlock() ioLimit <- true + v.bp, v.err = imp.conf.FindPackage(imp.conf.build(), importPath, fromDir, mode) + <-ioLimit if _, ok := v.err.(*build.NoGoError); ok { + v.err = nil // empty directory is not an error + } close(v.ready) // broadcast ready condition + } + return v.bp, v.err + } // importAll loads, parses, and type-checks the specified packages in + // parallel and returns their completed importInfos in unspecified order. + // + // fromPath is the package path of the importing package, if it is + // importable, "" otherwise. It is used for cycle detection. + // + // fromDir is the directory containing the import declaration that + // caused these imports. + func (imp *importer) importAll(fromPath, fromDir string, imports map[string]bool, mode build.ImportMode) (infos []*PackageInfo, errors []importError) { + if fromPath != "" { + // We're loading a set of imports. + // + // We must record graph edges from the importing package + // to its dependencies, and check for cycles. + imp.graphMu.Lock() + deps, ok := imp.graph[fromPath] + if !ok { + deps = make(map[string]bool) + imp.graph[fromPath] = deps + } + for importPath := range imports { + deps[importPath] = true + } + imp.graphMu.Unlock() + } var pending []*importInfo + for importPath := range imports { + if fromPath != "" { + if cycle := imp.findPath(importPath, fromPath); cycle != nil { + // Cycle-forming import: we must not check it + // since it would deadlock. + if trace { + fmt.Fprintf(os.Stderr, "import cycle: %q\n", cycle) + } + continue + } + } + bp, err := imp.findPackage(importPath, fromDir, mode) + if err != nil { + errors = append(errors, importError{ + path: importPath, - err: err, + + err: err, }) + continue + } + pending = append(pending, imp.startLoad(bp)) + } for _, ii := range pending { + ii.awaitCompletion() + infos = append(infos, ii.info) + } return infos, errors + } // findPath returns an arbitrary path from 'from' to 'to' in the import + // graph, or nil if there was none. + func (imp *importer) findPath(from, to string) []string { + imp.graphMu.Lock() + defer imp.graphMu.Unlock() seen := make(map[string]bool) + var search func(stack []string, importPath string) []string + search = func(stack []string, importPath string) []string { + if !seen[importPath] { + seen[importPath] = true + stack = append(stack, importPath) + if importPath == to { + return stack + } + for x := range imp.graph[importPath] { + if p := search(stack, x); p != nil { + return p + } + } + } + return nil + } + return search(make([]string, 0, 20), from) + } // startLoad initiates the loading, parsing and type-checking of the + // specified package and its dependencies, if it has not already begun. + // + // It returns an importInfo, not necessarily in a completed state. The + // caller must call awaitCompletion() before accessing its info field. + // + // startLoad is concurrency-safe and idempotent. + func (imp *importer) startLoad(bp *build.Package) *importInfo { + path := bp.ImportPath + imp.importedMu.Lock() + ii, ok := imp.imported[path] + if !ok { + ii = &importInfo{path: path, complete: make(chan struct{})} + imp.imported[path] = ii + go func() { + info := imp.load(bp) + ii.Complete(info) + }() + } + imp.importedMu.Unlock() return ii + } // load implements package loading by parsing Go source files + // located by go/build. + func (imp *importer) load(bp *build.Package) *PackageInfo { + info := imp.newPackageInfo(bp.ImportPath, bp.Dir) + info.Importable = true + files, errs := imp.conf.parsePackageFiles(bp, 'g') + for _, err := range errs { + info.appendError(err) + } imp.addFiles(info, files, true) imp.progMu.Lock() + imp.prog.importMap[bp.ImportPath] = info.Pkg + imp.progMu.Unlock() return info + } // addFiles adds and type-checks the specified files to info, loading + // their dependencies if needed. The order of files determines the + // package initialization order. It may be called multiple times on the + // same package. Errors are appended to the info.Errors field. + // + // cycleCheck determines whether the imports within files create + // dependency edges that should be checked for potential cycles. + func (imp *importer) addFiles(info *PackageInfo, files []*ast.File, cycleCheck bool) { + // Ensure the dependencies are loaded, in parallel. + var fromPath string + if cycleCheck { + fromPath = info.Pkg.Path() + } + // TODO(adonovan): opt: make the caller do scanImports. + // Callers with a build.Package can skip it. + imp.importAll(fromPath, info.dir, scanImports(files), 0) if trace { + fmt.Fprintf(os.Stderr, "%s: start %q (%d)\n", + time.Since(imp.start), info.Pkg.Path(), len(files)) + } // Don't call checker.Files on Unsafe, even with zero files, + // because it would mutate the package, which is a global. + if info.Pkg == types.Unsafe { + if len(files) > 0 { + panic(`"unsafe" package contains unexpected files`) + } + } else { + // Ignore the returned (first) error since we + // already collect them all in the PackageInfo. + info.checker.Files(files) + info.Files = append(info.Files, files...) + } if imp.conf.AfterTypeCheck != nil { + imp.conf.AfterTypeCheck(info, files) + } if trace { + fmt.Fprintf(os.Stderr, "%s: stop %q\n", + time.Since(imp.start), info.Pkg.Path()) + } + } func (imp *importer) newPackageInfo(path, dir string) *PackageInfo { + var pkg *types.Package + if path == "unsafe" { + pkg = types.Unsafe + } else { + pkg = types.NewPackage(path, "") + } + info := &PackageInfo{ + Pkg: pkg, + Info: types.Info{ - Types: make(map[ast.Expr]types.TypeAndValue), - Defs: make(map[*ast.Ident]types.Object), - Uses: make(map[*ast.Ident]types.Object), - Implicits: make(map[ast.Node]types.Object), - Instances: make(map[*ast.Ident]types.Instance), - Scopes: make(map[ast.Node]*types.Scope), + + Types: make(map[ast.Expr]types.TypeAndValue), + + Defs: make(map[*ast.Ident]types.Object), + + Uses: make(map[*ast.Ident]types.Object), + + Implicits: make(map[ast.Node]types.Object), + + Instances: make(map[*ast.Ident]types.Instance), + + Scopes: make(map[ast.Node]*types.Scope), + Selections: make(map[*ast.SelectorExpr]*types.Selection), }, + errorFunc: imp.conf.TypeChecker.Error, - dir: dir, + + dir: dir, } + versions.InitFileVersions(&info.Info) // Copy the types.Config so we can vary it across PackageInfos. + tc := imp.conf.TypeChecker + tc.IgnoreFuncBodies = false + if f := imp.conf.TypeCheckFuncBodies; f != nil { + tc.IgnoreFuncBodies = !f(path) + } + tc.Importer = closure{imp, info} + tc.Error = info.appendError // appendError wraps the user's Error function info.checker = types.NewChecker(&tc, imp.conf.fset(), pkg, &info.Info) + imp.progMu.Lock() + imp.prog.AllPackages[pkg] = info + imp.progMu.Unlock() + return info + } type closure struct { - imp *importer + imp *importer + info *PackageInfo } diff --git a/vendor/golang.org/x/tools/go/loader/util.go b/vendor/golang.org/x/tools/go/loader/util.go index 3a80aca..b3efe01 100644 --- a/vendor/golang.org/x/tools/go/loader/util.go +++ b/vendor/golang.org/x/tools/go/loader/util.go @@ -1,5 +1,7 @@ // Copyright 2013 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. package loader @@ -18,106 +20,191 @@ import ( ) // We use a counting semaphore to limit + // the number of parallel I/O calls per process. + var ioLimit = make(chan bool, 10) // parseFiles parses the Go source files within directory dir and + // returns the ASTs of the ones that could be at least partially parsed, + // along with a list of I/O and parse errors encountered. + // + // I/O is done via ctxt, which may specify a virtual file system. + // displayPath is used to transform the filenames attached to the ASTs. + func parseFiles(fset *token.FileSet, ctxt *build.Context, displayPath func(string) string, dir string, files []string, mode parser.Mode) ([]*ast.File, []error) { + if displayPath == nil { + displayPath = func(path string) string { return path } + } + var wg sync.WaitGroup + n := len(files) + parsed := make([]*ast.File, n) + errors := make([]error, n) + for i, file := range files { + if !buildutil.IsAbsPath(ctxt, file) { + file = buildutil.JoinPath(ctxt, dir, file) + } + wg.Add(1) + go func(i int, file string) { + ioLimit <- true // wait + defer func() { + wg.Done() + <-ioLimit // signal + }() + var rd io.ReadCloser + var err error + if ctxt.OpenFile != nil { + rd, err = ctxt.OpenFile(file) + } else { + rd, err = os.Open(file) + } + if err != nil { + errors[i] = err // open failed + return + } // ParseFile may return both an AST and an error. + parsed[i], errors[i] = parser.ParseFile(fset, displayPath(file), rd, mode) + rd.Close() + }(i, file) + } + wg.Wait() // Eliminate nils, preserving order. + var o int + for _, f := range parsed { + if f != nil { + parsed[o] = f + o++ + } + } + parsed = parsed[:o] o = 0 + for _, err := range errors { + if err != nil { + errors[o] = err + o++ + } + } + errors = errors[:o] return parsed, errors + } // scanImports returns the set of all import paths from all + // import specs in the specified files. + func scanImports(files []*ast.File) map[string]bool { + imports := make(map[string]bool) + for _, f := range files { + for _, decl := range f.Decls { + if decl, ok := decl.(*ast.GenDecl); ok && decl.Tok == token.IMPORT { + for _, spec := range decl.Specs { + spec := spec.(*ast.ImportSpec) // NB: do not assume the program is well-formed! + path, err := strconv.Unquote(spec.Path.Value) + if err != nil { + continue // quietly ignore the error + } + if path == "C" { + continue // skip pseudopackage + } + imports[path] = true + } + } + } + } + return imports + } // ---------- Internal helpers ---------- // TODO(adonovan): make this a method: func (*token.File) Contains(token.Pos) + func tokenFileContainsPos(f *token.File, pos token.Pos) bool { + p := int(pos) + base := f.Base() + return base <= p && p < base+f.Size() + } diff --git a/vendor/golang.org/x/tools/internal/versions/types_go121.go b/vendor/golang.org/x/tools/internal/versions/types_go121.go index b4345d3..b8233f7 100644 --- a/vendor/golang.org/x/tools/internal/versions/types_go121.go +++ b/vendor/golang.org/x/tools/internal/versions/types_go121.go @@ -1,5 +1,7 @@ // Copyright 2023 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build !go1.22 @@ -13,18 +15,31 @@ import ( ) // FileVersion returns a language version (<=1.21) derived from runtime.Version() + // or an unknown future version. + func FileVersion(info *types.Info, file *ast.File) string { + // In x/tools built with Go <= 1.21, we do not have Info.FileVersions + // available. We use a go version derived from the toolchain used to + // compile the tool by default. + // This will be <= go1.21. We take this as the maximum version that + // this tool can support. + // + // There are no features currently in x/tools that need to tell fine grained + // differences for versions <1.22. + return toolchain + } // InitFileVersions is a noop when compiled with this Go version. + func InitFileVersions(*types.Info) {} diff --git a/vendor/golang.org/x/tools/internal/versions/types_go122.go b/vendor/golang.org/x/tools/internal/versions/types_go122.go index e818063..180e253 100644 --- a/vendor/golang.org/x/tools/internal/versions/types_go122.go +++ b/vendor/golang.org/x/tools/internal/versions/types_go122.go @@ -1,5 +1,7 @@ // Copyright 2023 The Go Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. //go:build go1.22 @@ -13,29 +15,53 @@ import ( ) // FileVersions returns a file's Go version. + // The reported version is an unknown Future version if a + // version cannot be determined. + func FileVersion(info *types.Info, file *ast.File) string { + // In tools built with Go >= 1.22, the Go version of a file + // follow a cascades of sources: + // 1) types.Info.FileVersion, which follows the cascade: + // 1.a) file version (ast.File.GoVersion), + // 1.b) the package version (types.Config.GoVersion), or + // 2) is some unknown Future version. + // + // File versions require a valid package version to be provided to types + // in Config.GoVersion. Config.GoVersion is either from the package's module + // or the toolchain (go run). This value should be provided by go/packages + // or unitchecker.Config.GoVersion. + if v := info.FileVersions[file]; IsValid(v) { + return v + } + // Note: we could instead return runtime.Version() [if valid]. + // This would act as a max version on what a tool can support. + return Future + } // InitFileVersions initializes info to record Go versions for Go files. + func InitFileVersions(info *types.Info) { + info.FileVersions = make(map[*ast.File]string) + } diff --git a/vendor/gopkg.in/natefinch/lumberjack.v2/chown_linux.go b/vendor/gopkg.in/natefinch/lumberjack.v2/chown_linux.go index 465f569..3666a0a 100644 --- a/vendor/gopkg.in/natefinch/lumberjack.v2/chown_linux.go +++ b/vendor/gopkg.in/natefinch/lumberjack.v2/chown_linux.go @@ -6,14 +6,23 @@ import ( ) // osChown is a var so we can mock it out during tests. + var osChown = os.Chown func chown(name string, info os.FileInfo) error { + f, err := os.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, info.Mode()) + if err != nil { + return err + } + f.Close() + stat := info.Sys().(*syscall.Stat_t) + return osChown(name, int(stat.Uid), int(stat.Gid)) + } diff --git a/vendor/gopkg.in/natefinch/lumberjack.v2/lumberjack.go b/vendor/gopkg.in/natefinch/lumberjack.v2/lumberjack.go index 8fe043e..e0b2f77 100644 --- a/vendor/gopkg.in/natefinch/lumberjack.v2/lumberjack.go +++ b/vendor/gopkg.in/natefinch/lumberjack.v2/lumberjack.go @@ -1,24 +1,45 @@ // Package lumberjack provides a rolling logger. + // + // Note that this is v2.0 of lumberjack, and should be imported using gopkg.in + // thusly: + // + // import "gopkg.in/natefinch/lumberjack.v2" + // + // The package name remains simply lumberjack, and the code resides at + // https://github.com/natefinch/lumberjack under the v2.0 branch. + // + // Lumberjack is intended to be one part of a logging infrastructure. + // It is not an all-in-one solution, but instead is a pluggable + // component at the bottom of the logging stack that simply controls the files + // to which logs are written. + // + // Lumberjack plays well with any logging package that can write to an + // io.Writer, including the standard library's log package. + // + // Lumberjack assumes that only one process is writing to the output files. + // Using the same lumberjack configuration from multiple processes on the same + // machine will result in improper behavior. + package lumberjack import ( @@ -37,505 +58,867 @@ import ( const ( backupTimeFormat = "2006-01-02T15-04-05.000" - compressSuffix = ".gz" - defaultMaxSize = 100 + + compressSuffix = ".gz" + + defaultMaxSize = 100 ) // ensure we always implement io.WriteCloser + var _ io.WriteCloser = (*Logger)(nil) // Logger is an io.WriteCloser that writes to the specified filename. + // + // Logger opens or creates the logfile on first Write. If the file exists and + // is less than MaxSize megabytes, lumberjack will open and append to that file. + // If the file exists and its size is >= MaxSize megabytes, the file is renamed + // by putting the current time in a timestamp in the name immediately before the + // file's extension (or the end of the filename if there's no extension). A new + // log file is then created using original filename. + // + // Whenever a write would cause the current log file exceed MaxSize megabytes, + // the current file is closed, renamed, and a new log file created with the + // original name. Thus, the filename you give Logger is always the "current" log + // file. + // + // Backups use the log file name given to Logger, in the form + // `name-timestamp.ext` where name is the filename without the extension, + // timestamp is the time at which the log was rotated formatted with the + // time.Time format of `2006-01-02T15-04-05.000` and the extension is the + // original extension. For example, if your Logger.Filename is + // `/var/log/foo/server.log`, a backup created at 6:30pm on Nov 11 2016 would + // use the filename `/var/log/foo/server-2016-11-04T18-30-00.000.log` + // + // # Cleaning Up Old Log Files + // + // Whenever a new logfile gets created, old log files may be deleted. The most + // recent files according to the encoded timestamp will be retained, up to a + // number equal to MaxBackups (or all of them if MaxBackups is 0). Any files + // with an encoded timestamp older than MaxAge days are deleted, regardless of + // MaxBackups. Note that the time encoded in the timestamp is the rotation + // time, which may differ from the last time that file was written to. + // + // If MaxBackups and MaxAge are both 0, no old log files will be deleted. + type Logger struct { + // Filename is the file to write logs to. Backup log files will be retained + // in the same directory. It uses -lumberjack.log in + // os.TempDir() if empty. + Filename string `json:"filename" yaml:"filename"` // MaxSize is the maximum size in megabytes of the log file before it gets + // rotated. It defaults to 100 megabytes. + MaxSize int `json:"maxsize" yaml:"maxsize"` // MaxAge is the maximum number of days to retain old log files based on the + // timestamp encoded in their filename. Note that a day is defined as 24 + // hours and may not exactly correspond to calendar days due to daylight + // savings, leap seconds, etc. The default is not to remove old log files + // based on age. + MaxAge int `json:"maxage" yaml:"maxage"` // MaxBackups is the maximum number of old log files to retain. The default + // is to retain all old log files (though MaxAge may still cause them to get + // deleted.) + MaxBackups int `json:"maxbackups" yaml:"maxbackups"` // LocalTime determines if the time used for formatting the timestamps in + // backup files is the computer's local time. The default is to use UTC + // time. + LocalTime bool `json:"localtime" yaml:"localtime"` // Compress determines if the rotated log files should be compressed + // using gzip. The default is not to perform compression. + Compress bool `json:"compress" yaml:"compress"` size int64 - file *os.File - mu sync.Mutex - millCh chan bool + file *os.File + + mu sync.Mutex + + millCh chan bool + startMill sync.Once } var ( + // currentTime exists so it can be mocked out by tests. + currentTime = time.Now // os_Stat exists so it can be mocked out by tests. + osStat = os.Stat // megabyte is the conversion factor between MaxSize and bytes. It is a + // variable so tests can mock it out and not need to write megabytes of data + // to disk. + megabyte = 1024 * 1024 ) // Write implements io.Writer. If a write would cause the log file to be larger + // than MaxSize, the file is closed, renamed to include a timestamp of the + // current time, and a new log file is created using the original log file name. + // If the length of the write is greater than MaxSize, an error is returned. + func (l *Logger) Write(p []byte) (n int, err error) { + l.mu.Lock() + defer l.mu.Unlock() writeLen := int64(len(p)) + if writeLen > l.max() { + return 0, fmt.Errorf( + "write length %d exceeds maximum file size %d", writeLen, l.max(), ) + } if l.file == nil { + if err = l.openExistingOrNew(len(p)); err != nil { + return 0, err + } + } if l.size+writeLen > l.max() { + if err := l.rotate(); err != nil { + return 0, err + } + } n, err = l.file.Write(p) + l.size += int64(n) return n, err + } // Close implements io.Closer, and closes the current logfile. + func (l *Logger) Close() error { + l.mu.Lock() + defer l.mu.Unlock() + return l.close() + } // close closes the file if it is open. + func (l *Logger) close() error { + if l.file == nil { + return nil + } + err := l.file.Close() + l.file = nil + return err + } // Rotate causes Logger to close the existing log file and immediately create a + // new one. This is a helper function for applications that want to initiate + // rotations outside of the normal rotation rules, such as in response to + // SIGHUP. After rotating, this initiates compression and removal of old log + // files according to the configuration. + func (l *Logger) Rotate() error { + l.mu.Lock() + defer l.mu.Unlock() + return l.rotate() + } // rotate closes the current file, moves it aside with a timestamp in the name, + // (if it exists), opens a new file with the original filename, and then runs + // post-rotation processing and removal. + func (l *Logger) rotate() error { + if err := l.close(); err != nil { + return err + } + if err := l.openNew(); err != nil { + return err + } + l.mill() + return nil + } // openNew opens a new log file for writing, moving any old log file out of the + // way. This methods assumes the file has already been closed. + func (l *Logger) openNew() error { + err := os.MkdirAll(l.dir(), 0755) + if err != nil { + return fmt.Errorf("can't make directories for new logfile: %s", err) + } name := l.filename() + mode := os.FileMode(0600) + info, err := osStat(name) + if err == nil { + // Copy the mode off the old logfile. + mode = info.Mode() + // move the existing file + newname := backupName(name, l.LocalTime) + if err := os.Rename(name, newname); err != nil { + return fmt.Errorf("can't rename log file: %s", err) + } // this is a no-op anywhere but linux + if err := chown(name, info); err != nil { + return err + } + } // we use truncate here because this should only get called when we've moved + // the file ourselves. if someone else creates the file in the meantime, + // just wipe out the contents. + f, err := os.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode) + if err != nil { + return fmt.Errorf("can't open new logfile: %s", err) + } + l.file = f + l.size = 0 + return nil + } // backupName creates a new filename from the given name, inserting a timestamp + // between the filename and the extension, using the local time if requested + // (otherwise UTC). + func backupName(name string, local bool) string { + dir := filepath.Dir(name) + filename := filepath.Base(name) + ext := filepath.Ext(filename) + prefix := filename[:len(filename)-len(ext)] + t := currentTime() + if !local { + t = t.UTC() + } timestamp := t.Format(backupTimeFormat) + return filepath.Join(dir, fmt.Sprintf("%s-%s%s", prefix, timestamp, ext)) + } // openExistingOrNew opens the logfile if it exists and if the current write + // would not put it over MaxSize. If there is no such file or the write would + // put it over the MaxSize, a new file is created. + func (l *Logger) openExistingOrNew(writeLen int) error { + l.mill() filename := l.filename() + info, err := osStat(filename) + if os.IsNotExist(err) { + return l.openNew() + } + if err != nil { + return fmt.Errorf("error getting log file info: %s", err) + } if info.Size()+int64(writeLen) >= l.max() { + return l.rotate() + } file, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0644) + if err != nil { + // if we fail to open the old log file for some reason, just ignore + // it and open a new log file. + return l.openNew() + } + l.file = file + l.size = info.Size() + return nil + } // filename generates the name of the logfile from the current time. + func (l *Logger) filename() string { + if l.Filename != "" { + return l.Filename + } + name := filepath.Base(os.Args[0]) + "-lumberjack.log" + return filepath.Join(os.TempDir(), name) + } // millRunOnce performs compression and removal of stale log files. + // Log files are compressed if enabled via configuration and old log + // files are removed, keeping at most l.MaxBackups files, as long as + // none of them are older than MaxAge. + func (l *Logger) millRunOnce() error { + if l.MaxBackups == 0 && l.MaxAge == 0 && !l.Compress { + return nil + } files, err := l.oldLogFiles() + if err != nil { + return err + } var compress, remove []logInfo if l.MaxBackups > 0 && l.MaxBackups < len(files) { + preserved := make(map[string]bool) + var remaining []logInfo + for _, f := range files { + // Only count the uncompressed log file or the + // compressed log file, not both. + fn := f.Name() + if strings.HasSuffix(fn, compressSuffix) { + fn = fn[:len(fn)-len(compressSuffix)] + } + preserved[fn] = true if len(preserved) > l.MaxBackups { + remove = append(remove, f) + } else { + remaining = append(remaining, f) + } + } + files = remaining + } + if l.MaxAge > 0 { + diff := time.Duration(int64(24*time.Hour) * int64(l.MaxAge)) + cutoff := currentTime().Add(-1 * diff) var remaining []logInfo + for _, f := range files { + if f.timestamp.Before(cutoff) { + remove = append(remove, f) + } else { + remaining = append(remaining, f) + } + } + files = remaining + } if l.Compress { + for _, f := range files { + if !strings.HasSuffix(f.Name(), compressSuffix) { + compress = append(compress, f) + } + } + } for _, f := range remove { + errRemove := os.Remove(filepath.Join(l.dir(), f.Name())) + if err == nil && errRemove != nil { + err = errRemove + } + } + for _, f := range compress { + fn := filepath.Join(l.dir(), f.Name()) + errCompress := compressLogFile(fn, fn+compressSuffix) + if err == nil && errCompress != nil { + err = errCompress + } + } return err + } // millRun runs in a goroutine to manage post-rotation compression and removal + // of old log files. + func (l *Logger) millRun() { + for range l.millCh { + // what am I going to do, log this? + _ = l.millRunOnce() + } + } // mill performs post-rotation compression and removal of stale log files, + // starting the mill goroutine if necessary. + func (l *Logger) mill() { + l.startMill.Do(func() { + l.millCh = make(chan bool, 1) + go l.millRun() + }) + select { + case l.millCh <- true: + default: + } + } // oldLogFiles returns the list of backup log files stored in the same + // directory as the current log file, sorted by ModTime + func (l *Logger) oldLogFiles() ([]logInfo, error) { + files, err := ioutil.ReadDir(l.dir()) + if err != nil { + return nil, fmt.Errorf("can't read log file directory: %s", err) + } + logFiles := []logInfo{} prefix, ext := l.prefixAndExt() for _, f := range files { + if f.IsDir() { + continue + } + if t, err := l.timeFromName(f.Name(), prefix, ext); err == nil { + logFiles = append(logFiles, logInfo{t, f}) + continue + } + if t, err := l.timeFromName(f.Name(), prefix, ext+compressSuffix); err == nil { + logFiles = append(logFiles, logInfo{t, f}) + continue + } + // error parsing means that the suffix at the end was not generated + // by lumberjack, and therefore it's not a backup file. + } sort.Sort(byFormatTime(logFiles)) return logFiles, nil + } // timeFromName extracts the formatted time from the filename by stripping off + // the filename's prefix and extension. This prevents someone's filename from + // confusing time.parse. + func (l *Logger) timeFromName(filename, prefix, ext string) (time.Time, error) { + if !strings.HasPrefix(filename, prefix) { + return time.Time{}, errors.New("mismatched prefix") + } + if !strings.HasSuffix(filename, ext) { + return time.Time{}, errors.New("mismatched extension") + } + ts := filename[len(prefix) : len(filename)-len(ext)] + return time.Parse(backupTimeFormat, ts) + } // max returns the maximum size in bytes of log files before rolling. + func (l *Logger) max() int64 { + if l.MaxSize == 0 { + return int64(defaultMaxSize * megabyte) + } + return int64(l.MaxSize) * int64(megabyte) + } // dir returns the directory for the current filename. + func (l *Logger) dir() string { + return filepath.Dir(l.filename()) + } // prefixAndExt returns the filename part and extension part from the Logger's + // filename. + func (l *Logger) prefixAndExt() (prefix, ext string) { + filename := filepath.Base(l.filename()) + ext = filepath.Ext(filename) + prefix = filename[:len(filename)-len(ext)] + "-" + return prefix, ext + } // compressLogFile compresses the given log file, removing the + // uncompressed log file if successful. + func compressLogFile(src, dst string) (err error) { + f, err := os.Open(src) + if err != nil { + return fmt.Errorf("failed to open log file: %v", err) + } + defer f.Close() fi, err := osStat(src) + if err != nil { + return fmt.Errorf("failed to stat log file: %v", err) + } if err := chown(dst, fi); err != nil { + return fmt.Errorf("failed to chown compressed log file: %v", err) + } // If this file already exists, we presume it was created by + // a previous attempt to compress the log file. + gzf, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, fi.Mode()) + if err != nil { + return fmt.Errorf("failed to open compressed log file: %v", err) + } + defer gzf.Close() gz := gzip.NewWriter(gzf) defer func() { + if err != nil { + os.Remove(dst) + err = fmt.Errorf("failed to compress log file: %v", err) + } + }() if _, err := io.Copy(gz, f); err != nil { + return err + } + if err := gz.Close(); err != nil { + return err + } + if err := gzf.Close(); err != nil { + return err + } if err := f.Close(); err != nil { + return err + } + if err := os.Remove(src); err != nil { + return err + } return nil + } // logInfo is a convenience struct to return the filename and its embedded + // timestamp. + type logInfo struct { timestamp time.Time + os.FileInfo } // byFormatTime sorts by newest time formatted in the name. + type byFormatTime []logInfo func (b byFormatTime) Less(i, j int) bool { + return b[i].timestamp.After(b[j].timestamp) + } func (b byFormatTime) Swap(i, j int) { + b[i], b[j] = b[j], b[i] + } func (b byFormatTime) Len() int { + return len(b) + } diff --git a/vendor/gopkg.in/yaml.v2/decode.go b/vendor/gopkg.in/yaml.v2/decode.go index 129bc2a..351cc51 100644 --- a/vendor/gopkg.in/yaml.v2/decode.go +++ b/vendor/gopkg.in/yaml.v2/decode.go @@ -13,803 +13,1486 @@ import ( const ( documentNode = 1 << iota + mappingNode + sequenceNode + scalarNode + aliasNode ) type node struct { - kind int + kind int + line, column int - tag string + + tag string + // For an alias node, alias holds the resolved alias. - alias *node - value string + + alias *node + + value string + implicit bool + children []*node - anchors map[string]*node + + anchors map[string]*node } // ---------------------------------------------------------------------------- + // Parser, produces a node tree out of a libyaml event stream. type parser struct { - parser yaml_parser_t - event yaml_event_t - doc *node + parser yaml_parser_t + + event yaml_event_t + + doc *node + doneInit bool } func newParser(b []byte) *parser { + p := parser{} + if !yaml_parser_initialize(&p.parser) { + panic("failed to initialize YAML emitter") + } + if len(b) == 0 { + b = []byte{'\n'} + } + yaml_parser_set_input_string(&p.parser, b) + return &p + } func newParserFromReader(r io.Reader) *parser { + p := parser{} + if !yaml_parser_initialize(&p.parser) { + panic("failed to initialize YAML emitter") + } + yaml_parser_set_input_reader(&p.parser, r) + return &p + } func (p *parser) init() { + if p.doneInit { + return + } + p.expect(yaml_STREAM_START_EVENT) + p.doneInit = true + } func (p *parser) destroy() { + if p.event.typ != yaml_NO_EVENT { + yaml_event_delete(&p.event) + } + yaml_parser_delete(&p.parser) + } // expect consumes an event from the event stream and + // checks that it's of the expected type. + func (p *parser) expect(e yaml_event_type_t) { + if p.event.typ == yaml_NO_EVENT { + if !yaml_parser_parse(&p.parser, &p.event) { + p.fail() + } + } + if p.event.typ == yaml_STREAM_END_EVENT { + failf("attempted to go past the end of stream; corrupted value?") + } + if p.event.typ != e { + p.parser.problem = fmt.Sprintf("expected %s event but got %s", e, p.event.typ) + p.fail() + } + yaml_event_delete(&p.event) + p.event.typ = yaml_NO_EVENT + } // peek peeks at the next event in the event stream, + // puts the results into p.event and returns the event type. + func (p *parser) peek() yaml_event_type_t { + if p.event.typ != yaml_NO_EVENT { + return p.event.typ + } + if !yaml_parser_parse(&p.parser, &p.event) { + p.fail() + } + return p.event.typ + } func (p *parser) fail() { + var where string + var line int + if p.parser.problem_mark.line != 0 { + line = p.parser.problem_mark.line + // Scanner errors don't iterate line before returning error + if p.parser.error == yaml_SCANNER_ERROR { + line++ + } + } else if p.parser.context_mark.line != 0 { + line = p.parser.context_mark.line + } + if line != 0 { + where = "line " + strconv.Itoa(line) + ": " + } + var msg string + if len(p.parser.problem) > 0 { + msg = p.parser.problem + } else { + msg = "unknown problem parsing YAML content" + } + failf("%s%s", where, msg) + } func (p *parser) anchor(n *node, anchor []byte) { + if anchor != nil { + p.doc.anchors[string(anchor)] = n + } + } func (p *parser) parse() *node { + p.init() + switch p.peek() { + case yaml_SCALAR_EVENT: + return p.scalar() + case yaml_ALIAS_EVENT: + return p.alias() + case yaml_MAPPING_START_EVENT: + return p.mapping() + case yaml_SEQUENCE_START_EVENT: + return p.sequence() + case yaml_DOCUMENT_START_EVENT: + return p.document() + case yaml_STREAM_END_EVENT: + // Happens when attempting to decode an empty buffer. + return nil + default: + panic("attempted to parse unknown event: " + p.event.typ.String()) + } + } func (p *parser) node(kind int) *node { + return &node{ - kind: kind, - line: p.event.start_mark.line, + + kind: kind, + + line: p.event.start_mark.line, + column: p.event.start_mark.column, } + } func (p *parser) document() *node { + n := p.node(documentNode) + n.anchors = make(map[string]*node) + p.doc = n + p.expect(yaml_DOCUMENT_START_EVENT) + n.children = append(n.children, p.parse()) + p.expect(yaml_DOCUMENT_END_EVENT) + return n + } func (p *parser) alias() *node { + n := p.node(aliasNode) + n.value = string(p.event.anchor) + n.alias = p.doc.anchors[n.value] + if n.alias == nil { + failf("unknown anchor '%s' referenced", n.value) + } + p.expect(yaml_ALIAS_EVENT) + return n + } func (p *parser) scalar() *node { + n := p.node(scalarNode) + n.value = string(p.event.value) + n.tag = string(p.event.tag) + n.implicit = p.event.implicit + p.anchor(n, p.event.anchor) + p.expect(yaml_SCALAR_EVENT) + return n + } func (p *parser) sequence() *node { + n := p.node(sequenceNode) + p.anchor(n, p.event.anchor) + p.expect(yaml_SEQUENCE_START_EVENT) + for p.peek() != yaml_SEQUENCE_END_EVENT { + n.children = append(n.children, p.parse()) + } + p.expect(yaml_SEQUENCE_END_EVENT) + return n + } func (p *parser) mapping() *node { + n := p.node(mappingNode) + p.anchor(n, p.event.anchor) + p.expect(yaml_MAPPING_START_EVENT) + for p.peek() != yaml_MAPPING_END_EVENT { + n.children = append(n.children, p.parse(), p.parse()) + } + p.expect(yaml_MAPPING_END_EVENT) + return n + } // ---------------------------------------------------------------------------- + // Decoder, unmarshals a node into a provided value. type decoder struct { - doc *node + doc *node + aliases map[*node]bool + mapType reflect.Type + terrors []string - strict bool + + strict bool decodeCount int - aliasCount int - aliasDepth int + + aliasCount int + + aliasDepth int } var ( - mapItemType = reflect.TypeOf(MapItem{}) - durationType = reflect.TypeOf(time.Duration(0)) + mapItemType = reflect.TypeOf(MapItem{}) + + durationType = reflect.TypeOf(time.Duration(0)) + defaultMapType = reflect.TypeOf(map[interface{}]interface{}{}) - ifaceType = defaultMapType.Elem() - timeType = reflect.TypeOf(time.Time{}) - ptrTimeType = reflect.TypeOf(&time.Time{}) + + ifaceType = defaultMapType.Elem() + + timeType = reflect.TypeOf(time.Time{}) + + ptrTimeType = reflect.TypeOf(&time.Time{}) ) func newDecoder(strict bool) *decoder { + d := &decoder{mapType: defaultMapType, strict: strict} + d.aliases = make(map[*node]bool) + return d + } func (d *decoder) terror(n *node, tag string, out reflect.Value) { + if n.tag != "" { + tag = n.tag + } + value := n.value + if tag != yaml_SEQ_TAG && tag != yaml_MAP_TAG { + if len(value) > 10 { + value = " `" + value[:7] + "...`" + } else { + value = " `" + value + "`" + } + } + d.terrors = append(d.terrors, fmt.Sprintf("line %d: cannot unmarshal %s%s into %s", n.line+1, shortTag(tag), value, out.Type())) + } func (d *decoder) callUnmarshaler(n *node, u Unmarshaler) (good bool) { + terrlen := len(d.terrors) + err := u.UnmarshalYAML(func(v interface{}) (err error) { + defer handleErr(&err) + d.unmarshal(n, reflect.ValueOf(v)) + if len(d.terrors) > terrlen { + issues := d.terrors[terrlen:] + d.terrors = d.terrors[:terrlen] + return &TypeError{issues} + } + return nil + }) + if e, ok := err.(*TypeError); ok { + d.terrors = append(d.terrors, e.Errors...) + return false + } + if err != nil { + fail(err) + } + return true + } // d.prepare initializes and dereferences pointers and calls UnmarshalYAML + // if a value is found to implement it. + // It returns the initialized and dereferenced out value, whether + // unmarshalling was already done by UnmarshalYAML, and if so whether + // its types unmarshalled appropriately. + // + // If n holds a null value, prepare returns before doing anything. + func (d *decoder) prepare(n *node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) { + if n.tag == yaml_NULL_TAG || n.kind == scalarNode && n.tag == "" && (n.value == "null" || n.value == "~" || n.value == "" && n.implicit) { + return out, false, false + } + again := true + for again { + again = false + if out.Kind() == reflect.Ptr { + if out.IsNil() { + out.Set(reflect.New(out.Type().Elem())) + } + out = out.Elem() + again = true + } + if out.CanAddr() { + if u, ok := out.Addr().Interface().(Unmarshaler); ok { + good = d.callUnmarshaler(n, u) + return out, true, good + } + } + } + return out, false, false + } const ( + // 400,000 decode operations is ~500kb of dense object declarations, or + // ~5kb of dense object declarations with 10000% alias expansion + alias_ratio_range_low = 400000 // 4,000,000 decode operations is ~5MB of dense object declarations, or + // ~4.5MB of dense object declarations with 10% alias expansion + alias_ratio_range_high = 4000000 // alias_ratio_range is the range over which we scale allowed alias ratios + alias_ratio_range = float64(alias_ratio_range_high - alias_ratio_range_low) ) func allowedAliasRatio(decodeCount int) float64 { + switch { + case decodeCount <= alias_ratio_range_low: + // allow 99% to come from alias expansion for small-to-medium documents + return 0.99 + case decodeCount >= alias_ratio_range_high: + // allow 10% to come from alias expansion for very large documents + return 0.10 + default: + // scale smoothly from 99% down to 10% over the range. + // this maps to 396,000 - 400,000 allowed alias-driven decodes over the range. + // 400,000 decode operations is ~100MB of allocations in worst-case scenarios (single-item maps). + return 0.99 - 0.89*(float64(decodeCount-alias_ratio_range_low)/alias_ratio_range) + } + } func (d *decoder) unmarshal(n *node, out reflect.Value) (good bool) { + d.decodeCount++ + if d.aliasDepth > 0 { + d.aliasCount++ + } + if d.aliasCount > 100 && d.decodeCount > 1000 && float64(d.aliasCount)/float64(d.decodeCount) > allowedAliasRatio(d.decodeCount) { + failf("document contains excessive aliasing") + } + switch n.kind { + case documentNode: + return d.document(n, out) + case aliasNode: + return d.alias(n, out) + } + out, unmarshaled, good := d.prepare(n, out) + if unmarshaled { + return good + } + switch n.kind { + case scalarNode: + good = d.scalar(n, out) + case mappingNode: + good = d.mapping(n, out) + case sequenceNode: + good = d.sequence(n, out) + default: + panic("internal error: unknown node kind: " + strconv.Itoa(n.kind)) + } + return good + } func (d *decoder) document(n *node, out reflect.Value) (good bool) { + if len(n.children) == 1 { + d.doc = n + d.unmarshal(n.children[0], out) + return true + } + return false + } func (d *decoder) alias(n *node, out reflect.Value) (good bool) { + if d.aliases[n] { + // TODO this could actually be allowed in some circumstances. + failf("anchor '%s' value contains itself", n.value) + } + d.aliases[n] = true + d.aliasDepth++ + good = d.unmarshal(n.alias, out) + d.aliasDepth-- + delete(d.aliases, n) + return good + } var zeroValue reflect.Value func resetMap(out reflect.Value) { + for _, k := range out.MapKeys() { + out.SetMapIndex(k, zeroValue) + } + } func (d *decoder) scalar(n *node, out reflect.Value) bool { + var tag string + var resolved interface{} + if n.tag == "" && !n.implicit { + tag = yaml_STR_TAG + resolved = n.value + } else { + tag, resolved = resolve(n.tag, n.value) + if tag == yaml_BINARY_TAG { + data, err := base64.StdEncoding.DecodeString(resolved.(string)) + if err != nil { + failf("!!binary value contains invalid base64 data") + } + resolved = string(data) + } + } + if resolved == nil { + if out.Kind() == reflect.Map && !out.CanAddr() { + resetMap(out) + } else { + out.Set(reflect.Zero(out.Type())) + } + return true + } + if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { + // We've resolved to exactly the type we want, so use that. + out.Set(resolvedv) + return true + } + // Perhaps we can use the value as a TextUnmarshaler to + // set its value. + if out.CanAddr() { + u, ok := out.Addr().Interface().(encoding.TextUnmarshaler) + if ok { + var text []byte + if tag == yaml_BINARY_TAG { + text = []byte(resolved.(string)) + } else { + // We let any value be unmarshaled into TextUnmarshaler. + // That might be more lax than we'd like, but the + // TextUnmarshaler itself should bowl out any dubious values. + text = []byte(n.value) + } + err := u.UnmarshalText(text) + if err != nil { + fail(err) + } + return true + } + } + switch out.Kind() { + case reflect.String: + if tag == yaml_BINARY_TAG { + out.SetString(resolved.(string)) + return true + } + if resolved != nil { + out.SetString(n.value) + return true + } + case reflect.Interface: + if resolved == nil { + out.Set(reflect.Zero(out.Type())) + } else if tag == yaml_TIMESTAMP_TAG { + // It looks like a timestamp but for backward compatibility + // reasons we set it as a string, so that code that unmarshals + // timestamp-like values into interface{} will continue to + // see a string and not a time.Time. + // TODO(v3) Drop this. + out.Set(reflect.ValueOf(n.value)) + } else { + out.Set(reflect.ValueOf(resolved)) + } + return true + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + switch resolved := resolved.(type) { + case int: + if !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case int64: + if !out.OverflowInt(resolved) { + out.SetInt(resolved) + return true + } + case uint64: + if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case float64: + if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case string: + if out.Type() == durationType { + d, err := time.ParseDuration(resolved) + if err == nil { + out.SetInt(int64(d)) + return true + } + } + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + switch resolved := resolved.(type) { + case int: + if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case int64: + if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case uint64: + if !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case float64: + if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + } + case reflect.Bool: + switch resolved := resolved.(type) { + case bool: + out.SetBool(resolved) + return true + } + case reflect.Float32, reflect.Float64: + switch resolved := resolved.(type) { + case int: + out.SetFloat(float64(resolved)) + return true + case int64: + out.SetFloat(float64(resolved)) + return true + case uint64: + out.SetFloat(float64(resolved)) + return true + case float64: + out.SetFloat(resolved) + return true + } + case reflect.Struct: + if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { + out.Set(resolvedv) + return true + } + case reflect.Ptr: + if out.Type().Elem() == reflect.TypeOf(resolved) { + // TODO DOes this make sense? When is out a Ptr except when decoding a nil value? + elem := reflect.New(out.Type().Elem()) + elem.Elem().Set(reflect.ValueOf(resolved)) + out.Set(elem) + return true + } + } + d.terror(n, tag, out) + return false + } func settableValueOf(i interface{}) reflect.Value { + v := reflect.ValueOf(i) + sv := reflect.New(v.Type()).Elem() + sv.Set(v) + return sv + } func (d *decoder) sequence(n *node, out reflect.Value) (good bool) { + l := len(n.children) var iface reflect.Value + switch out.Kind() { + case reflect.Slice: + out.Set(reflect.MakeSlice(out.Type(), l, l)) + case reflect.Array: + if l != out.Len() { + failf("invalid array: want %d elements but got %d", out.Len(), l) + } + case reflect.Interface: + // No type hints. Will have to use a generic sequence. + iface = out + out = settableValueOf(make([]interface{}, l)) + default: + d.terror(n, yaml_SEQ_TAG, out) + return false + } + et := out.Type().Elem() j := 0 + for i := 0; i < l; i++ { + e := reflect.New(et).Elem() + if ok := d.unmarshal(n.children[i], e); ok { + out.Index(j).Set(e) + j++ + } + } + if out.Kind() != reflect.Array { + out.Set(out.Slice(0, j)) + } + if iface.IsValid() { + iface.Set(out) + } + return true + } func (d *decoder) mapping(n *node, out reflect.Value) (good bool) { + switch out.Kind() { + case reflect.Struct: + return d.mappingStruct(n, out) + case reflect.Slice: + return d.mappingSlice(n, out) + case reflect.Map: + // okay + case reflect.Interface: + if d.mapType.Kind() == reflect.Map { + iface := out + out = reflect.MakeMap(d.mapType) + iface.Set(out) + } else { + slicev := reflect.New(d.mapType).Elem() + if !d.mappingSlice(n, slicev) { + return false + } + out.Set(slicev) + return true + } + default: + d.terror(n, yaml_MAP_TAG, out) + return false + } + outt := out.Type() + kt := outt.Key() + et := outt.Elem() mapType := d.mapType + if outt.Key() == ifaceType && outt.Elem() == ifaceType { + d.mapType = outt + } if out.IsNil() { + out.Set(reflect.MakeMap(outt)) + } + l := len(n.children) + for i := 0; i < l; i += 2 { + if isMerge(n.children[i]) { + d.merge(n.children[i+1], out) + continue + } + k := reflect.New(kt).Elem() + if d.unmarshal(n.children[i], k) { + kkind := k.Kind() + if kkind == reflect.Interface { + kkind = k.Elem().Kind() + } + if kkind == reflect.Map || kkind == reflect.Slice { + failf("invalid map key: %#v", k.Interface()) + } + e := reflect.New(et).Elem() + if d.unmarshal(n.children[i+1], e) { + d.setMapIndex(n.children[i+1], out, k, e) + } + } + } + d.mapType = mapType + return true + } func (d *decoder) setMapIndex(n *node, out, k, v reflect.Value) { + if d.strict && out.MapIndex(k) != zeroValue { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: key %#v already set in map", n.line+1, k.Interface())) + return + } + out.SetMapIndex(k, v) + } func (d *decoder) mappingSlice(n *node, out reflect.Value) (good bool) { + outt := out.Type() + if outt.Elem() != mapItemType { + d.terror(n, yaml_MAP_TAG, out) + return false + } mapType := d.mapType + d.mapType = outt var slice []MapItem + var l = len(n.children) + for i := 0; i < l; i += 2 { + if isMerge(n.children[i]) { + d.merge(n.children[i+1], out) + continue + } + item := MapItem{} + k := reflect.ValueOf(&item.Key).Elem() + if d.unmarshal(n.children[i], k) { + v := reflect.ValueOf(&item.Value).Elem() + if d.unmarshal(n.children[i+1], v) { + slice = append(slice, item) + } + } + } + out.Set(reflect.ValueOf(slice)) + d.mapType = mapType + return true + } func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) { + sinfo, err := getStructInfo(out.Type()) + if err != nil { + panic(err) + } + name := settableValueOf("") + l := len(n.children) var inlineMap reflect.Value + var elemType reflect.Type + if sinfo.InlineMap != -1 { + inlineMap = out.Field(sinfo.InlineMap) + inlineMap.Set(reflect.New(inlineMap.Type()).Elem()) + elemType = inlineMap.Type().Elem() + } var doneFields []bool + if d.strict { + doneFields = make([]bool, len(sinfo.FieldsList)) + } + for i := 0; i < l; i += 2 { + ni := n.children[i] + if isMerge(ni) { + d.merge(n.children[i+1], out) + continue + } + if !d.unmarshal(ni, name) { + continue + } + if info, ok := sinfo.FieldsMap[name.String()]; ok { + if d.strict { + if doneFields[info.Id] { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s already set in type %s", ni.line+1, name.String(), out.Type())) + continue + } + doneFields[info.Id] = true + } + var field reflect.Value + if info.Inline == nil { + field = out.Field(info.Num) + } else { + field = out.FieldByIndex(info.Inline) + } + d.unmarshal(n.children[i+1], field) + } else if sinfo.InlineMap != -1 { + if inlineMap.IsNil() { + inlineMap.Set(reflect.MakeMap(inlineMap.Type())) + } + value := reflect.New(elemType).Elem() + d.unmarshal(n.children[i+1], value) + d.setMapIndex(n.children[i+1], inlineMap, name, value) + } else if d.strict { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in type %s", ni.line+1, name.String(), out.Type())) + } + } + return true + } func failWantMap() { + failf("map merge requires map or sequence of maps as the value") + } func (d *decoder) merge(n *node, out reflect.Value) { + switch n.kind { + case mappingNode: + d.unmarshal(n, out) + case aliasNode: + if n.alias != nil && n.alias.kind != mappingNode { + failWantMap() + } + d.unmarshal(n, out) + case sequenceNode: + // Step backwards as earlier nodes take precedence. + for i := len(n.children) - 1; i >= 0; i-- { + ni := n.children[i] + if ni.kind == aliasNode { + if ni.alias != nil && ni.alias.kind != mappingNode { + failWantMap() + } + } else if ni.kind != mappingNode { + failWantMap() + } + d.unmarshal(ni, out) + } + default: + failWantMap() + } + } func isMerge(n *node) bool { + return n.kind == scalarNode && n.value == "<<" && (n.implicit == true || n.tag == yaml_MERGE_TAG) + } diff --git a/vendor/gopkg.in/yaml.v2/emitterc.go b/vendor/gopkg.in/yaml.v2/emitterc.go index 638a268..a62d748 100644 --- a/vendor/gopkg.in/yaml.v2/emitterc.go +++ b/vendor/gopkg.in/yaml.v2/emitterc.go @@ -6,1679 +6,3084 @@ import ( ) // Flush the buffer if needed. + func flush(emitter *yaml_emitter_t) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) { + return yaml_emitter_flush(emitter) + } + return true + } // Put a character to the output buffer. + func put(emitter *yaml_emitter_t, value byte) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + emitter.buffer[emitter.buffer_pos] = value + emitter.buffer_pos++ + emitter.column++ + return true + } // Put a line break to the output buffer. + func put_break(emitter *yaml_emitter_t) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + switch emitter.line_break { + case yaml_CR_BREAK: + emitter.buffer[emitter.buffer_pos] = '\r' + emitter.buffer_pos += 1 + case yaml_LN_BREAK: + emitter.buffer[emitter.buffer_pos] = '\n' + emitter.buffer_pos += 1 + case yaml_CRLN_BREAK: + emitter.buffer[emitter.buffer_pos+0] = '\r' + emitter.buffer[emitter.buffer_pos+1] = '\n' + emitter.buffer_pos += 2 + default: + panic("unknown line break setting") + } + emitter.column = 0 + emitter.line++ + return true + } // Copy a character from a string into buffer. + func write(emitter *yaml_emitter_t, s []byte, i *int) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + p := emitter.buffer_pos + w := width(s[*i]) + switch w { + case 4: + emitter.buffer[p+3] = s[*i+3] + fallthrough + case 3: + emitter.buffer[p+2] = s[*i+2] + fallthrough + case 2: + emitter.buffer[p+1] = s[*i+1] + fallthrough + case 1: + emitter.buffer[p+0] = s[*i+0] + default: + panic("unknown character width") + } + emitter.column++ + emitter.buffer_pos += w + *i += w + return true + } // Write a whole string into buffer. + func write_all(emitter *yaml_emitter_t, s []byte) bool { + for i := 0; i < len(s); { + if !write(emitter, s, &i) { + return false + } + } + return true + } // Copy a line break character from a string into buffer. + func write_break(emitter *yaml_emitter_t, s []byte, i *int) bool { + if s[*i] == '\n' { + if !put_break(emitter) { + return false + } + *i++ + } else { + if !write(emitter, s, i) { + return false + } + emitter.column = 0 + emitter.line++ + } + return true + } // Set an emitter error and return false. + func yaml_emitter_set_emitter_error(emitter *yaml_emitter_t, problem string) bool { + emitter.error = yaml_EMITTER_ERROR + emitter.problem = problem + return false + } // Emit an event. + func yaml_emitter_emit(emitter *yaml_emitter_t, event *yaml_event_t) bool { + emitter.events = append(emitter.events, *event) + for !yaml_emitter_need_more_events(emitter) { + event := &emitter.events[emitter.events_head] + if !yaml_emitter_analyze_event(emitter, event) { + return false + } + if !yaml_emitter_state_machine(emitter, event) { + return false + } + yaml_event_delete(event) + emitter.events_head++ + } + return true + } // Check if we need to accumulate more events before emitting. + // + // We accumulate extra + // - 1 event for DOCUMENT-START + // - 2 events for SEQUENCE-START + // - 3 events for MAPPING-START + func yaml_emitter_need_more_events(emitter *yaml_emitter_t) bool { + if emitter.events_head == len(emitter.events) { + return true + } + var accumulate int + switch emitter.events[emitter.events_head].typ { + case yaml_DOCUMENT_START_EVENT: + accumulate = 1 + break + case yaml_SEQUENCE_START_EVENT: + accumulate = 2 + break + case yaml_MAPPING_START_EVENT: + accumulate = 3 + break + default: + return false + } + if len(emitter.events)-emitter.events_head > accumulate { + return false + } + var level int + for i := emitter.events_head; i < len(emitter.events); i++ { + switch emitter.events[i].typ { + case yaml_STREAM_START_EVENT, yaml_DOCUMENT_START_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT: + level++ + case yaml_STREAM_END_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_END_EVENT, yaml_MAPPING_END_EVENT: + level-- + } + if level == 0 { + return false + } + } + return true + } // Append a directive to the directives stack. + func yaml_emitter_append_tag_directive(emitter *yaml_emitter_t, value *yaml_tag_directive_t, allow_duplicates bool) bool { + for i := 0; i < len(emitter.tag_directives); i++ { + if bytes.Equal(value.handle, emitter.tag_directives[i].handle) { + if allow_duplicates { + return true + } + return yaml_emitter_set_emitter_error(emitter, "duplicate %TAG directive") + } + } // [Go] Do we actually need to copy this given garbage collection + // and the lack of deallocating destructors? + tag_copy := yaml_tag_directive_t{ + handle: make([]byte, len(value.handle)), + prefix: make([]byte, len(value.prefix)), } + copy(tag_copy.handle, value.handle) + copy(tag_copy.prefix, value.prefix) + emitter.tag_directives = append(emitter.tag_directives, tag_copy) + return true + } // Increase the indentation level. + func yaml_emitter_increase_indent(emitter *yaml_emitter_t, flow, indentless bool) bool { + emitter.indents = append(emitter.indents, emitter.indent) + if emitter.indent < 0 { + if flow { + emitter.indent = emitter.best_indent + } else { + emitter.indent = 0 + } + } else if !indentless { + emitter.indent += emitter.best_indent + } + return true + } // State dispatcher. + func yaml_emitter_state_machine(emitter *yaml_emitter_t, event *yaml_event_t) bool { + switch emitter.state { + default: + case yaml_EMIT_STREAM_START_STATE: + return yaml_emitter_emit_stream_start(emitter, event) case yaml_EMIT_FIRST_DOCUMENT_START_STATE: + return yaml_emitter_emit_document_start(emitter, event, true) case yaml_EMIT_DOCUMENT_START_STATE: + return yaml_emitter_emit_document_start(emitter, event, false) case yaml_EMIT_DOCUMENT_CONTENT_STATE: + return yaml_emitter_emit_document_content(emitter, event) case yaml_EMIT_DOCUMENT_END_STATE: + return yaml_emitter_emit_document_end(emitter, event) case yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, true) case yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, false) case yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, true) case yaml_EMIT_FLOW_MAPPING_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, false) case yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE: + return yaml_emitter_emit_flow_mapping_value(emitter, event, true) case yaml_EMIT_FLOW_MAPPING_VALUE_STATE: + return yaml_emitter_emit_flow_mapping_value(emitter, event, false) case yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE: + return yaml_emitter_emit_block_sequence_item(emitter, event, true) case yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE: + return yaml_emitter_emit_block_sequence_item(emitter, event, false) case yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE: + return yaml_emitter_emit_block_mapping_key(emitter, event, true) case yaml_EMIT_BLOCK_MAPPING_KEY_STATE: + return yaml_emitter_emit_block_mapping_key(emitter, event, false) case yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE: + return yaml_emitter_emit_block_mapping_value(emitter, event, true) case yaml_EMIT_BLOCK_MAPPING_VALUE_STATE: + return yaml_emitter_emit_block_mapping_value(emitter, event, false) case yaml_EMIT_END_STATE: + return yaml_emitter_set_emitter_error(emitter, "expected nothing after STREAM-END") + } + panic("invalid emitter state") + } // Expect STREAM-START. + func yaml_emitter_emit_stream_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if event.typ != yaml_STREAM_START_EVENT { + return yaml_emitter_set_emitter_error(emitter, "expected STREAM-START") + } + if emitter.encoding == yaml_ANY_ENCODING { + emitter.encoding = event.encoding + if emitter.encoding == yaml_ANY_ENCODING { + emitter.encoding = yaml_UTF8_ENCODING + } + } + if emitter.best_indent < 2 || emitter.best_indent > 9 { + emitter.best_indent = 2 + } + if emitter.best_width >= 0 && emitter.best_width <= emitter.best_indent*2 { + emitter.best_width = 80 + } + if emitter.best_width < 0 { + emitter.best_width = 1<<31 - 1 + } + if emitter.line_break == yaml_ANY_BREAK { + emitter.line_break = yaml_LN_BREAK + } emitter.indent = -1 + emitter.line = 0 + emitter.column = 0 + emitter.whitespace = true + emitter.indention = true if emitter.encoding != yaml_UTF8_ENCODING { + if !yaml_emitter_write_bom(emitter) { + return false + } + } + emitter.state = yaml_EMIT_FIRST_DOCUMENT_START_STATE + return true + } // Expect DOCUMENT-START or STREAM-END. + func yaml_emitter_emit_document_start(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { if event.typ == yaml_DOCUMENT_START_EVENT { if event.version_directive != nil { + if !yaml_emitter_analyze_version_directive(emitter, event.version_directive) { + return false + } + } for i := 0; i < len(event.tag_directives); i++ { + tag_directive := &event.tag_directives[i] + if !yaml_emitter_analyze_tag_directive(emitter, tag_directive) { + return false + } + if !yaml_emitter_append_tag_directive(emitter, tag_directive, false) { + return false + } + } for i := 0; i < len(default_tag_directives); i++ { + tag_directive := &default_tag_directives[i] + if !yaml_emitter_append_tag_directive(emitter, tag_directive, true) { + return false + } + } implicit := event.implicit + if !first || emitter.canonical { + implicit = false + } if emitter.open_ended && (event.version_directive != nil || len(event.tag_directives) > 0) { + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } if event.version_directive != nil { + implicit = false + if !yaml_emitter_write_indicator(emitter, []byte("%YAML"), true, false, false) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte("1.1"), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } if len(event.tag_directives) > 0 { + implicit = false + for i := 0; i < len(event.tag_directives); i++ { + tag_directive := &event.tag_directives[i] + if !yaml_emitter_write_indicator(emitter, []byte("%TAG"), true, false, false) { + return false + } + if !yaml_emitter_write_tag_handle(emitter, tag_directive.handle) { + return false + } + if !yaml_emitter_write_tag_content(emitter, tag_directive.prefix, true) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + } if yaml_emitter_check_empty_document(emitter) { + implicit = false + } + if !implicit { + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte("---"), true, false, false) { + return false + } + if emitter.canonical { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + } emitter.state = yaml_EMIT_DOCUMENT_CONTENT_STATE + return true + } if event.typ == yaml_STREAM_END_EVENT { + if emitter.open_ended { + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_flush(emitter) { + return false + } + emitter.state = yaml_EMIT_END_STATE + return true + } return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-START or STREAM-END") + } // Expect the root node. + func yaml_emitter_emit_document_content(emitter *yaml_emitter_t, event *yaml_event_t) bool { + emitter.states = append(emitter.states, yaml_EMIT_DOCUMENT_END_STATE) + return yaml_emitter_emit_node(emitter, event, true, false, false, false) + } // Expect DOCUMENT-END. + func yaml_emitter_emit_document_end(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if event.typ != yaml_DOCUMENT_END_EVENT { + return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-END") + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !event.implicit { + // [Go] Allocate the slice elsewhere. + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_flush(emitter) { + return false + } + emitter.state = yaml_EMIT_DOCUMENT_START_STATE + emitter.tag_directives = emitter.tag_directives[:0] + return true + } // Expect a flow item node. + func yaml_emitter_emit_flow_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_write_indicator(emitter, []byte{'['}, true, true, false) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + emitter.flow_level++ + } if event.typ == yaml_SEQUENCE_END_EVENT { + emitter.flow_level-- + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + if emitter.canonical && !first { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{']'}, false, false, false) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] return true + } if !first { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE) + return yaml_emitter_emit_node(emitter, event, false, true, false, false) + } // Expect a flow key node. + func yaml_emitter_emit_flow_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_write_indicator(emitter, []byte{'{'}, true, true, false) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + emitter.flow_level++ + } if event.typ == yaml_MAPPING_END_EVENT { + emitter.flow_level-- + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + if emitter.canonical && !first { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'}'}, false, false, false) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } if !first { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } if !emitter.canonical && yaml_emitter_check_simple_key(emitter) { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, true) + } + if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, false) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) + } // Expect a flow value node. + func yaml_emitter_emit_flow_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { + if simple { + if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { + return false + } + } else { + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, false) { + return false + } + } + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_KEY_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) + } // Expect a block item node. + func yaml_emitter_emit_block_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_increase_indent(emitter, false, emitter.mapping_context && !emitter.indention) { + return false + } + } + if event.typ == yaml_SEQUENCE_END_EVENT { + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{'-'}, true, false, true) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE) + return yaml_emitter_emit_node(emitter, event, false, true, false, false) + } // Expect a block key node. + func yaml_emitter_emit_block_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_increase_indent(emitter, false, false) { + return false + } + } + if event.typ == yaml_MAPPING_END_EVENT { + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if yaml_emitter_check_simple_key(emitter) { + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, true) + } + if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, true) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) + } // Expect a block value node. + func yaml_emitter_emit_block_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { + if simple { + if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { + return false + } + } else { + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, true) { + return false + } + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_KEY_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) + } // Expect a node. + func yaml_emitter_emit_node(emitter *yaml_emitter_t, event *yaml_event_t, + root bool, sequence bool, mapping bool, simple_key bool) bool { emitter.root_context = root + emitter.sequence_context = sequence + emitter.mapping_context = mapping + emitter.simple_key_context = simple_key switch event.typ { + case yaml_ALIAS_EVENT: + return yaml_emitter_emit_alias(emitter, event) + case yaml_SCALAR_EVENT: + return yaml_emitter_emit_scalar(emitter, event) + case yaml_SEQUENCE_START_EVENT: + return yaml_emitter_emit_sequence_start(emitter, event) + case yaml_MAPPING_START_EVENT: + return yaml_emitter_emit_mapping_start(emitter, event) + default: + return yaml_emitter_set_emitter_error(emitter, + fmt.Sprintf("expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, but got %v", event.typ)) + } + } // Expect ALIAS. + func yaml_emitter_emit_alias(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } // Expect SCALAR. + func yaml_emitter_emit_scalar(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_select_scalar_style(emitter, event) { + return false + } + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + if !yaml_emitter_process_scalar(emitter) { + return false + } + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } // Expect SEQUENCE-START. + func yaml_emitter_emit_sequence_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if emitter.flow_level > 0 || emitter.canonical || event.sequence_style() == yaml_FLOW_SEQUENCE_STYLE || + yaml_emitter_check_empty_sequence(emitter) { + emitter.state = yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE + } else { + emitter.state = yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE + } + return true + } // Expect MAPPING-START. + func yaml_emitter_emit_mapping_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if emitter.flow_level > 0 || emitter.canonical || event.mapping_style() == yaml_FLOW_MAPPING_STYLE || + yaml_emitter_check_empty_mapping(emitter) { + emitter.state = yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE + } else { + emitter.state = yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE + } + return true + } // Check if the document content is an empty scalar. + func yaml_emitter_check_empty_document(emitter *yaml_emitter_t) bool { + return false // [Go] Huh? + } // Check if the next events represent an empty sequence. + func yaml_emitter_check_empty_sequence(emitter *yaml_emitter_t) bool { + if len(emitter.events)-emitter.events_head < 2 { + return false + } + return emitter.events[emitter.events_head].typ == yaml_SEQUENCE_START_EVENT && + emitter.events[emitter.events_head+1].typ == yaml_SEQUENCE_END_EVENT + } // Check if the next events represent an empty mapping. + func yaml_emitter_check_empty_mapping(emitter *yaml_emitter_t) bool { + if len(emitter.events)-emitter.events_head < 2 { + return false + } + return emitter.events[emitter.events_head].typ == yaml_MAPPING_START_EVENT && + emitter.events[emitter.events_head+1].typ == yaml_MAPPING_END_EVENT + } // Check if the next node can be expressed as a simple key. + func yaml_emitter_check_simple_key(emitter *yaml_emitter_t) bool { + length := 0 + switch emitter.events[emitter.events_head].typ { + case yaml_ALIAS_EVENT: + length += len(emitter.anchor_data.anchor) + case yaml_SCALAR_EVENT: + if emitter.scalar_data.multiline { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + + len(emitter.scalar_data.value) + case yaml_SEQUENCE_START_EVENT: + if !yaml_emitter_check_empty_sequence(emitter) { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + case yaml_MAPPING_START_EVENT: + if !yaml_emitter_check_empty_mapping(emitter) { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + default: + return false + } + return length <= 128 + } // Determine an acceptable scalar style. + func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event_t) bool { no_tag := len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 + if no_tag && !event.implicit && !event.quoted_implicit { + return yaml_emitter_set_emitter_error(emitter, "neither tag nor implicit flags are specified") + } style := event.scalar_style() + if style == yaml_ANY_SCALAR_STYLE { + style = yaml_PLAIN_SCALAR_STYLE + } + if emitter.canonical { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + if emitter.simple_key_context && emitter.scalar_data.multiline { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } if style == yaml_PLAIN_SCALAR_STYLE { + if emitter.flow_level > 0 && !emitter.scalar_data.flow_plain_allowed || + emitter.flow_level == 0 && !emitter.scalar_data.block_plain_allowed { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + if len(emitter.scalar_data.value) == 0 && (emitter.flow_level > 0 || emitter.simple_key_context) { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + if no_tag && !event.implicit { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + } + if style == yaml_SINGLE_QUOTED_SCALAR_STYLE { + if !emitter.scalar_data.single_quoted_allowed { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + } + if style == yaml_LITERAL_SCALAR_STYLE || style == yaml_FOLDED_SCALAR_STYLE { + if !emitter.scalar_data.block_allowed || emitter.flow_level > 0 || emitter.simple_key_context { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + } if no_tag && !event.quoted_implicit && style != yaml_PLAIN_SCALAR_STYLE { + emitter.tag_data.handle = []byte{'!'} + } + emitter.scalar_data.style = style + return true + } // Write an anchor. + func yaml_emitter_process_anchor(emitter *yaml_emitter_t) bool { + if emitter.anchor_data.anchor == nil { + return true + } + c := []byte{'&'} + if emitter.anchor_data.alias { + c[0] = '*' + } + if !yaml_emitter_write_indicator(emitter, c, true, false, false) { + return false + } + return yaml_emitter_write_anchor(emitter, emitter.anchor_data.anchor) + } // Write a tag. + func yaml_emitter_process_tag(emitter *yaml_emitter_t) bool { + if len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 { + return true + } + if len(emitter.tag_data.handle) > 0 { + if !yaml_emitter_write_tag_handle(emitter, emitter.tag_data.handle) { + return false + } + if len(emitter.tag_data.suffix) > 0 { + if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { + return false + } + } + } else { + // [Go] Allocate these slices elsewhere. + if !yaml_emitter_write_indicator(emitter, []byte("!<"), true, false, false) { + return false + } + if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{'>'}, false, false, false) { + return false + } + } + return true + } // Write a scalar. + func yaml_emitter_process_scalar(emitter *yaml_emitter_t) bool { + switch emitter.scalar_data.style { + case yaml_PLAIN_SCALAR_STYLE: + return yaml_emitter_write_plain_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) case yaml_SINGLE_QUOTED_SCALAR_STYLE: + return yaml_emitter_write_single_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) case yaml_DOUBLE_QUOTED_SCALAR_STYLE: + return yaml_emitter_write_double_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) case yaml_LITERAL_SCALAR_STYLE: + return yaml_emitter_write_literal_scalar(emitter, emitter.scalar_data.value) case yaml_FOLDED_SCALAR_STYLE: + return yaml_emitter_write_folded_scalar(emitter, emitter.scalar_data.value) + } + panic("unknown scalar style") + } // Check if a %YAML directive is valid. + func yaml_emitter_analyze_version_directive(emitter *yaml_emitter_t, version_directive *yaml_version_directive_t) bool { + if version_directive.major != 1 || version_directive.minor != 1 { + return yaml_emitter_set_emitter_error(emitter, "incompatible %YAML directive") + } + return true + } // Check if a %TAG directive is valid. + func yaml_emitter_analyze_tag_directive(emitter *yaml_emitter_t, tag_directive *yaml_tag_directive_t) bool { + handle := tag_directive.handle + prefix := tag_directive.prefix + if len(handle) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag handle must not be empty") + } + if handle[0] != '!' { + return yaml_emitter_set_emitter_error(emitter, "tag handle must start with '!'") + } + if handle[len(handle)-1] != '!' { + return yaml_emitter_set_emitter_error(emitter, "tag handle must end with '!'") + } + for i := 1; i < len(handle)-1; i += width(handle[i]) { + if !is_alpha(handle, i) { + return yaml_emitter_set_emitter_error(emitter, "tag handle must contain alphanumerical characters only") + } + } + if len(prefix) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag prefix must not be empty") + } + return true + } // Check if an anchor is valid. + func yaml_emitter_analyze_anchor(emitter *yaml_emitter_t, anchor []byte, alias bool) bool { + if len(anchor) == 0 { + problem := "anchor value must not be empty" + if alias { + problem = "alias value must not be empty" + } + return yaml_emitter_set_emitter_error(emitter, problem) + } + for i := 0; i < len(anchor); i += width(anchor[i]) { + if !is_alpha(anchor, i) { + problem := "anchor value must contain alphanumerical characters only" + if alias { + problem = "alias value must contain alphanumerical characters only" + } + return yaml_emitter_set_emitter_error(emitter, problem) + } + } + emitter.anchor_data.anchor = anchor + emitter.anchor_data.alias = alias + return true + } // Check if a tag is valid. + func yaml_emitter_analyze_tag(emitter *yaml_emitter_t, tag []byte) bool { + if len(tag) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag value must not be empty") + } + for i := 0; i < len(emitter.tag_directives); i++ { + tag_directive := &emitter.tag_directives[i] + if bytes.HasPrefix(tag, tag_directive.prefix) { + emitter.tag_data.handle = tag_directive.handle + emitter.tag_data.suffix = tag[len(tag_directive.prefix):] + return true + } + } + emitter.tag_data.suffix = tag + return true + } // Check if a scalar is valid. + func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { + var ( - block_indicators = false - flow_indicators = false - line_breaks = false + block_indicators = false + + flow_indicators = false + + line_breaks = false + special_characters = false - leading_space = false - leading_break = false + leading_space = false + + leading_break = false + trailing_space = false + trailing_break = false - break_space = false - space_break = false + + break_space = false + + space_break = false preceded_by_whitespace = false + followed_by_whitespace = false - previous_space = false - previous_break = false + + previous_space = false + + previous_break = false ) emitter.scalar_data.value = value if len(value) == 0 { + emitter.scalar_data.multiline = false + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = true + emitter.scalar_data.single_quoted_allowed = true + emitter.scalar_data.block_allowed = false + return true + } if len(value) >= 3 && ((value[0] == '-' && value[1] == '-' && value[2] == '-') || (value[0] == '.' && value[1] == '.' && value[2] == '.')) { + block_indicators = true + flow_indicators = true + } preceded_by_whitespace = true + for i, w := 0, 0; i < len(value); i += w { + w = width(value[i]) + followed_by_whitespace = i+w >= len(value) || is_blank(value, i+w) if i == 0 { + switch value[i] { + case '#', ',', '[', ']', '{', '}', '&', '*', '!', '|', '>', '\'', '"', '%', '@', '`': + flow_indicators = true + block_indicators = true + case '?', ':': + flow_indicators = true + if followed_by_whitespace { + block_indicators = true + } + case '-': + if followed_by_whitespace { + flow_indicators = true + block_indicators = true + } + } + } else { + switch value[i] { + case ',', '?', '[', ']', '{', '}': + flow_indicators = true + case ':': + flow_indicators = true + if followed_by_whitespace { + block_indicators = true + } + case '#': + if preceded_by_whitespace { + flow_indicators = true + block_indicators = true + } + } + } if !is_printable(value, i) || !is_ascii(value, i) && !emitter.unicode { + special_characters = true + } + if is_space(value, i) { + if i == 0 { + leading_space = true + } + if i+width(value[i]) == len(value) { + trailing_space = true + } + if previous_break { + break_space = true + } + previous_space = true + previous_break = false + } else if is_break(value, i) { + line_breaks = true + if i == 0 { + leading_break = true + } + if i+width(value[i]) == len(value) { + trailing_break = true + } + if previous_space { + space_break = true + } + previous_space = false + previous_break = true + } else { + previous_space = false + previous_break = false + } // [Go]: Why 'z'? Couldn't be the end of the string as that's the loop condition. + preceded_by_whitespace = is_blankz(value, i) + } emitter.scalar_data.multiline = line_breaks + emitter.scalar_data.flow_plain_allowed = true + emitter.scalar_data.block_plain_allowed = true + emitter.scalar_data.single_quoted_allowed = true + emitter.scalar_data.block_allowed = true if leading_space || leading_break || trailing_space || trailing_break { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + } + if trailing_space { + emitter.scalar_data.block_allowed = false + } + if break_space { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + emitter.scalar_data.single_quoted_allowed = false + } + if space_break || special_characters { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + emitter.scalar_data.single_quoted_allowed = false + emitter.scalar_data.block_allowed = false + } + if line_breaks { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + } + if flow_indicators { + emitter.scalar_data.flow_plain_allowed = false + } + if block_indicators { + emitter.scalar_data.block_plain_allowed = false + } + return true + } // Check if the event data is valid. + func yaml_emitter_analyze_event(emitter *yaml_emitter_t, event *yaml_event_t) bool { emitter.anchor_data.anchor = nil + emitter.tag_data.handle = nil + emitter.tag_data.suffix = nil + emitter.scalar_data.value = nil switch event.typ { + case yaml_ALIAS_EVENT: + if !yaml_emitter_analyze_anchor(emitter, event.anchor, true) { + return false + } case yaml_SCALAR_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || (!event.implicit && !event.quoted_implicit)) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + if !yaml_emitter_analyze_scalar(emitter, event.value) { + return false + } case yaml_SEQUENCE_START_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } case yaml_MAPPING_START_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + } + return true + } // Write the BOM character. + func yaml_emitter_write_bom(emitter *yaml_emitter_t) bool { + if !flush(emitter) { + return false + } + pos := emitter.buffer_pos + emitter.buffer[pos+0] = '\xEF' + emitter.buffer[pos+1] = '\xBB' + emitter.buffer[pos+2] = '\xBF' + emitter.buffer_pos += 3 + return true + } func yaml_emitter_write_indent(emitter *yaml_emitter_t) bool { + indent := emitter.indent + if indent < 0 { + indent = 0 + } + if !emitter.indention || emitter.column > indent || (emitter.column == indent && !emitter.whitespace) { + if !put_break(emitter) { + return false + } + } + for emitter.column < indent { + if !put(emitter, ' ') { + return false + } + } + emitter.whitespace = true + emitter.indention = true + return true + } func yaml_emitter_write_indicator(emitter *yaml_emitter_t, indicator []byte, need_whitespace, is_whitespace, is_indention bool) bool { + if need_whitespace && !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + if !write_all(emitter, indicator) { + return false + } + emitter.whitespace = is_whitespace + emitter.indention = (emitter.indention && is_indention) + emitter.open_ended = false + return true + } func yaml_emitter_write_anchor(emitter *yaml_emitter_t, value []byte) bool { + if !write_all(emitter, value) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true + } func yaml_emitter_write_tag_handle(emitter *yaml_emitter_t, value []byte) bool { + if !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + if !write_all(emitter, value) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true + } func yaml_emitter_write_tag_content(emitter *yaml_emitter_t, value []byte, need_whitespace bool) bool { + if need_whitespace && !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + for i := 0; i < len(value); { + var must_write bool + switch value[i] { + case ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '_', '.', '~', '*', '\'', '(', ')', '[', ']': + must_write = true + default: + must_write = is_alpha(value, i) + } + if must_write { + if !write(emitter, value, &i) { + return false + } + } else { + w := width(value[i]) + for k := 0; k < w; k++ { + octet := value[i] + i++ + if !put(emitter, '%') { + return false + } c := octet >> 4 + if c < 10 { + c += '0' + } else { + c += 'A' - 10 + } + if !put(emitter, c) { + return false + } c = octet & 0x0f + if c < 10 { + c += '0' + } else { + c += 'A' - 10 + } + if !put(emitter, c) { + return false + } + } + } + } + emitter.whitespace = false + emitter.indention = false + return true + } func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + if !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } spaces := false + breaks := false + for i := 0; i < len(value); { + if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && !is_space(value, i+1) { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + spaces = true + } else if is_break(value, i) { + if !breaks && value[i] == '\n' { + if !put_break(emitter) { + return false + } + } + if !write_break(emitter, value, &i) { + return false + } + emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + spaces = false + breaks = false + } + } emitter.whitespace = false + emitter.indention = false + if emitter.root_context { + emitter.open_ended = true + } return true + } func yaml_emitter_write_single_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { if !yaml_emitter_write_indicator(emitter, []byte{'\''}, true, false, false) { + return false + } spaces := false + breaks := false + for i := 0; i < len(value); { + if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 && !is_space(value, i+1) { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + spaces = true + } else if is_break(value, i) { + if !breaks && value[i] == '\n' { + if !put_break(emitter) { + return false + } + } + if !write_break(emitter, value, &i) { + return false + } + emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if value[i] == '\'' { + if !put(emitter, '\'') { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + spaces = false + breaks = false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'\''}, false, false, false) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true + } func yaml_emitter_write_double_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + spaces := false + if !yaml_emitter_write_indicator(emitter, []byte{'"'}, true, false, false) { + return false + } for i := 0; i < len(value); { + if !is_printable(value, i) || (!emitter.unicode && !is_ascii(value, i)) || + is_bom(value, i) || is_break(value, i) || + value[i] == '"' || value[i] == '\\' { octet := value[i] var w int + var v rune + switch { + case octet&0x80 == 0x00: + w, v = 1, rune(octet&0x7F) + case octet&0xE0 == 0xC0: + w, v = 2, rune(octet&0x1F) + case octet&0xF0 == 0xE0: + w, v = 3, rune(octet&0x0F) + case octet&0xF8 == 0xF0: + w, v = 4, rune(octet&0x07) + } + for k := 1; k < w; k++ { + octet = value[i+k] + v = (v << 6) + (rune(octet) & 0x3F) + } + i += w if !put(emitter, '\\') { + return false + } var ok bool + switch v { + case 0x00: + ok = put(emitter, '0') + case 0x07: + ok = put(emitter, 'a') + case 0x08: + ok = put(emitter, 'b') + case 0x09: + ok = put(emitter, 't') + case 0x0A: + ok = put(emitter, 'n') + case 0x0b: + ok = put(emitter, 'v') + case 0x0c: + ok = put(emitter, 'f') + case 0x0d: + ok = put(emitter, 'r') + case 0x1b: + ok = put(emitter, 'e') + case 0x22: + ok = put(emitter, '"') + case 0x5c: + ok = put(emitter, '\\') + case 0x85: + ok = put(emitter, 'N') + case 0xA0: + ok = put(emitter, '_') + case 0x2028: + ok = put(emitter, 'L') + case 0x2029: + ok = put(emitter, 'P') + default: + if v <= 0xFF { + ok = put(emitter, 'x') + w = 2 + } else if v <= 0xFFFF { + ok = put(emitter, 'u') + w = 4 + } else { + ok = put(emitter, 'U') + w = 8 + } + for k := (w - 1) * 4; ok && k >= 0; k -= 4 { + digit := byte((v >> uint(k)) & 0x0F) + if digit < 10 { + ok = put(emitter, digit+'0') + } else { + ok = put(emitter, digit+'A'-10) + } + } + } + if !ok { + return false + } + spaces = false + } else if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 { + if !yaml_emitter_write_indent(emitter) { + return false + } + if is_space(value, i+1) { + if !put(emitter, '\\') { + return false + } + } + i += width(value[i]) + } else if !write(emitter, value, &i) { + return false + } + spaces = true + } else { + if !write(emitter, value, &i) { + return false + } + spaces = false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'"'}, false, false, false) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true + } func yaml_emitter_write_block_scalar_hints(emitter *yaml_emitter_t, value []byte) bool { + if is_space(value, 0) || is_break(value, 0) { + indent_hint := []byte{'0' + byte(emitter.best_indent)} + if !yaml_emitter_write_indicator(emitter, indent_hint, false, false, false) { + return false + } + } emitter.open_ended = false var chomp_hint [1]byte + if len(value) == 0 { + chomp_hint[0] = '-' + } else { + i := len(value) - 1 + for value[i]&0xC0 == 0x80 { + i-- + } + if !is_break(value, i) { + chomp_hint[0] = '-' + } else if i == 0 { + chomp_hint[0] = '+' + emitter.open_ended = true + } else { + i-- + for value[i]&0xC0 == 0x80 { + i-- + } + if is_break(value, i) { + chomp_hint[0] = '+' + emitter.open_ended = true + } + } + } + if chomp_hint[0] != 0 { + if !yaml_emitter_write_indicator(emitter, chomp_hint[:], false, false, false) { + return false + } + } + return true + } func yaml_emitter_write_literal_scalar(emitter *yaml_emitter_t, value []byte) bool { + if !yaml_emitter_write_indicator(emitter, []byte{'|'}, true, false, false) { + return false + } + if !yaml_emitter_write_block_scalar_hints(emitter, value) { + return false + } + if !put_break(emitter) { + return false + } + emitter.indention = true + emitter.whitespace = true + breaks := true + for i := 0; i < len(value); { + if is_break(value, i) { + if !write_break(emitter, value, &i) { + return false + } + emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + breaks = false + } + } return true + } func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) bool { + if !yaml_emitter_write_indicator(emitter, []byte{'>'}, true, false, false) { + return false + } + if !yaml_emitter_write_block_scalar_hints(emitter, value) { + return false + } if !put_break(emitter) { + return false + } + emitter.indention = true + emitter.whitespace = true breaks := true + leading_spaces := true + for i := 0; i < len(value); { + if is_break(value, i) { + if !breaks && !leading_spaces && value[i] == '\n' { + k := 0 + for is_break(value, k) { + k += width(value[k]) + } + if !is_blankz(value, k) { + if !put_break(emitter) { + return false + } + } + } + if !write_break(emitter, value, &i) { + return false + } + emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + leading_spaces = is_blank(value, i) + } + if !breaks && is_space(value, i) && !is_space(value, i+1) && emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + emitter.indention = false + breaks = false + } + } + return true + } diff --git a/vendor/gopkg.in/yaml.v2/encode.go b/vendor/gopkg.in/yaml.v2/encode.go index 0ee738e..75a221b 100644 --- a/vendor/gopkg.in/yaml.v2/encode.go +++ b/vendor/gopkg.in/yaml.v2/encode.go @@ -14,377 +14,695 @@ import ( ) // jsonNumber is the interface of the encoding/json.Number datatype. + // Repeating the interface here avoids a dependency on encoding/json, and also + // supports other libraries like jsoniter, which use a similar datatype with + // the same interface. Detecting this interface is useful when dealing with + // structures containing json.Number, which is a string under the hood. The + // encoder should prefer the use of Int64(), Float64() and string(), in that + // order, when encoding this type. + type jsonNumber interface { Float64() (float64, error) + Int64() (int64, error) + String() string } type encoder struct { emitter yaml_emitter_t - event yaml_event_t - out []byte - flow bool + + event yaml_event_t + + out []byte + + flow bool + // doneInit holds whether the initial stream_start_event has been + // emitted. + doneInit bool } func newEncoder() *encoder { + e := &encoder{} + yaml_emitter_initialize(&e.emitter) + yaml_emitter_set_output_string(&e.emitter, &e.out) + yaml_emitter_set_unicode(&e.emitter, true) + return e + } func newEncoderWithWriter(w io.Writer) *encoder { + e := &encoder{} + yaml_emitter_initialize(&e.emitter) + yaml_emitter_set_output_writer(&e.emitter, w) + yaml_emitter_set_unicode(&e.emitter, true) + return e + } func (e *encoder) init() { + if e.doneInit { + return + } + yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING) + e.emit() + e.doneInit = true + } func (e *encoder) finish() { + e.emitter.open_ended = false + yaml_stream_end_event_initialize(&e.event) + e.emit() + } func (e *encoder) destroy() { + yaml_emitter_delete(&e.emitter) + } func (e *encoder) emit() { + // This will internally delete the e.event value. + e.must(yaml_emitter_emit(&e.emitter, &e.event)) + } func (e *encoder) must(ok bool) { + if !ok { + msg := e.emitter.problem + if msg == "" { + msg = "unknown problem generating YAML content" + } + failf("%s", msg) + } + } func (e *encoder) marshalDoc(tag string, in reflect.Value) { + e.init() + yaml_document_start_event_initialize(&e.event, nil, nil, true) + e.emit() + e.marshal(tag, in) + yaml_document_end_event_initialize(&e.event, true) + e.emit() + } func (e *encoder) marshal(tag string, in reflect.Value) { + if !in.IsValid() || in.Kind() == reflect.Ptr && in.IsNil() { + e.nilv() + return + } + iface := in.Interface() + switch m := iface.(type) { + case jsonNumber: + integer, err := m.Int64() + if err == nil { + // In this case the json.Number is a valid int64 + in = reflect.ValueOf(integer) + break + } + float, err := m.Float64() + if err == nil { + // In this case the json.Number is a valid float64 + in = reflect.ValueOf(float) + break + } + // fallback case - no number could be obtained + in = reflect.ValueOf(m.String()) + case time.Time, *time.Time: + // Although time.Time implements TextMarshaler, + // we don't want to treat it as a string for YAML + // purposes because YAML has special support for + // timestamps. + case Marshaler: + v, err := m.MarshalYAML() + if err != nil { + fail(err) + } + if v == nil { + e.nilv() + return + } + in = reflect.ValueOf(v) + case encoding.TextMarshaler: + text, err := m.MarshalText() + if err != nil { + fail(err) + } + in = reflect.ValueOf(string(text)) + case nil: + e.nilv() + return + } + switch in.Kind() { + case reflect.Interface: + e.marshal(tag, in.Elem()) + case reflect.Map: + e.mapv(tag, in) + case reflect.Ptr: + if in.Type() == ptrTimeType { + e.timev(tag, in.Elem()) + } else { + e.marshal(tag, in.Elem()) + } + case reflect.Struct: + if in.Type() == timeType { + e.timev(tag, in) + } else { + e.structv(tag, in) + } + case reflect.Slice, reflect.Array: + if in.Type().Elem() == mapItemType { + e.itemsv(tag, in) + } else { + e.slicev(tag, in) + } + case reflect.String: + e.stringv(tag, in) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + if in.Type() == durationType { + e.stringv(tag, reflect.ValueOf(iface.(time.Duration).String())) + } else { + e.intv(tag, in) + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + e.uintv(tag, in) + case reflect.Float32, reflect.Float64: + e.floatv(tag, in) + case reflect.Bool: + e.boolv(tag, in) + default: + panic("cannot marshal type: " + in.Type().String()) + } + } func (e *encoder) mapv(tag string, in reflect.Value) { + e.mappingv(tag, func() { + keys := keyList(in.MapKeys()) + sort.Sort(keys) + for _, k := range keys { + e.marshal("", k) + e.marshal("", in.MapIndex(k)) + } + }) + } func (e *encoder) itemsv(tag string, in reflect.Value) { + e.mappingv(tag, func() { + slice := in.Convert(reflect.TypeOf([]MapItem{})).Interface().([]MapItem) + for _, item := range slice { + e.marshal("", reflect.ValueOf(item.Key)) + e.marshal("", reflect.ValueOf(item.Value)) + } + }) + } func (e *encoder) structv(tag string, in reflect.Value) { + sinfo, err := getStructInfo(in.Type()) + if err != nil { + panic(err) + } + e.mappingv(tag, func() { + for _, info := range sinfo.FieldsList { + var value reflect.Value + if info.Inline == nil { + value = in.Field(info.Num) + } else { + value = in.FieldByIndex(info.Inline) + } + if info.OmitEmpty && isZero(value) { + continue + } + e.marshal("", reflect.ValueOf(info.Key)) + e.flow = info.Flow + e.marshal("", value) + } + if sinfo.InlineMap >= 0 { + m := in.Field(sinfo.InlineMap) + if m.Len() > 0 { + e.flow = false + keys := keyList(m.MapKeys()) + sort.Sort(keys) + for _, k := range keys { + if _, found := sinfo.FieldsMap[k.String()]; found { + panic(fmt.Sprintf("Can't have key %q in inlined map; conflicts with struct field", k.String())) + } + e.marshal("", k) + e.flow = false + e.marshal("", m.MapIndex(k)) + } + } + } + }) + } func (e *encoder) mappingv(tag string, f func()) { + implicit := tag == "" + style := yaml_BLOCK_MAPPING_STYLE + if e.flow { + e.flow = false + style = yaml_FLOW_MAPPING_STYLE + } + yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style) + e.emit() + f() + yaml_mapping_end_event_initialize(&e.event) + e.emit() + } func (e *encoder) slicev(tag string, in reflect.Value) { + implicit := tag == "" + style := yaml_BLOCK_SEQUENCE_STYLE + if e.flow { + e.flow = false + style = yaml_FLOW_SEQUENCE_STYLE + } + e.must(yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)) + e.emit() + n := in.Len() + for i := 0; i < n; i++ { + e.marshal("", in.Index(i)) + } + e.must(yaml_sequence_end_event_initialize(&e.event)) + e.emit() + } // isBase60 returns whether s is in base 60 notation as defined in YAML 1.1. + // + // The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported + // in YAML 1.2 and by this package, but these should be marshalled quoted for + // the time being for compatibility with other parsers. + func isBase60Float(s string) (result bool) { + // Fast path. + if s == "" { + return false + } + c := s[0] + if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 { + return false + } + // Do the full match. + return base60float.MatchString(s) + } // From http://yaml.org/type/float.html, except the regular expression there + // is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix. + var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`) func (e *encoder) stringv(tag string, in reflect.Value) { + var style yaml_scalar_style_t + s := in.String() + canUsePlain := true + switch { + case !utf8.ValidString(s): + if tag == yaml_BINARY_TAG { + failf("explicitly tagged !!binary data must be base64-encoded") + } + if tag != "" { + failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag)) + } + // It can't be encoded directly as YAML so use a binary tag + // and encode it as base64. + tag = yaml_BINARY_TAG + s = encodeBase64(s) + case tag == "": + // Check to see if it would resolve to a specific + // tag when encoded unquoted. If it doesn't, + // there's no need to quote it. + rtag, _ := resolve("", s) + canUsePlain = rtag == yaml_STR_TAG && !isBase60Float(s) + } + // Note: it's possible for user code to emit invalid YAML + // if they explicitly specify a tag and a string containing + // text that's incompatible with that tag. + switch { + case strings.Contains(s, "\n"): + style = yaml_LITERAL_SCALAR_STYLE + case canUsePlain: + style = yaml_PLAIN_SCALAR_STYLE + default: + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + e.emitScalar(s, "", tag, style) + } func (e *encoder) boolv(tag string, in reflect.Value) { + var s string + if in.Bool() { + s = "true" + } else { + s = "false" + } + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) + } func (e *encoder) intv(tag string, in reflect.Value) { + s := strconv.FormatInt(in.Int(), 10) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) + } func (e *encoder) uintv(tag string, in reflect.Value) { + s := strconv.FormatUint(in.Uint(), 10) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) + } func (e *encoder) timev(tag string, in reflect.Value) { + t := in.Interface().(time.Time) + s := t.Format(time.RFC3339Nano) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) + } func (e *encoder) floatv(tag string, in reflect.Value) { + // Issue #352: When formatting, use the precision of the underlying value + precision := 64 + if in.Kind() == reflect.Float32 { + precision = 32 + } s := strconv.FormatFloat(in.Float(), 'g', -1, precision) + switch s { + case "+Inf": + s = ".inf" + case "-Inf": + s = "-.inf" + case "NaN": + s = ".nan" + } + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) + } func (e *encoder) nilv() { + e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE) + } func (e *encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t) { + implicit := tag == "" + e.must(yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(tag), []byte(value), implicit, implicit, style)) + e.emit() + } diff --git a/vendor/gopkg.in/yaml.v2/resolve.go b/vendor/gopkg.in/yaml.v2/resolve.go index e29c364..727c14e 100644 --- a/vendor/gopkg.in/yaml.v2/resolve.go +++ b/vendor/gopkg.in/yaml.v2/resolve.go @@ -11,248 +11,447 @@ import ( type resolveMapItem struct { value interface{} - tag string + + tag string } var resolveTable = make([]byte, 256) + var resolveMap = make(map[string]resolveMapItem) func init() { + t := resolveTable + t[int('+')] = 'S' // Sign + t[int('-')] = 'S' + for _, c := range "0123456789" { + t[int(c)] = 'D' // Digit + } + for _, c := range "yYnNtTfFoO~" { + t[int(c)] = 'M' // In map + } + t[int('.')] = '.' // Float (potentially in map) var resolveMapList = []struct { - v interface{} + v interface{} + tag string - l []string + + l []string }{ + {true, yaml_BOOL_TAG, []string{"y", "Y", "yes", "Yes", "YES"}}, + {true, yaml_BOOL_TAG, []string{"true", "True", "TRUE"}}, + {true, yaml_BOOL_TAG, []string{"on", "On", "ON"}}, + {false, yaml_BOOL_TAG, []string{"n", "N", "no", "No", "NO"}}, + {false, yaml_BOOL_TAG, []string{"false", "False", "FALSE"}}, + {false, yaml_BOOL_TAG, []string{"off", "Off", "OFF"}}, + {nil, yaml_NULL_TAG, []string{"", "~", "null", "Null", "NULL"}}, + {math.NaN(), yaml_FLOAT_TAG, []string{".nan", ".NaN", ".NAN"}}, + {math.Inf(+1), yaml_FLOAT_TAG, []string{".inf", ".Inf", ".INF"}}, + {math.Inf(+1), yaml_FLOAT_TAG, []string{"+.inf", "+.Inf", "+.INF"}}, + {math.Inf(-1), yaml_FLOAT_TAG, []string{"-.inf", "-.Inf", "-.INF"}}, + {"<<", yaml_MERGE_TAG, []string{"<<"}}, } m := resolveMap + for _, item := range resolveMapList { + for _, s := range item.l { + m[s] = resolveMapItem{item.v, item.tag} + } + } + } const longTagPrefix = "tag:yaml.org,2002:" func shortTag(tag string) string { + // TODO This can easily be made faster and produce less garbage. + if strings.HasPrefix(tag, longTagPrefix) { + return "!!" + tag[len(longTagPrefix):] + } + return tag + } func longTag(tag string) string { + if strings.HasPrefix(tag, "!!") { + return longTagPrefix + tag[2:] + } + return tag + } func resolvableTag(tag string) bool { + switch tag { + case "", yaml_STR_TAG, yaml_BOOL_TAG, yaml_INT_TAG, yaml_FLOAT_TAG, yaml_NULL_TAG, yaml_TIMESTAMP_TAG: + return true + } + return false + } var yamlStyleFloat = regexp.MustCompile(`^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$`) func resolve(tag string, in string) (rtag string, out interface{}) { + if !resolvableTag(tag) { + return tag, in + } defer func() { + switch tag { + case "", rtag, yaml_STR_TAG, yaml_BINARY_TAG: + return + case yaml_FLOAT_TAG: + if rtag == yaml_INT_TAG { + switch v := out.(type) { + case int64: + rtag = yaml_FLOAT_TAG + out = float64(v) + return + case int: + rtag = yaml_FLOAT_TAG + out = float64(v) + return + } + } + } + failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag)) + }() // Any data is accepted as a !!str or !!binary. + // Otherwise, the prefix is enough of a hint about what it might be. + hint := byte('N') + if in != "" { + hint = resolveTable[in[0]] + } + if hint != 0 && tag != yaml_STR_TAG && tag != yaml_BINARY_TAG { + // Handle things we can lookup in a map. + if item, ok := resolveMap[in]; ok { + return item.tag, item.value + } // Base 60 floats are a bad idea, were dropped in YAML 1.2, and + // are purposefully unsupported here. They're still quoted on + // the way out for compatibility with other parser, though. switch hint { + case 'M': + // We've already checked the map above. case '.': + // Not in the map, so maybe a normal float. + floatv, err := strconv.ParseFloat(in, 64) + if err == nil { + return yaml_FLOAT_TAG, floatv + } case 'D', 'S': + // Int, float, or timestamp. + // Only try values as a timestamp if the value is unquoted or there's an explicit + // !!timestamp tag. + if tag == "" || tag == yaml_TIMESTAMP_TAG { + t, ok := parseTimestamp(in) + if ok { + return yaml_TIMESTAMP_TAG, t + } + } plain := strings.Replace(in, "_", "", -1) + intv, err := strconv.ParseInt(plain, 0, 64) + if err == nil { + if intv == int64(int(intv)) { + return yaml_INT_TAG, int(intv) + } else { + return yaml_INT_TAG, intv + } + } + uintv, err := strconv.ParseUint(plain, 0, 64) + if err == nil { + return yaml_INT_TAG, uintv + } + if yamlStyleFloat.MatchString(plain) { + floatv, err := strconv.ParseFloat(plain, 64) + if err == nil { + return yaml_FLOAT_TAG, floatv + } + } + if strings.HasPrefix(plain, "0b") { + intv, err := strconv.ParseInt(plain[2:], 2, 64) + if err == nil { + if intv == int64(int(intv)) { + return yaml_INT_TAG, int(intv) + } else { + return yaml_INT_TAG, intv + } + } + uintv, err := strconv.ParseUint(plain[2:], 2, 64) + if err == nil { + return yaml_INT_TAG, uintv + } + } else if strings.HasPrefix(plain, "-0b") { + intv, err := strconv.ParseInt("-"+plain[3:], 2, 64) + if err == nil { + if true || intv == int64(int(intv)) { + return yaml_INT_TAG, int(intv) + } else { + return yaml_INT_TAG, intv + } + } + } + default: + panic("resolveTable item not yet handled: " + string(rune(hint)) + " (with " + in + ")") + } + } + return yaml_STR_TAG, in + } // encodeBase64 encodes s as base64 that is broken up into multiple lines + // as appropriate for the resulting length. + func encodeBase64(s string) string { + const lineLen = 70 + encLen := base64.StdEncoding.EncodedLen(len(s)) + lines := encLen/lineLen + 1 + buf := make([]byte, encLen*2+lines) + in := buf[0:encLen] + out := buf[encLen:] + base64.StdEncoding.Encode(in, []byte(s)) + k := 0 + for i := 0; i < len(in); i += lineLen { + j := i + lineLen + if j > len(in) { + j = len(in) + } + k += copy(out[k:], in[i:j]) + if lines > 1 { + out[k] = '\n' + k++ + } + } + return string(out[:k]) + } // This is a subset of the formats allowed by the regular expression + // defined at http://yaml.org/type/timestamp.html. + var allowedTimestampFormats = []string{ + "2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields. + "2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t". - "2006-1-2 15:4:5.999999999", // space separated with no time zone - "2006-1-2", // date only + + "2006-1-2 15:4:5.999999999", // space separated with no time zone + + "2006-1-2", // date only + // Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5" + // from the set of examples. + } // parseTimestamp parses s as a timestamp string and + // returns the timestamp and reports whether it succeeded. + // Timestamp formats are defined at http://yaml.org/type/timestamp.html + func parseTimestamp(s string) (time.Time, bool) { + // TODO write code to check all the formats supported by + // http://yaml.org/type/timestamp.html instead of using time.Parse. // Quick check: all date formats start with YYYY-. + i := 0 + for ; i < len(s); i++ { + if c := s[i]; c < '0' || c > '9' { + break + } + } + if i != 4 || i == len(s) || s[i] != '-' { + return time.Time{}, false + } + for _, format := range allowedTimestampFormats { + if t, err := time.Parse(format, s); err == nil { + return t, true + } + } + return time.Time{}, false + } diff --git a/vendor/gopkg.in/yaml.v2/scannerc.go b/vendor/gopkg.in/yaml.v2/scannerc.go index d634dca..92233b8 100644 --- a/vendor/gopkg.in/yaml.v2/scannerc.go +++ b/vendor/gopkg.in/yaml.v2/scannerc.go @@ -6,2708 +6,4800 @@ import ( ) // Introduction + // ************ + // + // The following notes assume that you are familiar with the YAML specification + // (http://yaml.org/spec/1.2/spec.html). We mostly follow it, although in + // some cases we are less restrictive that it requires. + // + // The process of transforming a YAML stream into a sequence of events is + // divided on two steps: Scanning and Parsing. + // + // The Scanner transforms the input stream into a sequence of tokens, while the + // parser transform the sequence of tokens produced by the Scanner into a + // sequence of parsing events. + // + // The Scanner is rather clever and complicated. The Parser, on the contrary, + // is a straightforward implementation of a recursive-descendant parser (or, + // LL(1) parser, as it is usually called). + // + // Actually there are two issues of Scanning that might be called "clever", the + // rest is quite straightforward. The issues are "block collection start" and + // "simple keys". Both issues are explained below in details. + // + // Here the Scanning step is explained and implemented. We start with the list + // of all the tokens produced by the Scanner together with short descriptions. + // + // Now, tokens: + // + // STREAM-START(encoding) # The stream start. + // STREAM-END # The stream end. + // VERSION-DIRECTIVE(major,minor) # The '%YAML' directive. + // TAG-DIRECTIVE(handle,prefix) # The '%TAG' directive. + // DOCUMENT-START # '---' + // DOCUMENT-END # '...' + // BLOCK-SEQUENCE-START # Indentation increase denoting a block + // BLOCK-MAPPING-START # sequence or a block mapping. + // BLOCK-END # Indentation decrease. + // FLOW-SEQUENCE-START # '[' + // FLOW-SEQUENCE-END # ']' + // BLOCK-SEQUENCE-START # '{' + // BLOCK-SEQUENCE-END # '}' + // BLOCK-ENTRY # '-' + // FLOW-ENTRY # ',' + // KEY # '?' or nothing (simple keys). + // VALUE # ':' + // ALIAS(anchor) # '*anchor' + // ANCHOR(anchor) # '&anchor' + // TAG(handle,suffix) # '!handle!suffix' + // SCALAR(value,style) # A scalar. + // + // The following two tokens are "virtual" tokens denoting the beginning and the + // end of the stream: + // + // STREAM-START(encoding) + // STREAM-END + // + // We pass the information about the input stream encoding with the + // STREAM-START token. + // + // The next two tokens are responsible for tags: + // + // VERSION-DIRECTIVE(major,minor) + // TAG-DIRECTIVE(handle,prefix) + // + // Example: + // + // %YAML 1.1 + // %TAG ! !foo + // %TAG !yaml! tag:yaml.org,2002: + // --- + // + // The correspoding sequence of tokens: + // + // STREAM-START(utf-8) + // VERSION-DIRECTIVE(1,1) + // TAG-DIRECTIVE("!","!foo") + // TAG-DIRECTIVE("!yaml","tag:yaml.org,2002:") + // DOCUMENT-START + // STREAM-END + // + // Note that the VERSION-DIRECTIVE and TAG-DIRECTIVE tokens occupy a whole + // line. + // + // The document start and end indicators are represented by: + // + // DOCUMENT-START + // DOCUMENT-END + // + // Note that if a YAML stream contains an implicit document (without '---' + // and '...' indicators), no DOCUMENT-START and DOCUMENT-END tokens will be + // produced. + // + // In the following examples, we present whole documents together with the + // produced tokens. + // + // 1. An implicit document: + // + // 'a scalar' + // + // Tokens: + // + // STREAM-START(utf-8) + // SCALAR("a scalar",single-quoted) + // STREAM-END + // + // 2. An explicit document: + // + // --- + // 'a scalar' + // ... + // + // Tokens: + // + // STREAM-START(utf-8) + // DOCUMENT-START + // SCALAR("a scalar",single-quoted) + // DOCUMENT-END + // STREAM-END + // + // 3. Several documents in a stream: + // + // 'a scalar' + // --- + // 'another scalar' + // --- + // 'yet another scalar' + // + // Tokens: + // + // STREAM-START(utf-8) + // SCALAR("a scalar",single-quoted) + // DOCUMENT-START + // SCALAR("another scalar",single-quoted) + // DOCUMENT-START + // SCALAR("yet another scalar",single-quoted) + // STREAM-END + // + // We have already introduced the SCALAR token above. The following tokens are + // used to describe aliases, anchors, tag, and scalars: + // + // ALIAS(anchor) + // ANCHOR(anchor) + // TAG(handle,suffix) + // SCALAR(value,style) + // + // The following series of examples illustrate the usage of these tokens: + // + // 1. A recursive sequence: + // + // &A [ *A ] + // + // Tokens: + // + // STREAM-START(utf-8) + // ANCHOR("A") + // FLOW-SEQUENCE-START + // ALIAS("A") + // FLOW-SEQUENCE-END + // STREAM-END + // + // 2. A tagged scalar: + // + // !!float "3.14" # A good approximation. + // + // Tokens: + // + // STREAM-START(utf-8) + // TAG("!!","float") + // SCALAR("3.14",double-quoted) + // STREAM-END + // + // 3. Various scalar styles: + // + // --- # Implicit empty plain scalars do not produce tokens. + // --- a plain scalar + // --- 'a single-quoted scalar' + // --- "a double-quoted scalar" + // --- |- + // a literal scalar + // --- >- + // a folded + // scalar + // + // Tokens: + // + // STREAM-START(utf-8) + // DOCUMENT-START + // DOCUMENT-START + // SCALAR("a plain scalar",plain) + // DOCUMENT-START + // SCALAR("a single-quoted scalar",single-quoted) + // DOCUMENT-START + // SCALAR("a double-quoted scalar",double-quoted) + // DOCUMENT-START + // SCALAR("a literal scalar",literal) + // DOCUMENT-START + // SCALAR("a folded scalar",folded) + // STREAM-END + // + // Now it's time to review collection-related tokens. We will start with + // flow collections: + // + // FLOW-SEQUENCE-START + // FLOW-SEQUENCE-END + // FLOW-MAPPING-START + // FLOW-MAPPING-END + // FLOW-ENTRY + // KEY + // VALUE + // + // The tokens FLOW-SEQUENCE-START, FLOW-SEQUENCE-END, FLOW-MAPPING-START, and + // FLOW-MAPPING-END represent the indicators '[', ']', '{', and '}' + // correspondingly. FLOW-ENTRY represent the ',' indicator. Finally the + // indicators '?' and ':', which are used for denoting mapping keys and values, + // are represented by the KEY and VALUE tokens. + // + // The following examples show flow collections: + // + // 1. A flow sequence: + // + // [item 1, item 2, item 3] + // + // Tokens: + // + // STREAM-START(utf-8) + // FLOW-SEQUENCE-START + // SCALAR("item 1",plain) + // FLOW-ENTRY + // SCALAR("item 2",plain) + // FLOW-ENTRY + // SCALAR("item 3",plain) + // FLOW-SEQUENCE-END + // STREAM-END + // + // 2. A flow mapping: + // + // { + // a simple key: a value, # Note that the KEY token is produced. + // ? a complex key: another value, + // } + // + // Tokens: + // + // STREAM-START(utf-8) + // FLOW-MAPPING-START + // KEY + // SCALAR("a simple key",plain) + // VALUE + // SCALAR("a value",plain) + // FLOW-ENTRY + // KEY + // SCALAR("a complex key",plain) + // VALUE + // SCALAR("another value",plain) + // FLOW-ENTRY + // FLOW-MAPPING-END + // STREAM-END + // + // A simple key is a key which is not denoted by the '?' indicator. Note that + // the Scanner still produce the KEY token whenever it encounters a simple key. + // + // For scanning block collections, the following tokens are used (note that we + // repeat KEY and VALUE here): + // + // BLOCK-SEQUENCE-START + // BLOCK-MAPPING-START + // BLOCK-END + // BLOCK-ENTRY + // KEY + // VALUE + // + // The tokens BLOCK-SEQUENCE-START and BLOCK-MAPPING-START denote indentation + // increase that precedes a block collection (cf. the INDENT token in Python). + // The token BLOCK-END denote indentation decrease that ends a block collection + // (cf. the DEDENT token in Python). However YAML has some syntax pecularities + // that makes detections of these tokens more complex. + // + // The tokens BLOCK-ENTRY, KEY, and VALUE are used to represent the indicators + // '-', '?', and ':' correspondingly. + // + // The following examples show how the tokens BLOCK-SEQUENCE-START, + // BLOCK-MAPPING-START, and BLOCK-END are emitted by the Scanner: + // + // 1. Block sequences: + // + // - item 1 + // - item 2 + // - + // - item 3.1 + // - item 3.2 + // - + // key 1: value 1 + // key 2: value 2 + // + // Tokens: + // + // STREAM-START(utf-8) + // BLOCK-SEQUENCE-START + // BLOCK-ENTRY + // SCALAR("item 1",plain) + // BLOCK-ENTRY + // SCALAR("item 2",plain) + // BLOCK-ENTRY + // BLOCK-SEQUENCE-START + // BLOCK-ENTRY + // SCALAR("item 3.1",plain) + // BLOCK-ENTRY + // SCALAR("item 3.2",plain) + // BLOCK-END + // BLOCK-ENTRY + // BLOCK-MAPPING-START + // KEY + // SCALAR("key 1",plain) + // VALUE + // SCALAR("value 1",plain) + // KEY + // SCALAR("key 2",plain) + // VALUE + // SCALAR("value 2",plain) + // BLOCK-END + // BLOCK-END + // STREAM-END + // + // 2. Block mappings: + // + // a simple key: a value # The KEY token is produced here. + // ? a complex key + // : another value + // a mapping: + // key 1: value 1 + // key 2: value 2 + // a sequence: + // - item 1 + // - item 2 + // + // Tokens: + // + // STREAM-START(utf-8) + // BLOCK-MAPPING-START + // KEY + // SCALAR("a simple key",plain) + // VALUE + // SCALAR("a value",plain) + // KEY + // SCALAR("a complex key",plain) + // VALUE + // SCALAR("another value",plain) + // KEY + // SCALAR("a mapping",plain) + // BLOCK-MAPPING-START + // KEY + // SCALAR("key 1",plain) + // VALUE + // SCALAR("value 1",plain) + // KEY + // SCALAR("key 2",plain) + // VALUE + // SCALAR("value 2",plain) + // BLOCK-END + // KEY + // SCALAR("a sequence",plain) + // VALUE + // BLOCK-SEQUENCE-START + // BLOCK-ENTRY + // SCALAR("item 1",plain) + // BLOCK-ENTRY + // SCALAR("item 2",plain) + // BLOCK-END + // BLOCK-END + // STREAM-END + // + // YAML does not always require to start a new block collection from a new + // line. If the current line contains only '-', '?', and ':' indicators, a new + // block collection may start at the current line. The following examples + // illustrate this case: + // + // 1. Collections in a sequence: + // + // - - item 1 + // - item 2 + // - key 1: value 1 + // key 2: value 2 + // - ? complex key + // : complex value + // + // Tokens: + // + // STREAM-START(utf-8) + // BLOCK-SEQUENCE-START + // BLOCK-ENTRY + // BLOCK-SEQUENCE-START + // BLOCK-ENTRY + // SCALAR("item 1",plain) + // BLOCK-ENTRY + // SCALAR("item 2",plain) + // BLOCK-END + // BLOCK-ENTRY + // BLOCK-MAPPING-START + // KEY + // SCALAR("key 1",plain) + // VALUE + // SCALAR("value 1",plain) + // KEY + // SCALAR("key 2",plain) + // VALUE + // SCALAR("value 2",plain) + // BLOCK-END + // BLOCK-ENTRY + // BLOCK-MAPPING-START + // KEY + // SCALAR("complex key") + // VALUE + // SCALAR("complex value") + // BLOCK-END + // BLOCK-END + // STREAM-END + // + // 2. Collections in a mapping: + // + // ? a sequence + // : - item 1 + // - item 2 + // ? a mapping + // : key 1: value 1 + // key 2: value 2 + // + // Tokens: + // + // STREAM-START(utf-8) + // BLOCK-MAPPING-START + // KEY + // SCALAR("a sequence",plain) + // VALUE + // BLOCK-SEQUENCE-START + // BLOCK-ENTRY + // SCALAR("item 1",plain) + // BLOCK-ENTRY + // SCALAR("item 2",plain) + // BLOCK-END + // KEY + // SCALAR("a mapping",plain) + // VALUE + // BLOCK-MAPPING-START + // KEY + // SCALAR("key 1",plain) + // VALUE + // SCALAR("value 1",plain) + // KEY + // SCALAR("key 2",plain) + // VALUE + // SCALAR("value 2",plain) + // BLOCK-END + // BLOCK-END + // STREAM-END + // + // YAML also permits non-indented sequences if they are included into a block + // mapping. In this case, the token BLOCK-SEQUENCE-START is not produced: + // + // key: + // - item 1 # BLOCK-SEQUENCE-START is NOT produced here. + // - item 2 + // + // Tokens: + // + // STREAM-START(utf-8) + // BLOCK-MAPPING-START + // KEY + // SCALAR("key",plain) + // VALUE + // BLOCK-ENTRY + // SCALAR("item 1",plain) + // BLOCK-ENTRY + // SCALAR("item 2",plain) + // BLOCK-END + // // Ensure that the buffer contains the required number of characters. + // Return true on success, false on failure (reader error or memory error). + func cache(parser *yaml_parser_t, length int) bool { + // [Go] This was inlined: !cache(A, B) -> unread < B && !update(A, B) + return parser.unread >= length || yaml_parser_update_buffer(parser, length) + } // Advance the buffer pointer. + func skip(parser *yaml_parser_t) { + parser.mark.index++ + parser.mark.column++ + parser.unread-- + parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) + } func skip_line(parser *yaml_parser_t) { + if is_crlf(parser.buffer, parser.buffer_pos) { + parser.mark.index += 2 + parser.mark.column = 0 + parser.mark.line++ + parser.unread -= 2 + parser.buffer_pos += 2 + } else if is_break(parser.buffer, parser.buffer_pos) { + parser.mark.index++ + parser.mark.column = 0 + parser.mark.line++ + parser.unread-- + parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) + } + } // Copy a character to a string buffer and advance pointers. + func read(parser *yaml_parser_t, s []byte) []byte { + w := width(parser.buffer[parser.buffer_pos]) + if w == 0 { + panic("invalid character sequence") + } + if len(s) == 0 { + s = make([]byte, 0, 32) + } + if w == 1 && len(s)+w <= cap(s) { + s = s[:len(s)+1] + s[len(s)-1] = parser.buffer[parser.buffer_pos] + parser.buffer_pos++ + } else { + s = append(s, parser.buffer[parser.buffer_pos:parser.buffer_pos+w]...) + parser.buffer_pos += w + } + parser.mark.index++ + parser.mark.column++ + parser.unread-- + return s + } // Copy a line break character to a string buffer and advance pointers. + func read_line(parser *yaml_parser_t, s []byte) []byte { + buf := parser.buffer + pos := parser.buffer_pos + switch { + case buf[pos] == '\r' && buf[pos+1] == '\n': + // CR LF . LF + s = append(s, '\n') + parser.buffer_pos += 2 + parser.mark.index++ + parser.unread-- + case buf[pos] == '\r' || buf[pos] == '\n': + // CR|LF . LF + s = append(s, '\n') + parser.buffer_pos += 1 + case buf[pos] == '\xC2' && buf[pos+1] == '\x85': + // NEL . LF + s = append(s, '\n') + parser.buffer_pos += 2 + case buf[pos] == '\xE2' && buf[pos+1] == '\x80' && (buf[pos+2] == '\xA8' || buf[pos+2] == '\xA9'): + // LS|PS . LS|PS + s = append(s, buf[parser.buffer_pos:pos+3]...) + parser.buffer_pos += 3 + default: + return s + } + parser.mark.index++ + parser.mark.column = 0 + parser.mark.line++ + parser.unread-- + return s + } // Get the next token. + func yaml_parser_scan(parser *yaml_parser_t, token *yaml_token_t) bool { + // Erase the token object. + *token = yaml_token_t{} // [Go] Is this necessary? // No tokens after STREAM-END or error. + if parser.stream_end_produced || parser.error != yaml_NO_ERROR { + return true + } // Ensure that the tokens queue contains enough tokens. + if !parser.token_available { + if !yaml_parser_fetch_more_tokens(parser) { + return false + } + } // Fetch the next token from the queue. + *token = parser.tokens[parser.tokens_head] + parser.tokens_head++ + parser.tokens_parsed++ + parser.token_available = false if token.typ == yaml_STREAM_END_TOKEN { + parser.stream_end_produced = true + } + return true + } // Set the scanner error and return false. + func yaml_parser_set_scanner_error(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string) bool { + parser.error = yaml_SCANNER_ERROR + parser.context = context + parser.context_mark = context_mark + parser.problem = problem + parser.problem_mark = parser.mark + return false + } func yaml_parser_set_scanner_tag_error(parser *yaml_parser_t, directive bool, context_mark yaml_mark_t, problem string) bool { + context := "while parsing a tag" + if directive { + context = "while parsing a %TAG directive" + } + return yaml_parser_set_scanner_error(parser, context, context_mark, problem) + } func trace(args ...interface{}) func() { + pargs := append([]interface{}{"+++"}, args...) + fmt.Println(pargs...) + pargs = append([]interface{}{"---"}, args...) + return func() { fmt.Println(pargs...) } + } // Ensure that the tokens queue contains at least one token which can be + // returned to the Parser. + func yaml_parser_fetch_more_tokens(parser *yaml_parser_t) bool { + // While we need more tokens to fetch, do it. + for { + if parser.tokens_head != len(parser.tokens) { + // If queue is non-empty, check if any potential simple key may + // occupy the head position. + head_tok_idx, ok := parser.simple_keys_by_tok[parser.tokens_parsed] + if !ok { + break + } else if valid, ok := yaml_simple_key_is_valid(parser, &parser.simple_keys[head_tok_idx]); !ok { + return false + } else if !valid { + break + } + } + // Fetch the next token. + if !yaml_parser_fetch_next_token(parser) { + return false + } + } parser.token_available = true + return true + } // The dispatcher for token fetchers. + func yaml_parser_fetch_next_token(parser *yaml_parser_t) bool { + // Ensure that the buffer is initialized. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } // Check if we just started scanning. Fetch STREAM-START then. + if !parser.stream_start_produced { + return yaml_parser_fetch_stream_start(parser) + } // Eat whitespaces and comments until we reach the next token. + if !yaml_parser_scan_to_next_token(parser) { + return false + } // Check the indentation level against the current column. + if !yaml_parser_unroll_indent(parser, parser.mark.column) { + return false + } // Ensure that the buffer contains at least 4 characters. 4 is the length + // of the longest indicators ('--- ' and '... '). + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } // Is it the end of the stream? + if is_z(parser.buffer, parser.buffer_pos) { + return yaml_parser_fetch_stream_end(parser) + } // Is it a directive? + if parser.mark.column == 0 && parser.buffer[parser.buffer_pos] == '%' { + return yaml_parser_fetch_directive(parser) + } buf := parser.buffer + pos := parser.buffer_pos // Is it the document start indicator? + if parser.mark.column == 0 && buf[pos] == '-' && buf[pos+1] == '-' && buf[pos+2] == '-' && is_blankz(buf, pos+3) { + return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_START_TOKEN) + } // Is it the document end indicator? + if parser.mark.column == 0 && buf[pos] == '.' && buf[pos+1] == '.' && buf[pos+2] == '.' && is_blankz(buf, pos+3) { + return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_END_TOKEN) + } // Is it the flow sequence start indicator? + if buf[pos] == '[' { + return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_SEQUENCE_START_TOKEN) + } // Is it the flow mapping start indicator? + if parser.buffer[parser.buffer_pos] == '{' { + return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_MAPPING_START_TOKEN) + } // Is it the flow sequence end indicator? + if parser.buffer[parser.buffer_pos] == ']' { + return yaml_parser_fetch_flow_collection_end(parser, + yaml_FLOW_SEQUENCE_END_TOKEN) + } // Is it the flow mapping end indicator? + if parser.buffer[parser.buffer_pos] == '}' { + return yaml_parser_fetch_flow_collection_end(parser, + yaml_FLOW_MAPPING_END_TOKEN) + } // Is it the flow entry indicator? + if parser.buffer[parser.buffer_pos] == ',' { + return yaml_parser_fetch_flow_entry(parser) + } // Is it the block entry indicator? + if parser.buffer[parser.buffer_pos] == '-' && is_blankz(parser.buffer, parser.buffer_pos+1) { + return yaml_parser_fetch_block_entry(parser) + } // Is it the key indicator? + if parser.buffer[parser.buffer_pos] == '?' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_key(parser) + } // Is it the value indicator? + if parser.buffer[parser.buffer_pos] == ':' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_value(parser) + } // Is it an alias? + if parser.buffer[parser.buffer_pos] == '*' { + return yaml_parser_fetch_anchor(parser, yaml_ALIAS_TOKEN) + } // Is it an anchor? + if parser.buffer[parser.buffer_pos] == '&' { + return yaml_parser_fetch_anchor(parser, yaml_ANCHOR_TOKEN) + } // Is it a tag? + if parser.buffer[parser.buffer_pos] == '!' { + return yaml_parser_fetch_tag(parser) + } // Is it a literal scalar? + if parser.buffer[parser.buffer_pos] == '|' && parser.flow_level == 0 { + return yaml_parser_fetch_block_scalar(parser, true) + } // Is it a folded scalar? + if parser.buffer[parser.buffer_pos] == '>' && parser.flow_level == 0 { + return yaml_parser_fetch_block_scalar(parser, false) + } // Is it a single-quoted scalar? + if parser.buffer[parser.buffer_pos] == '\'' { + return yaml_parser_fetch_flow_scalar(parser, true) + } // Is it a double-quoted scalar? + if parser.buffer[parser.buffer_pos] == '"' { + return yaml_parser_fetch_flow_scalar(parser, false) + } // Is it a plain scalar? + // + // A plain scalar may start with any non-blank characters except + // + // '-', '?', ':', ',', '[', ']', '{', '}', + // '#', '&', '*', '!', '|', '>', '\'', '\"', + // '%', '@', '`'. + // + // In the block context (and, for the '-' indicator, in the flow context + // too), it may also start with the characters + // + // '-', '?', ':' + // + // if it is followed by a non-space character. + // + // The last rule is more restrictive than the specification requires. + // [Go] Make this logic more reasonable. + //switch parser.buffer[parser.buffer_pos] { + //case '-', '?', ':', ',', '?', '-', ',', ':', ']', '[', '}', '{', '&', '#', '!', '*', '>', '|', '"', '\'', '@', '%', '-', '`': + //} + if !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '-' || + parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':' || + parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '[' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || + parser.buffer[parser.buffer_pos] == '}' || parser.buffer[parser.buffer_pos] == '#' || + parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '*' || + parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '|' || + parser.buffer[parser.buffer_pos] == '>' || parser.buffer[parser.buffer_pos] == '\'' || + parser.buffer[parser.buffer_pos] == '"' || parser.buffer[parser.buffer_pos] == '%' || + parser.buffer[parser.buffer_pos] == '@' || parser.buffer[parser.buffer_pos] == '`') || + (parser.buffer[parser.buffer_pos] == '-' && !is_blank(parser.buffer, parser.buffer_pos+1)) || + (parser.flow_level == 0 && + (parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':') && + !is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_plain_scalar(parser) + } // If we don't determine the token type so far, it is an error. + return yaml_parser_set_scanner_error(parser, + "while scanning for the next token", parser.mark, + "found character that cannot start any token") + } func yaml_simple_key_is_valid(parser *yaml_parser_t, simple_key *yaml_simple_key_t) (valid, ok bool) { + if !simple_key.possible { + return false, true + } // The 1.2 specification says: + // + // "If the ? indicator is omitted, parsing needs to see past the + // implicit key to recognize it as such. To limit the amount of + // lookahead required, the “:” indicator must appear at most 1024 + // Unicode characters beyond the start of the key. In addition, the key + // is restricted to a single line." + // + if simple_key.mark.line < parser.mark.line || simple_key.mark.index+1024 < parser.mark.index { + // Check if the potential simple key to be removed is required. + if simple_key.required { + return false, yaml_parser_set_scanner_error(parser, + "while scanning a simple key", simple_key.mark, + "could not find expected ':'") + } + simple_key.possible = false + return false, true + } + return true, true + } // Check if a simple key may start at the current position and add it if + // needed. + func yaml_parser_save_simple_key(parser *yaml_parser_t) bool { + // A simple key is required at the current position if the scanner is in + // the block context and the current column coincides with the indentation + // level. required := parser.flow_level == 0 && parser.indent == parser.mark.column // + // If the current position may start a simple key, save it. + // + if parser.simple_key_allowed { + simple_key := yaml_simple_key_t{ - possible: true, - required: required, + + possible: true, + + required: required, + token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), - mark: parser.mark, + + mark: parser.mark, } if !yaml_parser_remove_simple_key(parser) { + return false + } + parser.simple_keys[len(parser.simple_keys)-1] = simple_key + parser.simple_keys_by_tok[simple_key.token_number] = len(parser.simple_keys) - 1 + } + return true + } // Remove a potential simple key at the current flow level. + func yaml_parser_remove_simple_key(parser *yaml_parser_t) bool { + i := len(parser.simple_keys) - 1 + if parser.simple_keys[i].possible { + // If the key is required, it is an error. + if parser.simple_keys[i].required { + return yaml_parser_set_scanner_error(parser, + "while scanning a simple key", parser.simple_keys[i].mark, + "could not find expected ':'") + } + // Remove the key from the stack. + parser.simple_keys[i].possible = false + delete(parser.simple_keys_by_tok, parser.simple_keys[i].token_number) + } + return true + } // max_flow_level limits the flow_level + const max_flow_level = 10000 // Increase the flow level and resize the simple key list if needed. + func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool { + // Reset the simple key on the next level. + parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{ - possible: false, - required: false, + + possible: false, + + required: false, + token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), - mark: parser.mark, + + mark: parser.mark, }) // Increase the flow level. + parser.flow_level++ + if parser.flow_level > max_flow_level { + return yaml_parser_set_scanner_error(parser, + "while increasing flow level", parser.simple_keys[len(parser.simple_keys)-1].mark, + fmt.Sprintf("exceeded max depth of %d", max_flow_level)) + } + return true + } // Decrease the flow level. + func yaml_parser_decrease_flow_level(parser *yaml_parser_t) bool { + if parser.flow_level > 0 { + parser.flow_level-- + last := len(parser.simple_keys) - 1 + delete(parser.simple_keys_by_tok, parser.simple_keys[last].token_number) + parser.simple_keys = parser.simple_keys[:last] + } + return true + } // max_indents limits the indents stack size + const max_indents = 10000 // Push the current indentation level to the stack and set the new level + // the current column is greater than the indentation level. In this case, + // append or insert the specified token into the token queue. + func yaml_parser_roll_indent(parser *yaml_parser_t, column, number int, typ yaml_token_type_t, mark yaml_mark_t) bool { + // In the flow context, do nothing. + if parser.flow_level > 0 { + return true + } if parser.indent < column { + // Push the current indentation level to the stack and set the new + // indentation level. + parser.indents = append(parser.indents, parser.indent) + parser.indent = column + if len(parser.indents) > max_indents { + return yaml_parser_set_scanner_error(parser, + "while increasing indent level", parser.simple_keys[len(parser.simple_keys)-1].mark, + fmt.Sprintf("exceeded max depth of %d", max_indents)) + } // Create a token and insert it into the queue. + token := yaml_token_t{ - typ: typ, + + typ: typ, + start_mark: mark, - end_mark: mark, + + end_mark: mark, } + if number > -1 { + number -= parser.tokens_parsed + } + yaml_insert_token(parser, number, &token) + } + return true + } // Pop indentation levels from the indents stack until the current level + // becomes less or equal to the column. For each indentation level, append + // the BLOCK-END token. + func yaml_parser_unroll_indent(parser *yaml_parser_t, column int) bool { + // In the flow context, do nothing. + if parser.flow_level > 0 { + return true + } // Loop through the indentation levels in the stack. + for parser.indent > column { + // Create a token and append it to the queue. + token := yaml_token_t{ - typ: yaml_BLOCK_END_TOKEN, + + typ: yaml_BLOCK_END_TOKEN, + start_mark: parser.mark, - end_mark: parser.mark, + + end_mark: parser.mark, } + yaml_insert_token(parser, -1, &token) // Pop the indentation level. + parser.indent = parser.indents[len(parser.indents)-1] + parser.indents = parser.indents[:len(parser.indents)-1] + } + return true + } // Initialize the scanner and produce the STREAM-START token. + func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool { // Set the initial indentation. + parser.indent = -1 // Initialize the simple key stack. + parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) parser.simple_keys_by_tok = make(map[int]int) // A simple key is allowed at the beginning of the stream. + parser.simple_key_allowed = true // We have started. + parser.stream_start_produced = true // Create the STREAM-START token and append it to the queue. + token := yaml_token_t{ - typ: yaml_STREAM_START_TOKEN, + + typ: yaml_STREAM_START_TOKEN, + start_mark: parser.mark, - end_mark: parser.mark, - encoding: parser.encoding, + + end_mark: parser.mark, + + encoding: parser.encoding, } + yaml_insert_token(parser, -1, &token) + return true + } // Produce the STREAM-END token and shut down the scanner. + func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool { // Force new line. + if parser.mark.column != 0 { + parser.mark.column = 0 + parser.mark.line++ + } // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1) { + return false + } // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } parser.simple_key_allowed = false // Create the STREAM-END token and append it to the queue. + token := yaml_token_t{ - typ: yaml_STREAM_END_TOKEN, + + typ: yaml_STREAM_END_TOKEN, + start_mark: parser.mark, - end_mark: parser.mark, + + end_mark: parser.mark, } + yaml_insert_token(parser, -1, &token) + return true + } // Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token. + func yaml_parser_fetch_directive(parser *yaml_parser_t) bool { + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1) { + return false + } // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } parser.simple_key_allowed = false // Create the YAML-DIRECTIVE or TAG-DIRECTIVE token. + token := yaml_token_t{} + if !yaml_parser_scan_directive(parser, &token) { + return false + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true + } // Produce the DOCUMENT-START or DOCUMENT-END token. + func yaml_parser_fetch_document_indicator(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1) { + return false + } // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } parser.simple_key_allowed = false // Consume the token. + start_mark := parser.mark skip(parser) + skip(parser) + skip(parser) end_mark := parser.mark // Create the DOCUMENT-START or DOCUMENT-END token. + token := yaml_token_t{ - typ: typ, + + typ: typ, + start_mark: start_mark, - end_mark: end_mark, + + end_mark: end_mark, } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true + } // Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token. + func yaml_parser_fetch_flow_collection_start(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // The indicators '[' and '{' may start a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } // Increase the flow level. + if !yaml_parser_increase_flow_level(parser) { + return false + } // A simple key may follow the indicators '[' and '{'. + parser.simple_key_allowed = true // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark // Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token. + token := yaml_token_t{ - typ: typ, + + typ: typ, + start_mark: start_mark, - end_mark: end_mark, + + end_mark: end_mark, } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true + } // Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token. + func yaml_parser_fetch_flow_collection_end(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // Reset any potential simple key on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } // Decrease the flow level. + if !yaml_parser_decrease_flow_level(parser) { + return false + } // No simple keys after the indicators ']' and '}'. + parser.simple_key_allowed = false // Consume the token. start_mark := parser.mark + skip(parser) + end_mark := parser.mark // Create the FLOW-SEQUENCE-END of FLOW-MAPPING-END token. + token := yaml_token_t{ - typ: typ, + + typ: typ, + start_mark: start_mark, - end_mark: end_mark, + + end_mark: end_mark, } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true + } // Produce the FLOW-ENTRY token. + func yaml_parser_fetch_flow_entry(parser *yaml_parser_t) bool { + // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } // Simple keys are allowed after ','. + parser.simple_key_allowed = true // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark // Create the FLOW-ENTRY token and append it to the queue. + token := yaml_token_t{ - typ: yaml_FLOW_ENTRY_TOKEN, + + typ: yaml_FLOW_ENTRY_TOKEN, + start_mark: start_mark, - end_mark: end_mark, + + end_mark: end_mark, } + yaml_insert_token(parser, -1, &token) + return true + } // Produce the BLOCK-ENTRY token. + func yaml_parser_fetch_block_entry(parser *yaml_parser_t) bool { + // Check if the scanner is in the block context. + if parser.flow_level == 0 { + // Check if we are allowed to start a new entry. + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "block sequence entries are not allowed in this context") + } + // Add the BLOCK-SEQUENCE-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_SEQUENCE_START_TOKEN, parser.mark) { + return false + } + } else { + // It is an error for the '-' indicator to occur in the flow context, + // but we let the Parser detect and report about it because the Parser + // is able to point to the context. + } // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } // Simple keys are allowed after '-'. + parser.simple_key_allowed = true // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark // Create the BLOCK-ENTRY token and append it to the queue. + token := yaml_token_t{ - typ: yaml_BLOCK_ENTRY_TOKEN, + + typ: yaml_BLOCK_ENTRY_TOKEN, + start_mark: start_mark, - end_mark: end_mark, + + end_mark: end_mark, } + yaml_insert_token(parser, -1, &token) + return true + } // Produce the KEY token. + func yaml_parser_fetch_key(parser *yaml_parser_t) bool { // In the block context, additional checks are required. + if parser.flow_level == 0 { + // Check if we are allowed to start a new key (not nessesary simple). + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "mapping keys are not allowed in this context") + } + // Add the BLOCK-MAPPING-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { + return false + } + } // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } // Simple keys are allowed after '?' in the block context. + parser.simple_key_allowed = parser.flow_level == 0 // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark // Create the KEY token and append it to the queue. + token := yaml_token_t{ - typ: yaml_KEY_TOKEN, + + typ: yaml_KEY_TOKEN, + start_mark: start_mark, - end_mark: end_mark, + + end_mark: end_mark, } + yaml_insert_token(parser, -1, &token) + return true + } // Produce the VALUE token. + func yaml_parser_fetch_value(parser *yaml_parser_t) bool { simple_key := &parser.simple_keys[len(parser.simple_keys)-1] // Have we found a simple key? + if valid, ok := yaml_simple_key_is_valid(parser, simple_key); !ok { + return false } else if valid { // Create the KEY token and insert it into the queue. + token := yaml_token_t{ - typ: yaml_KEY_TOKEN, + + typ: yaml_KEY_TOKEN, + start_mark: simple_key.mark, - end_mark: simple_key.mark, + + end_mark: simple_key.mark, } + yaml_insert_token(parser, simple_key.token_number-parser.tokens_parsed, &token) // In the block context, we may need to add the BLOCK-MAPPING-START token. + if !yaml_parser_roll_indent(parser, simple_key.mark.column, + simple_key.token_number, + yaml_BLOCK_MAPPING_START_TOKEN, simple_key.mark) { + return false + } // Remove the simple key. + simple_key.possible = false + delete(parser.simple_keys_by_tok, simple_key.token_number) // A simple key cannot follow another simple key. + parser.simple_key_allowed = false } else { + // The ':' indicator follows a complex key. // In the block context, extra checks are required. + if parser.flow_level == 0 { // Check if we are allowed to start a complex value. + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "mapping values are not allowed in this context") + } // Add the BLOCK-MAPPING-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { + return false + } + } // Simple keys after ':' are allowed in the block context. + parser.simple_key_allowed = parser.flow_level == 0 + } // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark // Create the VALUE token and append it to the queue. + token := yaml_token_t{ - typ: yaml_VALUE_TOKEN, + + typ: yaml_VALUE_TOKEN, + start_mark: start_mark, - end_mark: end_mark, + + end_mark: end_mark, } + yaml_insert_token(parser, -1, &token) + return true + } // Produce the ALIAS or ANCHOR token. + func yaml_parser_fetch_anchor(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // An anchor or an alias could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } // A simple key cannot follow an anchor or an alias. + parser.simple_key_allowed = false // Create the ALIAS or ANCHOR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_anchor(parser, &token, typ) { + return false + } + yaml_insert_token(parser, -1, &token) + return true + } // Produce the TAG token. + func yaml_parser_fetch_tag(parser *yaml_parser_t) bool { + // A tag could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } // A simple key cannot follow a tag. + parser.simple_key_allowed = false // Create the TAG token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_tag(parser, &token) { + return false + } + yaml_insert_token(parser, -1, &token) + return true + } // Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens. + func yaml_parser_fetch_block_scalar(parser *yaml_parser_t, literal bool) bool { + // Remove any potential simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } // A simple key may follow a block scalar. + parser.simple_key_allowed = true // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_block_scalar(parser, &token, literal) { + return false + } + yaml_insert_token(parser, -1, &token) + return true + } // Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens. + func yaml_parser_fetch_flow_scalar(parser *yaml_parser_t, single bool) bool { + // A plain scalar could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } // A simple key cannot follow a flow scalar. + parser.simple_key_allowed = false // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_flow_scalar(parser, &token, single) { + return false + } + yaml_insert_token(parser, -1, &token) + return true + } // Produce the SCALAR(...,plain) token. + func yaml_parser_fetch_plain_scalar(parser *yaml_parser_t) bool { + // A plain scalar could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } // A simple key cannot follow a flow scalar. + parser.simple_key_allowed = false // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_plain_scalar(parser, &token) { + return false + } + yaml_insert_token(parser, -1, &token) + return true + } // Eat whitespaces and comments until the next token is found. + func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool { // Until the next token is not found. + for { + // Allow the BOM mark to start a line. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.mark.column == 0 && is_bom(parser.buffer, parser.buffer_pos) { + skip(parser) + } // Eat whitespaces. + // Tabs are allowed: + // - in the flow context + // - in the block context, but not at the beginning of the line or + // after '-', '?', or ':' (complex value). + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } for parser.buffer[parser.buffer_pos] == ' ' || ((parser.flow_level > 0 || !parser.simple_key_allowed) && parser.buffer[parser.buffer_pos] == '\t') { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } // Eat a comment until a line break. + if parser.buffer[parser.buffer_pos] == '#' { + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } // If it is a line break, eat it. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) // In the block context, a new line may start a simple key. + if parser.flow_level == 0 { + parser.simple_key_allowed = true + } + } else { + break // We have found a token. + } + } return true + } // Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token. + // + // Scope: + // + // %YAML 1.1 # a comment \n + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // %TAG !yaml! tag:yaml.org,2002: \n + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool { + // Eat '%'. + start_mark := parser.mark + skip(parser) // Scan the directive name. + var name []byte + if !yaml_parser_scan_directive_name(parser, start_mark, &name) { + return false + } // Is it a YAML directive? + if bytes.Equal(name, []byte("YAML")) { + // Scan the VERSION directive value. + var major, minor int8 + if !yaml_parser_scan_version_directive_value(parser, start_mark, &major, &minor) { + return false + } + end_mark := parser.mark // Create a VERSION-DIRECTIVE token. + *token = yaml_token_t{ - typ: yaml_VERSION_DIRECTIVE_TOKEN, + + typ: yaml_VERSION_DIRECTIVE_TOKEN, + start_mark: start_mark, - end_mark: end_mark, - major: major, - minor: minor, + + end_mark: end_mark, + + major: major, + + minor: minor, } // Is it a TAG directive? + } else if bytes.Equal(name, []byte("TAG")) { + // Scan the TAG directive value. + var handle, prefix []byte + if !yaml_parser_scan_tag_directive_value(parser, start_mark, &handle, &prefix) { + return false + } + end_mark := parser.mark // Create a TAG-DIRECTIVE token. + *token = yaml_token_t{ - typ: yaml_TAG_DIRECTIVE_TOKEN, + + typ: yaml_TAG_DIRECTIVE_TOKEN, + start_mark: start_mark, - end_mark: end_mark, - value: handle, - prefix: prefix, + + end_mark: end_mark, + + value: handle, + + prefix: prefix, } // Unknown directive. + } else { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "found unknown directive name") + return false + } // Eat the rest of the line including any comments. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } if parser.buffer[parser.buffer_pos] == '#' { + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } // Check if we are at the end of the line. + if !is_breakz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "did not find expected comment or line break") + return false + } // Eat a line break. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } return true + } // Scan the directive name. + // + // Scope: + // + // %YAML 1.1 # a comment \n + // ^^^^ + // %TAG !yaml! tag:yaml.org,2002: \n + // ^^^ + func yaml_parser_scan_directive_name(parser *yaml_parser_t, start_mark yaml_mark_t, name *[]byte) bool { + // Consume the directive name. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } var s []byte + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } // Check if the name is empty. + if len(s) == 0 { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "could not find expected directive name") + return false + } // Check for an blank character after the name. + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "found unexpected non-alphabetical character") + return false + } + *name = s + return true + } // Scan the value of VERSION-DIRECTIVE. + // + // Scope: + // + // %YAML 1.1 # a comment \n + // ^^^^^^ + func yaml_parser_scan_version_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, major, minor *int8) bool { + // Eat whitespaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } // Consume the major version number. + if !yaml_parser_scan_version_directive_number(parser, start_mark, major) { + return false + } // Eat '.'. + if parser.buffer[parser.buffer_pos] != '.' { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "did not find expected digit or '.' character") + } skip(parser) // Consume the minor version number. + if !yaml_parser_scan_version_directive_number(parser, start_mark, minor) { + return false + } + return true + } const max_number_length = 2 // Scan the version number of VERSION-DIRECTIVE. + // + // Scope: + // + // %YAML 1.1 # a comment \n + // ^ + // %YAML 1.1 # a comment \n + // ^ + func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark yaml_mark_t, number *int8) bool { // Repeat while the next character is digit. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + var value, length int8 + for is_digit(parser.buffer, parser.buffer_pos) { + // Check if the number is too long. + length++ + if length > max_number_length { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "found extremely long version number") + } + value = value*10 + int8(as_digit(parser.buffer, parser.buffer_pos)) + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } // Check if the number was present. + if length == 0 { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "did not find expected version number") + } + *number = value + return true + } // Scan the value of a TAG-DIRECTIVE token. + // + // Scope: + // + // %TAG !yaml! tag:yaml.org,2002: \n + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + func yaml_parser_scan_tag_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, handle, prefix *[]byte) bool { + var handle_value, prefix_value []byte // Eat whitespaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } // Scan a handle. + if !yaml_parser_scan_tag_handle(parser, true, start_mark, &handle_value) { + return false + } // Expect a whitespace. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blank(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", + start_mark, "did not find expected whitespace") + return false + } // Eat whitespaces. + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } // Scan a prefix. + if !yaml_parser_scan_tag_uri(parser, true, nil, start_mark, &prefix_value) { + return false + } // Expect a whitespace or line break. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", + start_mark, "did not find expected whitespace or line break") + return false + } *handle = handle_value + *prefix = prefix_value + return true + } func yaml_parser_scan_anchor(parser *yaml_parser_t, token *yaml_token_t, typ yaml_token_type_t) bool { + var s []byte // Eat the indicator character. + start_mark := parser.mark + skip(parser) // Consume the value. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } end_mark := parser.mark /* + * Check if length of the anchor is greater than 0 and it is followed by + * a whitespace character or one of the indicators: + * + * '?', ':', ',', ']', '}', '%', '@', '`'. + */ if len(s) == 0 || + !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '?' || + parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == ',' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '}' || + parser.buffer[parser.buffer_pos] == '%' || parser.buffer[parser.buffer_pos] == '@' || + parser.buffer[parser.buffer_pos] == '`') { + context := "while scanning an alias" + if typ == yaml_ANCHOR_TOKEN { + context = "while scanning an anchor" + } + yaml_parser_set_scanner_error(parser, context, start_mark, + "did not find expected alphabetic or numeric character") + return false + } // Create a token. + *token = yaml_token_t{ - typ: typ, + + typ: typ, + start_mark: start_mark, - end_mark: end_mark, - value: s, + + end_mark: end_mark, + + value: s, } return true + } /* + * Scan a TAG token. + */ func yaml_parser_scan_tag(parser *yaml_parser_t, token *yaml_token_t) bool { + var handle, suffix []byte start_mark := parser.mark // Check if the tag is in the canonical form. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } if parser.buffer[parser.buffer_pos+1] == '<' { + // Keep the handle as '' // Eat '!<' + skip(parser) + skip(parser) // Consume the tag value. + if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { + return false + } // Check for '>' and eat it. + if parser.buffer[parser.buffer_pos] != '>' { + yaml_parser_set_scanner_error(parser, "while scanning a tag", + start_mark, "did not find the expected '>'") + return false + } skip(parser) + } else { + // The tag has either the '!suffix' or the '!handle!suffix' form. // First, try to scan a handle. + if !yaml_parser_scan_tag_handle(parser, false, start_mark, &handle) { + return false + } // Check if it is, indeed, handle. + if handle[0] == '!' && len(handle) > 1 && handle[len(handle)-1] == '!' { + // Scan the suffix now. + if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { + return false + } + } else { + // It wasn't a handle after all. Scan the rest of the tag. + if !yaml_parser_scan_tag_uri(parser, false, handle, start_mark, &suffix) { + return false + } // Set the handle to '!'. + handle = []byte{'!'} // A special case: the '!' tag. Set the handle to '' and the + // suffix to '!'. + if len(suffix) == 0 { + handle, suffix = suffix, handle + } + } + } // Check the character which ends the tag. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a tag", + start_mark, "did not find expected whitespace or line break") + return false + } end_mark := parser.mark // Create a token. + *token = yaml_token_t{ - typ: yaml_TAG_TOKEN, + + typ: yaml_TAG_TOKEN, + start_mark: start_mark, - end_mark: end_mark, - value: handle, - suffix: suffix, + + end_mark: end_mark, + + value: handle, + + suffix: suffix, } + return true + } // Scan a tag handle. + func yaml_parser_scan_tag_handle(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, handle *[]byte) bool { + // Check the initial '!' character. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.buffer[parser.buffer_pos] != '!' { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected '!'") + return false + } var s []byte // Copy the '!' character. + s = read(parser, s) // Copy all subsequent alphabetical and numerical characters. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } // Check if the trailing character is '!' and copy it. + if parser.buffer[parser.buffer_pos] == '!' { + s = read(parser, s) + } else { + // It's either the '!' tag or not really a tag handle. If it's a %TAG + // directive, it's an error. If it's a tag token, it must be a part of URI. + if directive && string(s) != "!" { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected '!'") + return false + } + } *handle = s + return true + } // Scan a tag. + func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte, start_mark yaml_mark_t, uri *[]byte) bool { + //size_t length = head ? strlen((char *)head) : 0 + var s []byte + hasTag := len(head) > 0 // Copy the head if needed. + // + // Note that we don't copy the leading '!' character. + if len(head) > 1 { + s = append(s, head[1:]...) + } // Scan the tag. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } // The set of characters that may appear in URI is as follows: + // + // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&', + // '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']', + // '%'. + // [Go] Convert this into more reasonable logic. + for is_alpha(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == ';' || + parser.buffer[parser.buffer_pos] == '/' || parser.buffer[parser.buffer_pos] == '?' || + parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == '@' || + parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '=' || + parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '$' || + parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '.' || + parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '~' || + parser.buffer[parser.buffer_pos] == '*' || parser.buffer[parser.buffer_pos] == '\'' || + parser.buffer[parser.buffer_pos] == '(' || parser.buffer[parser.buffer_pos] == ')' || + parser.buffer[parser.buffer_pos] == '[' || parser.buffer[parser.buffer_pos] == ']' || + parser.buffer[parser.buffer_pos] == '%' { + // Check if it is a URI-escape sequence. + if parser.buffer[parser.buffer_pos] == '%' { + if !yaml_parser_scan_uri_escapes(parser, directive, start_mark, &s) { + return false + } + } else { + s = read(parser, s) + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + hasTag = true + } if !hasTag { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected tag URI") + return false + } + *uri = s + return true + } // Decode an URI-escape sequence corresponding to a single UTF-8 character. + func yaml_parser_scan_uri_escapes(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, s *[]byte) bool { // Decode the required number of characters. + w := 1024 + for w > 0 { + // Check for a URI-escaped octet. + if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { + return false + } if !(parser.buffer[parser.buffer_pos] == '%' && + is_hex(parser.buffer, parser.buffer_pos+1) && + is_hex(parser.buffer, parser.buffer_pos+2)) { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find URI escaped octet") + } // Get the octet. + octet := byte((as_hex(parser.buffer, parser.buffer_pos+1) << 4) + as_hex(parser.buffer, parser.buffer_pos+2)) // If it is the leading octet, determine the length of the UTF-8 sequence. + if w == 1024 { + w = width(octet) + if w == 0 { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "found an incorrect leading UTF-8 octet") + } + } else { + // Check if the trailing octet is correct. + if octet&0xC0 != 0x80 { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "found an incorrect trailing UTF-8 octet") + } + } // Copy the octet and move the pointers. + *s = append(*s, octet) + skip(parser) + skip(parser) + skip(parser) + w-- + } + return true + } // Scan a block scalar. + func yaml_parser_scan_block_scalar(parser *yaml_parser_t, token *yaml_token_t, literal bool) bool { + // Eat the indicator '|' or '>'. + start_mark := parser.mark + skip(parser) // Scan the additional block scalar indicators. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } // Check for a chomping indicator. + var chomping, increment int + if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { + // Set the chomping method and eat the indicator. + if parser.buffer[parser.buffer_pos] == '+' { + chomping = +1 + } else { + chomping = -1 + } + skip(parser) // Check for an indentation indicator. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if is_digit(parser.buffer, parser.buffer_pos) { + // Check that the indentation is greater than 0. + if parser.buffer[parser.buffer_pos] == '0' { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found an indentation indicator equal to 0") + return false + } // Get the indentation level and eat the indicator. + increment = as_digit(parser.buffer, parser.buffer_pos) + skip(parser) + } } else if is_digit(parser.buffer, parser.buffer_pos) { + // Do the same as above, but in the opposite order. if parser.buffer[parser.buffer_pos] == '0' { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found an indentation indicator equal to 0") + return false + } + increment = as_digit(parser.buffer, parser.buffer_pos) + skip(parser) if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { + if parser.buffer[parser.buffer_pos] == '+' { + chomping = +1 + } else { + chomping = -1 + } + skip(parser) + } + } // Eat whitespaces and comments to the end of the line. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + if parser.buffer[parser.buffer_pos] == '#' { + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } // Check if we are at the end of the line. + if !is_breakz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "did not find expected comment or line break") + return false + } // Eat a line break. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } end_mark := parser.mark // Set the indentation level if it was specified. + var indent int + if increment > 0 { + if parser.indent >= 0 { + indent = parser.indent + increment + } else { + indent = increment + } + } // Scan the leading line breaks and determine the indentation level if needed. + var s, leading_break, trailing_breaks []byte + if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { + return false + } // Scan the block scalar content. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + var leading_blank, trailing_blank bool + for parser.mark.column == indent && !is_z(parser.buffer, parser.buffer_pos) { + // We are at the beginning of a non-empty line. // Is it a trailing whitespace? + trailing_blank = is_blank(parser.buffer, parser.buffer_pos) // Check if we need to fold the leading line break. + if !literal && !leading_blank && !trailing_blank && len(leading_break) > 0 && leading_break[0] == '\n' { + // Do we need to join the lines by space? + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } + } else { + s = append(s, leading_break...) + } + leading_break = leading_break[:0] // Append the remaining line breaks. + s = append(s, trailing_breaks...) + trailing_breaks = trailing_breaks[:0] // Is it a leading whitespace? + leading_blank = is_blank(parser.buffer, parser.buffer_pos) // Consume the current line. + for !is_breakz(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } // Consume the line break. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } leading_break = read_line(parser, leading_break) // Eat the following indentation spaces and line breaks. + if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { + return false + } + } // Chomp the tail. + if chomping != -1 { + s = append(s, leading_break...) + } + if chomping == 1 { + s = append(s, trailing_breaks...) + } // Create a token. + *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, + + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_LITERAL_SCALAR_STYLE, + + end_mark: end_mark, + + value: s, + + style: yaml_LITERAL_SCALAR_STYLE, } + if !literal { + token.style = yaml_FOLDED_SCALAR_STYLE + } + return true + } // Scan indentation spaces and line breaks for a block scalar. Determine the + // indentation level if needed. + func yaml_parser_scan_block_scalar_breaks(parser *yaml_parser_t, indent *int, breaks *[]byte, start_mark yaml_mark_t, end_mark *yaml_mark_t) bool { + *end_mark = parser.mark // Eat the indentation spaces and line breaks. + max_indent := 0 + for { + // Eat the indentation spaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for (*indent == 0 || parser.mark.column < *indent) && is_space(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + if parser.mark.column > max_indent { + max_indent = parser.mark.column + } // Check for a tab character messing the indentation. + if (*indent == 0 || parser.mark.column < *indent) && is_tab(parser.buffer, parser.buffer_pos) { + return yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found a tab character where an indentation space is expected") + } // Have we found a non-empty line? + if !is_break(parser.buffer, parser.buffer_pos) { + break + } // Consume the line break. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + // [Go] Should really be returning breaks instead. + *breaks = read_line(parser, *breaks) + *end_mark = parser.mark + } // Determine the indentation level if needed. + if *indent == 0 { + *indent = max_indent + if *indent < parser.indent+1 { + *indent = parser.indent + 1 + } + if *indent < 1 { + *indent = 1 + } + } + return true + } // Scan a quoted scalar. + func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, single bool) bool { + // Eat the left quote. + start_mark := parser.mark + skip(parser) // Consume the content of the quoted scalar. + var s, leading_break, trailing_breaks, whitespaces []byte + for { + // Check that there are no document indicators at the beginning of the line. + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } if parser.mark.column == 0 && + ((parser.buffer[parser.buffer_pos+0] == '-' && + parser.buffer[parser.buffer_pos+1] == '-' && + parser.buffer[parser.buffer_pos+2] == '-') || + (parser.buffer[parser.buffer_pos+0] == '.' && + parser.buffer[parser.buffer_pos+1] == '.' && + parser.buffer[parser.buffer_pos+2] == '.')) && + is_blankz(parser.buffer, parser.buffer_pos+3) { + yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", + start_mark, "found unexpected document indicator") + return false + } // Check for EOF. + if is_z(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", + start_mark, "found unexpected end of stream") + return false + } // Consume non-blank characters. + leading_blanks := false + for !is_blankz(parser.buffer, parser.buffer_pos) { + if single && parser.buffer[parser.buffer_pos] == '\'' && parser.buffer[parser.buffer_pos+1] == '\'' { + // Is is an escaped single quote. + s = append(s, '\'') + skip(parser) + skip(parser) } else if single && parser.buffer[parser.buffer_pos] == '\'' { + // It is a right single quote. + break + } else if !single && parser.buffer[parser.buffer_pos] == '"' { + // It is a right double quote. + break } else if !single && parser.buffer[parser.buffer_pos] == '\\' && is_break(parser.buffer, parser.buffer_pos+1) { + // It is an escaped line break. + if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { + return false + } + skip(parser) + skip_line(parser) + leading_blanks = true + break } else if !single && parser.buffer[parser.buffer_pos] == '\\' { + // It is an escape sequence. + code_length := 0 // Check the escape character. + switch parser.buffer[parser.buffer_pos+1] { + case '0': + s = append(s, 0) + case 'a': + s = append(s, '\x07') + case 'b': + s = append(s, '\x08') + case 't', '\t': + s = append(s, '\x09') + case 'n': + s = append(s, '\x0A') + case 'v': + s = append(s, '\x0B') + case 'f': + s = append(s, '\x0C') + case 'r': + s = append(s, '\x0D') + case 'e': + s = append(s, '\x1B') + case ' ': + s = append(s, '\x20') + case '"': + s = append(s, '"') + case '\'': + s = append(s, '\'') + case '\\': + s = append(s, '\\') + case 'N': // NEL (#x85) + s = append(s, '\xC2') + s = append(s, '\x85') + case '_': // #xA0 + s = append(s, '\xC2') + s = append(s, '\xA0') + case 'L': // LS (#x2028) + s = append(s, '\xE2') + s = append(s, '\x80') + s = append(s, '\xA8') + case 'P': // PS (#x2029) + s = append(s, '\xE2') + s = append(s, '\x80') + s = append(s, '\xA9') + case 'x': + code_length = 2 + case 'u': + code_length = 4 + case 'U': + code_length = 8 + default: + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "found unknown escape character") + return false + } skip(parser) + skip(parser) // Consume an arbitrary escape code. + if code_length > 0 { + var value int // Scan the character value. + if parser.unread < code_length && !yaml_parser_update_buffer(parser, code_length) { + return false + } + for k := 0; k < code_length; k++ { + if !is_hex(parser.buffer, parser.buffer_pos+k) { + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "did not find expected hexdecimal number") + return false + } + value = (value << 4) + as_hex(parser.buffer, parser.buffer_pos+k) + } // Check the value and write the character. + if (value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF { + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "found invalid Unicode character escape code") + return false + } + if value <= 0x7F { + s = append(s, byte(value)) + } else if value <= 0x7FF { + s = append(s, byte(0xC0+(value>>6))) + s = append(s, byte(0x80+(value&0x3F))) + } else if value <= 0xFFFF { + s = append(s, byte(0xE0+(value>>12))) + s = append(s, byte(0x80+((value>>6)&0x3F))) + s = append(s, byte(0x80+(value&0x3F))) + } else { + s = append(s, byte(0xF0+(value>>18))) + s = append(s, byte(0x80+((value>>12)&0x3F))) + s = append(s, byte(0x80+((value>>6)&0x3F))) + s = append(s, byte(0x80+(value&0x3F))) + } // Advance the pointer. + for k := 0; k < code_length; k++ { + skip(parser) + } + } + } else { + // It is a non-escaped non-blank character. + s = read(parser, s) + } + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + } if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } // Check if we are at the end of the scalar. + if single { + if parser.buffer[parser.buffer_pos] == '\'' { + break + } + } else { + if parser.buffer[parser.buffer_pos] == '"' { + break + } + } // Consume blank characters. + for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { + if is_blank(parser.buffer, parser.buffer_pos) { + // Consume a space or a tab character. + if !leading_blanks { + whitespaces = read(parser, whitespaces) + } else { + skip(parser) + } + } else { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } // Check if it is a first line break. + if !leading_blanks { + whitespaces = whitespaces[:0] + leading_break = read_line(parser, leading_break) + leading_blanks = true + } else { + trailing_breaks = read_line(parser, trailing_breaks) + } + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } // Join the whitespaces or fold line breaks. + if leading_blanks { + // Do we need to fold line breaks? + if len(leading_break) > 0 && leading_break[0] == '\n' { + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } else { + s = append(s, trailing_breaks...) + } + } else { + s = append(s, leading_break...) + s = append(s, trailing_breaks...) + } + trailing_breaks = trailing_breaks[:0] + leading_break = leading_break[:0] + } else { + s = append(s, whitespaces...) + whitespaces = whitespaces[:0] + } + } // Eat the right quote. + skip(parser) + end_mark := parser.mark // Create a token. + *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, + + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_SINGLE_QUOTED_SCALAR_STYLE, + + end_mark: end_mark, + + value: s, + + style: yaml_SINGLE_QUOTED_SCALAR_STYLE, } + if !single { + token.style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + return true + } // Scan a plain scalar. + func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) bool { var s, leading_break, trailing_breaks, whitespaces []byte + var leading_blanks bool + var indent = parser.indent + 1 start_mark := parser.mark + end_mark := parser.mark // Consume the content of the plain scalar. + for { + // Check for a document indicator. + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } + if parser.mark.column == 0 && + ((parser.buffer[parser.buffer_pos+0] == '-' && + parser.buffer[parser.buffer_pos+1] == '-' && + parser.buffer[parser.buffer_pos+2] == '-') || + (parser.buffer[parser.buffer_pos+0] == '.' && + parser.buffer[parser.buffer_pos+1] == '.' && + parser.buffer[parser.buffer_pos+2] == '.')) && + is_blankz(parser.buffer, parser.buffer_pos+3) { + break + } // Check for a comment. + if parser.buffer[parser.buffer_pos] == '#' { + break + } // Consume non-blank characters. + for !is_blankz(parser.buffer, parser.buffer_pos) { // Check for indicators that may end a plain scalar. + if (parser.buffer[parser.buffer_pos] == ':' && is_blankz(parser.buffer, parser.buffer_pos+1)) || + (parser.flow_level > 0 && + (parser.buffer[parser.buffer_pos] == ',' || + parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == '[' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || + parser.buffer[parser.buffer_pos] == '}')) { + break + } // Check if we need to join whitespaces and breaks. + if leading_blanks || len(whitespaces) > 0 { + if leading_blanks { + // Do we need to fold line breaks? + if leading_break[0] == '\n' { + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } else { + s = append(s, trailing_breaks...) + } + } else { + s = append(s, leading_break...) + s = append(s, trailing_breaks...) + } + trailing_breaks = trailing_breaks[:0] + leading_break = leading_break[:0] + leading_blanks = false + } else { + s = append(s, whitespaces...) + whitespaces = whitespaces[:0] + } + } // Copy the character. + s = read(parser, s) end_mark = parser.mark + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + } // Is it the end? + if !(is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos)) { + break + } // Consume blank characters. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { + if is_blank(parser.buffer, parser.buffer_pos) { // Check for tab characters that abuse indentation. + if leading_blanks && parser.mark.column < indent && is_tab(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", + start_mark, "found a tab character that violates indentation") + return false + } // Consume a space or a tab character. + if !leading_blanks { + whitespaces = read(parser, whitespaces) + } else { + skip(parser) + } + } else { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } // Check if it is a first line break. + if !leading_blanks { + whitespaces = whitespaces[:0] + leading_break = read_line(parser, leading_break) + leading_blanks = true + } else { + trailing_breaks = read_line(parser, trailing_breaks) + } + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } // Check indentation level. + if parser.flow_level == 0 && parser.mark.column < indent { + break + } + } // Create a token. + *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, + + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_PLAIN_SCALAR_STYLE, + + end_mark: end_mark, + + value: s, + + style: yaml_PLAIN_SCALAR_STYLE, } // Note that we change the 'simple_key_allowed' flag. + if leading_blanks { + parser.simple_key_allowed = true + } + return true + } diff --git a/vendor/gopkg.in/yaml.v2/sorter.go b/vendor/gopkg.in/yaml.v2/sorter.go index 2edd734..356b4ab 100644 --- a/vendor/gopkg.in/yaml.v2/sorter.go +++ b/vendor/gopkg.in/yaml.v2/sorter.go @@ -7,107 +7,206 @@ import ( type keyList []reflect.Value -func (l keyList) Len() int { return len(l) } +func (l keyList) Len() int { return len(l) } + func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } + func (l keyList) Less(i, j int) bool { + a := l[i] + b := l[j] + ak := a.Kind() + bk := b.Kind() + for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() { + a = a.Elem() + ak = a.Kind() + } + for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() { + b = b.Elem() + bk = b.Kind() + } + af, aok := keyFloat(a) + bf, bok := keyFloat(b) + if aok && bok { + if af != bf { + return af < bf + } + if ak != bk { + return ak < bk + } + return numLess(a, b) + } + if ak != reflect.String || bk != reflect.String { + return ak < bk + } + ar, br := []rune(a.String()), []rune(b.String()) + for i := 0; i < len(ar) && i < len(br); i++ { + if ar[i] == br[i] { + continue + } + al := unicode.IsLetter(ar[i]) + bl := unicode.IsLetter(br[i]) + if al && bl { + return ar[i] < br[i] + } + if al || bl { + return bl + } + var ai, bi int + var an, bn int64 + if ar[i] == '0' || br[i] == '0' { + for j := i - 1; j >= 0 && unicode.IsDigit(ar[j]); j-- { + if ar[j] != '0' { + an = 1 + bn = 1 + break + } + } + } + for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { + an = an*10 + int64(ar[ai]-'0') + } + for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ { + bn = bn*10 + int64(br[bi]-'0') + } + if an != bn { + return an < bn + } + if ai != bi { + return ai < bi + } + return ar[i] < br[i] + } + return len(ar) < len(br) + } // keyFloat returns a float value for v if it is a number/bool + // and whether it is a number/bool or not. + func keyFloat(v reflect.Value) (f float64, ok bool) { + switch v.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return float64(v.Int()), true + case reflect.Float32, reflect.Float64: + return v.Float(), true + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return float64(v.Uint()), true + case reflect.Bool: + if v.Bool() { + return 1, true + } + return 0, true + } + return 0, false + } // numLess returns whether a < b. + // a and b must necessarily have the same kind. + func numLess(a, b reflect.Value) bool { + switch a.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return a.Int() < b.Int() + case reflect.Float32, reflect.Float64: + return a.Float() < b.Float() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return a.Uint() < b.Uint() + case reflect.Bool: + return !a.Bool() && b.Bool() + } + panic("not a number") + } diff --git a/vendor/gopkg.in/yaml.v2/yaml.go b/vendor/gopkg.in/yaml.v2/yaml.go index 03756f6..637e7ae 100644 --- a/vendor/gopkg.in/yaml.v2/yaml.go +++ b/vendor/gopkg.in/yaml.v2/yaml.go @@ -1,8 +1,13 @@ // Package yaml implements YAML support for the Go language. + // + // Source code and other details for the project are available at GitHub: + // + // https://github.com/go-yaml/yaml + package yaml import ( @@ -15,237 +20,425 @@ import ( ) // MapSlice encodes and decodes as a YAML map. + // The order of keys is preserved when encoding and decoding. + type MapSlice []MapItem // MapItem is an item in a MapSlice. + type MapItem struct { Key, Value interface{} } // The Unmarshaler interface may be implemented by types to customize their + // behavior when being unmarshaled from a YAML document. The UnmarshalYAML + // method receives a function that may be called to unmarshal the original + // YAML value into a field or variable. It is safe to call the unmarshal + // function parameter more than once if necessary. + type Unmarshaler interface { UnmarshalYAML(unmarshal func(interface{}) error) error } // The Marshaler interface may be implemented by types to customize their + // behavior when being marshaled into a YAML document. The returned value + // is marshaled in place of the original value implementing Marshaler. + // + // If an error is returned by MarshalYAML, the marshaling procedure stops + // and returns with the provided error. + type Marshaler interface { MarshalYAML() (interface{}, error) } // Unmarshal decodes the first document found within the in byte slice + // and assigns decoded values into the out value. + // + // Maps and pointers (to a struct, string, int, etc) are accepted as out + // values. If an internal pointer within a struct is not initialized, + // the yaml package will initialize it if necessary for unmarshalling + // the provided data. The out parameter must not be nil. + // + // The type of the decoded values should be compatible with the respective + // values in out. If one or more values cannot be decoded due to a type + // mismatches, decoding continues partially until the end of the YAML + // content, and a *yaml.TypeError is returned with details for all + // missed values. + // + // Struct fields are only unmarshalled if they are exported (have an + // upper case first letter), and are unmarshalled using the field name + // lowercased as the default key. Custom keys may be defined via the + // "yaml" name in the field tag: the content preceding the first comma + // is used as the key, and the following comma-separated options are + // used to tweak the marshalling process (see Marshal). + // Conflicting names result in a runtime error. + // + // For example: + // + // type T struct { + // F int `yaml:"a,omitempty"` + // B int + // } + // var t T + // yaml.Unmarshal([]byte("a: 1\nb: 2"), &t) + // + // See the documentation of Marshal for the format of tags and a list of + // supported tag options. + func Unmarshal(in []byte, out interface{}) (err error) { + return unmarshal(in, out, false) + } // UnmarshalStrict is like Unmarshal except that any fields that are found + // in the data that do not have corresponding struct members, or mapping + // keys that are duplicates, will result in + // an error. + func UnmarshalStrict(in []byte, out interface{}) (err error) { + return unmarshal(in, out, true) + } // A Decoder reads and decodes YAML values from an input stream. + type Decoder struct { strict bool + parser *parser } // NewDecoder returns a new decoder that reads from r. + // + // The decoder introduces its own buffering and may read + // data from r beyond the YAML values requested. + func NewDecoder(r io.Reader) *Decoder { + return &Decoder{ + parser: newParserFromReader(r), } + } // SetStrict sets whether strict decoding behaviour is enabled when + // decoding items in the data (see UnmarshalStrict). By default, decoding is not strict. + func (dec *Decoder) SetStrict(strict bool) { + dec.strict = strict + } // Decode reads the next YAML-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 YAML into a Go value. + func (dec *Decoder) Decode(v interface{}) (err error) { + d := newDecoder(dec.strict) + defer handleErr(&err) + node := dec.parser.parse() + if node == nil { + return io.EOF + } + out := reflect.ValueOf(v) + if out.Kind() == reflect.Ptr && !out.IsNil() { + out = out.Elem() + } + d.unmarshal(node, out) + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil + } func unmarshal(in []byte, out interface{}, strict bool) (err error) { + defer handleErr(&err) + d := newDecoder(strict) + p := newParser(in) + defer p.destroy() + node := p.parse() + if node != nil { + v := reflect.ValueOf(out) + if v.Kind() == reflect.Ptr && !v.IsNil() { + v = v.Elem() + } + d.unmarshal(node, v) + } + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil + } // Marshal serializes the value provided into a YAML document. The structure + // of the generated document will reflect the structure of the value itself. + // Maps and pointers (to struct, string, int, etc) are accepted as the in value. + // + // Struct fields are only marshalled if they are exported (have an upper case + // first letter), and are marshalled using the field name lowercased as the + // default key. Custom keys may be defined via the "yaml" name in the field + // tag: the content preceding the first comma is used as the key, and the + // following comma-separated options are used to tweak the marshalling process. + // Conflicting names result in a runtime error. + // + // The field tag format accepted is: + // + // `(...) yaml:"[][,[,]]" (...)` + // + // The following flags are currently supported: + // + // omitempty Only include the field if it's not set to the zero + // value for the type or to empty slices or maps. + // Zero valued structs will be omitted if all their public + // fields are zero, unless they implement an IsZero + // method (see the IsZeroer interface type), in which + // case the field will be excluded if IsZero returns true. + // + // flow Marshal using a flow style (useful for structs, + // sequences and maps). + // + // inline Inline the field, which must be a struct or a map, + // causing all of its fields or keys to be processed as if + // they were part of the outer struct. For maps, keys must + // not conflict with the yaml keys of other struct fields. + // + // In addition, if the key is "-", the field is ignored. + // + // For example: + // + // type T struct { + // F int `yaml:"a,omitempty"` + // B int + // } + // yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" + // yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n" + func Marshal(in interface{}) (out []byte, err error) { + defer handleErr(&err) + e := newEncoder() + defer e.destroy() + e.marshalDoc("", reflect.ValueOf(in)) + e.finish() + out = e.out + return + } // An Encoder writes YAML values to an output stream. + type Encoder struct { encoder *encoder } // NewEncoder returns a new encoder that writes to w. + // The Encoder should be closed after use to flush all data + // to w. + func NewEncoder(w io.Writer) *Encoder { + return &Encoder{ + encoder: newEncoderWithWriter(w), } + } // Encode writes the YAML encoding of v to the stream. + // If multiple items are encoded to the stream, the + // second and subsequent document will be preceded + // with a "---" document separator, but the first will not. + // + // See the documentation for Marshal for details about the conversion of Go + // values to YAML. + func (e *Encoder) Encode(v interface{}) (err error) { + defer handleErr(&err) + e.encoder.marshalDoc("", reflect.ValueOf(v)) + return nil + } // Close closes the encoder by writing any remaining data. + // It does not write a stream terminating string "...". + func (e *Encoder) Close() (err error) { + defer handleErr(&err) + e.encoder.finish() + return nil + } func handleErr(err *error) { + if v := recover(); v != nil { + if e, ok := v.(yamlError); ok { + *err = e.err + } else { + panic(v) + } + } + } type yamlError struct { @@ -253,223 +446,386 @@ type yamlError struct { } func fail(err error) { + panic(yamlError{err}) + } func failf(format string, args ...interface{}) { + panic(yamlError{fmt.Errorf("yaml: "+format, args...)}) + } // A TypeError is returned by Unmarshal when one or more fields in + // the YAML document cannot be properly decoded into the requested + // types. When this error is returned, the value is still + // unmarshaled partially. + type TypeError struct { Errors []string } func (e *TypeError) Error() string { + return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n ")) + } // -------------------------------------------------------------------------- + // Maintain a mapping of keys to structure field indexes // The code in this section was copied from mgo/bson. // structInfo holds details for the serialization of fields of + // a given struct. + type structInfo struct { - FieldsMap map[string]fieldInfo + FieldsMap map[string]fieldInfo + FieldsList []fieldInfo // InlineMap is the number of the field in the struct that + // contains an ,inline map, or -1 if there's none. + InlineMap int } type fieldInfo struct { - Key string - Num int + Key string + + Num int + OmitEmpty bool - Flow bool + + Flow bool + // Id holds the unique field identifier, so we can cheaply + // check for field duplicates without maintaining an extra map. + Id int // Inline holds the field index if the field is part of an inlined struct. + Inline []int } var structMap = make(map[reflect.Type]*structInfo) + var fieldMapMutex sync.RWMutex func getStructInfo(st reflect.Type) (*structInfo, error) { + fieldMapMutex.RLock() + sinfo, found := structMap[st] + fieldMapMutex.RUnlock() + if found { + return sinfo, nil + } n := st.NumField() + fieldsMap := make(map[string]fieldInfo) + fieldsList := make([]fieldInfo, 0, n) + inlineMap := -1 + for i := 0; i != n; i++ { + field := st.Field(i) + if field.PkgPath != "" && !field.Anonymous { + continue // Private field + } info := fieldInfo{Num: i} tag := field.Tag.Get("yaml") + if tag == "" && strings.Index(string(field.Tag), ":") < 0 { + tag = string(field.Tag) + } + if tag == "-" { + continue + } inline := false + fields := strings.Split(tag, ",") + if len(fields) > 1 { + for _, flag := range fields[1:] { + switch flag { + case "omitempty": + info.OmitEmpty = true + case "flow": + info.Flow = true + case "inline": + inline = true + default: + return nil, errors.New(fmt.Sprintf("Unsupported flag %q in tag %q of type %s", flag, tag, st)) + } + } + tag = fields[0] + } if inline { + switch field.Type.Kind() { + case reflect.Map: + if inlineMap >= 0 { + return nil, errors.New("Multiple ,inline maps in struct " + st.String()) + } + if field.Type.Key() != reflect.TypeOf("") { + return nil, errors.New("Option ,inline needs a map with string keys in struct " + st.String()) + } + inlineMap = info.Num + case reflect.Struct: + sinfo, err := getStructInfo(field.Type) + if err != nil { + return nil, err + } + for _, finfo := range sinfo.FieldsList { + if _, found := fieldsMap[finfo.Key]; found { + msg := "Duplicated key '" + finfo.Key + "' in struct " + st.String() + return nil, errors.New(msg) + } + if finfo.Inline == nil { + finfo.Inline = []int{i, finfo.Num} + } else { + finfo.Inline = append([]int{i}, finfo.Inline...) + } + finfo.Id = len(fieldsList) + fieldsMap[finfo.Key] = finfo + fieldsList = append(fieldsList, finfo) + } + default: + //return nil, errors.New("Option ,inline needs a struct value or map field") + return nil, errors.New("Option ,inline needs a struct value field") + } + continue + } if tag != "" { + info.Key = tag + } else { + info.Key = strings.ToLower(field.Name) + } if _, found = fieldsMap[info.Key]; found { + msg := "Duplicated key '" + info.Key + "' in struct " + st.String() + return nil, errors.New(msg) + } info.Id = len(fieldsList) + fieldsList = append(fieldsList, info) + fieldsMap[info.Key] = info + } sinfo = &structInfo{ - FieldsMap: fieldsMap, + + FieldsMap: fieldsMap, + FieldsList: fieldsList, - InlineMap: inlineMap, + + InlineMap: inlineMap, } fieldMapMutex.Lock() + structMap[st] = sinfo + fieldMapMutex.Unlock() + return sinfo, nil + } // IsZeroer is used to check whether an object is zero to + // determine whether it should be omitted when marshaling + // with the omitempty flag. One notable implementation + // is time.Time. + type IsZeroer interface { IsZero() bool } func isZero(v reflect.Value) bool { + kind := v.Kind() + if z, ok := v.Interface().(IsZeroer); ok { + if (kind == reflect.Ptr || kind == reflect.Interface) && v.IsNil() { + return true + } + return z.IsZero() + } + switch kind { + case reflect.String: + return len(v.String()) == 0 + case reflect.Interface, reflect.Ptr: + return v.IsNil() + case reflect.Slice: + return v.Len() == 0 + case reflect.Map: + return v.Len() == 0 + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Struct: + vt := v.Type() + for i := v.NumField() - 1; i >= 0; i-- { + if vt.Field(i).PkgPath != "" { + continue // Private field + } + if !isZero(v.Field(i)) { + return false + } + } + return true + } + return false + } // FutureLineWrap globally disables line wrapping when encoding long strings. + // This is a temporary and thus deprecated method introduced to faciliate + // migration towards v3, which offers more control of line lengths on + // individual encodings, and has a default matching the behavior introduced + // by this function. + // + // The default formatting of v2 was erroneously changed in v2.3.0 and reverted + // in v2.4.0, at which point this function was introduced to help migration. + func FutureLineWrap() { + disableLineWrapping = true + } diff --git a/vendor/gopkg.in/yaml.v2/yamlh.go b/vendor/gopkg.in/yaml.v2/yamlh.go index 640f9d9..b375b13 100644 --- a/vendor/gopkg.in/yaml.v2/yamlh.go +++ b/vendor/gopkg.in/yaml.v2/yamlh.go @@ -6,62 +6,94 @@ import ( ) // The version directive data. + type yaml_version_directive_t struct { major int8 // The major version number. + minor int8 // The minor version number. + } // The tag directive data. + type yaml_tag_directive_t struct { handle []byte // The tag handle. + prefix []byte // The tag prefix. + } type yaml_encoding_t int // The stream encoding. + const ( + // Let the parser choose the encoding. + yaml_ANY_ENCODING yaml_encoding_t = iota - yaml_UTF8_ENCODING // The default UTF-8 encoding. + yaml_UTF8_ENCODING // The default UTF-8 encoding. + yaml_UTF16LE_ENCODING // The UTF-16-LE encoding with BOM. + yaml_UTF16BE_ENCODING // The UTF-16-BE encoding with BOM. + ) type yaml_break_t int // Line break types. + const ( + // Let the parser choose the break type. + yaml_ANY_BREAK yaml_break_t = iota - yaml_CR_BREAK // Use CR for line breaks (Mac style). - yaml_LN_BREAK // Use LN for line breaks (Unix style). + yaml_CR_BREAK // Use CR for line breaks (Mac style). + + yaml_LN_BREAK // Use LN for line breaks (Unix style). + yaml_CRLN_BREAK // Use CR LN for line breaks (DOS style). + ) type yaml_error_type_t int // Many bad things could happen with the parser and emitter. + const ( + // No error is produced. + yaml_NO_ERROR yaml_error_type_t = iota - yaml_MEMORY_ERROR // Cannot allocate or reallocate a block of memory. - yaml_READER_ERROR // Cannot read or decode the input stream. - yaml_SCANNER_ERROR // Cannot scan the input stream. - yaml_PARSER_ERROR // Cannot parse the input stream. + yaml_MEMORY_ERROR // Cannot allocate or reallocate a block of memory. + + yaml_READER_ERROR // Cannot read or decode the input stream. + + yaml_SCANNER_ERROR // Cannot scan the input stream. + + yaml_PARSER_ERROR // Cannot parse the input stream. + yaml_COMPOSER_ERROR // Cannot compose a YAML document. - yaml_WRITER_ERROR // Cannot write to the output stream. - yaml_EMITTER_ERROR // Cannot emit a YAML stream. + + yaml_WRITER_ERROR // Cannot write to the output stream. + + yaml_EMITTER_ERROR // Cannot emit a YAML stream. + ) // The pointer position. + type yaml_mark_t struct { - index int // The position index. - line int // The position line. + index int // The position index. + + line int // The position line. + column int // The position column. + } // Node Styles @@ -71,37 +103,55 @@ type yaml_style_t int8 type yaml_scalar_style_t yaml_style_t // Scalar styles. + const ( + // Let the emitter choose the style. + yaml_ANY_SCALAR_STYLE yaml_scalar_style_t = iota - yaml_PLAIN_SCALAR_STYLE // The plain scalar style. + yaml_PLAIN_SCALAR_STYLE // The plain scalar style. + yaml_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style. + yaml_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style. - yaml_LITERAL_SCALAR_STYLE // The literal scalar style. - yaml_FOLDED_SCALAR_STYLE // The folded scalar style. + + yaml_LITERAL_SCALAR_STYLE // The literal scalar style. + + yaml_FOLDED_SCALAR_STYLE // The folded scalar style. + ) type yaml_sequence_style_t yaml_style_t // Sequence styles. + const ( + // Let the emitter choose the style. + yaml_ANY_SEQUENCE_STYLE yaml_sequence_style_t = iota yaml_BLOCK_SEQUENCE_STYLE // The block sequence style. - yaml_FLOW_SEQUENCE_STYLE // The flow sequence style. + + yaml_FLOW_SEQUENCE_STYLE // The flow sequence style. + ) type yaml_mapping_style_t yaml_style_t // Mapping styles. + const ( + // Let the emitter choose the style. + yaml_ANY_MAPPING_STYLE yaml_mapping_style_t = iota yaml_BLOCK_MAPPING_STYLE // The block mapping style. - yaml_FLOW_MAPPING_STYLE // The flow mapping style. + + yaml_FLOW_MAPPING_STYLE // The flow mapping style. + ) // Tokens @@ -109,113 +159,191 @@ const ( type yaml_token_type_t int // Token types. + const ( + // An empty token. + yaml_NO_TOKEN yaml_token_type_t = iota yaml_STREAM_START_TOKEN // A STREAM-START token. - yaml_STREAM_END_TOKEN // A STREAM-END token. + + yaml_STREAM_END_TOKEN // A STREAM-END token. yaml_VERSION_DIRECTIVE_TOKEN // A VERSION-DIRECTIVE token. - yaml_TAG_DIRECTIVE_TOKEN // A TAG-DIRECTIVE token. - yaml_DOCUMENT_START_TOKEN // A DOCUMENT-START token. - yaml_DOCUMENT_END_TOKEN // A DOCUMENT-END token. + + yaml_TAG_DIRECTIVE_TOKEN // A TAG-DIRECTIVE token. + + yaml_DOCUMENT_START_TOKEN // A DOCUMENT-START token. + + yaml_DOCUMENT_END_TOKEN // A DOCUMENT-END token. yaml_BLOCK_SEQUENCE_START_TOKEN // A BLOCK-SEQUENCE-START token. - yaml_BLOCK_MAPPING_START_TOKEN // A BLOCK-SEQUENCE-END token. - yaml_BLOCK_END_TOKEN // A BLOCK-END token. + + yaml_BLOCK_MAPPING_START_TOKEN // A BLOCK-SEQUENCE-END token. + + yaml_BLOCK_END_TOKEN // A BLOCK-END token. yaml_FLOW_SEQUENCE_START_TOKEN // A FLOW-SEQUENCE-START token. - yaml_FLOW_SEQUENCE_END_TOKEN // A FLOW-SEQUENCE-END token. - yaml_FLOW_MAPPING_START_TOKEN // A FLOW-MAPPING-START token. - yaml_FLOW_MAPPING_END_TOKEN // A FLOW-MAPPING-END token. + + yaml_FLOW_SEQUENCE_END_TOKEN // A FLOW-SEQUENCE-END token. + + yaml_FLOW_MAPPING_START_TOKEN // A FLOW-MAPPING-START token. + + yaml_FLOW_MAPPING_END_TOKEN // A FLOW-MAPPING-END token. yaml_BLOCK_ENTRY_TOKEN // A BLOCK-ENTRY token. - yaml_FLOW_ENTRY_TOKEN // A FLOW-ENTRY token. - yaml_KEY_TOKEN // A KEY token. - yaml_VALUE_TOKEN // A VALUE token. - yaml_ALIAS_TOKEN // An ALIAS token. + yaml_FLOW_ENTRY_TOKEN // A FLOW-ENTRY token. + + yaml_KEY_TOKEN // A KEY token. + + yaml_VALUE_TOKEN // A VALUE token. + + yaml_ALIAS_TOKEN // An ALIAS token. + yaml_ANCHOR_TOKEN // An ANCHOR token. - yaml_TAG_TOKEN // A TAG token. + + yaml_TAG_TOKEN // A TAG token. + yaml_SCALAR_TOKEN // A SCALAR token. + ) func (tt yaml_token_type_t) String() string { + switch tt { + case yaml_NO_TOKEN: + return "yaml_NO_TOKEN" + case yaml_STREAM_START_TOKEN: + return "yaml_STREAM_START_TOKEN" + case yaml_STREAM_END_TOKEN: + return "yaml_STREAM_END_TOKEN" + case yaml_VERSION_DIRECTIVE_TOKEN: + return "yaml_VERSION_DIRECTIVE_TOKEN" + case yaml_TAG_DIRECTIVE_TOKEN: + return "yaml_TAG_DIRECTIVE_TOKEN" + case yaml_DOCUMENT_START_TOKEN: + return "yaml_DOCUMENT_START_TOKEN" + case yaml_DOCUMENT_END_TOKEN: + return "yaml_DOCUMENT_END_TOKEN" + case yaml_BLOCK_SEQUENCE_START_TOKEN: + return "yaml_BLOCK_SEQUENCE_START_TOKEN" + case yaml_BLOCK_MAPPING_START_TOKEN: + return "yaml_BLOCK_MAPPING_START_TOKEN" + case yaml_BLOCK_END_TOKEN: + return "yaml_BLOCK_END_TOKEN" + case yaml_FLOW_SEQUENCE_START_TOKEN: + return "yaml_FLOW_SEQUENCE_START_TOKEN" + case yaml_FLOW_SEQUENCE_END_TOKEN: + return "yaml_FLOW_SEQUENCE_END_TOKEN" + case yaml_FLOW_MAPPING_START_TOKEN: + return "yaml_FLOW_MAPPING_START_TOKEN" + case yaml_FLOW_MAPPING_END_TOKEN: + return "yaml_FLOW_MAPPING_END_TOKEN" + case yaml_BLOCK_ENTRY_TOKEN: + return "yaml_BLOCK_ENTRY_TOKEN" + case yaml_FLOW_ENTRY_TOKEN: + return "yaml_FLOW_ENTRY_TOKEN" + case yaml_KEY_TOKEN: + return "yaml_KEY_TOKEN" + case yaml_VALUE_TOKEN: + return "yaml_VALUE_TOKEN" + case yaml_ALIAS_TOKEN: + return "yaml_ALIAS_TOKEN" + case yaml_ANCHOR_TOKEN: + return "yaml_ANCHOR_TOKEN" + case yaml_TAG_TOKEN: + return "yaml_TAG_TOKEN" + case yaml_SCALAR_TOKEN: + return "yaml_SCALAR_TOKEN" + } + return "" + } // The token structure. + type yaml_token_t struct { + // The token type. + typ yaml_token_type_t // The start/end of the token. + start_mark, end_mark yaml_mark_t // The stream encoding (for yaml_STREAM_START_TOKEN). + encoding yaml_encoding_t // The alias/anchor/scalar value or tag/tag directive handle + // (for yaml_ALIAS_TOKEN, yaml_ANCHOR_TOKEN, yaml_SCALAR_TOKEN, yaml_TAG_TOKEN, yaml_TAG_DIRECTIVE_TOKEN). + value []byte // The tag suffix (for yaml_TAG_TOKEN). + suffix []byte // The tag directive prefix (for yaml_TAG_DIRECTIVE_TOKEN). + prefix []byte // The scalar style (for yaml_SCALAR_TOKEN). + style yaml_scalar_style_t // The version directive major/minor (for yaml_VERSION_DIRECTIVE_TOKEN). + major, minor int8 } @@ -224,306 +352,501 @@ type yaml_token_t struct { type yaml_event_type_t int8 // Event types. + const ( + // An empty event. + yaml_NO_EVENT yaml_event_type_t = iota - yaml_STREAM_START_EVENT // A STREAM-START event. - yaml_STREAM_END_EVENT // A STREAM-END event. + yaml_STREAM_START_EVENT // A STREAM-START event. + + yaml_STREAM_END_EVENT // A STREAM-END event. + yaml_DOCUMENT_START_EVENT // A DOCUMENT-START event. - yaml_DOCUMENT_END_EVENT // A DOCUMENT-END event. - yaml_ALIAS_EVENT // An ALIAS event. - yaml_SCALAR_EVENT // A SCALAR event. + + yaml_DOCUMENT_END_EVENT // A DOCUMENT-END event. + + yaml_ALIAS_EVENT // An ALIAS event. + + yaml_SCALAR_EVENT // A SCALAR event. + yaml_SEQUENCE_START_EVENT // A SEQUENCE-START event. - yaml_SEQUENCE_END_EVENT // A SEQUENCE-END event. - yaml_MAPPING_START_EVENT // A MAPPING-START event. - yaml_MAPPING_END_EVENT // A MAPPING-END event. + + yaml_SEQUENCE_END_EVENT // A SEQUENCE-END event. + + yaml_MAPPING_START_EVENT // A MAPPING-START event. + + yaml_MAPPING_END_EVENT // A MAPPING-END event. + ) var eventStrings = []string{ - yaml_NO_EVENT: "none", - yaml_STREAM_START_EVENT: "stream start", - yaml_STREAM_END_EVENT: "stream end", + + yaml_NO_EVENT: "none", + + yaml_STREAM_START_EVENT: "stream start", + + yaml_STREAM_END_EVENT: "stream end", + yaml_DOCUMENT_START_EVENT: "document start", - yaml_DOCUMENT_END_EVENT: "document end", - yaml_ALIAS_EVENT: "alias", - yaml_SCALAR_EVENT: "scalar", + + yaml_DOCUMENT_END_EVENT: "document end", + + yaml_ALIAS_EVENT: "alias", + + yaml_SCALAR_EVENT: "scalar", + yaml_SEQUENCE_START_EVENT: "sequence start", - yaml_SEQUENCE_END_EVENT: "sequence end", - yaml_MAPPING_START_EVENT: "mapping start", - yaml_MAPPING_END_EVENT: "mapping end", + + yaml_SEQUENCE_END_EVENT: "sequence end", + + yaml_MAPPING_START_EVENT: "mapping start", + + yaml_MAPPING_END_EVENT: "mapping end", } func (e yaml_event_type_t) String() string { + if e < 0 || int(e) >= len(eventStrings) { + return fmt.Sprintf("unknown event %d", e) + } + return eventStrings[e] + } // The event structure. + type yaml_event_t struct { // The event type. + typ yaml_event_type_t // The start and end of the event. + start_mark, end_mark yaml_mark_t // The document encoding (for yaml_STREAM_START_EVENT). + encoding yaml_encoding_t // The version directive (for yaml_DOCUMENT_START_EVENT). + version_directive *yaml_version_directive_t // The list of tag directives (for yaml_DOCUMENT_START_EVENT). + tag_directives []yaml_tag_directive_t // The anchor (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_ALIAS_EVENT). + anchor []byte // The tag (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). + tag []byte // The scalar value (for yaml_SCALAR_EVENT). + value []byte // Is the document start/end indicator implicit, or the tag optional? + // (for yaml_DOCUMENT_START_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_SCALAR_EVENT). + implicit bool // Is the tag optional for any non-plain style? (for yaml_SCALAR_EVENT). + quoted_implicit bool // The style (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). + style yaml_style_t } -func (e *yaml_event_t) scalar_style() yaml_scalar_style_t { return yaml_scalar_style_t(e.style) } +func (e *yaml_event_t) scalar_style() yaml_scalar_style_t { return yaml_scalar_style_t(e.style) } + func (e *yaml_event_t) sequence_style() yaml_sequence_style_t { return yaml_sequence_style_t(e.style) } -func (e *yaml_event_t) mapping_style() yaml_mapping_style_t { return yaml_mapping_style_t(e.style) } + +func (e *yaml_event_t) mapping_style() yaml_mapping_style_t { return yaml_mapping_style_t(e.style) } // Nodes const ( - yaml_NULL_TAG = "tag:yaml.org,2002:null" // The tag !!null with the only possible value: null. - yaml_BOOL_TAG = "tag:yaml.org,2002:bool" // The tag !!bool with the values: true and false. - yaml_STR_TAG = "tag:yaml.org,2002:str" // The tag !!str for string values. - yaml_INT_TAG = "tag:yaml.org,2002:int" // The tag !!int for integer values. - yaml_FLOAT_TAG = "tag:yaml.org,2002:float" // The tag !!float for float values. + yaml_NULL_TAG = "tag:yaml.org,2002:null" // The tag !!null with the only possible value: null. + + yaml_BOOL_TAG = "tag:yaml.org,2002:bool" // The tag !!bool with the values: true and false. + + yaml_STR_TAG = "tag:yaml.org,2002:str" // The tag !!str for string values. + + yaml_INT_TAG = "tag:yaml.org,2002:int" // The tag !!int for integer values. + + yaml_FLOAT_TAG = "tag:yaml.org,2002:float" // The tag !!float for float values. + yaml_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp" // The tag !!timestamp for date and time values. yaml_SEQ_TAG = "tag:yaml.org,2002:seq" // The tag !!seq is used to denote sequences. + yaml_MAP_TAG = "tag:yaml.org,2002:map" // The tag !!map is used to denote mapping. // Not in original libyaml. - yaml_BINARY_TAG = "tag:yaml.org,2002:binary" - yaml_MERGE_TAG = "tag:yaml.org,2002:merge" - yaml_DEFAULT_SCALAR_TAG = yaml_STR_TAG // The default scalar tag is !!str. + yaml_BINARY_TAG = "tag:yaml.org,2002:binary" + + yaml_MERGE_TAG = "tag:yaml.org,2002:merge" + + yaml_DEFAULT_SCALAR_TAG = yaml_STR_TAG // The default scalar tag is !!str. + yaml_DEFAULT_SEQUENCE_TAG = yaml_SEQ_TAG // The default sequence tag is !!seq. - yaml_DEFAULT_MAPPING_TAG = yaml_MAP_TAG // The default mapping tag is !!map. + + yaml_DEFAULT_MAPPING_TAG = yaml_MAP_TAG // The default mapping tag is !!map. + ) type yaml_node_type_t int // Node types. + const ( + // An empty node. + yaml_NO_NODE yaml_node_type_t = iota - yaml_SCALAR_NODE // A scalar node. + yaml_SCALAR_NODE // A scalar node. + yaml_SEQUENCE_NODE // A sequence node. - yaml_MAPPING_NODE // A mapping node. + + yaml_MAPPING_NODE // A mapping node. + ) // An element of a sequence node. + type yaml_node_item_t int // An element of a mapping node. + type yaml_node_pair_t struct { - key int // The key of the element. + key int // The key of the element. + value int // The value of the element. + } // The node structure. + type yaml_node_t struct { typ yaml_node_type_t // The node type. - tag []byte // The node tag. + + tag []byte // The node tag. // The node data. // The scalar parameters (for yaml_SCALAR_NODE). + scalar struct { - value []byte // The scalar value. - length int // The length of the scalar value. - style yaml_scalar_style_t // The scalar style. + value []byte // The scalar value. + + length int // The length of the scalar value. + + style yaml_scalar_style_t // The scalar style. + } // The sequence parameters (for YAML_SEQUENCE_NODE). + sequence struct { - items_data []yaml_node_item_t // The stack of sequence items. - style yaml_sequence_style_t // The sequence style. + items_data []yaml_node_item_t // The stack of sequence items. + + style yaml_sequence_style_t // The sequence style. + } // The mapping parameters (for yaml_MAPPING_NODE). + mapping struct { - pairs_data []yaml_node_pair_t // The stack of mapping pairs (key, value). - pairs_start *yaml_node_pair_t // The beginning of the stack. - pairs_end *yaml_node_pair_t // The end of the stack. - pairs_top *yaml_node_pair_t // The top of the stack. - style yaml_mapping_style_t // The mapping style. + pairs_data []yaml_node_pair_t // The stack of mapping pairs (key, value). + + pairs_start *yaml_node_pair_t // The beginning of the stack. + + pairs_end *yaml_node_pair_t // The end of the stack. + + pairs_top *yaml_node_pair_t // The top of the stack. + + style yaml_mapping_style_t // The mapping style. + } start_mark yaml_mark_t // The beginning of the node. - end_mark yaml_mark_t // The end of the node. + + end_mark yaml_mark_t // The end of the node. } // The document structure. + type yaml_document_t struct { // The document nodes. + nodes []yaml_node_t // The version directive. + version_directive *yaml_version_directive_t // The list of tag directives. - tag_directives_data []yaml_tag_directive_t + + tag_directives_data []yaml_tag_directive_t + tag_directives_start int // The beginning of the tag directives list. - tag_directives_end int // The end of the tag directives list. + + tag_directives_end int // The end of the tag directives list. start_implicit int // Is the document start indicator implicit? - end_implicit int // Is the document end indicator implicit? + + end_implicit int // Is the document end indicator implicit? // The start/end of the document. + start_mark, end_mark yaml_mark_t } // The prototype of a read handler. + // + // The read handler is called when the parser needs to read more bytes from the + // source. The handler should write not more than size bytes to the buffer. + // The number of written bytes should be set to the size_read variable. + // + // [in,out] data A pointer to an application data specified by + // + // yaml_parser_set_input(). + // + // [out] buffer The buffer to write the data from the source. + // [in] size The size of the buffer. + // [out] size_read The actual number of bytes read from the source. + // + // On success, the handler should return 1. If the handler failed, + // the returned value should be 0. On EOF, the handler should set the + // size_read to 0 and return 1. + type yaml_read_handler_t func(parser *yaml_parser_t, buffer []byte) (n int, err error) // This structure holds information about a potential simple key. + type yaml_simple_key_t struct { - possible bool // Is a simple key possible? - required bool // Is a simple key required? - token_number int // The number of the token. - mark yaml_mark_t // The position mark. + possible bool // Is a simple key possible? + + required bool // Is a simple key required? + + token_number int // The number of the token. + + mark yaml_mark_t // The position mark. + } // The states of the parser. + type yaml_parser_state_t int const ( yaml_PARSE_STREAM_START_STATE yaml_parser_state_t = iota - yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE // Expect the beginning of an implicit document. - yaml_PARSE_DOCUMENT_START_STATE // Expect DOCUMENT-START. - yaml_PARSE_DOCUMENT_CONTENT_STATE // Expect the content of a document. - yaml_PARSE_DOCUMENT_END_STATE // Expect DOCUMENT-END. - yaml_PARSE_BLOCK_NODE_STATE // Expect a block node. + yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE // Expect the beginning of an implicit document. + + yaml_PARSE_DOCUMENT_START_STATE // Expect DOCUMENT-START. + + yaml_PARSE_DOCUMENT_CONTENT_STATE // Expect the content of a document. + + yaml_PARSE_DOCUMENT_END_STATE // Expect DOCUMENT-END. + + yaml_PARSE_BLOCK_NODE_STATE // Expect a block node. + yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE // Expect a block node or indentless sequence. - yaml_PARSE_FLOW_NODE_STATE // Expect a flow node. - yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a block sequence. - yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE // Expect an entry of a block sequence. - yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE // Expect an entry of an indentless sequence. - yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. - yaml_PARSE_BLOCK_MAPPING_KEY_STATE // Expect a block mapping key. - yaml_PARSE_BLOCK_MAPPING_VALUE_STATE // Expect a block mapping value. - yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a flow sequence. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE // Expect an entry of a flow sequence. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE // Expect a key of an ordered mapping. + + yaml_PARSE_FLOW_NODE_STATE // Expect a flow node. + + yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a block sequence. + + yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE // Expect an entry of a block sequence. + + yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE // Expect an entry of an indentless sequence. + + yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. + + yaml_PARSE_BLOCK_MAPPING_KEY_STATE // Expect a block mapping key. + + yaml_PARSE_BLOCK_MAPPING_VALUE_STATE // Expect a block mapping value. + + yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a flow sequence. + + yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE // Expect an entry of a flow sequence. + + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE // Expect a key of an ordered mapping. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE // Expect a value of an ordered mapping. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE // Expect the and of an ordered mapping entry. - yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. - yaml_PARSE_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. - yaml_PARSE_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. - yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE // Expect an empty value of a flow mapping. - yaml_PARSE_END_STATE // Expect nothing. + + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE // Expect the and of an ordered mapping entry. + + yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. + + yaml_PARSE_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. + + yaml_PARSE_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. + + yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE // Expect an empty value of a flow mapping. + + yaml_PARSE_END_STATE // Expect nothing. + ) func (ps yaml_parser_state_t) String() string { + switch ps { + case yaml_PARSE_STREAM_START_STATE: + return "yaml_PARSE_STREAM_START_STATE" + case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: + return "yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE" + case yaml_PARSE_DOCUMENT_START_STATE: + return "yaml_PARSE_DOCUMENT_START_STATE" + case yaml_PARSE_DOCUMENT_CONTENT_STATE: + return "yaml_PARSE_DOCUMENT_CONTENT_STATE" + case yaml_PARSE_DOCUMENT_END_STATE: + return "yaml_PARSE_DOCUMENT_END_STATE" + case yaml_PARSE_BLOCK_NODE_STATE: + return "yaml_PARSE_BLOCK_NODE_STATE" + case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: + return "yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE" + case yaml_PARSE_FLOW_NODE_STATE: + return "yaml_PARSE_FLOW_NODE_STATE" + case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: + return "yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE" + case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: + return "yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE" + case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: + return "yaml_PARSE_BLOCK_MAPPING_KEY_STATE" + case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: + return "yaml_PARSE_BLOCK_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE" + case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: + return "yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE" + case yaml_PARSE_FLOW_MAPPING_KEY_STATE: + return "yaml_PARSE_FLOW_MAPPING_KEY_STATE" + case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: + return "yaml_PARSE_FLOW_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: + return "yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE" + case yaml_PARSE_END_STATE: + return "yaml_PARSE_END_STATE" + } + return "" + } // This structure holds aliases data. + type yaml_alias_data_t struct { - anchor []byte // The anchor. - index int // The node id. - mark yaml_mark_t // The anchor mark. + anchor []byte // The anchor. + + index int // The node id. + + mark yaml_mark_t // The anchor mark. + } // The parser structure. + // + // All members are internal. Manage the structure using the + // yaml_parser_ family of functions. + type yaml_parser_t struct { // Error handling @@ -533,12 +856,17 @@ type yaml_parser_t struct { problem string // Error description. // The byte about which the problem occurred. + problem_offset int - problem_value int - problem_mark yaml_mark_t + + problem_value int + + problem_mark yaml_mark_t // The error context. - context string + + context string + context_mark yaml_mark_t // Reader stuff @@ -546,48 +874,63 @@ type yaml_parser_t struct { read_handler yaml_read_handler_t // Read handler. input_reader io.Reader // File input data. - input []byte // String input data. - input_pos int + + input []byte // String input data. + + input_pos int eof bool // EOF flag - buffer []byte // The working buffer. - buffer_pos int // The current position of the buffer. + buffer []byte // The working buffer. + + buffer_pos int // The current position of the buffer. unread int // The number of unread characters in the buffer. - raw_buffer []byte // The raw buffer. - raw_buffer_pos int // The current position of the buffer. + raw_buffer []byte // The raw buffer. + + raw_buffer_pos int // The current position of the buffer. encoding yaml_encoding_t // The input encoding. - offset int // The offset of the current position (in bytes). - mark yaml_mark_t // The mark of the current position. + offset int // The offset of the current position (in bytes). + + mark yaml_mark_t // The mark of the current position. // Scanner stuff stream_start_produced bool // Have we started to scan the input stream? - stream_end_produced bool // Have we reached the end of the input stream? + + stream_end_produced bool // Have we reached the end of the input stream? flow_level int // The number of unclosed '[' and '{' indicators. - tokens []yaml_token_t // The tokens queue. - tokens_head int // The head of the tokens queue. - tokens_parsed int // The number of tokens fetched from the queue. - token_available bool // Does the tokens queue contain a token ready for dequeueing. + tokens []yaml_token_t // The tokens queue. + + tokens_head int // The head of the tokens queue. + + tokens_parsed int // The number of tokens fetched from the queue. + + token_available bool // Does the tokens queue contain a token ready for dequeueing. + + indent int // The current indentation level. - indent int // The current indentation level. indents []int // The indentation levels stack. - simple_key_allowed bool // May a simple key occur at the current position? - simple_keys []yaml_simple_key_t // The stack of simple keys. - simple_keys_by_tok map[int]int // possible simple_key indexes indexed by token_number + simple_key_allowed bool // May a simple key occur at the current position? + + simple_keys []yaml_simple_key_t // The stack of simple keys. + + simple_keys_by_tok map[int]int // possible simple_key indexes indexed by token_number // Parser stuff - state yaml_parser_state_t // The current parser state. - states []yaml_parser_state_t // The parser states stack. - marks []yaml_mark_t // The stack of marks. + state yaml_parser_state_t // The current parser state. + + states []yaml_parser_state_t // The parser states stack. + + marks []yaml_mark_t // The stack of marks. + tag_directives []yaml_tag_directive_t // The list of TAG directives. // Dumper stuff @@ -595,92 +938,142 @@ type yaml_parser_t struct { aliases []yaml_alias_data_t // The alias data. document *yaml_document_t // The currently parsed document. + } // Emitter Definitions // The prototype of a write handler. + // + // The write handler is called when the emitter needs to flush the accumulated + // characters to the output. The handler should write @a size bytes of the + // @a buffer to the output. + // + // @param[in,out] data A pointer to an application data specified by + // + // yaml_emitter_set_output(). + // + // @param[in] buffer The buffer with bytes to be written. + // @param[in] size The size of the buffer. + // + // @returns On success, the handler should return @c 1. If the handler failed, + // the returned value should be @c 0. + type yaml_write_handler_t func(emitter *yaml_emitter_t, buffer []byte) error type yaml_emitter_state_t int // The emitter states. + const ( + // Expect STREAM-START. + yaml_EMIT_STREAM_START_STATE yaml_emitter_state_t = iota - yaml_EMIT_FIRST_DOCUMENT_START_STATE // Expect the first DOCUMENT-START or STREAM-END. - yaml_EMIT_DOCUMENT_START_STATE // Expect DOCUMENT-START or STREAM-END. - yaml_EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document. - yaml_EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END. - yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence. - yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence. - yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. - yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a block sequence. - yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE // Expect an item of a block sequence. - yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. - yaml_EMIT_BLOCK_MAPPING_KEY_STATE // Expect the key of a block mapping. + yaml_EMIT_FIRST_DOCUMENT_START_STATE // Expect the first DOCUMENT-START or STREAM-END. + + yaml_EMIT_DOCUMENT_START_STATE // Expect DOCUMENT-START or STREAM-END. + + yaml_EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document. + + yaml_EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END. + + yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence. + + yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence. + + yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. + + yaml_EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. + + yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping. + + yaml_EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. + + yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a block sequence. + + yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE // Expect an item of a block sequence. + + yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. + + yaml_EMIT_BLOCK_MAPPING_KEY_STATE // Expect the key of a block mapping. + yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a block mapping. - yaml_EMIT_BLOCK_MAPPING_VALUE_STATE // Expect a value of a block mapping. - yaml_EMIT_END_STATE // Expect nothing. + + yaml_EMIT_BLOCK_MAPPING_VALUE_STATE // Expect a value of a block mapping. + + yaml_EMIT_END_STATE // Expect nothing. + ) // The emitter structure. + // + // All members are internal. Manage the structure using the @c yaml_emitter_ + // family of functions. + type yaml_emitter_t struct { // Error handling - error yaml_error_type_t // Error type. - problem string // Error description. + error yaml_error_type_t // Error type. + + problem string // Error description. // Writer stuff write_handler yaml_write_handler_t // Write handler. - output_buffer *[]byte // String output data. + output_buffer *[]byte // String output data. + output_writer io.Writer // File output data. - buffer []byte // The working buffer. - buffer_pos int // The current position of the buffer. + buffer []byte // The working buffer. - raw_buffer []byte // The raw buffer. - raw_buffer_pos int // The current position of the buffer. + buffer_pos int // The current position of the buffer. + + raw_buffer []byte // The raw buffer. + + raw_buffer_pos int // The current position of the buffer. encoding yaml_encoding_t // The stream encoding. // Emitter stuff - canonical bool // If the output is in the canonical style? - best_indent int // The number of indentation spaces. - best_width int // The preferred width of the output lines. - unicode bool // Allow unescaped non-ASCII characters? - line_break yaml_break_t // The preferred line break. + canonical bool // If the output is in the canonical style? + + best_indent int // The number of indentation spaces. + + best_width int // The preferred width of the output lines. + + unicode bool // Allow unescaped non-ASCII characters? + + line_break yaml_break_t // The preferred line break. + + state yaml_emitter_state_t // The current emitter state. - state yaml_emitter_state_t // The current emitter state. states []yaml_emitter_state_t // The stack of states. - events []yaml_event_t // The event queue. - events_head int // The head of the event queue. + events []yaml_event_t // The event queue. + + events_head int // The head of the event queue. indents []int // The stack of indentation levels. @@ -690,53 +1083,80 @@ type yaml_emitter_t struct { flow_level int // The current flow level. - root_context bool // Is it the document root context? - sequence_context bool // Is it a sequence context? - mapping_context bool // Is it a mapping context? + root_context bool // Is it the document root context? + + sequence_context bool // Is it a sequence context? + + mapping_context bool // Is it a mapping context? + simple_key_context bool // Is it a simple mapping key context? - line int // The current line. - column int // The current column. + line int // The current line. + + column int // The current column. + whitespace bool // If the last character was a whitespace? - indention bool // If the last character was an indentation character (' ', '-', '?', ':')? + + indention bool // If the last character was an indentation character (' ', '-', '?', ':')? + open_ended bool // If an explicit document end is required? // Anchor analysis. + anchor_data struct { anchor []byte // The anchor value. - alias bool // Is it an alias? + + alias bool // Is it an alias? + } // Tag analysis. + tag_data struct { handle []byte // The tag handle. + suffix []byte // The tag suffix. + } // Scalar analysis. + scalar_data struct { - value []byte // The scalar value. - multiline bool // Does the scalar contain line breaks? - flow_plain_allowed bool // Can the scalar be expessed in the flow plain style? - block_plain_allowed bool // Can the scalar be expressed in the block plain style? - single_quoted_allowed bool // Can the scalar be expressed in the single quoted style? - block_allowed bool // Can the scalar be expressed in the literal or folded styles? - style yaml_scalar_style_t // The output style. + value []byte // The scalar value. + + multiline bool // Does the scalar contain line breaks? + + flow_plain_allowed bool // Can the scalar be expessed in the flow plain style? + + block_plain_allowed bool // Can the scalar be expressed in the block plain style? + + single_quoted_allowed bool // Can the scalar be expressed in the single quoted style? + + block_allowed bool // Can the scalar be expressed in the literal or folded styles? + + style yaml_scalar_style_t // The output style. + } // Dumper stuff opened bool // If the stream was already opened? + closed bool // If the stream was already closed? // The information associated with the document nodes. + anchors *struct { - references int // The number of references. - anchor int // The anchor id. + references int // The number of references. + + anchor int // The anchor id. + serialized bool // If the node has been emitted? + } last_anchor_id int // The last assigned anchor id. document *yaml_document_t // The currently emitted document. + } diff --git a/vendor/gopkg.in/yaml.v3/decode.go b/vendor/gopkg.in/yaml.v3/decode.go index 0173b69..65fa221 100644 --- a/vendor/gopkg.in/yaml.v3/decode.go +++ b/vendor/gopkg.in/yaml.v3/decode.go @@ -1,16 +1,29 @@ // + // Copyright (c) 2011-2019 Canonical Ltd + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package yaml @@ -27,974 +40,1808 @@ import ( ) // ---------------------------------------------------------------------------- + // Parser, produces a node tree out of a libyaml event stream. type parser struct { - parser yaml_parser_t - event yaml_event_t - doc *Node - anchors map[string]*Node + parser yaml_parser_t + + event yaml_event_t + + doc *Node + + anchors map[string]*Node + doneInit bool + textless bool } func newParser(b []byte) *parser { + p := parser{} + if !yaml_parser_initialize(&p.parser) { + panic("failed to initialize YAML emitter") + } + if len(b) == 0 { + b = []byte{'\n'} + } + yaml_parser_set_input_string(&p.parser, b) + return &p + } func newParserFromReader(r io.Reader) *parser { + p := parser{} + if !yaml_parser_initialize(&p.parser) { + panic("failed to initialize YAML emitter") + } + yaml_parser_set_input_reader(&p.parser, r) + return &p + } func (p *parser) init() { + if p.doneInit { + return + } + p.anchors = make(map[string]*Node) + p.expect(yaml_STREAM_START_EVENT) + p.doneInit = true + } func (p *parser) destroy() { + if p.event.typ != yaml_NO_EVENT { + yaml_event_delete(&p.event) + } + yaml_parser_delete(&p.parser) + } // expect consumes an event from the event stream and + // checks that it's of the expected type. + func (p *parser) expect(e yaml_event_type_t) { + if p.event.typ == yaml_NO_EVENT { + if !yaml_parser_parse(&p.parser, &p.event) { + p.fail() + } + } + if p.event.typ == yaml_STREAM_END_EVENT { + failf("attempted to go past the end of stream; corrupted value?") + } + if p.event.typ != e { + p.parser.problem = fmt.Sprintf("expected %s event but got %s", e, p.event.typ) + p.fail() + } + yaml_event_delete(&p.event) + p.event.typ = yaml_NO_EVENT + } // peek peeks at the next event in the event stream, + // puts the results into p.event and returns the event type. + func (p *parser) peek() yaml_event_type_t { + if p.event.typ != yaml_NO_EVENT { + return p.event.typ + } + // It's curious choice from the underlying API to generally return a + // positive result on success, but on this case return true in an error + // scenario. This was the source of bugs in the past (issue #666). + if !yaml_parser_parse(&p.parser, &p.event) || p.parser.error != yaml_NO_ERROR { + p.fail() + } + return p.event.typ + } func (p *parser) fail() { + var where string + var line int + if p.parser.context_mark.line != 0 { + line = p.parser.context_mark.line + // Scanner errors don't iterate line before returning error + if p.parser.error == yaml_SCANNER_ERROR { + line++ + } + } else if p.parser.problem_mark.line != 0 { + line = p.parser.problem_mark.line + // Scanner errors don't iterate line before returning error + if p.parser.error == yaml_SCANNER_ERROR { + line++ + } + } + if line != 0 { + where = "line " + strconv.Itoa(line) + ": " + } + var msg string + if len(p.parser.problem) > 0 { + msg = p.parser.problem + } else { + msg = "unknown problem parsing YAML content" + } + failf("%s%s", where, msg) + } func (p *parser) anchor(n *Node, anchor []byte) { + if anchor != nil { + n.Anchor = string(anchor) + p.anchors[n.Anchor] = n + } + } func (p *parser) parse() *Node { + p.init() + switch p.peek() { + case yaml_SCALAR_EVENT: + return p.scalar() + case yaml_ALIAS_EVENT: + return p.alias() + case yaml_MAPPING_START_EVENT: + return p.mapping() + case yaml_SEQUENCE_START_EVENT: + return p.sequence() + case yaml_DOCUMENT_START_EVENT: + return p.document() + case yaml_STREAM_END_EVENT: + // Happens when attempting to decode an empty buffer. + return nil + case yaml_TAIL_COMMENT_EVENT: + panic("internal error: unexpected tail comment event (please report)") + default: + panic("internal error: attempted to parse unknown event (please report): " + p.event.typ.String()) + } + } func (p *parser) node(kind Kind, defaultTag, tag, value string) *Node { + var style Style + if tag != "" && tag != "!" { + tag = shortTag(tag) + style = TaggedStyle + } else if defaultTag != "" { + tag = defaultTag + } else if kind == ScalarNode { + tag, _ = resolve("", value) + } + n := &Node{ - Kind: kind, - Tag: tag, + + Kind: kind, + + Tag: tag, + Value: value, + Style: style, } + if !p.textless { + n.Line = p.event.start_mark.line + 1 + n.Column = p.event.start_mark.column + 1 + n.HeadComment = string(p.event.head_comment) + n.LineComment = string(p.event.line_comment) + n.FootComment = string(p.event.foot_comment) + } + return n + } func (p *parser) parseChild(parent *Node) *Node { + child := p.parse() + parent.Content = append(parent.Content, child) + return child + } func (p *parser) document() *Node { + n := p.node(DocumentNode, "", "", "") + p.doc = n + p.expect(yaml_DOCUMENT_START_EVENT) + p.parseChild(n) + if p.peek() == yaml_DOCUMENT_END_EVENT { + n.FootComment = string(p.event.foot_comment) + } + p.expect(yaml_DOCUMENT_END_EVENT) + return n + } func (p *parser) alias() *Node { + n := p.node(AliasNode, "", "", string(p.event.anchor)) + n.Alias = p.anchors[n.Value] + if n.Alias == nil { + failf("unknown anchor '%s' referenced", n.Value) + } + p.expect(yaml_ALIAS_EVENT) + return n + } func (p *parser) scalar() *Node { + var parsedStyle = p.event.scalar_style() + var nodeStyle Style + switch { + case parsedStyle&yaml_DOUBLE_QUOTED_SCALAR_STYLE != 0: + nodeStyle = DoubleQuotedStyle + case parsedStyle&yaml_SINGLE_QUOTED_SCALAR_STYLE != 0: + nodeStyle = SingleQuotedStyle + case parsedStyle&yaml_LITERAL_SCALAR_STYLE != 0: + nodeStyle = LiteralStyle + case parsedStyle&yaml_FOLDED_SCALAR_STYLE != 0: + nodeStyle = FoldedStyle + } + var nodeValue = string(p.event.value) + var nodeTag = string(p.event.tag) + var defaultTag string + if nodeStyle == 0 { + if nodeValue == "<<" { + defaultTag = mergeTag + } + } else { + defaultTag = strTag + } + n := p.node(ScalarNode, defaultTag, nodeTag, nodeValue) + n.Style |= nodeStyle + p.anchor(n, p.event.anchor) + p.expect(yaml_SCALAR_EVENT) + return n + } func (p *parser) sequence() *Node { + n := p.node(SequenceNode, seqTag, string(p.event.tag), "") + if p.event.sequence_style()&yaml_FLOW_SEQUENCE_STYLE != 0 { + n.Style |= FlowStyle + } + p.anchor(n, p.event.anchor) + p.expect(yaml_SEQUENCE_START_EVENT) + for p.peek() != yaml_SEQUENCE_END_EVENT { + p.parseChild(n) + } + n.LineComment = string(p.event.line_comment) + n.FootComment = string(p.event.foot_comment) + p.expect(yaml_SEQUENCE_END_EVENT) + return n + } func (p *parser) mapping() *Node { + n := p.node(MappingNode, mapTag, string(p.event.tag), "") + block := true + if p.event.mapping_style()&yaml_FLOW_MAPPING_STYLE != 0 { + block = false + n.Style |= FlowStyle + } + p.anchor(n, p.event.anchor) + p.expect(yaml_MAPPING_START_EVENT) + for p.peek() != yaml_MAPPING_END_EVENT { + k := p.parseChild(n) + if block && k.FootComment != "" { + // Must be a foot comment for the prior value when being dedented. + if len(n.Content) > 2 { + n.Content[len(n.Content)-3].FootComment = k.FootComment + k.FootComment = "" + } + } + v := p.parseChild(n) + if k.FootComment == "" && v.FootComment != "" { + k.FootComment = v.FootComment + v.FootComment = "" + } + if p.peek() == yaml_TAIL_COMMENT_EVENT { + if k.FootComment == "" { + k.FootComment = string(p.event.foot_comment) + } + p.expect(yaml_TAIL_COMMENT_EVENT) + } + } + n.LineComment = string(p.event.line_comment) + n.FootComment = string(p.event.foot_comment) + if n.Style&FlowStyle == 0 && n.FootComment != "" && len(n.Content) > 1 { + n.Content[len(n.Content)-2].FootComment = n.FootComment + n.FootComment = "" + } + p.expect(yaml_MAPPING_END_EVENT) + return n + } // ---------------------------------------------------------------------------- + // Decoder, unmarshals a node into a provided value. type decoder struct { - doc *Node + doc *Node + aliases map[*Node]bool + terrors []string - stringMapType reflect.Type + stringMapType reflect.Type + generalMapType reflect.Type knownFields bool - uniqueKeys bool + + uniqueKeys bool + decodeCount int - aliasCount int - aliasDepth int + + aliasCount int + + aliasDepth int mergedFields map[interface{}]bool } var ( - nodeType = reflect.TypeOf(Node{}) - durationType = reflect.TypeOf(time.Duration(0)) - stringMapType = reflect.TypeOf(map[string]interface{}{}) + nodeType = reflect.TypeOf(Node{}) + + durationType = reflect.TypeOf(time.Duration(0)) + + stringMapType = reflect.TypeOf(map[string]interface{}{}) + generalMapType = reflect.TypeOf(map[interface{}]interface{}{}) - ifaceType = generalMapType.Elem() - timeType = reflect.TypeOf(time.Time{}) - ptrTimeType = reflect.TypeOf(&time.Time{}) + + ifaceType = generalMapType.Elem() + + timeType = reflect.TypeOf(time.Time{}) + + ptrTimeType = reflect.TypeOf(&time.Time{}) ) func newDecoder() *decoder { + d := &decoder{ - stringMapType: stringMapType, + + stringMapType: stringMapType, + generalMapType: generalMapType, - uniqueKeys: true, + + uniqueKeys: true, } + d.aliases = make(map[*Node]bool) + return d + } func (d *decoder) terror(n *Node, tag string, out reflect.Value) { + if n.Tag != "" { + tag = n.Tag + } + value := n.Value + if tag != seqTag && tag != mapTag { + if len(value) > 10 { + value = " `" + value[:7] + "...`" + } else { + value = " `" + value + "`" + } + } + d.terrors = append(d.terrors, fmt.Sprintf("line %d: cannot unmarshal %s%s into %s", n.Line, shortTag(tag), value, out.Type())) + } func (d *decoder) callUnmarshaler(n *Node, u Unmarshaler) (good bool) { + err := u.UnmarshalYAML(n) + if e, ok := err.(*TypeError); ok { + d.terrors = append(d.terrors, e.Errors...) + return false + } + if err != nil { + fail(err) + } + return true + } func (d *decoder) callObsoleteUnmarshaler(n *Node, u obsoleteUnmarshaler) (good bool) { + terrlen := len(d.terrors) + err := u.UnmarshalYAML(func(v interface{}) (err error) { + defer handleErr(&err) + d.unmarshal(n, reflect.ValueOf(v)) + if len(d.terrors) > terrlen { + issues := d.terrors[terrlen:] + d.terrors = d.terrors[:terrlen] + return &TypeError{issues} + } + return nil + }) + if e, ok := err.(*TypeError); ok { + d.terrors = append(d.terrors, e.Errors...) + return false + } + if err != nil { + fail(err) + } + return true + } // d.prepare initializes and dereferences pointers and calls UnmarshalYAML + // if a value is found to implement it. + // It returns the initialized and dereferenced out value, whether + // unmarshalling was already done by UnmarshalYAML, and if so whether + // its types unmarshalled appropriately. + // + // If n holds a null value, prepare returns before doing anything. + func (d *decoder) prepare(n *Node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) { + if n.ShortTag() == nullTag { + return out, false, false + } + again := true + for again { + again = false + if out.Kind() == reflect.Ptr { + if out.IsNil() { + out.Set(reflect.New(out.Type().Elem())) + } + out = out.Elem() + again = true + } + if out.CanAddr() { + outi := out.Addr().Interface() + if u, ok := outi.(Unmarshaler); ok { + good = d.callUnmarshaler(n, u) + return out, true, good + } + if u, ok := outi.(obsoleteUnmarshaler); ok { + good = d.callObsoleteUnmarshaler(n, u) + return out, true, good + } + } + } + return out, false, false + } func (d *decoder) fieldByIndex(n *Node, v reflect.Value, index []int) (field reflect.Value) { + if n.ShortTag() == nullTag { + return reflect.Value{} + } + for _, num := range index { + for { + if v.Kind() == reflect.Ptr { + if v.IsNil() { + v.Set(reflect.New(v.Type().Elem())) + } + v = v.Elem() + continue + } + break + } + v = v.Field(num) + } + return v + } const ( + // 400,000 decode operations is ~500kb of dense object declarations, or + // ~5kb of dense object declarations with 10000% alias expansion + alias_ratio_range_low = 400000 // 4,000,000 decode operations is ~5MB of dense object declarations, or + // ~4.5MB of dense object declarations with 10% alias expansion + alias_ratio_range_high = 4000000 // alias_ratio_range is the range over which we scale allowed alias ratios + alias_ratio_range = float64(alias_ratio_range_high - alias_ratio_range_low) ) func allowedAliasRatio(decodeCount int) float64 { + switch { + case decodeCount <= alias_ratio_range_low: + // allow 99% to come from alias expansion for small-to-medium documents + return 0.99 + case decodeCount >= alias_ratio_range_high: + // allow 10% to come from alias expansion for very large documents + return 0.10 + default: + // scale smoothly from 99% down to 10% over the range. + // this maps to 396,000 - 400,000 allowed alias-driven decodes over the range. + // 400,000 decode operations is ~100MB of allocations in worst-case scenarios (single-item maps). + return 0.99 - 0.89*(float64(decodeCount-alias_ratio_range_low)/alias_ratio_range) + } + } func (d *decoder) unmarshal(n *Node, out reflect.Value) (good bool) { + d.decodeCount++ + if d.aliasDepth > 0 { + d.aliasCount++ + } + if d.aliasCount > 100 && d.decodeCount > 1000 && float64(d.aliasCount)/float64(d.decodeCount) > allowedAliasRatio(d.decodeCount) { + failf("document contains excessive aliasing") + } + if out.Type() == nodeType { + out.Set(reflect.ValueOf(n).Elem()) + return true + } + switch n.Kind { + case DocumentNode: + return d.document(n, out) + case AliasNode: + return d.alias(n, out) + } + out, unmarshaled, good := d.prepare(n, out) + if unmarshaled { + return good + } + switch n.Kind { + case ScalarNode: + good = d.scalar(n, out) + case MappingNode: + good = d.mapping(n, out) + case SequenceNode: + good = d.sequence(n, out) + case 0: + if n.IsZero() { + return d.null(out) + } + fallthrough + default: + failf("cannot decode node with unknown kind %d", n.Kind) + } + return good + } func (d *decoder) document(n *Node, out reflect.Value) (good bool) { + if len(n.Content) == 1 { + d.doc = n + d.unmarshal(n.Content[0], out) + return true + } + return false + } func (d *decoder) alias(n *Node, out reflect.Value) (good bool) { + if d.aliases[n] { + // TODO this could actually be allowed in some circumstances. + failf("anchor '%s' value contains itself", n.Value) + } + d.aliases[n] = true + d.aliasDepth++ + good = d.unmarshal(n.Alias, out) + d.aliasDepth-- + delete(d.aliases, n) + return good + } var zeroValue reflect.Value func resetMap(out reflect.Value) { + for _, k := range out.MapKeys() { + out.SetMapIndex(k, zeroValue) + } + } func (d *decoder) null(out reflect.Value) bool { + if out.CanAddr() { + switch out.Kind() { + case reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice: + out.Set(reflect.Zero(out.Type())) + return true + } + } + return false + } func (d *decoder) scalar(n *Node, out reflect.Value) bool { + var tag string + var resolved interface{} + if n.indicatedString() { + tag = strTag + resolved = n.Value + } else { + tag, resolved = resolve(n.Tag, n.Value) + if tag == binaryTag { + data, err := base64.StdEncoding.DecodeString(resolved.(string)) + if err != nil { + failf("!!binary value contains invalid base64 data") + } + resolved = string(data) + } + } + if resolved == nil { + return d.null(out) + } + if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { + // We've resolved to exactly the type we want, so use that. + out.Set(resolvedv) + return true + } + // Perhaps we can use the value as a TextUnmarshaler to + // set its value. + if out.CanAddr() { + u, ok := out.Addr().Interface().(encoding.TextUnmarshaler) + if ok { + var text []byte + if tag == binaryTag { + text = []byte(resolved.(string)) + } else { + // We let any value be unmarshaled into TextUnmarshaler. + // That might be more lax than we'd like, but the + // TextUnmarshaler itself should bowl out any dubious values. + text = []byte(n.Value) + } + err := u.UnmarshalText(text) + if err != nil { + fail(err) + } + return true + } + } + switch out.Kind() { + case reflect.String: + if tag == binaryTag { + out.SetString(resolved.(string)) + return true + } + out.SetString(n.Value) + return true + case reflect.Interface: + out.Set(reflect.ValueOf(resolved)) + return true + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + // This used to work in v2, but it's very unfriendly. + isDuration := out.Type() == durationType switch resolved := resolved.(type) { + case int: + if !isDuration && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case int64: + if !isDuration && !out.OverflowInt(resolved) { + out.SetInt(resolved) + return true + } + case uint64: + if !isDuration && resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case float64: + if !isDuration && resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case string: + if out.Type() == durationType { + d, err := time.ParseDuration(resolved) + if err == nil { + out.SetInt(int64(d)) + return true + } + } + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + switch resolved := resolved.(type) { + case int: + if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case int64: + if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case uint64: + if !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case float64: + if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + } + case reflect.Bool: + switch resolved := resolved.(type) { + case bool: + out.SetBool(resolved) + return true + case string: + // This offers some compatibility with the 1.1 spec (https://yaml.org/type/bool.html). + // It only works if explicitly attempting to unmarshal into a typed bool value. + switch resolved { + case "y", "Y", "yes", "Yes", "YES", "on", "On", "ON": + out.SetBool(true) + return true + case "n", "N", "no", "No", "NO", "off", "Off", "OFF": + out.SetBool(false) + return true + } + } + case reflect.Float32, reflect.Float64: + switch resolved := resolved.(type) { + case int: + out.SetFloat(float64(resolved)) + return true + case int64: + out.SetFloat(float64(resolved)) + return true + case uint64: + out.SetFloat(float64(resolved)) + return true + case float64: + out.SetFloat(resolved) + return true + } + case reflect.Struct: + if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { + out.Set(resolvedv) + return true + } + case reflect.Ptr: + panic("yaml internal error: please report the issue") + } + d.terror(n, tag, out) + return false + } func settableValueOf(i interface{}) reflect.Value { + v := reflect.ValueOf(i) + sv := reflect.New(v.Type()).Elem() + sv.Set(v) + return sv + } func (d *decoder) sequence(n *Node, out reflect.Value) (good bool) { + l := len(n.Content) var iface reflect.Value + switch out.Kind() { + case reflect.Slice: + out.Set(reflect.MakeSlice(out.Type(), l, l)) + case reflect.Array: + if l != out.Len() { + failf("invalid array: want %d elements but got %d", out.Len(), l) + } + case reflect.Interface: + // No type hints. Will have to use a generic sequence. + iface = out + out = settableValueOf(make([]interface{}, l)) + default: + d.terror(n, seqTag, out) + return false + } + et := out.Type().Elem() j := 0 + for i := 0; i < l; i++ { + e := reflect.New(et).Elem() + if ok := d.unmarshal(n.Content[i], e); ok { + out.Index(j).Set(e) + j++ + } + } + if out.Kind() != reflect.Array { + out.Set(out.Slice(0, j)) + } + if iface.IsValid() { + iface.Set(out) + } + return true + } func (d *decoder) mapping(n *Node, out reflect.Value) (good bool) { + l := len(n.Content) + if d.uniqueKeys { + nerrs := len(d.terrors) + for i := 0; i < l; i += 2 { + ni := n.Content[i] + for j := i + 2; j < l; j += 2 { + nj := n.Content[j] + if ni.Kind == nj.Kind && ni.Value == nj.Value { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: mapping key %#v already defined at line %d", nj.Line, nj.Value, ni.Line)) + } + } + } + if len(d.terrors) > nerrs { + return false + } + } + switch out.Kind() { + case reflect.Struct: + return d.mappingStruct(n, out) + case reflect.Map: + // okay + case reflect.Interface: + iface := out + if isStringMap(n) { + out = reflect.MakeMap(d.stringMapType) + } else { + out = reflect.MakeMap(d.generalMapType) + } + iface.Set(out) + default: + d.terror(n, mapTag, out) + return false + } outt := out.Type() + kt := outt.Key() + et := outt.Elem() stringMapType := d.stringMapType + generalMapType := d.generalMapType + if outt.Elem() == ifaceType { + if outt.Key().Kind() == reflect.String { + d.stringMapType = outt + } else if outt.Key() == ifaceType { + d.generalMapType = outt + } + } mergedFields := d.mergedFields + d.mergedFields = nil var mergeNode *Node mapIsNew := false + if out.IsNil() { + out.Set(reflect.MakeMap(outt)) + mapIsNew = true + } + for i := 0; i < l; i += 2 { + if isMerge(n.Content[i]) { + mergeNode = n.Content[i+1] + continue + } + k := reflect.New(kt).Elem() + if d.unmarshal(n.Content[i], k) { + if mergedFields != nil { + ki := k.Interface() + if mergedFields[ki] { + continue + } + mergedFields[ki] = true + } + kkind := k.Kind() + if kkind == reflect.Interface { + kkind = k.Elem().Kind() + } + if kkind == reflect.Map || kkind == reflect.Slice { + failf("invalid map key: %#v", k.Interface()) + } + e := reflect.New(et).Elem() + if d.unmarshal(n.Content[i+1], e) || n.Content[i+1].ShortTag() == nullTag && (mapIsNew || !out.MapIndex(k).IsValid()) { + out.SetMapIndex(k, e) + } + } + } d.mergedFields = mergedFields + if mergeNode != nil { + d.merge(n, mergeNode, out) + } d.stringMapType = stringMapType + d.generalMapType = generalMapType + return true + } func isStringMap(n *Node) bool { + if n.Kind != MappingNode { + return false + } + l := len(n.Content) + for i := 0; i < l; i += 2 { + shortTag := n.Content[i].ShortTag() + if shortTag != strTag && shortTag != mergeTag { + return false + } + } + return true + } func (d *decoder) mappingStruct(n *Node, out reflect.Value) (good bool) { + sinfo, err := getStructInfo(out.Type()) + if err != nil { + panic(err) + } var inlineMap reflect.Value + var elemType reflect.Type + if sinfo.InlineMap != -1 { + inlineMap = out.Field(sinfo.InlineMap) + elemType = inlineMap.Type().Elem() + } for _, index := range sinfo.InlineUnmarshalers { + field := d.fieldByIndex(n, out, index) + d.prepare(n, field) + } mergedFields := d.mergedFields + d.mergedFields = nil + var mergeNode *Node + var doneFields []bool + if d.uniqueKeys { + doneFields = make([]bool, len(sinfo.FieldsList)) + } + name := settableValueOf("") + l := len(n.Content) + for i := 0; i < l; i += 2 { + ni := n.Content[i] + if isMerge(ni) { + mergeNode = n.Content[i+1] + continue + } + if !d.unmarshal(ni, name) { + continue + } + sname := name.String() + if mergedFields != nil { + if mergedFields[sname] { + continue + } + mergedFields[sname] = true + } + if info, ok := sinfo.FieldsMap[sname]; ok { + if d.uniqueKeys { + if doneFields[info.Id] { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s already set in type %s", ni.Line, name.String(), out.Type())) + continue + } + doneFields[info.Id] = true + } + var field reflect.Value + if info.Inline == nil { + field = out.Field(info.Num) + } else { + field = d.fieldByIndex(n, out, info.Inline) + } + d.unmarshal(n.Content[i+1], field) + } else if sinfo.InlineMap != -1 { + if inlineMap.IsNil() { + inlineMap.Set(reflect.MakeMap(inlineMap.Type())) + } + value := reflect.New(elemType).Elem() + d.unmarshal(n.Content[i+1], value) + inlineMap.SetMapIndex(name, value) + } else if d.knownFields { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in type %s", ni.Line, name.String(), out.Type())) + } + } d.mergedFields = mergedFields + if mergeNode != nil { + d.merge(n, mergeNode, out) + } + return true + } func failWantMap() { + failf("map merge requires map or sequence of maps as the value") + } func (d *decoder) merge(parent *Node, merge *Node, out reflect.Value) { + mergedFields := d.mergedFields + if mergedFields == nil { + d.mergedFields = make(map[interface{}]bool) + for i := 0; i < len(parent.Content); i += 2 { + k := reflect.New(ifaceType).Elem() + if d.unmarshal(parent.Content[i], k) { + d.mergedFields[k.Interface()] = true + } + } + } switch merge.Kind { + case MappingNode: + d.unmarshal(merge, out) + case AliasNode: + if merge.Alias != nil && merge.Alias.Kind != MappingNode { + failWantMap() + } + d.unmarshal(merge, out) + case SequenceNode: + for i := 0; i < len(merge.Content); i++ { + ni := merge.Content[i] + if ni.Kind == AliasNode { + if ni.Alias != nil && ni.Alias.Kind != MappingNode { + failWantMap() + } + } else if ni.Kind != MappingNode { + failWantMap() + } + d.unmarshal(ni, out) + } + default: + failWantMap() + } d.mergedFields = mergedFields + } func isMerge(n *Node) bool { + return n.Kind == ScalarNode && n.Value == "<<" && (n.Tag == "" || n.Tag == "!" || shortTag(n.Tag) == mergeTag) + } diff --git a/vendor/gopkg.in/yaml.v3/emitterc.go b/vendor/gopkg.in/yaml.v3/emitterc.go index dde20e5..79ad8e2 100644 --- a/vendor/gopkg.in/yaml.v3/emitterc.go +++ b/vendor/gopkg.in/yaml.v3/emitterc.go @@ -1,23 +1,43 @@ // + // Copyright (c) 2011-2019 Canonical Ltd + // Copyright (c) 2006-2010 Kirill Simonov + // + // Permission is hereby granted, free of charge, to any person obtaining a copy of + // this software and associated documentation files (the "Software"), to deal in + // the Software without restriction, including without limitation the rights to + // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + // of the Software, and to permit persons to whom the Software is furnished to do + // so, subject to the following conditions: + // + // The above copyright notice and this permission notice shall be included in all + // copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + // SOFTWARE. package yaml @@ -28,1992 +48,3678 @@ import ( ) // Flush the buffer if needed. + func flush(emitter *yaml_emitter_t) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) { + return yaml_emitter_flush(emitter) + } + return true + } // Put a character to the output buffer. + func put(emitter *yaml_emitter_t, value byte) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + emitter.buffer[emitter.buffer_pos] = value + emitter.buffer_pos++ + emitter.column++ + return true + } // Put a line break to the output buffer. + func put_break(emitter *yaml_emitter_t) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + switch emitter.line_break { + case yaml_CR_BREAK: + emitter.buffer[emitter.buffer_pos] = '\r' + emitter.buffer_pos += 1 + case yaml_LN_BREAK: + emitter.buffer[emitter.buffer_pos] = '\n' + emitter.buffer_pos += 1 + case yaml_CRLN_BREAK: + emitter.buffer[emitter.buffer_pos+0] = '\r' + emitter.buffer[emitter.buffer_pos+1] = '\n' + emitter.buffer_pos += 2 + default: + panic("unknown line break setting") + } + if emitter.column == 0 { + emitter.space_above = true + } + emitter.column = 0 + emitter.line++ + // [Go] Do this here and below and drop from everywhere else (see commented lines). + emitter.indention = true + return true + } // Copy a character from a string into buffer. + func write(emitter *yaml_emitter_t, s []byte, i *int) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + p := emitter.buffer_pos + w := width(s[*i]) + switch w { + case 4: + emitter.buffer[p+3] = s[*i+3] + fallthrough + case 3: + emitter.buffer[p+2] = s[*i+2] + fallthrough + case 2: + emitter.buffer[p+1] = s[*i+1] + fallthrough + case 1: + emitter.buffer[p+0] = s[*i+0] + default: + panic("unknown character width") + } + emitter.column++ + emitter.buffer_pos += w + *i += w + return true + } // Write a whole string into buffer. + func write_all(emitter *yaml_emitter_t, s []byte) bool { + for i := 0; i < len(s); { + if !write(emitter, s, &i) { + return false + } + } + return true + } // Copy a line break character from a string into buffer. + func write_break(emitter *yaml_emitter_t, s []byte, i *int) bool { + if s[*i] == '\n' { + if !put_break(emitter) { + return false + } + *i++ + } else { + if !write(emitter, s, i) { + return false + } + if emitter.column == 0 { + emitter.space_above = true + } + emitter.column = 0 + emitter.line++ + // [Go] Do this here and above and drop from everywhere else (see commented lines). + emitter.indention = true + } + return true + } // Set an emitter error and return false. + func yaml_emitter_set_emitter_error(emitter *yaml_emitter_t, problem string) bool { + emitter.error = yaml_EMITTER_ERROR + emitter.problem = problem + return false + } // Emit an event. + func yaml_emitter_emit(emitter *yaml_emitter_t, event *yaml_event_t) bool { + emitter.events = append(emitter.events, *event) + for !yaml_emitter_need_more_events(emitter) { + event := &emitter.events[emitter.events_head] + if !yaml_emitter_analyze_event(emitter, event) { + return false + } + if !yaml_emitter_state_machine(emitter, event) { + return false + } + yaml_event_delete(event) + emitter.events_head++ + } + return true + } // Check if we need to accumulate more events before emitting. + // + // We accumulate extra + // - 1 event for DOCUMENT-START + // - 2 events for SEQUENCE-START + // - 3 events for MAPPING-START + func yaml_emitter_need_more_events(emitter *yaml_emitter_t) bool { + if emitter.events_head == len(emitter.events) { + return true + } + var accumulate int + switch emitter.events[emitter.events_head].typ { + case yaml_DOCUMENT_START_EVENT: + accumulate = 1 + break + case yaml_SEQUENCE_START_EVENT: + accumulate = 2 + break + case yaml_MAPPING_START_EVENT: + accumulate = 3 + break + default: + return false + } + if len(emitter.events)-emitter.events_head > accumulate { + return false + } + var level int + for i := emitter.events_head; i < len(emitter.events); i++ { + switch emitter.events[i].typ { + case yaml_STREAM_START_EVENT, yaml_DOCUMENT_START_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT: + level++ + case yaml_STREAM_END_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_END_EVENT, yaml_MAPPING_END_EVENT: + level-- + } + if level == 0 { + return false + } + } + return true + } // Append a directive to the directives stack. + func yaml_emitter_append_tag_directive(emitter *yaml_emitter_t, value *yaml_tag_directive_t, allow_duplicates bool) bool { + for i := 0; i < len(emitter.tag_directives); i++ { + if bytes.Equal(value.handle, emitter.tag_directives[i].handle) { + if allow_duplicates { + return true + } + return yaml_emitter_set_emitter_error(emitter, "duplicate %TAG directive") + } + } // [Go] Do we actually need to copy this given garbage collection + // and the lack of deallocating destructors? + tag_copy := yaml_tag_directive_t{ + handle: make([]byte, len(value.handle)), + prefix: make([]byte, len(value.prefix)), } + copy(tag_copy.handle, value.handle) + copy(tag_copy.prefix, value.prefix) + emitter.tag_directives = append(emitter.tag_directives, tag_copy) + return true + } // Increase the indentation level. + func yaml_emitter_increase_indent(emitter *yaml_emitter_t, flow, indentless bool) bool { + emitter.indents = append(emitter.indents, emitter.indent) + if emitter.indent < 0 { + if flow { + emitter.indent = emitter.best_indent + } else { + emitter.indent = 0 + } + } else if !indentless { + // [Go] This was changed so that indentations are more regular. + if emitter.states[len(emitter.states)-1] == yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE { + // The first indent inside a sequence will just skip the "- " indicator. + emitter.indent += 2 + } else { + // Everything else aligns to the chosen indentation. + emitter.indent = emitter.best_indent * ((emitter.indent + emitter.best_indent) / emitter.best_indent) + } + } + return true + } // State dispatcher. + func yaml_emitter_state_machine(emitter *yaml_emitter_t, event *yaml_event_t) bool { + switch emitter.state { + default: + case yaml_EMIT_STREAM_START_STATE: + return yaml_emitter_emit_stream_start(emitter, event) case yaml_EMIT_FIRST_DOCUMENT_START_STATE: + return yaml_emitter_emit_document_start(emitter, event, true) case yaml_EMIT_DOCUMENT_START_STATE: + return yaml_emitter_emit_document_start(emitter, event, false) case yaml_EMIT_DOCUMENT_CONTENT_STATE: + return yaml_emitter_emit_document_content(emitter, event) case yaml_EMIT_DOCUMENT_END_STATE: + return yaml_emitter_emit_document_end(emitter, event) case yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, true, false) case yaml_EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, false, true) case yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, false, false) case yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, true, false) case yaml_EMIT_FLOW_MAPPING_TRAIL_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, false, true) case yaml_EMIT_FLOW_MAPPING_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, false, false) case yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE: + return yaml_emitter_emit_flow_mapping_value(emitter, event, true) case yaml_EMIT_FLOW_MAPPING_VALUE_STATE: + return yaml_emitter_emit_flow_mapping_value(emitter, event, false) case yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE: + return yaml_emitter_emit_block_sequence_item(emitter, event, true) case yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE: + return yaml_emitter_emit_block_sequence_item(emitter, event, false) case yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE: + return yaml_emitter_emit_block_mapping_key(emitter, event, true) case yaml_EMIT_BLOCK_MAPPING_KEY_STATE: + return yaml_emitter_emit_block_mapping_key(emitter, event, false) case yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE: + return yaml_emitter_emit_block_mapping_value(emitter, event, true) case yaml_EMIT_BLOCK_MAPPING_VALUE_STATE: + return yaml_emitter_emit_block_mapping_value(emitter, event, false) case yaml_EMIT_END_STATE: + return yaml_emitter_set_emitter_error(emitter, "expected nothing after STREAM-END") + } + panic("invalid emitter state") + } // Expect STREAM-START. + func yaml_emitter_emit_stream_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if event.typ != yaml_STREAM_START_EVENT { + return yaml_emitter_set_emitter_error(emitter, "expected STREAM-START") + } + if emitter.encoding == yaml_ANY_ENCODING { + emitter.encoding = event.encoding + if emitter.encoding == yaml_ANY_ENCODING { + emitter.encoding = yaml_UTF8_ENCODING + } + } + if emitter.best_indent < 2 || emitter.best_indent > 9 { + emitter.best_indent = 2 + } + if emitter.best_width >= 0 && emitter.best_width <= emitter.best_indent*2 { + emitter.best_width = 80 + } + if emitter.best_width < 0 { + emitter.best_width = 1<<31 - 1 + } + if emitter.line_break == yaml_ANY_BREAK { + emitter.line_break = yaml_LN_BREAK + } emitter.indent = -1 + emitter.line = 0 + emitter.column = 0 + emitter.whitespace = true + emitter.indention = true + emitter.space_above = true + emitter.foot_indent = -1 if emitter.encoding != yaml_UTF8_ENCODING { + if !yaml_emitter_write_bom(emitter) { + return false + } + } + emitter.state = yaml_EMIT_FIRST_DOCUMENT_START_STATE + return true + } // Expect DOCUMENT-START or STREAM-END. + func yaml_emitter_emit_document_start(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { if event.typ == yaml_DOCUMENT_START_EVENT { if event.version_directive != nil { + if !yaml_emitter_analyze_version_directive(emitter, event.version_directive) { + return false + } + } for i := 0; i < len(event.tag_directives); i++ { + tag_directive := &event.tag_directives[i] + if !yaml_emitter_analyze_tag_directive(emitter, tag_directive) { + return false + } + if !yaml_emitter_append_tag_directive(emitter, tag_directive, false) { + return false + } + } for i := 0; i < len(default_tag_directives); i++ { + tag_directive := &default_tag_directives[i] + if !yaml_emitter_append_tag_directive(emitter, tag_directive, true) { + return false + } + } implicit := event.implicit + if !first || emitter.canonical { + implicit = false + } if emitter.open_ended && (event.version_directive != nil || len(event.tag_directives) > 0) { + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } if event.version_directive != nil { + implicit = false + if !yaml_emitter_write_indicator(emitter, []byte("%YAML"), true, false, false) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte("1.1"), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } if len(event.tag_directives) > 0 { + implicit = false + for i := 0; i < len(event.tag_directives); i++ { + tag_directive := &event.tag_directives[i] + if !yaml_emitter_write_indicator(emitter, []byte("%TAG"), true, false, false) { + return false + } + if !yaml_emitter_write_tag_handle(emitter, tag_directive.handle) { + return false + } + if !yaml_emitter_write_tag_content(emitter, tag_directive.prefix, true) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + } if yaml_emitter_check_empty_document(emitter) { + implicit = false + } + if !implicit { + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte("---"), true, false, false) { + return false + } + if emitter.canonical || true { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + } if len(emitter.head_comment) > 0 { + if !yaml_emitter_process_head_comment(emitter) { + return false + } + if !put_break(emitter) { + return false + } + } emitter.state = yaml_EMIT_DOCUMENT_CONTENT_STATE + return true + } if event.typ == yaml_STREAM_END_EVENT { + if emitter.open_ended { + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_flush(emitter) { + return false + } + emitter.state = yaml_EMIT_END_STATE + return true + } return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-START or STREAM-END") + } // Expect the root node. + func yaml_emitter_emit_document_content(emitter *yaml_emitter_t, event *yaml_event_t) bool { + emitter.states = append(emitter.states, yaml_EMIT_DOCUMENT_END_STATE) if !yaml_emitter_process_head_comment(emitter) { + return false + } + if !yaml_emitter_emit_node(emitter, event, true, false, false, false) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + return true + } // Expect DOCUMENT-END. + func yaml_emitter_emit_document_end(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if event.typ != yaml_DOCUMENT_END_EVENT { + return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-END") + } + // [Go] Force document foot separation. + emitter.foot_indent = 0 + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + emitter.foot_indent = -1 + if !yaml_emitter_write_indent(emitter) { + return false + } + if !event.implicit { + // [Go] Allocate the slice elsewhere. + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_flush(emitter) { + return false + } + emitter.state = yaml_EMIT_DOCUMENT_START_STATE + emitter.tag_directives = emitter.tag_directives[:0] + return true + } // Expect a flow item node. + func yaml_emitter_emit_flow_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first, trail bool) bool { + if first { + if !yaml_emitter_write_indicator(emitter, []byte{'['}, true, true, false) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + emitter.flow_level++ + } if event.typ == yaml_SEQUENCE_END_EVENT { + if emitter.canonical && !first && !trail { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + emitter.flow_level-- + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + if emitter.column == 0 || emitter.canonical && !first { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{']'}, false, false, false) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] return true + } if !first && !trail { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } if !yaml_emitter_process_head_comment(emitter) { + return false + } + if emitter.column == 0 { + if !yaml_emitter_write_indent(emitter) { + return false + } + } if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE) + } else { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE) + } + if !yaml_emitter_emit_node(emitter, event, false, true, false, false) { + return false + } + if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + return true + } // Expect a flow key node. + func yaml_emitter_emit_flow_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first, trail bool) bool { + if first { + if !yaml_emitter_write_indicator(emitter, []byte{'{'}, true, true, false) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + emitter.flow_level++ + } if event.typ == yaml_MAPPING_END_EVENT { + if (emitter.canonical || len(emitter.head_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0) && !first && !trail { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + if !yaml_emitter_process_head_comment(emitter) { + return false + } + emitter.flow_level-- + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + if emitter.canonical && !first { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'}'}, false, false, false) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } if !first && !trail { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } if !yaml_emitter_process_head_comment(emitter) { + return false + } if emitter.column == 0 { + if !yaml_emitter_write_indent(emitter) { + return false + } + } if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } if !emitter.canonical && yaml_emitter_check_simple_key(emitter) { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, true) + } + if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, false) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) + } // Expect a flow value node. + func yaml_emitter_emit_flow_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { + if simple { + if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { + return false + } + } else { + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, false) { + return false + } + } + if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_TRAIL_KEY_STATE) + } else { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_KEY_STATE) + } + if !yaml_emitter_emit_node(emitter, event, false, false, true, false) { + return false + } + if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + return true + } // Expect a block item node. + func yaml_emitter_emit_block_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_increase_indent(emitter, false, false) { + return false + } + } + if event.typ == yaml_SEQUENCE_END_EVENT { + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + if !yaml_emitter_process_head_comment(emitter) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{'-'}, true, false, true) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE) + if !yaml_emitter_emit_node(emitter, event, false, true, false, false) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + return true + } // Expect a block key node. + func yaml_emitter_emit_block_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_increase_indent(emitter, false, false) { + return false + } + } + if !yaml_emitter_process_head_comment(emitter) { + return false + } + if event.typ == yaml_MAPPING_END_EVENT { + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if len(emitter.line_comment) > 0 { + // [Go] A line comment was provided for the key. That's unusual as the + // scanner associates line comments with the value. Either way, + // save the line comment and render it appropriately later. + emitter.key_line_comment = emitter.line_comment + emitter.line_comment = nil + } + if yaml_emitter_check_simple_key(emitter) { + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, true) + } + if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, true) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) + } // Expect a block value node. + func yaml_emitter_emit_block_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { + if simple { + if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { + return false + } + } else { + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, true) { + return false + } + } + if len(emitter.key_line_comment) > 0 { + // [Go] Line comments are generally associated with the value, but when there's + // no value on the same line as a mapping key they end up attached to the + // key itself. + if event.typ == yaml_SCALAR_EVENT { + if len(emitter.line_comment) == 0 { + // A scalar is coming and it has no line comments by itself yet, + // so just let it handle the line comment as usual. If it has a + // line comment, we can't have both so the one from the key is lost. + emitter.line_comment = emitter.key_line_comment + emitter.key_line_comment = nil + } + } else if event.sequence_style() != yaml_FLOW_SEQUENCE_STYLE && (event.typ == yaml_MAPPING_START_EVENT || event.typ == yaml_SEQUENCE_START_EVENT) { + // An indented block follows, so write the comment right now. + emitter.line_comment, emitter.key_line_comment = emitter.key_line_comment, emitter.line_comment + if !yaml_emitter_process_line_comment(emitter) { + return false + } + emitter.line_comment, emitter.key_line_comment = emitter.key_line_comment, emitter.line_comment + } + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_KEY_STATE) + if !yaml_emitter_emit_node(emitter, event, false, false, true, false) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + return true + } func yaml_emitter_silent_nil_event(emitter *yaml_emitter_t, event *yaml_event_t) bool { + return event.typ == yaml_SCALAR_EVENT && event.implicit && !emitter.canonical && len(emitter.scalar_data.value) == 0 + } // Expect a node. + func yaml_emitter_emit_node(emitter *yaml_emitter_t, event *yaml_event_t, + root bool, sequence bool, mapping bool, simple_key bool) bool { emitter.root_context = root + emitter.sequence_context = sequence + emitter.mapping_context = mapping + emitter.simple_key_context = simple_key switch event.typ { + case yaml_ALIAS_EVENT: + return yaml_emitter_emit_alias(emitter, event) + case yaml_SCALAR_EVENT: + return yaml_emitter_emit_scalar(emitter, event) + case yaml_SEQUENCE_START_EVENT: + return yaml_emitter_emit_sequence_start(emitter, event) + case yaml_MAPPING_START_EVENT: + return yaml_emitter_emit_mapping_start(emitter, event) + default: + return yaml_emitter_set_emitter_error(emitter, + fmt.Sprintf("expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, but got %v", event.typ)) + } + } // Expect ALIAS. + func yaml_emitter_emit_alias(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } // Expect SCALAR. + func yaml_emitter_emit_scalar(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_select_scalar_style(emitter, event) { + return false + } + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + if !yaml_emitter_process_scalar(emitter) { + return false + } + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } // Expect SEQUENCE-START. + func yaml_emitter_emit_sequence_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if emitter.flow_level > 0 || emitter.canonical || event.sequence_style() == yaml_FLOW_SEQUENCE_STYLE || + yaml_emitter_check_empty_sequence(emitter) { + emitter.state = yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE + } else { + emitter.state = yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE + } + return true + } // Expect MAPPING-START. + func yaml_emitter_emit_mapping_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if emitter.flow_level > 0 || emitter.canonical || event.mapping_style() == yaml_FLOW_MAPPING_STYLE || + yaml_emitter_check_empty_mapping(emitter) { + emitter.state = yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE + } else { + emitter.state = yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE + } + return true + } // Check if the document content is an empty scalar. + func yaml_emitter_check_empty_document(emitter *yaml_emitter_t) bool { + return false // [Go] Huh? + } // Check if the next events represent an empty sequence. + func yaml_emitter_check_empty_sequence(emitter *yaml_emitter_t) bool { + if len(emitter.events)-emitter.events_head < 2 { + return false + } + return emitter.events[emitter.events_head].typ == yaml_SEQUENCE_START_EVENT && + emitter.events[emitter.events_head+1].typ == yaml_SEQUENCE_END_EVENT + } // Check if the next events represent an empty mapping. + func yaml_emitter_check_empty_mapping(emitter *yaml_emitter_t) bool { + if len(emitter.events)-emitter.events_head < 2 { + return false + } + return emitter.events[emitter.events_head].typ == yaml_MAPPING_START_EVENT && + emitter.events[emitter.events_head+1].typ == yaml_MAPPING_END_EVENT + } // Check if the next node can be expressed as a simple key. + func yaml_emitter_check_simple_key(emitter *yaml_emitter_t) bool { + length := 0 + switch emitter.events[emitter.events_head].typ { + case yaml_ALIAS_EVENT: + length += len(emitter.anchor_data.anchor) + case yaml_SCALAR_EVENT: + if emitter.scalar_data.multiline { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + + len(emitter.scalar_data.value) + case yaml_SEQUENCE_START_EVENT: + if !yaml_emitter_check_empty_sequence(emitter) { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + case yaml_MAPPING_START_EVENT: + if !yaml_emitter_check_empty_mapping(emitter) { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + default: + return false + } + return length <= 128 + } // Determine an acceptable scalar style. + func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event_t) bool { no_tag := len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 + if no_tag && !event.implicit && !event.quoted_implicit { + return yaml_emitter_set_emitter_error(emitter, "neither tag nor implicit flags are specified") + } style := event.scalar_style() + if style == yaml_ANY_SCALAR_STYLE { + style = yaml_PLAIN_SCALAR_STYLE + } + if emitter.canonical { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + if emitter.simple_key_context && emitter.scalar_data.multiline { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } if style == yaml_PLAIN_SCALAR_STYLE { + if emitter.flow_level > 0 && !emitter.scalar_data.flow_plain_allowed || + emitter.flow_level == 0 && !emitter.scalar_data.block_plain_allowed { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + if len(emitter.scalar_data.value) == 0 && (emitter.flow_level > 0 || emitter.simple_key_context) { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + if no_tag && !event.implicit { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + } + if style == yaml_SINGLE_QUOTED_SCALAR_STYLE { + if !emitter.scalar_data.single_quoted_allowed { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + } + if style == yaml_LITERAL_SCALAR_STYLE || style == yaml_FOLDED_SCALAR_STYLE { + if !emitter.scalar_data.block_allowed || emitter.flow_level > 0 || emitter.simple_key_context { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + } if no_tag && !event.quoted_implicit && style != yaml_PLAIN_SCALAR_STYLE { + emitter.tag_data.handle = []byte{'!'} + } + emitter.scalar_data.style = style + return true + } // Write an anchor. + func yaml_emitter_process_anchor(emitter *yaml_emitter_t) bool { + if emitter.anchor_data.anchor == nil { + return true + } + c := []byte{'&'} + if emitter.anchor_data.alias { + c[0] = '*' + } + if !yaml_emitter_write_indicator(emitter, c, true, false, false) { + return false + } + return yaml_emitter_write_anchor(emitter, emitter.anchor_data.anchor) + } // Write a tag. + func yaml_emitter_process_tag(emitter *yaml_emitter_t) bool { + if len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 { + return true + } + if len(emitter.tag_data.handle) > 0 { + if !yaml_emitter_write_tag_handle(emitter, emitter.tag_data.handle) { + return false + } + if len(emitter.tag_data.suffix) > 0 { + if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { + return false + } + } + } else { + // [Go] Allocate these slices elsewhere. + if !yaml_emitter_write_indicator(emitter, []byte("!<"), true, false, false) { + return false + } + if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{'>'}, false, false, false) { + return false + } + } + return true + } // Write a scalar. + func yaml_emitter_process_scalar(emitter *yaml_emitter_t) bool { + switch emitter.scalar_data.style { + case yaml_PLAIN_SCALAR_STYLE: + return yaml_emitter_write_plain_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) case yaml_SINGLE_QUOTED_SCALAR_STYLE: + return yaml_emitter_write_single_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) case yaml_DOUBLE_QUOTED_SCALAR_STYLE: + return yaml_emitter_write_double_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) case yaml_LITERAL_SCALAR_STYLE: + return yaml_emitter_write_literal_scalar(emitter, emitter.scalar_data.value) case yaml_FOLDED_SCALAR_STYLE: + return yaml_emitter_write_folded_scalar(emitter, emitter.scalar_data.value) + } + panic("unknown scalar style") + } // Write a head comment. + func yaml_emitter_process_head_comment(emitter *yaml_emitter_t) bool { + if len(emitter.tail_comment) > 0 { + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_comment(emitter, emitter.tail_comment) { + return false + } + emitter.tail_comment = emitter.tail_comment[:0] + emitter.foot_indent = emitter.indent + if emitter.foot_indent < 0 { + emitter.foot_indent = 0 + } + } if len(emitter.head_comment) == 0 { + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_comment(emitter, emitter.head_comment) { + return false + } + emitter.head_comment = emitter.head_comment[:0] + return true + } // Write an line comment. + func yaml_emitter_process_line_comment(emitter *yaml_emitter_t) bool { + if len(emitter.line_comment) == 0 { + return true + } + if !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + if !yaml_emitter_write_comment(emitter, emitter.line_comment) { + return false + } + emitter.line_comment = emitter.line_comment[:0] + return true + } // Write a foot comment. + func yaml_emitter_process_foot_comment(emitter *yaml_emitter_t) bool { + if len(emitter.foot_comment) == 0 { + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_comment(emitter, emitter.foot_comment) { + return false + } + emitter.foot_comment = emitter.foot_comment[:0] + emitter.foot_indent = emitter.indent + if emitter.foot_indent < 0 { + emitter.foot_indent = 0 + } + return true + } // Check if a %YAML directive is valid. + func yaml_emitter_analyze_version_directive(emitter *yaml_emitter_t, version_directive *yaml_version_directive_t) bool { + if version_directive.major != 1 || version_directive.minor != 1 { + return yaml_emitter_set_emitter_error(emitter, "incompatible %YAML directive") + } + return true + } // Check if a %TAG directive is valid. + func yaml_emitter_analyze_tag_directive(emitter *yaml_emitter_t, tag_directive *yaml_tag_directive_t) bool { + handle := tag_directive.handle + prefix := tag_directive.prefix + if len(handle) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag handle must not be empty") + } + if handle[0] != '!' { + return yaml_emitter_set_emitter_error(emitter, "tag handle must start with '!'") + } + if handle[len(handle)-1] != '!' { + return yaml_emitter_set_emitter_error(emitter, "tag handle must end with '!'") + } + for i := 1; i < len(handle)-1; i += width(handle[i]) { + if !is_alpha(handle, i) { + return yaml_emitter_set_emitter_error(emitter, "tag handle must contain alphanumerical characters only") + } + } + if len(prefix) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag prefix must not be empty") + } + return true + } // Check if an anchor is valid. + func yaml_emitter_analyze_anchor(emitter *yaml_emitter_t, anchor []byte, alias bool) bool { + if len(anchor) == 0 { + problem := "anchor value must not be empty" + if alias { + problem = "alias value must not be empty" + } + return yaml_emitter_set_emitter_error(emitter, problem) + } + for i := 0; i < len(anchor); i += width(anchor[i]) { + if !is_alpha(anchor, i) { + problem := "anchor value must contain alphanumerical characters only" + if alias { + problem = "alias value must contain alphanumerical characters only" + } + return yaml_emitter_set_emitter_error(emitter, problem) + } + } + emitter.anchor_data.anchor = anchor + emitter.anchor_data.alias = alias + return true + } // Check if a tag is valid. + func yaml_emitter_analyze_tag(emitter *yaml_emitter_t, tag []byte) bool { + if len(tag) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag value must not be empty") + } + for i := 0; i < len(emitter.tag_directives); i++ { + tag_directive := &emitter.tag_directives[i] + if bytes.HasPrefix(tag, tag_directive.prefix) { + emitter.tag_data.handle = tag_directive.handle + emitter.tag_data.suffix = tag[len(tag_directive.prefix):] + return true + } + } + emitter.tag_data.suffix = tag + return true + } // Check if a scalar is valid. -func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { - var ( - block_indicators = false - flow_indicators = false - line_breaks = false - special_characters = false - tab_characters = false - leading_space = false - leading_break = false +func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { + + var ( + block_indicators = false + + flow_indicators = false + + line_breaks = false + + special_characters = false + + tab_characters = false + + leading_space = false + + leading_break = false + trailing_space = false + trailing_break = false - break_space = false - space_break = false + + break_space = false + + space_break = false preceded_by_whitespace = false + followed_by_whitespace = false - previous_space = false - previous_break = false + + previous_space = false + + previous_break = false ) emitter.scalar_data.value = value if len(value) == 0 { + emitter.scalar_data.multiline = false + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = true + emitter.scalar_data.single_quoted_allowed = true + emitter.scalar_data.block_allowed = false + return true + } if len(value) >= 3 && ((value[0] == '-' && value[1] == '-' && value[2] == '-') || (value[0] == '.' && value[1] == '.' && value[2] == '.')) { + block_indicators = true + flow_indicators = true + } preceded_by_whitespace = true + for i, w := 0, 0; i < len(value); i += w { + w = width(value[i]) + followed_by_whitespace = i+w >= len(value) || is_blank(value, i+w) if i == 0 { + switch value[i] { + case '#', ',', '[', ']', '{', '}', '&', '*', '!', '|', '>', '\'', '"', '%', '@', '`': + flow_indicators = true + block_indicators = true + case '?', ':': + flow_indicators = true + if followed_by_whitespace { + block_indicators = true + } + case '-': + if followed_by_whitespace { + flow_indicators = true + block_indicators = true + } + } + } else { + switch value[i] { + case ',', '?', '[', ']', '{', '}': + flow_indicators = true + case ':': + flow_indicators = true + if followed_by_whitespace { + block_indicators = true + } + case '#': + if preceded_by_whitespace { + flow_indicators = true + block_indicators = true + } + } + } if value[i] == '\t' { + tab_characters = true + } else if !is_printable(value, i) || !is_ascii(value, i) && !emitter.unicode { + special_characters = true + } + if is_space(value, i) { + if i == 0 { + leading_space = true + } + if i+width(value[i]) == len(value) { + trailing_space = true + } + if previous_break { + break_space = true + } + previous_space = true + previous_break = false + } else if is_break(value, i) { + line_breaks = true + if i == 0 { + leading_break = true + } + if i+width(value[i]) == len(value) { + trailing_break = true + } + if previous_space { + space_break = true + } + previous_space = false + previous_break = true + } else { + previous_space = false + previous_break = false + } // [Go]: Why 'z'? Couldn't be the end of the string as that's the loop condition. + preceded_by_whitespace = is_blankz(value, i) + } emitter.scalar_data.multiline = line_breaks + emitter.scalar_data.flow_plain_allowed = true + emitter.scalar_data.block_plain_allowed = true + emitter.scalar_data.single_quoted_allowed = true + emitter.scalar_data.block_allowed = true if leading_space || leading_break || trailing_space || trailing_break { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + } + if trailing_space { + emitter.scalar_data.block_allowed = false + } + if break_space { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + emitter.scalar_data.single_quoted_allowed = false + } + if space_break || tab_characters || special_characters { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + emitter.scalar_data.single_quoted_allowed = false + } + if space_break || special_characters { + emitter.scalar_data.block_allowed = false + } + if line_breaks { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + } + if flow_indicators { + emitter.scalar_data.flow_plain_allowed = false + } + if block_indicators { + emitter.scalar_data.block_plain_allowed = false + } + return true + } // Check if the event data is valid. + func yaml_emitter_analyze_event(emitter *yaml_emitter_t, event *yaml_event_t) bool { emitter.anchor_data.anchor = nil + emitter.tag_data.handle = nil + emitter.tag_data.suffix = nil + emitter.scalar_data.value = nil if len(event.head_comment) > 0 { + emitter.head_comment = event.head_comment + } + if len(event.line_comment) > 0 { + emitter.line_comment = event.line_comment + } + if len(event.foot_comment) > 0 { + emitter.foot_comment = event.foot_comment + } + if len(event.tail_comment) > 0 { + emitter.tail_comment = event.tail_comment + } switch event.typ { + case yaml_ALIAS_EVENT: + if !yaml_emitter_analyze_anchor(emitter, event.anchor, true) { + return false + } case yaml_SCALAR_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || (!event.implicit && !event.quoted_implicit)) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + if !yaml_emitter_analyze_scalar(emitter, event.value) { + return false + } case yaml_SEQUENCE_START_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } case yaml_MAPPING_START_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + } + return true + } // Write the BOM character. + func yaml_emitter_write_bom(emitter *yaml_emitter_t) bool { + if !flush(emitter) { + return false + } + pos := emitter.buffer_pos + emitter.buffer[pos+0] = '\xEF' + emitter.buffer[pos+1] = '\xBB' + emitter.buffer[pos+2] = '\xBF' + emitter.buffer_pos += 3 + return true + } func yaml_emitter_write_indent(emitter *yaml_emitter_t) bool { + indent := emitter.indent + if indent < 0 { + indent = 0 + } + if !emitter.indention || emitter.column > indent || (emitter.column == indent && !emitter.whitespace) { + if !put_break(emitter) { + return false + } + } + if emitter.foot_indent == indent { + if !put_break(emitter) { + return false + } + } + for emitter.column < indent { + if !put(emitter, ' ') { + return false + } + } + emitter.whitespace = true + //emitter.indention = true + emitter.space_above = false + emitter.foot_indent = -1 + return true + } func yaml_emitter_write_indicator(emitter *yaml_emitter_t, indicator []byte, need_whitespace, is_whitespace, is_indention bool) bool { + if need_whitespace && !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + if !write_all(emitter, indicator) { + return false + } + emitter.whitespace = is_whitespace + emitter.indention = (emitter.indention && is_indention) + emitter.open_ended = false + return true + } func yaml_emitter_write_anchor(emitter *yaml_emitter_t, value []byte) bool { + if !write_all(emitter, value) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true + } func yaml_emitter_write_tag_handle(emitter *yaml_emitter_t, value []byte) bool { + if !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + if !write_all(emitter, value) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true + } func yaml_emitter_write_tag_content(emitter *yaml_emitter_t, value []byte, need_whitespace bool) bool { + if need_whitespace && !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + for i := 0; i < len(value); { + var must_write bool + switch value[i] { + case ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '_', '.', '~', '*', '\'', '(', ')', '[', ']': + must_write = true + default: + must_write = is_alpha(value, i) + } + if must_write { + if !write(emitter, value, &i) { + return false + } + } else { + w := width(value[i]) + for k := 0; k < w; k++ { + octet := value[i] + i++ + if !put(emitter, '%') { + return false + } c := octet >> 4 + if c < 10 { + c += '0' + } else { + c += 'A' - 10 + } + if !put(emitter, c) { + return false + } c = octet & 0x0f + if c < 10 { + c += '0' + } else { + c += 'A' - 10 + } + if !put(emitter, c) { + return false + } + } + } + } + emitter.whitespace = false + emitter.indention = false + return true + } func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + if len(value) > 0 && !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } spaces := false + breaks := false + for i := 0; i < len(value); { + if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && !is_space(value, i+1) { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + spaces = true + } else if is_break(value, i) { + if !breaks && value[i] == '\n' { + if !put_break(emitter) { + return false + } + } + if !write_break(emitter, value, &i) { + return false + } + //emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + spaces = false + breaks = false + } + } if len(value) > 0 { + emitter.whitespace = false + } + emitter.indention = false + if emitter.root_context { + emitter.open_ended = true + } return true + } func yaml_emitter_write_single_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { if !yaml_emitter_write_indicator(emitter, []byte{'\''}, true, false, false) { + return false + } spaces := false + breaks := false + for i := 0; i < len(value); { + if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 && !is_space(value, i+1) { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + spaces = true + } else if is_break(value, i) { + if !breaks && value[i] == '\n' { + if !put_break(emitter) { + return false + } + } + if !write_break(emitter, value, &i) { + return false + } + //emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if value[i] == '\'' { + if !put(emitter, '\'') { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + spaces = false + breaks = false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'\''}, false, false, false) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true + } func yaml_emitter_write_double_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + spaces := false + if !yaml_emitter_write_indicator(emitter, []byte{'"'}, true, false, false) { + return false + } for i := 0; i < len(value); { + if !is_printable(value, i) || (!emitter.unicode && !is_ascii(value, i)) || + is_bom(value, i) || is_break(value, i) || + value[i] == '"' || value[i] == '\\' { octet := value[i] var w int + var v rune + switch { + case octet&0x80 == 0x00: + w, v = 1, rune(octet&0x7F) + case octet&0xE0 == 0xC0: + w, v = 2, rune(octet&0x1F) + case octet&0xF0 == 0xE0: + w, v = 3, rune(octet&0x0F) + case octet&0xF8 == 0xF0: + w, v = 4, rune(octet&0x07) + } + for k := 1; k < w; k++ { + octet = value[i+k] + v = (v << 6) + (rune(octet) & 0x3F) + } + i += w if !put(emitter, '\\') { + return false + } var ok bool + switch v { + case 0x00: + ok = put(emitter, '0') + case 0x07: + ok = put(emitter, 'a') + case 0x08: + ok = put(emitter, 'b') + case 0x09: + ok = put(emitter, 't') + case 0x0A: + ok = put(emitter, 'n') + case 0x0b: + ok = put(emitter, 'v') + case 0x0c: + ok = put(emitter, 'f') + case 0x0d: + ok = put(emitter, 'r') + case 0x1b: + ok = put(emitter, 'e') + case 0x22: + ok = put(emitter, '"') + case 0x5c: + ok = put(emitter, '\\') + case 0x85: + ok = put(emitter, 'N') + case 0xA0: + ok = put(emitter, '_') + case 0x2028: + ok = put(emitter, 'L') + case 0x2029: + ok = put(emitter, 'P') + default: + if v <= 0xFF { + ok = put(emitter, 'x') + w = 2 + } else if v <= 0xFFFF { + ok = put(emitter, 'u') + w = 4 + } else { + ok = put(emitter, 'U') + w = 8 + } + for k := (w - 1) * 4; ok && k >= 0; k -= 4 { + digit := byte((v >> uint(k)) & 0x0F) + if digit < 10 { + ok = put(emitter, digit+'0') + } else { + ok = put(emitter, digit+'A'-10) + } + } + } + if !ok { + return false + } + spaces = false + } else if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 { + if !yaml_emitter_write_indent(emitter) { + return false + } + if is_space(value, i+1) { + if !put(emitter, '\\') { + return false + } + } + i += width(value[i]) + } else if !write(emitter, value, &i) { + return false + } + spaces = true + } else { + if !write(emitter, value, &i) { + return false + } + spaces = false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'"'}, false, false, false) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true + } func yaml_emitter_write_block_scalar_hints(emitter *yaml_emitter_t, value []byte) bool { + if is_space(value, 0) || is_break(value, 0) { + indent_hint := []byte{'0' + byte(emitter.best_indent)} + if !yaml_emitter_write_indicator(emitter, indent_hint, false, false, false) { + return false + } + } emitter.open_ended = false var chomp_hint [1]byte + if len(value) == 0 { + chomp_hint[0] = '-' + } else { + i := len(value) - 1 + for value[i]&0xC0 == 0x80 { + i-- + } + if !is_break(value, i) { + chomp_hint[0] = '-' + } else if i == 0 { + chomp_hint[0] = '+' + emitter.open_ended = true + } else { + i-- + for value[i]&0xC0 == 0x80 { + i-- + } + if is_break(value, i) { + chomp_hint[0] = '+' + emitter.open_ended = true + } + } + } + if chomp_hint[0] != 0 { + if !yaml_emitter_write_indicator(emitter, chomp_hint[:], false, false, false) { + return false + } + } + return true + } func yaml_emitter_write_literal_scalar(emitter *yaml_emitter_t, value []byte) bool { + if !yaml_emitter_write_indicator(emitter, []byte{'|'}, true, false, false) { + return false + } + if !yaml_emitter_write_block_scalar_hints(emitter, value) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + //emitter.indention = true + emitter.whitespace = true + breaks := true + for i := 0; i < len(value); { + if is_break(value, i) { + if !write_break(emitter, value, &i) { + return false + } + //emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + breaks = false + } + } return true + } func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) bool { + if !yaml_emitter_write_indicator(emitter, []byte{'>'}, true, false, false) { + return false + } + if !yaml_emitter_write_block_scalar_hints(emitter, value) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } //emitter.indention = true + emitter.whitespace = true breaks := true + leading_spaces := true + for i := 0; i < len(value); { + if is_break(value, i) { + if !breaks && !leading_spaces && value[i] == '\n' { + k := 0 + for is_break(value, k) { + k += width(value[k]) + } + if !is_blankz(value, k) { + if !put_break(emitter) { + return false + } + } + } + if !write_break(emitter, value, &i) { + return false + } + //emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + leading_spaces = is_blank(value, i) + } + if !breaks && is_space(value, i) && !is_space(value, i+1) && emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + emitter.indention = false + breaks = false + } + } + return true + } func yaml_emitter_write_comment(emitter *yaml_emitter_t, comment []byte) bool { + breaks := false + pound := false + for i := 0; i < len(comment); { + if is_break(comment, i) { + if !write_break(emitter, comment, &i) { + return false + } + //emitter.indention = true + breaks = true + pound = false + } else { + if breaks && !yaml_emitter_write_indent(emitter) { + return false + } + if !pound { + if comment[i] != '#' && (!put(emitter, '#') || !put(emitter, ' ')) { + return false + } + pound = true + } + if !write(emitter, comment, &i) { + return false + } + emitter.indention = false + breaks = false + } + } + if !breaks && !put_break(emitter) { + return false + } emitter.whitespace = true + //emitter.indention = true + return true + } diff --git a/vendor/gopkg.in/yaml.v3/encode.go b/vendor/gopkg.in/yaml.v3/encode.go index de9e72a..38e9d9c 100644 --- a/vendor/gopkg.in/yaml.v3/encode.go +++ b/vendor/gopkg.in/yaml.v3/encode.go @@ -1,16 +1,29 @@ // + // Copyright (c) 2011-2019 Canonical Ltd + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package yaml @@ -29,549 +42,1015 @@ import ( ) type encoder struct { - emitter yaml_emitter_t - event yaml_event_t - out []byte - flow bool - indent int + emitter yaml_emitter_t + + event yaml_event_t + + out []byte + + flow bool + + indent int + doneInit bool } func newEncoder() *encoder { + e := &encoder{} + yaml_emitter_initialize(&e.emitter) + yaml_emitter_set_output_string(&e.emitter, &e.out) + yaml_emitter_set_unicode(&e.emitter, true) + return e + } func newEncoderWithWriter(w io.Writer) *encoder { + e := &encoder{} + yaml_emitter_initialize(&e.emitter) + yaml_emitter_set_output_writer(&e.emitter, w) + yaml_emitter_set_unicode(&e.emitter, true) + return e + } func (e *encoder) init() { + if e.doneInit { + return + } + if e.indent == 0 { + e.indent = 4 + } + e.emitter.best_indent = e.indent + yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING) + e.emit() + e.doneInit = true + } func (e *encoder) finish() { + e.emitter.open_ended = false + yaml_stream_end_event_initialize(&e.event) + e.emit() + } func (e *encoder) destroy() { + yaml_emitter_delete(&e.emitter) + } func (e *encoder) emit() { + // This will internally delete the e.event value. + e.must(yaml_emitter_emit(&e.emitter, &e.event)) + } func (e *encoder) must(ok bool) { + if !ok { + msg := e.emitter.problem + if msg == "" { + msg = "unknown problem generating YAML content" + } + failf("%s", msg) + } + } func (e *encoder) marshalDoc(tag string, in reflect.Value) { + e.init() + var node *Node + if in.IsValid() { + node, _ = in.Interface().(*Node) + } + if node != nil && node.Kind == DocumentNode { + e.nodev(in) + } else { + yaml_document_start_event_initialize(&e.event, nil, nil, true) + e.emit() + e.marshal(tag, in) + yaml_document_end_event_initialize(&e.event, true) + e.emit() + } + } func (e *encoder) marshal(tag string, in reflect.Value) { + tag = shortTag(tag) + if !in.IsValid() || in.Kind() == reflect.Ptr && in.IsNil() { + e.nilv() + return + } + iface := in.Interface() + switch value := iface.(type) { + case *Node: + e.nodev(in) + return + case Node: + if !in.CanAddr() { + var n = reflect.New(in.Type()).Elem() + n.Set(in) + in = n + } + e.nodev(in.Addr()) + return + case time.Time: + e.timev(tag, in) + return + case *time.Time: + e.timev(tag, in.Elem()) + return + case time.Duration: + e.stringv(tag, reflect.ValueOf(value.String())) + return + case Marshaler: + v, err := value.MarshalYAML() + if err != nil { + fail(err) + } + if v == nil { + e.nilv() + return + } + e.marshal(tag, reflect.ValueOf(v)) + return + case encoding.TextMarshaler: + text, err := value.MarshalText() + if err != nil { + fail(err) + } + in = reflect.ValueOf(string(text)) + case nil: + e.nilv() + return + } + switch in.Kind() { + case reflect.Interface: + e.marshal(tag, in.Elem()) + case reflect.Map: + e.mapv(tag, in) + case reflect.Ptr: + e.marshal(tag, in.Elem()) + case reflect.Struct: + e.structv(tag, in) + case reflect.Slice, reflect.Array: + e.slicev(tag, in) + case reflect.String: + e.stringv(tag, in) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + e.intv(tag, in) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + e.uintv(tag, in) + case reflect.Float32, reflect.Float64: + e.floatv(tag, in) + case reflect.Bool: + e.boolv(tag, in) + default: + panic("cannot marshal type: " + in.Type().String()) + } + } func (e *encoder) mapv(tag string, in reflect.Value) { + e.mappingv(tag, func() { + keys := keyList(in.MapKeys()) + sort.Sort(keys) + for _, k := range keys { + e.marshal("", k) + e.marshal("", in.MapIndex(k)) + } + }) + } func (e *encoder) fieldByIndex(v reflect.Value, index []int) (field reflect.Value) { + for _, num := range index { + for { + if v.Kind() == reflect.Ptr { + if v.IsNil() { + return reflect.Value{} + } + v = v.Elem() + continue + } + break + } + v = v.Field(num) + } + return v + } func (e *encoder) structv(tag string, in reflect.Value) { + sinfo, err := getStructInfo(in.Type()) + if err != nil { + panic(err) + } + e.mappingv(tag, func() { + for _, info := range sinfo.FieldsList { + var value reflect.Value + if info.Inline == nil { + value = in.Field(info.Num) + } else { + value = e.fieldByIndex(in, info.Inline) + if !value.IsValid() { + continue + } + } + if info.OmitEmpty && isZero(value) { + continue + } + e.marshal("", reflect.ValueOf(info.Key)) + e.flow = info.Flow + e.marshal("", value) + } + if sinfo.InlineMap >= 0 { + m := in.Field(sinfo.InlineMap) + if m.Len() > 0 { + e.flow = false + keys := keyList(m.MapKeys()) + sort.Sort(keys) + for _, k := range keys { + if _, found := sinfo.FieldsMap[k.String()]; found { + panic(fmt.Sprintf("cannot have key %q in inlined map: conflicts with struct field", k.String())) + } + e.marshal("", k) + e.flow = false + e.marshal("", m.MapIndex(k)) + } + } + } + }) + } func (e *encoder) mappingv(tag string, f func()) { + implicit := tag == "" + style := yaml_BLOCK_MAPPING_STYLE + if e.flow { + e.flow = false + style = yaml_FLOW_MAPPING_STYLE + } + yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style) + e.emit() + f() + yaml_mapping_end_event_initialize(&e.event) + e.emit() + } func (e *encoder) slicev(tag string, in reflect.Value) { + implicit := tag == "" + style := yaml_BLOCK_SEQUENCE_STYLE + if e.flow { + e.flow = false + style = yaml_FLOW_SEQUENCE_STYLE + } + e.must(yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)) + e.emit() + n := in.Len() + for i := 0; i < n; i++ { + e.marshal("", in.Index(i)) + } + e.must(yaml_sequence_end_event_initialize(&e.event)) + e.emit() + } // isBase60 returns whether s is in base 60 notation as defined in YAML 1.1. + // + // The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported + // in YAML 1.2 and by this package, but these should be marshalled quoted for + // the time being for compatibility with other parsers. + func isBase60Float(s string) (result bool) { + // Fast path. + if s == "" { + return false + } + c := s[0] + if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 { + return false + } + // Do the full match. + return base60float.MatchString(s) + } // From http://yaml.org/type/float.html, except the regular expression there + // is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix. + var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`) // isOldBool returns whether s is bool notation as defined in YAML 1.1. + // + // We continue to force strings that YAML 1.1 would interpret as booleans to be + // rendered as quotes strings so that the marshalled output valid for YAML 1.1 + // parsing. + func isOldBool(s string) (result bool) { + switch s { + case "y", "Y", "yes", "Yes", "YES", "on", "On", "ON", + "n", "N", "no", "No", "NO", "off", "Off", "OFF": + return true + default: + return false + } + } func (e *encoder) stringv(tag string, in reflect.Value) { + var style yaml_scalar_style_t + s := in.String() + canUsePlain := true + switch { + case !utf8.ValidString(s): + if tag == binaryTag { + failf("explicitly tagged !!binary data must be base64-encoded") + } + if tag != "" { + failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag)) + } + // It can't be encoded directly as YAML so use a binary tag + // and encode it as base64. + tag = binaryTag + s = encodeBase64(s) + case tag == "": + // Check to see if it would resolve to a specific + // tag when encoded unquoted. If it doesn't, + // there's no need to quote it. + rtag, _ := resolve("", s) + canUsePlain = rtag == strTag && !(isBase60Float(s) || isOldBool(s)) + } + // Note: it's possible for user code to emit invalid YAML + // if they explicitly specify a tag and a string containing + // text that's incompatible with that tag. + switch { + case strings.Contains(s, "\n"): + if e.flow { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } else { + style = yaml_LITERAL_SCALAR_STYLE + } + case canUsePlain: + style = yaml_PLAIN_SCALAR_STYLE + default: + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + e.emitScalar(s, "", tag, style, nil, nil, nil, nil) + } func (e *encoder) boolv(tag string, in reflect.Value) { + var s string + if in.Bool() { + s = "true" + } else { + s = "false" + } + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) + } func (e *encoder) intv(tag string, in reflect.Value) { + s := strconv.FormatInt(in.Int(), 10) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) + } func (e *encoder) uintv(tag string, in reflect.Value) { + s := strconv.FormatUint(in.Uint(), 10) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) + } func (e *encoder) timev(tag string, in reflect.Value) { + t := in.Interface().(time.Time) + s := t.Format(time.RFC3339Nano) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) + } func (e *encoder) floatv(tag string, in reflect.Value) { + // Issue #352: When formatting, use the precision of the underlying value + precision := 64 + if in.Kind() == reflect.Float32 { + precision = 32 + } s := strconv.FormatFloat(in.Float(), 'g', -1, precision) + switch s { + case "+Inf": + s = ".inf" + case "-Inf": + s = "-.inf" + case "NaN": + s = ".nan" + } + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) + } func (e *encoder) nilv() { + e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) + } func (e *encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t, head, line, foot, tail []byte) { + // TODO Kill this function. Replace all initialize calls by their underlining Go literals. + implicit := tag == "" + if !implicit { + tag = longTag(tag) + } + e.must(yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(tag), []byte(value), implicit, implicit, style)) + e.event.head_comment = head + e.event.line_comment = line + e.event.foot_comment = foot + e.event.tail_comment = tail + e.emit() + } func (e *encoder) nodev(in reflect.Value) { + e.node(in.Interface().(*Node), "") + } func (e *encoder) node(node *Node, tail string) { + // Zero nodes behave as nil. + if node.Kind == 0 && node.IsZero() { + e.nilv() + return + } // If the tag was not explicitly requested, and dropping it won't change the + // implicit tag of the value, don't include it in the presentation. + var tag = node.Tag + var stag = shortTag(tag) + var forceQuoting bool + if tag != "" && node.Style&TaggedStyle == 0 { + if node.Kind == ScalarNode { + if stag == strTag && node.Style&(SingleQuotedStyle|DoubleQuotedStyle|LiteralStyle|FoldedStyle) != 0 { + tag = "" + } else { + rtag, _ := resolve("", node.Value) + if rtag == stag { + tag = "" + } else if stag == strTag { + tag = "" + forceQuoting = true + } + } + } else { + var rtag string + switch node.Kind { + case MappingNode: + rtag = mapTag + case SequenceNode: + rtag = seqTag + } + if rtag == stag { + tag = "" + } + } + } switch node.Kind { + case DocumentNode: + yaml_document_start_event_initialize(&e.event, nil, nil, true) + e.event.head_comment = []byte(node.HeadComment) + e.emit() + for _, node := range node.Content { + e.node(node, "") + } + yaml_document_end_event_initialize(&e.event, true) + e.event.foot_comment = []byte(node.FootComment) + e.emit() case SequenceNode: + style := yaml_BLOCK_SEQUENCE_STYLE + if node.Style&FlowStyle != 0 { + style = yaml_FLOW_SEQUENCE_STYLE + } + e.must(yaml_sequence_start_event_initialize(&e.event, []byte(node.Anchor), []byte(longTag(tag)), tag == "", style)) + e.event.head_comment = []byte(node.HeadComment) + e.emit() + for _, node := range node.Content { + e.node(node, "") + } + e.must(yaml_sequence_end_event_initialize(&e.event)) + e.event.line_comment = []byte(node.LineComment) + e.event.foot_comment = []byte(node.FootComment) + e.emit() case MappingNode: + style := yaml_BLOCK_MAPPING_STYLE + if node.Style&FlowStyle != 0 { + style = yaml_FLOW_MAPPING_STYLE + } + yaml_mapping_start_event_initialize(&e.event, []byte(node.Anchor), []byte(longTag(tag)), tag == "", style) + e.event.tail_comment = []byte(tail) + e.event.head_comment = []byte(node.HeadComment) + e.emit() // The tail logic below moves the foot comment of prior keys to the following key, + // since the value for each key may be a nested structure and the foot needs to be + // processed only the entirety of the value is streamed. The last tail is processed + // with the mapping end event. + var tail string + for i := 0; i+1 < len(node.Content); i += 2 { + k := node.Content[i] + foot := k.FootComment + if foot != "" { + kopy := *k + kopy.FootComment = "" + k = &kopy + } + e.node(k, tail) + tail = foot v := node.Content[i+1] + e.node(v, "") + } yaml_mapping_end_event_initialize(&e.event) + e.event.tail_comment = []byte(tail) + e.event.line_comment = []byte(node.LineComment) + e.event.foot_comment = []byte(node.FootComment) + e.emit() case AliasNode: + yaml_alias_event_initialize(&e.event, []byte(node.Value)) + e.event.head_comment = []byte(node.HeadComment) + e.event.line_comment = []byte(node.LineComment) + e.event.foot_comment = []byte(node.FootComment) + e.emit() case ScalarNode: + value := node.Value + if !utf8.ValidString(value) { + if stag == binaryTag { + failf("explicitly tagged !!binary data must be base64-encoded") + } + if stag != "" { + failf("cannot marshal invalid UTF-8 data as %s", stag) + } + // It can't be encoded directly as YAML so use a binary tag + // and encode it as base64. + tag = binaryTag + value = encodeBase64(value) + } style := yaml_PLAIN_SCALAR_STYLE + switch { + case node.Style&DoubleQuotedStyle != 0: + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + case node.Style&SingleQuotedStyle != 0: + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + case node.Style&LiteralStyle != 0: + style = yaml_LITERAL_SCALAR_STYLE + case node.Style&FoldedStyle != 0: + style = yaml_FOLDED_SCALAR_STYLE + case strings.Contains(value, "\n"): + style = yaml_LITERAL_SCALAR_STYLE + case forceQuoting: + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } e.emitScalar(value, node.Anchor, tag, style, []byte(node.HeadComment), []byte(node.LineComment), []byte(node.FootComment), []byte(tail)) + default: + failf("cannot encode node with unknown kind %d", node.Kind) + } + } diff --git a/vendor/gopkg.in/yaml.v3/resolve.go b/vendor/gopkg.in/yaml.v3/resolve.go index 64ae888..3afc603 100644 --- a/vendor/gopkg.in/yaml.v3/resolve.go +++ b/vendor/gopkg.in/yaml.v3/resolve.go @@ -1,16 +1,29 @@ // + // Copyright (c) 2011-2019 Canonical Ltd + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package yaml @@ -26,301 +39,545 @@ import ( type resolveMapItem struct { value interface{} - tag string + + tag string } var resolveTable = make([]byte, 256) + var resolveMap = make(map[string]resolveMapItem) func init() { + t := resolveTable + t[int('+')] = 'S' // Sign + t[int('-')] = 'S' + for _, c := range "0123456789" { + t[int(c)] = 'D' // Digit + } + for _, c := range "yYnNtTfFoO~" { + t[int(c)] = 'M' // In map + } + t[int('.')] = '.' // Float (potentially in map) var resolveMapList = []struct { - v interface{} + v interface{} + tag string - l []string + + l []string }{ + {true, boolTag, []string{"true", "True", "TRUE"}}, + {false, boolTag, []string{"false", "False", "FALSE"}}, + {nil, nullTag, []string{"", "~", "null", "Null", "NULL"}}, + {math.NaN(), floatTag, []string{".nan", ".NaN", ".NAN"}}, + {math.Inf(+1), floatTag, []string{".inf", ".Inf", ".INF"}}, + {math.Inf(+1), floatTag, []string{"+.inf", "+.Inf", "+.INF"}}, + {math.Inf(-1), floatTag, []string{"-.inf", "-.Inf", "-.INF"}}, + {"<<", mergeTag, []string{"<<"}}, } m := resolveMap + for _, item := range resolveMapList { + for _, s := range item.l { + m[s] = resolveMapItem{item.v, item.tag} + } + } + } const ( - nullTag = "!!null" - boolTag = "!!bool" - strTag = "!!str" - intTag = "!!int" - floatTag = "!!float" + nullTag = "!!null" + + boolTag = "!!bool" + + strTag = "!!str" + + intTag = "!!int" + + floatTag = "!!float" + timestampTag = "!!timestamp" - seqTag = "!!seq" - mapTag = "!!map" - binaryTag = "!!binary" - mergeTag = "!!merge" + + seqTag = "!!seq" + + mapTag = "!!map" + + binaryTag = "!!binary" + + mergeTag = "!!merge" ) var longTags = make(map[string]string) + var shortTags = make(map[string]string) func init() { + for _, stag := range []string{nullTag, boolTag, strTag, intTag, floatTag, timestampTag, seqTag, mapTag, binaryTag, mergeTag} { + ltag := longTag(stag) + longTags[stag] = ltag + shortTags[ltag] = stag + } + } const longTagPrefix = "tag:yaml.org,2002:" func shortTag(tag string) string { + if strings.HasPrefix(tag, longTagPrefix) { + if stag, ok := shortTags[tag]; ok { + return stag + } + return "!!" + tag[len(longTagPrefix):] + } + return tag + } func longTag(tag string) string { + if strings.HasPrefix(tag, "!!") { + if ltag, ok := longTags[tag]; ok { + return ltag + } + return longTagPrefix + tag[2:] + } + return tag + } func resolvableTag(tag string) bool { + switch tag { + case "", strTag, boolTag, intTag, floatTag, nullTag, timestampTag: + return true + } + return false + } var yamlStyleFloat = regexp.MustCompile(`^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$`) func resolve(tag string, in string) (rtag string, out interface{}) { + tag = shortTag(tag) + if !resolvableTag(tag) { + return tag, in + } defer func() { + switch tag { + case "", rtag, strTag, binaryTag: + return + case floatTag: + if rtag == intTag { + switch v := out.(type) { + case int64: + rtag = floatTag + out = float64(v) + return + case int: + rtag = floatTag + out = float64(v) + return + } + } + } + failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag)) + }() // Any data is accepted as a !!str or !!binary. + // Otherwise, the prefix is enough of a hint about what it might be. + hint := byte('N') + if in != "" { + hint = resolveTable[in[0]] + } + if hint != 0 && tag != strTag && tag != binaryTag { + // Handle things we can lookup in a map. + if item, ok := resolveMap[in]; ok { + return item.tag, item.value + } // Base 60 floats are a bad idea, were dropped in YAML 1.2, and + // are purposefully unsupported here. They're still quoted on + // the way out for compatibility with other parser, though. switch hint { + case 'M': + // We've already checked the map above. case '.': + // Not in the map, so maybe a normal float. + floatv, err := strconv.ParseFloat(in, 64) + if err == nil { + return floatTag, floatv + } case 'D', 'S': + // Int, float, or timestamp. + // Only try values as a timestamp if the value is unquoted or there's an explicit + // !!timestamp tag. + if tag == "" || tag == timestampTag { + t, ok := parseTimestamp(in) + if ok { + return timestampTag, t + } + } plain := strings.Replace(in, "_", "", -1) + intv, err := strconv.ParseInt(plain, 0, 64) + if err == nil { + if intv == int64(int(intv)) { + return intTag, int(intv) + } else { + return intTag, intv + } + } + uintv, err := strconv.ParseUint(plain, 0, 64) + if err == nil { + return intTag, uintv + } + if yamlStyleFloat.MatchString(plain) { + floatv, err := strconv.ParseFloat(plain, 64) + if err == nil { + return floatTag, floatv + } + } + if strings.HasPrefix(plain, "0b") { + intv, err := strconv.ParseInt(plain[2:], 2, 64) + if err == nil { + if intv == int64(int(intv)) { + return intTag, int(intv) + } else { + return intTag, intv + } + } + uintv, err := strconv.ParseUint(plain[2:], 2, 64) + if err == nil { + return intTag, uintv + } + } else if strings.HasPrefix(plain, "-0b") { + intv, err := strconv.ParseInt("-"+plain[3:], 2, 64) + if err == nil { + if true || intv == int64(int(intv)) { + return intTag, int(intv) + } else { + return intTag, intv + } + } + } + // Octals as introduced in version 1.2 of the spec. + // Octals from the 1.1 spec, spelled as 0777, are still + // decoded by default in v3 as well for compatibility. + // May be dropped in v4 depending on how usage evolves. + if strings.HasPrefix(plain, "0o") { + intv, err := strconv.ParseInt(plain[2:], 8, 64) + if err == nil { + if intv == int64(int(intv)) { + return intTag, int(intv) + } else { + return intTag, intv + } + } + uintv, err := strconv.ParseUint(plain[2:], 8, 64) + if err == nil { + return intTag, uintv + } + } else if strings.HasPrefix(plain, "-0o") { + intv, err := strconv.ParseInt("-"+plain[3:], 8, 64) + if err == nil { + if true || intv == int64(int(intv)) { + return intTag, int(intv) + } else { + return intTag, intv + } + } + } + default: + panic("internal error: missing handler for resolver table: " + string(rune(hint)) + " (with " + in + ")") + } + } + return strTag, in + } // encodeBase64 encodes s as base64 that is broken up into multiple lines + // as appropriate for the resulting length. + func encodeBase64(s string) string { + const lineLen = 70 + encLen := base64.StdEncoding.EncodedLen(len(s)) + lines := encLen/lineLen + 1 + buf := make([]byte, encLen*2+lines) + in := buf[0:encLen] + out := buf[encLen:] + base64.StdEncoding.Encode(in, []byte(s)) + k := 0 + for i := 0; i < len(in); i += lineLen { + j := i + lineLen + if j > len(in) { + j = len(in) + } + k += copy(out[k:], in[i:j]) + if lines > 1 { + out[k] = '\n' + k++ + } + } + return string(out[:k]) + } // This is a subset of the formats allowed by the regular expression + // defined at http://yaml.org/type/timestamp.html. + var allowedTimestampFormats = []string{ + "2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields. + "2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t". - "2006-1-2 15:4:5.999999999", // space separated with no time zone - "2006-1-2", // date only + + "2006-1-2 15:4:5.999999999", // space separated with no time zone + + "2006-1-2", // date only + // Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5" + // from the set of examples. + } // parseTimestamp parses s as a timestamp string and + // returns the timestamp and reports whether it succeeded. + // Timestamp formats are defined at http://yaml.org/type/timestamp.html + func parseTimestamp(s string) (time.Time, bool) { + // TODO write code to check all the formats supported by + // http://yaml.org/type/timestamp.html instead of using time.Parse. // Quick check: all date formats start with YYYY-. + i := 0 + for ; i < len(s); i++ { + if c := s[i]; c < '0' || c > '9' { + break + } + } + if i != 4 || i == len(s) || s[i] != '-' { + return time.Time{}, false + } + for _, format := range allowedTimestampFormats { + if t, err := time.Parse(format, s); err == nil { + return t, true + } + } + return time.Time{}, false + } diff --git a/vendor/gopkg.in/yaml.v3/scannerc.go b/vendor/gopkg.in/yaml.v3/scannerc.go index 30b1f08..0bd826b 100644 --- a/vendor/gopkg.in/yaml.v3/scannerc.go +++ b/vendor/gopkg.in/yaml.v3/scannerc.go @@ -1,23 +1,43 @@ // + // Copyright (c) 2011-2019 Canonical Ltd + // Copyright (c) 2006-2010 Kirill Simonov + // + // Permission is hereby granted, free of charge, to any person obtaining a copy of + // this software and associated documentation files (the "Software"), to deal in + // the Software without restriction, including without limitation the rights to + // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + // of the Software, and to permit persons to whom the Software is furnished to do + // so, subject to the following conditions: + // + // The above copyright notice and this permission notice shall be included in all + // copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + // SOFTWARE. package yaml @@ -28,3013 +48,5348 @@ import ( ) // Introduction + // ************ + // + // The following notes assume that you are familiar with the YAML specification + // (http://yaml.org/spec/1.2/spec.html). We mostly follow it, although in + // some cases we are less restrictive that it requires. + // + // The process of transforming a YAML stream into a sequence of events is + // divided on two steps: Scanning and Parsing. + // + // The Scanner transforms the input stream into a sequence of tokens, while the + // parser transform the sequence of tokens produced by the Scanner into a + // sequence of parsing events. + // + // The Scanner is rather clever and complicated. The Parser, on the contrary, + // is a straightforward implementation of a recursive-descendant parser (or, + // LL(1) parser, as it is usually called). + // + // Actually there are two issues of Scanning that might be called "clever", the + // rest is quite straightforward. The issues are "block collection start" and + // "simple keys". Both issues are explained below in details. + // + // Here the Scanning step is explained and implemented. We start with the list + // of all the tokens produced by the Scanner together with short descriptions. + // + // Now, tokens: + // + // STREAM-START(encoding) # The stream start. + // STREAM-END # The stream end. + // VERSION-DIRECTIVE(major,minor) # The '%YAML' directive. + // TAG-DIRECTIVE(handle,prefix) # The '%TAG' directive. + // DOCUMENT-START # '---' + // DOCUMENT-END # '...' + // BLOCK-SEQUENCE-START # Indentation increase denoting a block + // BLOCK-MAPPING-START # sequence or a block mapping. + // BLOCK-END # Indentation decrease. + // FLOW-SEQUENCE-START # '[' + // FLOW-SEQUENCE-END # ']' + // BLOCK-SEQUENCE-START # '{' + // BLOCK-SEQUENCE-END # '}' + // BLOCK-ENTRY # '-' + // FLOW-ENTRY # ',' + // KEY # '?' or nothing (simple keys). + // VALUE # ':' + // ALIAS(anchor) # '*anchor' + // ANCHOR(anchor) # '&anchor' + // TAG(handle,suffix) # '!handle!suffix' + // SCALAR(value,style) # A scalar. + // + // The following two tokens are "virtual" tokens denoting the beginning and the + // end of the stream: + // + // STREAM-START(encoding) + // STREAM-END + // + // We pass the information about the input stream encoding with the + // STREAM-START token. + // + // The next two tokens are responsible for tags: + // + // VERSION-DIRECTIVE(major,minor) + // TAG-DIRECTIVE(handle,prefix) + // + // Example: + // + // %YAML 1.1 + // %TAG ! !foo + // %TAG !yaml! tag:yaml.org,2002: + // --- + // + // The correspoding sequence of tokens: + // + // STREAM-START(utf-8) + // VERSION-DIRECTIVE(1,1) + // TAG-DIRECTIVE("!","!foo") + // TAG-DIRECTIVE("!yaml","tag:yaml.org,2002:") + // DOCUMENT-START + // STREAM-END + // + // Note that the VERSION-DIRECTIVE and TAG-DIRECTIVE tokens occupy a whole + // line. + // + // The document start and end indicators are represented by: + // + // DOCUMENT-START + // DOCUMENT-END + // + // Note that if a YAML stream contains an implicit document (without '---' + // and '...' indicators), no DOCUMENT-START and DOCUMENT-END tokens will be + // produced. + // + // In the following examples, we present whole documents together with the + // produced tokens. + // + // 1. An implicit document: + // + // 'a scalar' + // + // Tokens: + // + // STREAM-START(utf-8) + // SCALAR("a scalar",single-quoted) + // STREAM-END + // + // 2. An explicit document: + // + // --- + // 'a scalar' + // ... + // + // Tokens: + // + // STREAM-START(utf-8) + // DOCUMENT-START + // SCALAR("a scalar",single-quoted) + // DOCUMENT-END + // STREAM-END + // + // 3. Several documents in a stream: + // + // 'a scalar' + // --- + // 'another scalar' + // --- + // 'yet another scalar' + // + // Tokens: + // + // STREAM-START(utf-8) + // SCALAR("a scalar",single-quoted) + // DOCUMENT-START + // SCALAR("another scalar",single-quoted) + // DOCUMENT-START + // SCALAR("yet another scalar",single-quoted) + // STREAM-END + // + // We have already introduced the SCALAR token above. The following tokens are + // used to describe aliases, anchors, tag, and scalars: + // + // ALIAS(anchor) + // ANCHOR(anchor) + // TAG(handle,suffix) + // SCALAR(value,style) + // + // The following series of examples illustrate the usage of these tokens: + // + // 1. A recursive sequence: + // + // &A [ *A ] + // + // Tokens: + // + // STREAM-START(utf-8) + // ANCHOR("A") + // FLOW-SEQUENCE-START + // ALIAS("A") + // FLOW-SEQUENCE-END + // STREAM-END + // + // 2. A tagged scalar: + // + // !!float "3.14" # A good approximation. + // + // Tokens: + // + // STREAM-START(utf-8) + // TAG("!!","float") + // SCALAR("3.14",double-quoted) + // STREAM-END + // + // 3. Various scalar styles: + // + // --- # Implicit empty plain scalars do not produce tokens. + // --- a plain scalar + // --- 'a single-quoted scalar' + // --- "a double-quoted scalar" + // --- |- + // a literal scalar + // --- >- + // a folded + // scalar + // + // Tokens: + // + // STREAM-START(utf-8) + // DOCUMENT-START + // DOCUMENT-START + // SCALAR("a plain scalar",plain) + // DOCUMENT-START + // SCALAR("a single-quoted scalar",single-quoted) + // DOCUMENT-START + // SCALAR("a double-quoted scalar",double-quoted) + // DOCUMENT-START + // SCALAR("a literal scalar",literal) + // DOCUMENT-START + // SCALAR("a folded scalar",folded) + // STREAM-END + // + // Now it's time to review collection-related tokens. We will start with + // flow collections: + // + // FLOW-SEQUENCE-START + // FLOW-SEQUENCE-END + // FLOW-MAPPING-START + // FLOW-MAPPING-END + // FLOW-ENTRY + // KEY + // VALUE + // + // The tokens FLOW-SEQUENCE-START, FLOW-SEQUENCE-END, FLOW-MAPPING-START, and + // FLOW-MAPPING-END represent the indicators '[', ']', '{', and '}' + // correspondingly. FLOW-ENTRY represent the ',' indicator. Finally the + // indicators '?' and ':', which are used for denoting mapping keys and values, + // are represented by the KEY and VALUE tokens. + // + // The following examples show flow collections: + // + // 1. A flow sequence: + // + // [item 1, item 2, item 3] + // + // Tokens: + // + // STREAM-START(utf-8) + // FLOW-SEQUENCE-START + // SCALAR("item 1",plain) + // FLOW-ENTRY + // SCALAR("item 2",plain) + // FLOW-ENTRY + // SCALAR("item 3",plain) + // FLOW-SEQUENCE-END + // STREAM-END + // + // 2. A flow mapping: + // + // { + // a simple key: a value, # Note that the KEY token is produced. + // ? a complex key: another value, + // } + // + // Tokens: + // + // STREAM-START(utf-8) + // FLOW-MAPPING-START + // KEY + // SCALAR("a simple key",plain) + // VALUE + // SCALAR("a value",plain) + // FLOW-ENTRY + // KEY + // SCALAR("a complex key",plain) + // VALUE + // SCALAR("another value",plain) + // FLOW-ENTRY + // FLOW-MAPPING-END + // STREAM-END + // + // A simple key is a key which is not denoted by the '?' indicator. Note that + // the Scanner still produce the KEY token whenever it encounters a simple key. + // + // For scanning block collections, the following tokens are used (note that we + // repeat KEY and VALUE here): + // + // BLOCK-SEQUENCE-START + // BLOCK-MAPPING-START + // BLOCK-END + // BLOCK-ENTRY + // KEY + // VALUE + // + // The tokens BLOCK-SEQUENCE-START and BLOCK-MAPPING-START denote indentation + // increase that precedes a block collection (cf. the INDENT token in Python). + // The token BLOCK-END denote indentation decrease that ends a block collection + // (cf. the DEDENT token in Python). However YAML has some syntax pecularities + // that makes detections of these tokens more complex. + // + // The tokens BLOCK-ENTRY, KEY, and VALUE are used to represent the indicators + // '-', '?', and ':' correspondingly. + // + // The following examples show how the tokens BLOCK-SEQUENCE-START, + // BLOCK-MAPPING-START, and BLOCK-END are emitted by the Scanner: + // + // 1. Block sequences: + // + // - item 1 + // - item 2 + // - + // - item 3.1 + // - item 3.2 + // - + // key 1: value 1 + // key 2: value 2 + // + // Tokens: + // + // STREAM-START(utf-8) + // BLOCK-SEQUENCE-START + // BLOCK-ENTRY + // SCALAR("item 1",plain) + // BLOCK-ENTRY + // SCALAR("item 2",plain) + // BLOCK-ENTRY + // BLOCK-SEQUENCE-START + // BLOCK-ENTRY + // SCALAR("item 3.1",plain) + // BLOCK-ENTRY + // SCALAR("item 3.2",plain) + // BLOCK-END + // BLOCK-ENTRY + // BLOCK-MAPPING-START + // KEY + // SCALAR("key 1",plain) + // VALUE + // SCALAR("value 1",plain) + // KEY + // SCALAR("key 2",plain) + // VALUE + // SCALAR("value 2",plain) + // BLOCK-END + // BLOCK-END + // STREAM-END + // + // 2. Block mappings: + // + // a simple key: a value # The KEY token is produced here. + // ? a complex key + // : another value + // a mapping: + // key 1: value 1 + // key 2: value 2 + // a sequence: + // - item 1 + // - item 2 + // + // Tokens: + // + // STREAM-START(utf-8) + // BLOCK-MAPPING-START + // KEY + // SCALAR("a simple key",plain) + // VALUE + // SCALAR("a value",plain) + // KEY + // SCALAR("a complex key",plain) + // VALUE + // SCALAR("another value",plain) + // KEY + // SCALAR("a mapping",plain) + // BLOCK-MAPPING-START + // KEY + // SCALAR("key 1",plain) + // VALUE + // SCALAR("value 1",plain) + // KEY + // SCALAR("key 2",plain) + // VALUE + // SCALAR("value 2",plain) + // BLOCK-END + // KEY + // SCALAR("a sequence",plain) + // VALUE + // BLOCK-SEQUENCE-START + // BLOCK-ENTRY + // SCALAR("item 1",plain) + // BLOCK-ENTRY + // SCALAR("item 2",plain) + // BLOCK-END + // BLOCK-END + // STREAM-END + // + // YAML does not always require to start a new block collection from a new + // line. If the current line contains only '-', '?', and ':' indicators, a new + // block collection may start at the current line. The following examples + // illustrate this case: + // + // 1. Collections in a sequence: + // + // - - item 1 + // - item 2 + // - key 1: value 1 + // key 2: value 2 + // - ? complex key + // : complex value + // + // Tokens: + // + // STREAM-START(utf-8) + // BLOCK-SEQUENCE-START + // BLOCK-ENTRY + // BLOCK-SEQUENCE-START + // BLOCK-ENTRY + // SCALAR("item 1",plain) + // BLOCK-ENTRY + // SCALAR("item 2",plain) + // BLOCK-END + // BLOCK-ENTRY + // BLOCK-MAPPING-START + // KEY + // SCALAR("key 1",plain) + // VALUE + // SCALAR("value 1",plain) + // KEY + // SCALAR("key 2",plain) + // VALUE + // SCALAR("value 2",plain) + // BLOCK-END + // BLOCK-ENTRY + // BLOCK-MAPPING-START + // KEY + // SCALAR("complex key") + // VALUE + // SCALAR("complex value") + // BLOCK-END + // BLOCK-END + // STREAM-END + // + // 2. Collections in a mapping: + // + // ? a sequence + // : - item 1 + // - item 2 + // ? a mapping + // : key 1: value 1 + // key 2: value 2 + // + // Tokens: + // + // STREAM-START(utf-8) + // BLOCK-MAPPING-START + // KEY + // SCALAR("a sequence",plain) + // VALUE + // BLOCK-SEQUENCE-START + // BLOCK-ENTRY + // SCALAR("item 1",plain) + // BLOCK-ENTRY + // SCALAR("item 2",plain) + // BLOCK-END + // KEY + // SCALAR("a mapping",plain) + // VALUE + // BLOCK-MAPPING-START + // KEY + // SCALAR("key 1",plain) + // VALUE + // SCALAR("value 1",plain) + // KEY + // SCALAR("key 2",plain) + // VALUE + // SCALAR("value 2",plain) + // BLOCK-END + // BLOCK-END + // STREAM-END + // + // YAML also permits non-indented sequences if they are included into a block + // mapping. In this case, the token BLOCK-SEQUENCE-START is not produced: + // + // key: + // - item 1 # BLOCK-SEQUENCE-START is NOT produced here. + // - item 2 + // + // Tokens: + // + // STREAM-START(utf-8) + // BLOCK-MAPPING-START + // KEY + // SCALAR("key",plain) + // VALUE + // BLOCK-ENTRY + // SCALAR("item 1",plain) + // BLOCK-ENTRY + // SCALAR("item 2",plain) + // BLOCK-END + // // Ensure that the buffer contains the required number of characters. + // Return true on success, false on failure (reader error or memory error). + func cache(parser *yaml_parser_t, length int) bool { + // [Go] This was inlined: !cache(A, B) -> unread < B && !update(A, B) + return parser.unread >= length || yaml_parser_update_buffer(parser, length) + } // Advance the buffer pointer. + func skip(parser *yaml_parser_t) { + if !is_blank(parser.buffer, parser.buffer_pos) { + parser.newlines = 0 + } + parser.mark.index++ + parser.mark.column++ + parser.unread-- + parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) + } func skip_line(parser *yaml_parser_t) { + if is_crlf(parser.buffer, parser.buffer_pos) { + parser.mark.index += 2 + parser.mark.column = 0 + parser.mark.line++ + parser.unread -= 2 + parser.buffer_pos += 2 + parser.newlines++ + } else if is_break(parser.buffer, parser.buffer_pos) { + parser.mark.index++ + parser.mark.column = 0 + parser.mark.line++ + parser.unread-- + parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) + parser.newlines++ + } + } // Copy a character to a string buffer and advance pointers. + func read(parser *yaml_parser_t, s []byte) []byte { + if !is_blank(parser.buffer, parser.buffer_pos) { + parser.newlines = 0 + } + w := width(parser.buffer[parser.buffer_pos]) + if w == 0 { + panic("invalid character sequence") + } + if len(s) == 0 { + s = make([]byte, 0, 32) + } + if w == 1 && len(s)+w <= cap(s) { + s = s[:len(s)+1] + s[len(s)-1] = parser.buffer[parser.buffer_pos] + parser.buffer_pos++ + } else { + s = append(s, parser.buffer[parser.buffer_pos:parser.buffer_pos+w]...) + parser.buffer_pos += w + } + parser.mark.index++ + parser.mark.column++ + parser.unread-- + return s + } // Copy a line break character to a string buffer and advance pointers. + func read_line(parser *yaml_parser_t, s []byte) []byte { + buf := parser.buffer + pos := parser.buffer_pos + switch { + case buf[pos] == '\r' && buf[pos+1] == '\n': + // CR LF . LF + s = append(s, '\n') + parser.buffer_pos += 2 + parser.mark.index++ + parser.unread-- + case buf[pos] == '\r' || buf[pos] == '\n': + // CR|LF . LF + s = append(s, '\n') + parser.buffer_pos += 1 + case buf[pos] == '\xC2' && buf[pos+1] == '\x85': + // NEL . LF + s = append(s, '\n') + parser.buffer_pos += 2 + case buf[pos] == '\xE2' && buf[pos+1] == '\x80' && (buf[pos+2] == '\xA8' || buf[pos+2] == '\xA9'): + // LS|PS . LS|PS + s = append(s, buf[parser.buffer_pos:pos+3]...) + parser.buffer_pos += 3 + default: + return s + } + parser.mark.index++ + parser.mark.column = 0 + parser.mark.line++ + parser.unread-- + parser.newlines++ + return s + } // Get the next token. + func yaml_parser_scan(parser *yaml_parser_t, token *yaml_token_t) bool { + // Erase the token object. + *token = yaml_token_t{} // [Go] Is this necessary? // No tokens after STREAM-END or error. + if parser.stream_end_produced || parser.error != yaml_NO_ERROR { + return true + } // Ensure that the tokens queue contains enough tokens. + if !parser.token_available { + if !yaml_parser_fetch_more_tokens(parser) { + return false + } + } // Fetch the next token from the queue. + *token = parser.tokens[parser.tokens_head] + parser.tokens_head++ + parser.tokens_parsed++ + parser.token_available = false if token.typ == yaml_STREAM_END_TOKEN { + parser.stream_end_produced = true + } + return true + } // Set the scanner error and return false. + func yaml_parser_set_scanner_error(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string) bool { + parser.error = yaml_SCANNER_ERROR + parser.context = context + parser.context_mark = context_mark + parser.problem = problem + parser.problem_mark = parser.mark + return false + } func yaml_parser_set_scanner_tag_error(parser *yaml_parser_t, directive bool, context_mark yaml_mark_t, problem string) bool { + context := "while parsing a tag" + if directive { + context = "while parsing a %TAG directive" + } + return yaml_parser_set_scanner_error(parser, context, context_mark, problem) + } func trace(args ...interface{}) func() { + pargs := append([]interface{}{"+++"}, args...) + fmt.Println(pargs...) + pargs = append([]interface{}{"---"}, args...) + return func() { fmt.Println(pargs...) } + } // Ensure that the tokens queue contains at least one token which can be + // returned to the Parser. + func yaml_parser_fetch_more_tokens(parser *yaml_parser_t) bool { + // While we need more tokens to fetch, do it. + for { + // [Go] The comment parsing logic requires a lookahead of two tokens + // so that foot comments may be parsed in time of associating them + // with the tokens that are parsed before them, and also for line + // comments to be transformed into head comments in some edge cases. + if parser.tokens_head < len(parser.tokens)-2 { + // If a potential simple key is at the head position, we need to fetch + // the next token to disambiguate it. + head_tok_idx, ok := parser.simple_keys_by_tok[parser.tokens_parsed] + if !ok { + break + } else if valid, ok := yaml_simple_key_is_valid(parser, &parser.simple_keys[head_tok_idx]); !ok { + return false + } else if !valid { + break + } + } + // Fetch the next token. + if !yaml_parser_fetch_next_token(parser) { + return false + } + } parser.token_available = true + return true + } // The dispatcher for token fetchers. + func yaml_parser_fetch_next_token(parser *yaml_parser_t) (ok bool) { + // Ensure that the buffer is initialized. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } // Check if we just started scanning. Fetch STREAM-START then. + if !parser.stream_start_produced { + return yaml_parser_fetch_stream_start(parser) + } scan_mark := parser.mark // Eat whitespaces and comments until we reach the next token. + if !yaml_parser_scan_to_next_token(parser) { + return false + } // [Go] While unrolling indents, transform the head comments of prior + // indentation levels observed after scan_start into foot comments at + // the respective indexes. // Check the indentation level against the current column. + if !yaml_parser_unroll_indent(parser, parser.mark.column, scan_mark) { + return false + } // Ensure that the buffer contains at least 4 characters. 4 is the length + // of the longest indicators ('--- ' and '... '). + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } // Is it the end of the stream? + if is_z(parser.buffer, parser.buffer_pos) { + return yaml_parser_fetch_stream_end(parser) + } // Is it a directive? + if parser.mark.column == 0 && parser.buffer[parser.buffer_pos] == '%' { + return yaml_parser_fetch_directive(parser) + } buf := parser.buffer + pos := parser.buffer_pos // Is it the document start indicator? + if parser.mark.column == 0 && buf[pos] == '-' && buf[pos+1] == '-' && buf[pos+2] == '-' && is_blankz(buf, pos+3) { + return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_START_TOKEN) + } // Is it the document end indicator? + if parser.mark.column == 0 && buf[pos] == '.' && buf[pos+1] == '.' && buf[pos+2] == '.' && is_blankz(buf, pos+3) { + return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_END_TOKEN) + } comment_mark := parser.mark + if len(parser.tokens) > 0 && (parser.flow_level == 0 && buf[pos] == ':' || parser.flow_level > 0 && buf[pos] == ',') { + // Associate any following comments with the prior token. + comment_mark = parser.tokens[len(parser.tokens)-1].start_mark + } + defer func() { + if !ok { + return + } + if len(parser.tokens) > 0 && parser.tokens[len(parser.tokens)-1].typ == yaml_BLOCK_ENTRY_TOKEN { + // Sequence indicators alone have no line comments. It becomes + // a head comment for whatever follows. + return + } + if !yaml_parser_scan_line_comment(parser, comment_mark) { + ok = false + return + } + }() // Is it the flow sequence start indicator? + if buf[pos] == '[' { + return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_SEQUENCE_START_TOKEN) + } // Is it the flow mapping start indicator? + if parser.buffer[parser.buffer_pos] == '{' { + return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_MAPPING_START_TOKEN) + } // Is it the flow sequence end indicator? + if parser.buffer[parser.buffer_pos] == ']' { + return yaml_parser_fetch_flow_collection_end(parser, + yaml_FLOW_SEQUENCE_END_TOKEN) + } // Is it the flow mapping end indicator? + if parser.buffer[parser.buffer_pos] == '}' { + return yaml_parser_fetch_flow_collection_end(parser, + yaml_FLOW_MAPPING_END_TOKEN) + } // Is it the flow entry indicator? + if parser.buffer[parser.buffer_pos] == ',' { + return yaml_parser_fetch_flow_entry(parser) + } // Is it the block entry indicator? + if parser.buffer[parser.buffer_pos] == '-' && is_blankz(parser.buffer, parser.buffer_pos+1) { + return yaml_parser_fetch_block_entry(parser) + } // Is it the key indicator? + if parser.buffer[parser.buffer_pos] == '?' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_key(parser) + } // Is it the value indicator? + if parser.buffer[parser.buffer_pos] == ':' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_value(parser) + } // Is it an alias? + if parser.buffer[parser.buffer_pos] == '*' { + return yaml_parser_fetch_anchor(parser, yaml_ALIAS_TOKEN) + } // Is it an anchor? + if parser.buffer[parser.buffer_pos] == '&' { + return yaml_parser_fetch_anchor(parser, yaml_ANCHOR_TOKEN) + } // Is it a tag? + if parser.buffer[parser.buffer_pos] == '!' { + return yaml_parser_fetch_tag(parser) + } // Is it a literal scalar? + if parser.buffer[parser.buffer_pos] == '|' && parser.flow_level == 0 { + return yaml_parser_fetch_block_scalar(parser, true) + } // Is it a folded scalar? + if parser.buffer[parser.buffer_pos] == '>' && parser.flow_level == 0 { + return yaml_parser_fetch_block_scalar(parser, false) + } // Is it a single-quoted scalar? + if parser.buffer[parser.buffer_pos] == '\'' { + return yaml_parser_fetch_flow_scalar(parser, true) + } // Is it a double-quoted scalar? + if parser.buffer[parser.buffer_pos] == '"' { + return yaml_parser_fetch_flow_scalar(parser, false) + } // Is it a plain scalar? + // + // A plain scalar may start with any non-blank characters except + // + // '-', '?', ':', ',', '[', ']', '{', '}', + // '#', '&', '*', '!', '|', '>', '\'', '\"', + // '%', '@', '`'. + // + // In the block context (and, for the '-' indicator, in the flow context + // too), it may also start with the characters + // + // '-', '?', ':' + // + // if it is followed by a non-space character. + // + // The last rule is more restrictive than the specification requires. + // [Go] TODO Make this logic more reasonable. + //switch parser.buffer[parser.buffer_pos] { + //case '-', '?', ':', ',', '?', '-', ',', ':', ']', '[', '}', '{', '&', '#', '!', '*', '>', '|', '"', '\'', '@', '%', '-', '`': + //} + if !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '-' || + parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':' || + parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '[' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || + parser.buffer[parser.buffer_pos] == '}' || parser.buffer[parser.buffer_pos] == '#' || + parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '*' || + parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '|' || + parser.buffer[parser.buffer_pos] == '>' || parser.buffer[parser.buffer_pos] == '\'' || + parser.buffer[parser.buffer_pos] == '"' || parser.buffer[parser.buffer_pos] == '%' || + parser.buffer[parser.buffer_pos] == '@' || parser.buffer[parser.buffer_pos] == '`') || + (parser.buffer[parser.buffer_pos] == '-' && !is_blank(parser.buffer, parser.buffer_pos+1)) || + (parser.flow_level == 0 && + (parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':') && + !is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_plain_scalar(parser) + } // If we don't determine the token type so far, it is an error. + return yaml_parser_set_scanner_error(parser, + "while scanning for the next token", parser.mark, + "found character that cannot start any token") + } func yaml_simple_key_is_valid(parser *yaml_parser_t, simple_key *yaml_simple_key_t) (valid, ok bool) { + if !simple_key.possible { + return false, true + } // The 1.2 specification says: + // + // "If the ? indicator is omitted, parsing needs to see past the + // implicit key to recognize it as such. To limit the amount of + // lookahead required, the “:” indicator must appear at most 1024 + // Unicode characters beyond the start of the key. In addition, the key + // is restricted to a single line." + // + if simple_key.mark.line < parser.mark.line || simple_key.mark.index+1024 < parser.mark.index { + // Check if the potential simple key to be removed is required. + if simple_key.required { + return false, yaml_parser_set_scanner_error(parser, + "while scanning a simple key", simple_key.mark, + "could not find expected ':'") + } + simple_key.possible = false + return false, true + } + return true, true + } // Check if a simple key may start at the current position and add it if + // needed. + func yaml_parser_save_simple_key(parser *yaml_parser_t) bool { + // A simple key is required at the current position if the scanner is in + // the block context and the current column coincides with the indentation + // level. required := parser.flow_level == 0 && parser.indent == parser.mark.column // + // If the current position may start a simple key, save it. + // + if parser.simple_key_allowed { + simple_key := yaml_simple_key_t{ - possible: true, - required: required, + + possible: true, + + required: required, + token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), - mark: parser.mark, + + mark: parser.mark, } if !yaml_parser_remove_simple_key(parser) { + return false + } + parser.simple_keys[len(parser.simple_keys)-1] = simple_key + parser.simple_keys_by_tok[simple_key.token_number] = len(parser.simple_keys) - 1 + } + return true + } // Remove a potential simple key at the current flow level. + func yaml_parser_remove_simple_key(parser *yaml_parser_t) bool { + i := len(parser.simple_keys) - 1 + if parser.simple_keys[i].possible { + // If the key is required, it is an error. + if parser.simple_keys[i].required { + return yaml_parser_set_scanner_error(parser, + "while scanning a simple key", parser.simple_keys[i].mark, + "could not find expected ':'") + } + // Remove the key from the stack. + parser.simple_keys[i].possible = false + delete(parser.simple_keys_by_tok, parser.simple_keys[i].token_number) + } + return true + } // max_flow_level limits the flow_level + const max_flow_level = 10000 // Increase the flow level and resize the simple key list if needed. + func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool { + // Reset the simple key on the next level. + parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{ - possible: false, - required: false, + + possible: false, + + required: false, + token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), - mark: parser.mark, + + mark: parser.mark, }) // Increase the flow level. + parser.flow_level++ + if parser.flow_level > max_flow_level { + return yaml_parser_set_scanner_error(parser, + "while increasing flow level", parser.simple_keys[len(parser.simple_keys)-1].mark, + fmt.Sprintf("exceeded max depth of %d", max_flow_level)) + } + return true + } // Decrease the flow level. + func yaml_parser_decrease_flow_level(parser *yaml_parser_t) bool { + if parser.flow_level > 0 { + parser.flow_level-- + last := len(parser.simple_keys) - 1 + delete(parser.simple_keys_by_tok, parser.simple_keys[last].token_number) + parser.simple_keys = parser.simple_keys[:last] + } + return true + } // max_indents limits the indents stack size + const max_indents = 10000 // Push the current indentation level to the stack and set the new level + // the current column is greater than the indentation level. In this case, + // append or insert the specified token into the token queue. + func yaml_parser_roll_indent(parser *yaml_parser_t, column, number int, typ yaml_token_type_t, mark yaml_mark_t) bool { + // In the flow context, do nothing. + if parser.flow_level > 0 { + return true + } if parser.indent < column { + // Push the current indentation level to the stack and set the new + // indentation level. + parser.indents = append(parser.indents, parser.indent) + parser.indent = column + if len(parser.indents) > max_indents { + return yaml_parser_set_scanner_error(parser, + "while increasing indent level", parser.simple_keys[len(parser.simple_keys)-1].mark, + fmt.Sprintf("exceeded max depth of %d", max_indents)) + } // Create a token and insert it into the queue. + token := yaml_token_t{ - typ: typ, + + typ: typ, + start_mark: mark, - end_mark: mark, + + end_mark: mark, } + if number > -1 { + number -= parser.tokens_parsed + } + yaml_insert_token(parser, number, &token) + } + return true + } // Pop indentation levels from the indents stack until the current level + // becomes less or equal to the column. For each indentation level, append + // the BLOCK-END token. + func yaml_parser_unroll_indent(parser *yaml_parser_t, column int, scan_mark yaml_mark_t) bool { + // In the flow context, do nothing. + if parser.flow_level > 0 { + return true + } block_mark := scan_mark + block_mark.index-- // Loop through the indentation levels in the stack. + for parser.indent > column { // [Go] Reposition the end token before potential following + // foot comments of parent blocks. For that, search + // backwards for recent comments that were at the same + // indent as the block that is ending now. + stop_index := block_mark.index + for i := len(parser.comments) - 1; i >= 0; i-- { + comment := &parser.comments[i] if comment.end_mark.index < stop_index { + // Don't go back beyond the start of the comment/whitespace scan, unless column < 0. + // If requested indent column is < 0, then the document is over and everything else + // is a foot anyway. + break + } + if comment.start_mark.column == parser.indent+1 { + // This is a good match. But maybe there's a former comment + // at that same indent level, so keep searching. + block_mark = comment.start_mark + } // While the end of the former comment matches with + // the start of the following one, we know there's + // nothing in between and scanning is still safe. + stop_index = comment.scan_mark.index + } // Create a token and append it to the queue. + token := yaml_token_t{ - typ: yaml_BLOCK_END_TOKEN, + + typ: yaml_BLOCK_END_TOKEN, + start_mark: block_mark, - end_mark: block_mark, + + end_mark: block_mark, } + yaml_insert_token(parser, -1, &token) // Pop the indentation level. + parser.indent = parser.indents[len(parser.indents)-1] + parser.indents = parser.indents[:len(parser.indents)-1] + } + return true + } // Initialize the scanner and produce the STREAM-START token. + func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool { // Set the initial indentation. + parser.indent = -1 // Initialize the simple key stack. + parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) parser.simple_keys_by_tok = make(map[int]int) // A simple key is allowed at the beginning of the stream. + parser.simple_key_allowed = true // We have started. + parser.stream_start_produced = true // Create the STREAM-START token and append it to the queue. + token := yaml_token_t{ - typ: yaml_STREAM_START_TOKEN, + + typ: yaml_STREAM_START_TOKEN, + start_mark: parser.mark, - end_mark: parser.mark, - encoding: parser.encoding, + + end_mark: parser.mark, + + encoding: parser.encoding, } + yaml_insert_token(parser, -1, &token) + return true + } // Produce the STREAM-END token and shut down the scanner. + func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool { // Force new line. + if parser.mark.column != 0 { + parser.mark.column = 0 + parser.mark.line++ + } // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1, parser.mark) { + return false + } // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } parser.simple_key_allowed = false // Create the STREAM-END token and append it to the queue. + token := yaml_token_t{ - typ: yaml_STREAM_END_TOKEN, + + typ: yaml_STREAM_END_TOKEN, + start_mark: parser.mark, - end_mark: parser.mark, + + end_mark: parser.mark, } + yaml_insert_token(parser, -1, &token) + return true + } // Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token. + func yaml_parser_fetch_directive(parser *yaml_parser_t) bool { + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1, parser.mark) { + return false + } // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } parser.simple_key_allowed = false // Create the YAML-DIRECTIVE or TAG-DIRECTIVE token. + token := yaml_token_t{} + if !yaml_parser_scan_directive(parser, &token) { + return false + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true + } // Produce the DOCUMENT-START or DOCUMENT-END token. + func yaml_parser_fetch_document_indicator(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1, parser.mark) { + return false + } // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } parser.simple_key_allowed = false // Consume the token. + start_mark := parser.mark skip(parser) + skip(parser) + skip(parser) end_mark := parser.mark // Create the DOCUMENT-START or DOCUMENT-END token. + token := yaml_token_t{ - typ: typ, + + typ: typ, + start_mark: start_mark, - end_mark: end_mark, + + end_mark: end_mark, } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true + } // Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token. + func yaml_parser_fetch_flow_collection_start(parser *yaml_parser_t, typ yaml_token_type_t) bool { // The indicators '[' and '{' may start a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } // Increase the flow level. + if !yaml_parser_increase_flow_level(parser) { + return false + } // A simple key may follow the indicators '[' and '{'. + parser.simple_key_allowed = true // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark // Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token. + token := yaml_token_t{ - typ: typ, + + typ: typ, + start_mark: start_mark, - end_mark: end_mark, + + end_mark: end_mark, } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true + } // Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token. + func yaml_parser_fetch_flow_collection_end(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // Reset any potential simple key on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } // Decrease the flow level. + if !yaml_parser_decrease_flow_level(parser) { + return false + } // No simple keys after the indicators ']' and '}'. + parser.simple_key_allowed = false // Consume the token. start_mark := parser.mark + skip(parser) + end_mark := parser.mark // Create the FLOW-SEQUENCE-END of FLOW-MAPPING-END token. + token := yaml_token_t{ - typ: typ, + + typ: typ, + start_mark: start_mark, - end_mark: end_mark, + + end_mark: end_mark, } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true + } // Produce the FLOW-ENTRY token. + func yaml_parser_fetch_flow_entry(parser *yaml_parser_t) bool { + // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } // Simple keys are allowed after ','. + parser.simple_key_allowed = true // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark // Create the FLOW-ENTRY token and append it to the queue. + token := yaml_token_t{ - typ: yaml_FLOW_ENTRY_TOKEN, + + typ: yaml_FLOW_ENTRY_TOKEN, + start_mark: start_mark, - end_mark: end_mark, + + end_mark: end_mark, } + yaml_insert_token(parser, -1, &token) + return true + } // Produce the BLOCK-ENTRY token. + func yaml_parser_fetch_block_entry(parser *yaml_parser_t) bool { + // Check if the scanner is in the block context. + if parser.flow_level == 0 { + // Check if we are allowed to start a new entry. + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "block sequence entries are not allowed in this context") + } + // Add the BLOCK-SEQUENCE-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_SEQUENCE_START_TOKEN, parser.mark) { + return false + } + } else { + // It is an error for the '-' indicator to occur in the flow context, + // but we let the Parser detect and report about it because the Parser + // is able to point to the context. + } // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } // Simple keys are allowed after '-'. + parser.simple_key_allowed = true // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark // Create the BLOCK-ENTRY token and append it to the queue. + token := yaml_token_t{ - typ: yaml_BLOCK_ENTRY_TOKEN, + + typ: yaml_BLOCK_ENTRY_TOKEN, + start_mark: start_mark, - end_mark: end_mark, + + end_mark: end_mark, } + yaml_insert_token(parser, -1, &token) + return true + } // Produce the KEY token. + func yaml_parser_fetch_key(parser *yaml_parser_t) bool { // In the block context, additional checks are required. + if parser.flow_level == 0 { + // Check if we are allowed to start a new key (not nessesary simple). + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "mapping keys are not allowed in this context") + } + // Add the BLOCK-MAPPING-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { + return false + } + } // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } // Simple keys are allowed after '?' in the block context. + parser.simple_key_allowed = parser.flow_level == 0 // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark // Create the KEY token and append it to the queue. + token := yaml_token_t{ - typ: yaml_KEY_TOKEN, + + typ: yaml_KEY_TOKEN, + start_mark: start_mark, - end_mark: end_mark, + + end_mark: end_mark, } + yaml_insert_token(parser, -1, &token) + return true + } // Produce the VALUE token. + func yaml_parser_fetch_value(parser *yaml_parser_t) bool { simple_key := &parser.simple_keys[len(parser.simple_keys)-1] // Have we found a simple key? + if valid, ok := yaml_simple_key_is_valid(parser, simple_key); !ok { + return false } else if valid { // Create the KEY token and insert it into the queue. + token := yaml_token_t{ - typ: yaml_KEY_TOKEN, + + typ: yaml_KEY_TOKEN, + start_mark: simple_key.mark, - end_mark: simple_key.mark, + + end_mark: simple_key.mark, } + yaml_insert_token(parser, simple_key.token_number-parser.tokens_parsed, &token) // In the block context, we may need to add the BLOCK-MAPPING-START token. + if !yaml_parser_roll_indent(parser, simple_key.mark.column, + simple_key.token_number, + yaml_BLOCK_MAPPING_START_TOKEN, simple_key.mark) { + return false + } // Remove the simple key. + simple_key.possible = false + delete(parser.simple_keys_by_tok, simple_key.token_number) // A simple key cannot follow another simple key. + parser.simple_key_allowed = false } else { + // The ':' indicator follows a complex key. // In the block context, extra checks are required. + if parser.flow_level == 0 { // Check if we are allowed to start a complex value. + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "mapping values are not allowed in this context") + } // Add the BLOCK-MAPPING-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { + return false + } + } // Simple keys after ':' are allowed in the block context. + parser.simple_key_allowed = parser.flow_level == 0 + } // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark // Create the VALUE token and append it to the queue. + token := yaml_token_t{ - typ: yaml_VALUE_TOKEN, + + typ: yaml_VALUE_TOKEN, + start_mark: start_mark, - end_mark: end_mark, + + end_mark: end_mark, } + yaml_insert_token(parser, -1, &token) + return true + } // Produce the ALIAS or ANCHOR token. + func yaml_parser_fetch_anchor(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // An anchor or an alias could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } // A simple key cannot follow an anchor or an alias. + parser.simple_key_allowed = false // Create the ALIAS or ANCHOR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_anchor(parser, &token, typ) { + return false + } + yaml_insert_token(parser, -1, &token) + return true + } // Produce the TAG token. + func yaml_parser_fetch_tag(parser *yaml_parser_t) bool { + // A tag could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } // A simple key cannot follow a tag. + parser.simple_key_allowed = false // Create the TAG token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_tag(parser, &token) { + return false + } + yaml_insert_token(parser, -1, &token) + return true + } // Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens. + func yaml_parser_fetch_block_scalar(parser *yaml_parser_t, literal bool) bool { + // Remove any potential simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } // A simple key may follow a block scalar. + parser.simple_key_allowed = true // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_block_scalar(parser, &token, literal) { + return false + } + yaml_insert_token(parser, -1, &token) + return true + } // Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens. + func yaml_parser_fetch_flow_scalar(parser *yaml_parser_t, single bool) bool { + // A plain scalar could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } // A simple key cannot follow a flow scalar. + parser.simple_key_allowed = false // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_flow_scalar(parser, &token, single) { + return false + } + yaml_insert_token(parser, -1, &token) + return true + } // Produce the SCALAR(...,plain) token. + func yaml_parser_fetch_plain_scalar(parser *yaml_parser_t) bool { + // A plain scalar could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } // A simple key cannot follow a flow scalar. + parser.simple_key_allowed = false // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_plain_scalar(parser, &token) { + return false + } + yaml_insert_token(parser, -1, &token) + return true + } // Eat whitespaces and comments until the next token is found. + func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool { scan_mark := parser.mark // Until the next token is not found. + for { + // Allow the BOM mark to start a line. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.mark.column == 0 && is_bom(parser.buffer, parser.buffer_pos) { + skip(parser) + } // Eat whitespaces. + // Tabs are allowed: + // - in the flow context + // - in the block context, but not at the beginning of the line or + // after '-', '?', or ':' (complex value). + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } for parser.buffer[parser.buffer_pos] == ' ' || ((parser.flow_level > 0 || !parser.simple_key_allowed) && parser.buffer[parser.buffer_pos] == '\t') { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } // Check if we just had a line comment under a sequence entry that + // looks more like a header to the following content. Similar to this: + // + // - # The comment + // - Some data + // + // If so, transform the line comment to a head comment and reposition. + if len(parser.comments) > 0 && len(parser.tokens) > 1 { + tokenA := parser.tokens[len(parser.tokens)-2] + tokenB := parser.tokens[len(parser.tokens)-1] + comment := &parser.comments[len(parser.comments)-1] + if tokenA.typ == yaml_BLOCK_SEQUENCE_START_TOKEN && tokenB.typ == yaml_BLOCK_ENTRY_TOKEN && len(comment.line) > 0 && !is_break(parser.buffer, parser.buffer_pos) { + // If it was in the prior line, reposition so it becomes a + // header of the follow up token. Otherwise, keep it in place + // so it becomes a header of the former. + comment.head = comment.line + comment.line = nil + if comment.start_mark.line == parser.mark.line-1 { + comment.token_mark = parser.mark + } + } + } // Eat a comment until a line break. + if parser.buffer[parser.buffer_pos] == '#' { + if !yaml_parser_scan_comments(parser, scan_mark) { + return false + } + } // If it is a line break, eat it. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) // In the block context, a new line may start a simple key. + if parser.flow_level == 0 { + parser.simple_key_allowed = true + } + } else { + break // We have found a token. + } + } return true + } // Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token. + // + // Scope: + // + // %YAML 1.1 # a comment \n + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + // %TAG !yaml! tag:yaml.org,2002: \n + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool { + // Eat '%'. + start_mark := parser.mark + skip(parser) // Scan the directive name. + var name []byte + if !yaml_parser_scan_directive_name(parser, start_mark, &name) { + return false + } // Is it a YAML directive? + if bytes.Equal(name, []byte("YAML")) { + // Scan the VERSION directive value. + var major, minor int8 + if !yaml_parser_scan_version_directive_value(parser, start_mark, &major, &minor) { + return false + } + end_mark := parser.mark // Create a VERSION-DIRECTIVE token. + *token = yaml_token_t{ - typ: yaml_VERSION_DIRECTIVE_TOKEN, + + typ: yaml_VERSION_DIRECTIVE_TOKEN, + start_mark: start_mark, - end_mark: end_mark, - major: major, - minor: minor, + + end_mark: end_mark, + + major: major, + + minor: minor, } // Is it a TAG directive? + } else if bytes.Equal(name, []byte("TAG")) { + // Scan the TAG directive value. + var handle, prefix []byte + if !yaml_parser_scan_tag_directive_value(parser, start_mark, &handle, &prefix) { + return false + } + end_mark := parser.mark // Create a TAG-DIRECTIVE token. + *token = yaml_token_t{ - typ: yaml_TAG_DIRECTIVE_TOKEN, + + typ: yaml_TAG_DIRECTIVE_TOKEN, + start_mark: start_mark, - end_mark: end_mark, - value: handle, - prefix: prefix, + + end_mark: end_mark, + + value: handle, + + prefix: prefix, } // Unknown directive. + } else { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "found unknown directive name") + return false + } // Eat the rest of the line including any comments. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } if parser.buffer[parser.buffer_pos] == '#' { + // [Go] Discard this inline comment for the time being. + //if !yaml_parser_scan_line_comment(parser, start_mark) { + // return false + //} + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } // Check if we are at the end of the line. + if !is_breakz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "did not find expected comment or line break") + return false + } // Eat a line break. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } return true + } // Scan the directive name. + // + // Scope: + // + // %YAML 1.1 # a comment \n + // ^^^^ + // %TAG !yaml! tag:yaml.org,2002: \n + // ^^^ + func yaml_parser_scan_directive_name(parser *yaml_parser_t, start_mark yaml_mark_t, name *[]byte) bool { + // Consume the directive name. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } var s []byte + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } // Check if the name is empty. + if len(s) == 0 { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "could not find expected directive name") + return false + } // Check for an blank character after the name. + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "found unexpected non-alphabetical character") + return false + } + *name = s + return true + } // Scan the value of VERSION-DIRECTIVE. + // + // Scope: + // + // %YAML 1.1 # a comment \n + // ^^^^^^ + func yaml_parser_scan_version_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, major, minor *int8) bool { + // Eat whitespaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } // Consume the major version number. + if !yaml_parser_scan_version_directive_number(parser, start_mark, major) { + return false + } // Eat '.'. + if parser.buffer[parser.buffer_pos] != '.' { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "did not find expected digit or '.' character") + } skip(parser) // Consume the minor version number. + if !yaml_parser_scan_version_directive_number(parser, start_mark, minor) { + return false + } + return true + } const max_number_length = 2 // Scan the version number of VERSION-DIRECTIVE. + // + // Scope: + // + // %YAML 1.1 # a comment \n + // ^ + // %YAML 1.1 # a comment \n + // ^ + func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark yaml_mark_t, number *int8) bool { // Repeat while the next character is digit. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + var value, length int8 + for is_digit(parser.buffer, parser.buffer_pos) { + // Check if the number is too long. + length++ + if length > max_number_length { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "found extremely long version number") + } + value = value*10 + int8(as_digit(parser.buffer, parser.buffer_pos)) + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } // Check if the number was present. + if length == 0 { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "did not find expected version number") + } + *number = value + return true + } // Scan the value of a TAG-DIRECTIVE token. + // + // Scope: + // + // %TAG !yaml! tag:yaml.org,2002: \n + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + func yaml_parser_scan_tag_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, handle, prefix *[]byte) bool { + var handle_value, prefix_value []byte // Eat whitespaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } // Scan a handle. + if !yaml_parser_scan_tag_handle(parser, true, start_mark, &handle_value) { + return false + } // Expect a whitespace. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blank(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", + start_mark, "did not find expected whitespace") + return false + } // Eat whitespaces. + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } // Scan a prefix. + if !yaml_parser_scan_tag_uri(parser, true, nil, start_mark, &prefix_value) { + return false + } // Expect a whitespace or line break. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", + start_mark, "did not find expected whitespace or line break") + return false + } *handle = handle_value + *prefix = prefix_value + return true + } func yaml_parser_scan_anchor(parser *yaml_parser_t, token *yaml_token_t, typ yaml_token_type_t) bool { + var s []byte // Eat the indicator character. + start_mark := parser.mark + skip(parser) // Consume the value. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } end_mark := parser.mark /* + * Check if length of the anchor is greater than 0 and it is followed by + * a whitespace character or one of the indicators: + * + * '?', ':', ',', ']', '}', '%', '@', '`'. + */ if len(s) == 0 || + !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '?' || + parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == ',' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '}' || + parser.buffer[parser.buffer_pos] == '%' || parser.buffer[parser.buffer_pos] == '@' || + parser.buffer[parser.buffer_pos] == '`') { + context := "while scanning an alias" + if typ == yaml_ANCHOR_TOKEN { + context = "while scanning an anchor" + } + yaml_parser_set_scanner_error(parser, context, start_mark, + "did not find expected alphabetic or numeric character") + return false + } // Create a token. + *token = yaml_token_t{ - typ: typ, + + typ: typ, + start_mark: start_mark, - end_mark: end_mark, - value: s, + + end_mark: end_mark, + + value: s, } return true + } /* + * Scan a TAG token. + */ func yaml_parser_scan_tag(parser *yaml_parser_t, token *yaml_token_t) bool { + var handle, suffix []byte start_mark := parser.mark // Check if the tag is in the canonical form. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } if parser.buffer[parser.buffer_pos+1] == '<' { + // Keep the handle as '' // Eat '!<' + skip(parser) + skip(parser) // Consume the tag value. + if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { + return false + } // Check for '>' and eat it. + if parser.buffer[parser.buffer_pos] != '>' { + yaml_parser_set_scanner_error(parser, "while scanning a tag", + start_mark, "did not find the expected '>'") + return false + } skip(parser) + } else { + // The tag has either the '!suffix' or the '!handle!suffix' form. // First, try to scan a handle. + if !yaml_parser_scan_tag_handle(parser, false, start_mark, &handle) { + return false + } // Check if it is, indeed, handle. + if handle[0] == '!' && len(handle) > 1 && handle[len(handle)-1] == '!' { + // Scan the suffix now. + if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { + return false + } + } else { + // It wasn't a handle after all. Scan the rest of the tag. + if !yaml_parser_scan_tag_uri(parser, false, handle, start_mark, &suffix) { + return false + } // Set the handle to '!'. + handle = []byte{'!'} // A special case: the '!' tag. Set the handle to '' and the + // suffix to '!'. + if len(suffix) == 0 { + handle, suffix = suffix, handle + } + } + } // Check the character which ends the tag. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a tag", + start_mark, "did not find expected whitespace or line break") + return false + } end_mark := parser.mark // Create a token. + *token = yaml_token_t{ - typ: yaml_TAG_TOKEN, + + typ: yaml_TAG_TOKEN, + start_mark: start_mark, - end_mark: end_mark, - value: handle, - suffix: suffix, + + end_mark: end_mark, + + value: handle, + + suffix: suffix, } + return true + } // Scan a tag handle. + func yaml_parser_scan_tag_handle(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, handle *[]byte) bool { + // Check the initial '!' character. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.buffer[parser.buffer_pos] != '!' { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected '!'") + return false + } var s []byte // Copy the '!' character. + s = read(parser, s) // Copy all subsequent alphabetical and numerical characters. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } // Check if the trailing character is '!' and copy it. + if parser.buffer[parser.buffer_pos] == '!' { + s = read(parser, s) + } else { + // It's either the '!' tag or not really a tag handle. If it's a %TAG + // directive, it's an error. If it's a tag token, it must be a part of URI. + if directive && string(s) != "!" { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected '!'") + return false + } + } *handle = s + return true + } // Scan a tag. + func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte, start_mark yaml_mark_t, uri *[]byte) bool { + //size_t length = head ? strlen((char *)head) : 0 + var s []byte + hasTag := len(head) > 0 // Copy the head if needed. + // + // Note that we don't copy the leading '!' character. + if len(head) > 1 { + s = append(s, head[1:]...) + } // Scan the tag. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } // The set of characters that may appear in URI is as follows: + // + // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&', + // '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']', + // '%'. + // [Go] TODO Convert this into more reasonable logic. + for is_alpha(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == ';' || + parser.buffer[parser.buffer_pos] == '/' || parser.buffer[parser.buffer_pos] == '?' || + parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == '@' || + parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '=' || + parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '$' || + parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '.' || + parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '~' || + parser.buffer[parser.buffer_pos] == '*' || parser.buffer[parser.buffer_pos] == '\'' || + parser.buffer[parser.buffer_pos] == '(' || parser.buffer[parser.buffer_pos] == ')' || + parser.buffer[parser.buffer_pos] == '[' || parser.buffer[parser.buffer_pos] == ']' || + parser.buffer[parser.buffer_pos] == '%' { + // Check if it is a URI-escape sequence. + if parser.buffer[parser.buffer_pos] == '%' { + if !yaml_parser_scan_uri_escapes(parser, directive, start_mark, &s) { + return false + } + } else { + s = read(parser, s) + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + hasTag = true + } if !hasTag { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected tag URI") + return false + } + *uri = s + return true + } // Decode an URI-escape sequence corresponding to a single UTF-8 character. + func yaml_parser_scan_uri_escapes(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, s *[]byte) bool { // Decode the required number of characters. + w := 1024 + for w > 0 { + // Check for a URI-escaped octet. + if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { + return false + } if !(parser.buffer[parser.buffer_pos] == '%' && + is_hex(parser.buffer, parser.buffer_pos+1) && + is_hex(parser.buffer, parser.buffer_pos+2)) { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find URI escaped octet") + } // Get the octet. + octet := byte((as_hex(parser.buffer, parser.buffer_pos+1) << 4) + as_hex(parser.buffer, parser.buffer_pos+2)) // If it is the leading octet, determine the length of the UTF-8 sequence. + if w == 1024 { + w = width(octet) + if w == 0 { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "found an incorrect leading UTF-8 octet") + } + } else { + // Check if the trailing octet is correct. + if octet&0xC0 != 0x80 { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "found an incorrect trailing UTF-8 octet") + } + } // Copy the octet and move the pointers. + *s = append(*s, octet) + skip(parser) + skip(parser) + skip(parser) + w-- + } + return true + } // Scan a block scalar. + func yaml_parser_scan_block_scalar(parser *yaml_parser_t, token *yaml_token_t, literal bool) bool { + // Eat the indicator '|' or '>'. + start_mark := parser.mark + skip(parser) // Scan the additional block scalar indicators. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } // Check for a chomping indicator. + var chomping, increment int + if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { + // Set the chomping method and eat the indicator. + if parser.buffer[parser.buffer_pos] == '+' { + chomping = +1 + } else { + chomping = -1 + } + skip(parser) // Check for an indentation indicator. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if is_digit(parser.buffer, parser.buffer_pos) { + // Check that the indentation is greater than 0. + if parser.buffer[parser.buffer_pos] == '0' { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found an indentation indicator equal to 0") + return false + } // Get the indentation level and eat the indicator. + increment = as_digit(parser.buffer, parser.buffer_pos) + skip(parser) + } } else if is_digit(parser.buffer, parser.buffer_pos) { + // Do the same as above, but in the opposite order. if parser.buffer[parser.buffer_pos] == '0' { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found an indentation indicator equal to 0") + return false + } + increment = as_digit(parser.buffer, parser.buffer_pos) + skip(parser) if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { + if parser.buffer[parser.buffer_pos] == '+' { + chomping = +1 + } else { + chomping = -1 + } + skip(parser) + } + } // Eat whitespaces and comments to the end of the line. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + if parser.buffer[parser.buffer_pos] == '#' { + if !yaml_parser_scan_line_comment(parser, start_mark) { + return false + } + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } // Check if we are at the end of the line. + if !is_breakz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "did not find expected comment or line break") + return false + } // Eat a line break. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } end_mark := parser.mark // Set the indentation level if it was specified. + var indent int + if increment > 0 { + if parser.indent >= 0 { + indent = parser.indent + increment + } else { + indent = increment + } + } // Scan the leading line breaks and determine the indentation level if needed. + var s, leading_break, trailing_breaks []byte + if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { + return false + } // Scan the block scalar content. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + var leading_blank, trailing_blank bool + for parser.mark.column == indent && !is_z(parser.buffer, parser.buffer_pos) { + // We are at the beginning of a non-empty line. // Is it a trailing whitespace? + trailing_blank = is_blank(parser.buffer, parser.buffer_pos) // Check if we need to fold the leading line break. + if !literal && !leading_blank && !trailing_blank && len(leading_break) > 0 && leading_break[0] == '\n' { + // Do we need to join the lines by space? + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } + } else { + s = append(s, leading_break...) + } + leading_break = leading_break[:0] // Append the remaining line breaks. + s = append(s, trailing_breaks...) + trailing_breaks = trailing_breaks[:0] // Is it a leading whitespace? + leading_blank = is_blank(parser.buffer, parser.buffer_pos) // Consume the current line. + for !is_breakz(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } // Consume the line break. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } leading_break = read_line(parser, leading_break) // Eat the following indentation spaces and line breaks. + if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { + return false + } + } // Chomp the tail. + if chomping != -1 { + s = append(s, leading_break...) + } + if chomping == 1 { + s = append(s, trailing_breaks...) + } // Create a token. + *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, + + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_LITERAL_SCALAR_STYLE, + + end_mark: end_mark, + + value: s, + + style: yaml_LITERAL_SCALAR_STYLE, } + if !literal { + token.style = yaml_FOLDED_SCALAR_STYLE + } + return true + } // Scan indentation spaces and line breaks for a block scalar. Determine the + // indentation level if needed. + func yaml_parser_scan_block_scalar_breaks(parser *yaml_parser_t, indent *int, breaks *[]byte, start_mark yaml_mark_t, end_mark *yaml_mark_t) bool { + *end_mark = parser.mark // Eat the indentation spaces and line breaks. + max_indent := 0 + for { + // Eat the indentation spaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for (*indent == 0 || parser.mark.column < *indent) && is_space(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + if parser.mark.column > max_indent { + max_indent = parser.mark.column + } // Check for a tab character messing the indentation. + if (*indent == 0 || parser.mark.column < *indent) && is_tab(parser.buffer, parser.buffer_pos) { + return yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found a tab character where an indentation space is expected") + } // Have we found a non-empty line? + if !is_break(parser.buffer, parser.buffer_pos) { + break + } // Consume the line break. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + // [Go] Should really be returning breaks instead. + *breaks = read_line(parser, *breaks) + *end_mark = parser.mark + } // Determine the indentation level if needed. + if *indent == 0 { + *indent = max_indent + if *indent < parser.indent+1 { + *indent = parser.indent + 1 + } + if *indent < 1 { + *indent = 1 + } + } + return true + } // Scan a quoted scalar. + func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, single bool) bool { + // Eat the left quote. + start_mark := parser.mark + skip(parser) // Consume the content of the quoted scalar. + var s, leading_break, trailing_breaks, whitespaces []byte + for { + // Check that there are no document indicators at the beginning of the line. + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } if parser.mark.column == 0 && + ((parser.buffer[parser.buffer_pos+0] == '-' && + parser.buffer[parser.buffer_pos+1] == '-' && + parser.buffer[parser.buffer_pos+2] == '-') || + (parser.buffer[parser.buffer_pos+0] == '.' && + parser.buffer[parser.buffer_pos+1] == '.' && + parser.buffer[parser.buffer_pos+2] == '.')) && + is_blankz(parser.buffer, parser.buffer_pos+3) { + yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", + start_mark, "found unexpected document indicator") + return false + } // Check for EOF. + if is_z(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", + start_mark, "found unexpected end of stream") + return false + } // Consume non-blank characters. + leading_blanks := false + for !is_blankz(parser.buffer, parser.buffer_pos) { + if single && parser.buffer[parser.buffer_pos] == '\'' && parser.buffer[parser.buffer_pos+1] == '\'' { + // Is is an escaped single quote. + s = append(s, '\'') + skip(parser) + skip(parser) } else if single && parser.buffer[parser.buffer_pos] == '\'' { + // It is a right single quote. + break + } else if !single && parser.buffer[parser.buffer_pos] == '"' { + // It is a right double quote. + break } else if !single && parser.buffer[parser.buffer_pos] == '\\' && is_break(parser.buffer, parser.buffer_pos+1) { + // It is an escaped line break. + if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { + return false + } + skip(parser) + skip_line(parser) + leading_blanks = true + break } else if !single && parser.buffer[parser.buffer_pos] == '\\' { + // It is an escape sequence. + code_length := 0 // Check the escape character. + switch parser.buffer[parser.buffer_pos+1] { + case '0': + s = append(s, 0) + case 'a': + s = append(s, '\x07') + case 'b': + s = append(s, '\x08') + case 't', '\t': + s = append(s, '\x09') + case 'n': + s = append(s, '\x0A') + case 'v': + s = append(s, '\x0B') + case 'f': + s = append(s, '\x0C') + case 'r': + s = append(s, '\x0D') + case 'e': + s = append(s, '\x1B') + case ' ': + s = append(s, '\x20') + case '"': + s = append(s, '"') + case '\'': + s = append(s, '\'') + case '\\': + s = append(s, '\\') + case 'N': // NEL (#x85) + s = append(s, '\xC2') + s = append(s, '\x85') + case '_': // #xA0 + s = append(s, '\xC2') + s = append(s, '\xA0') + case 'L': // LS (#x2028) + s = append(s, '\xE2') + s = append(s, '\x80') + s = append(s, '\xA8') + case 'P': // PS (#x2029) + s = append(s, '\xE2') + s = append(s, '\x80') + s = append(s, '\xA9') + case 'x': + code_length = 2 + case 'u': + code_length = 4 + case 'U': + code_length = 8 + default: + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "found unknown escape character") + return false + } skip(parser) + skip(parser) // Consume an arbitrary escape code. + if code_length > 0 { + var value int // Scan the character value. + if parser.unread < code_length && !yaml_parser_update_buffer(parser, code_length) { + return false + } + for k := 0; k < code_length; k++ { + if !is_hex(parser.buffer, parser.buffer_pos+k) { + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "did not find expected hexdecimal number") + return false + } + value = (value << 4) + as_hex(parser.buffer, parser.buffer_pos+k) + } // Check the value and write the character. + if (value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF { + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "found invalid Unicode character escape code") + return false + } + if value <= 0x7F { + s = append(s, byte(value)) + } else if value <= 0x7FF { + s = append(s, byte(0xC0+(value>>6))) + s = append(s, byte(0x80+(value&0x3F))) + } else if value <= 0xFFFF { + s = append(s, byte(0xE0+(value>>12))) + s = append(s, byte(0x80+((value>>6)&0x3F))) + s = append(s, byte(0x80+(value&0x3F))) + } else { + s = append(s, byte(0xF0+(value>>18))) + s = append(s, byte(0x80+((value>>12)&0x3F))) + s = append(s, byte(0x80+((value>>6)&0x3F))) + s = append(s, byte(0x80+(value&0x3F))) + } // Advance the pointer. + for k := 0; k < code_length; k++ { + skip(parser) + } + } + } else { + // It is a non-escaped non-blank character. + s = read(parser, s) + } + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + } if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } // Check if we are at the end of the scalar. + if single { + if parser.buffer[parser.buffer_pos] == '\'' { + break + } + } else { + if parser.buffer[parser.buffer_pos] == '"' { + break + } + } // Consume blank characters. + for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { + if is_blank(parser.buffer, parser.buffer_pos) { + // Consume a space or a tab character. + if !leading_blanks { + whitespaces = read(parser, whitespaces) + } else { + skip(parser) + } + } else { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } // Check if it is a first line break. + if !leading_blanks { + whitespaces = whitespaces[:0] + leading_break = read_line(parser, leading_break) + leading_blanks = true + } else { + trailing_breaks = read_line(parser, trailing_breaks) + } + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } // Join the whitespaces or fold line breaks. + if leading_blanks { + // Do we need to fold line breaks? + if len(leading_break) > 0 && leading_break[0] == '\n' { + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } else { + s = append(s, trailing_breaks...) + } + } else { + s = append(s, leading_break...) + s = append(s, trailing_breaks...) + } + trailing_breaks = trailing_breaks[:0] + leading_break = leading_break[:0] + } else { + s = append(s, whitespaces...) + whitespaces = whitespaces[:0] + } + } // Eat the right quote. + skip(parser) + end_mark := parser.mark // Create a token. + *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, + + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_SINGLE_QUOTED_SCALAR_STYLE, + + end_mark: end_mark, + + value: s, + + style: yaml_SINGLE_QUOTED_SCALAR_STYLE, } + if !single { + token.style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + return true + } // Scan a plain scalar. + func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) bool { var s, leading_break, trailing_breaks, whitespaces []byte + var leading_blanks bool + var indent = parser.indent + 1 start_mark := parser.mark + end_mark := parser.mark // Consume the content of the plain scalar. + for { + // Check for a document indicator. + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } + if parser.mark.column == 0 && + ((parser.buffer[parser.buffer_pos+0] == '-' && + parser.buffer[parser.buffer_pos+1] == '-' && + parser.buffer[parser.buffer_pos+2] == '-') || + (parser.buffer[parser.buffer_pos+0] == '.' && + parser.buffer[parser.buffer_pos+1] == '.' && + parser.buffer[parser.buffer_pos+2] == '.')) && + is_blankz(parser.buffer, parser.buffer_pos+3) { + break + } // Check for a comment. + if parser.buffer[parser.buffer_pos] == '#' { + break + } // Consume non-blank characters. + for !is_blankz(parser.buffer, parser.buffer_pos) { // Check for indicators that may end a plain scalar. + if (parser.buffer[parser.buffer_pos] == ':' && is_blankz(parser.buffer, parser.buffer_pos+1)) || + (parser.flow_level > 0 && + (parser.buffer[parser.buffer_pos] == ',' || + parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == '[' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || + parser.buffer[parser.buffer_pos] == '}')) { + break + } // Check if we need to join whitespaces and breaks. + if leading_blanks || len(whitespaces) > 0 { + if leading_blanks { + // Do we need to fold line breaks? + if leading_break[0] == '\n' { + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } else { + s = append(s, trailing_breaks...) + } + } else { + s = append(s, leading_break...) + s = append(s, trailing_breaks...) + } + trailing_breaks = trailing_breaks[:0] + leading_break = leading_break[:0] + leading_blanks = false + } else { + s = append(s, whitespaces...) + whitespaces = whitespaces[:0] + } + } // Copy the character. + s = read(parser, s) end_mark = parser.mark + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + } // Is it the end? + if !(is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos)) { + break + } // Consume blank characters. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { + if is_blank(parser.buffer, parser.buffer_pos) { // Check for tab characters that abuse indentation. + if leading_blanks && parser.mark.column < indent && is_tab(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", + start_mark, "found a tab character that violates indentation") + return false + } // Consume a space or a tab character. + if !leading_blanks { + whitespaces = read(parser, whitespaces) + } else { + skip(parser) + } + } else { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } // Check if it is a first line break. + if !leading_blanks { + whitespaces = whitespaces[:0] + leading_break = read_line(parser, leading_break) + leading_blanks = true + } else { + trailing_breaks = read_line(parser, trailing_breaks) + } + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } // Check indentation level. + if parser.flow_level == 0 && parser.mark.column < indent { + break + } + } // Create a token. + *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, + + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_PLAIN_SCALAR_STYLE, + + end_mark: end_mark, + + value: s, + + style: yaml_PLAIN_SCALAR_STYLE, } // Note that we change the 'simple_key_allowed' flag. + if leading_blanks { + parser.simple_key_allowed = true + } + return true + } func yaml_parser_scan_line_comment(parser *yaml_parser_t, token_mark yaml_mark_t) bool { + if parser.newlines > 0 { + return true + } var start_mark yaml_mark_t + var text []byte for peek := 0; peek < 512; peek++ { + if parser.unread < peek+1 && !yaml_parser_update_buffer(parser, peek+1) { + break + } + if is_blank(parser.buffer, parser.buffer_pos+peek) { + continue + } + if parser.buffer[parser.buffer_pos+peek] == '#' { + seen := parser.mark.index + peek + for { + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if is_breakz(parser.buffer, parser.buffer_pos) { + if parser.mark.index >= seen { + break + } + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } else if parser.mark.index >= seen { + if len(text) == 0 { + start_mark = parser.mark + } + text = read(parser, text) + } else { + skip(parser) + } + } + } + break + } + if len(text) > 0 { + parser.comments = append(parser.comments, yaml_comment_t{ + token_mark: token_mark, + start_mark: start_mark, - line: text, + + line: text, }) + } + return true + } func yaml_parser_scan_comments(parser *yaml_parser_t, scan_mark yaml_mark_t) bool { + token := parser.tokens[len(parser.tokens)-1] if token.typ == yaml_FLOW_ENTRY_TOKEN && len(parser.tokens) > 1 { + token = parser.tokens[len(parser.tokens)-2] + } var token_mark = token.start_mark + var start_mark yaml_mark_t + var next_indent = parser.indent + if next_indent < 0 { + next_indent = 0 + } var recent_empty = false + var first_empty = parser.newlines <= 1 var line = parser.mark.line + var column = parser.mark.column var text []byte // The foot line is the place where a comment must start to + // still be considered as a foot of the prior content. + // If there's some content in the currently parsed line, then + // the foot is the line below it. + var foot_line = -1 + if scan_mark.line > 0 { + foot_line = parser.mark.line - parser.newlines + 1 + if parser.newlines == 0 && parser.mark.column > 1 { + foot_line++ + } + } var peek = 0 + for ; peek < 512; peek++ { + if parser.unread < peek+1 && !yaml_parser_update_buffer(parser, peek+1) { + break + } + column++ + if is_blank(parser.buffer, parser.buffer_pos+peek) { + continue + } + c := parser.buffer[parser.buffer_pos+peek] + var close_flow = parser.flow_level > 0 && (c == ']' || c == '}') + if close_flow || is_breakz(parser.buffer, parser.buffer_pos+peek) { + // Got line break or terminator. + if close_flow || !recent_empty { + if close_flow || first_empty && (start_mark.line == foot_line && token.typ != yaml_VALUE_TOKEN || start_mark.column-1 < next_indent) { + // This is the first empty line and there were no empty lines before, + // so this initial part of the comment is a foot of the prior token + // instead of being a head for the following one. Split it up. + // Alternatively, this might also be the last comment inside a flow + // scope, so it must be a footer. + if len(text) > 0 { + if start_mark.column-1 < next_indent { + // If dedented it's unrelated to the prior token. + token_mark = start_mark + } + parser.comments = append(parser.comments, yaml_comment_t{ - scan_mark: scan_mark, + + scan_mark: scan_mark, + token_mark: token_mark, + start_mark: start_mark, - end_mark: yaml_mark_t{parser.mark.index + peek, line, column}, - foot: text, + + end_mark: yaml_mark_t{parser.mark.index + peek, line, column}, + + foot: text, }) + scan_mark = yaml_mark_t{parser.mark.index + peek, line, column} + token_mark = scan_mark + text = nil + } + } else { + if len(text) > 0 && parser.buffer[parser.buffer_pos+peek] != 0 { + text = append(text, '\n') + } + } + } + if !is_break(parser.buffer, parser.buffer_pos+peek) { + break + } + first_empty = false + recent_empty = true + column = 0 + line++ + continue + } if len(text) > 0 && (close_flow || column-1 < next_indent && column != start_mark.column) { + // The comment at the different indentation is a foot of the + // preceding data rather than a head of the upcoming one. + parser.comments = append(parser.comments, yaml_comment_t{ - scan_mark: scan_mark, + + scan_mark: scan_mark, + token_mark: token_mark, + start_mark: start_mark, - end_mark: yaml_mark_t{parser.mark.index + peek, line, column}, - foot: text, + + end_mark: yaml_mark_t{parser.mark.index + peek, line, column}, + + foot: text, }) + scan_mark = yaml_mark_t{parser.mark.index + peek, line, column} + token_mark = scan_mark + text = nil + } if parser.buffer[parser.buffer_pos+peek] != '#' { + break + } if len(text) == 0 { + start_mark = yaml_mark_t{parser.mark.index + peek, line, column} + } else { + text = append(text, '\n') + } recent_empty = false // Consume until after the consumed comment line. + seen := parser.mark.index + peek + for { + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if is_breakz(parser.buffer, parser.buffer_pos) { + if parser.mark.index >= seen { + break + } + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } else if parser.mark.index >= seen { + text = read(parser, text) + } else { + skip(parser) + } + } peek = 0 + column = 0 + line = parser.mark.line + next_indent = parser.indent + if next_indent < 0 { + next_indent = 0 + } + } if len(text) > 0 { + parser.comments = append(parser.comments, yaml_comment_t{ - scan_mark: scan_mark, + + scan_mark: scan_mark, + token_mark: start_mark, + start_mark: start_mark, - end_mark: yaml_mark_t{parser.mark.index + peek - 1, line, column}, - head: text, + + end_mark: yaml_mark_t{parser.mark.index + peek - 1, line, column}, + + head: text, }) + } + return true + } diff --git a/vendor/gopkg.in/yaml.v3/sorter.go b/vendor/gopkg.in/yaml.v3/sorter.go index 9210ece..97b77a0 100644 --- a/vendor/gopkg.in/yaml.v3/sorter.go +++ b/vendor/gopkg.in/yaml.v3/sorter.go @@ -1,16 +1,29 @@ // + // Copyright (c) 2011-2019 Canonical Ltd + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. package yaml @@ -22,113 +35,218 @@ import ( type keyList []reflect.Value -func (l keyList) Len() int { return len(l) } +func (l keyList) Len() int { return len(l) } + func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } + func (l keyList) Less(i, j int) bool { + a := l[i] + b := l[j] + ak := a.Kind() + bk := b.Kind() + for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() { + a = a.Elem() + ak = a.Kind() + } + for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() { + b = b.Elem() + bk = b.Kind() + } + af, aok := keyFloat(a) + bf, bok := keyFloat(b) + if aok && bok { + if af != bf { + return af < bf + } + if ak != bk { + return ak < bk + } + return numLess(a, b) + } + if ak != reflect.String || bk != reflect.String { + return ak < bk + } + ar, br := []rune(a.String()), []rune(b.String()) + digits := false + for i := 0; i < len(ar) && i < len(br); i++ { + if ar[i] == br[i] { + digits = unicode.IsDigit(ar[i]) + continue + } + al := unicode.IsLetter(ar[i]) + bl := unicode.IsLetter(br[i]) + if al && bl { + return ar[i] < br[i] + } + if al || bl { + if digits { + return al + } else { + return bl + } + } + var ai, bi int + var an, bn int64 + if ar[i] == '0' || br[i] == '0' { + for j := i - 1; j >= 0 && unicode.IsDigit(ar[j]); j-- { + if ar[j] != '0' { + an = 1 + bn = 1 + break + } + } + } + for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { + an = an*10 + int64(ar[ai]-'0') + } + for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ { + bn = bn*10 + int64(br[bi]-'0') + } + if an != bn { + return an < bn + } + if ai != bi { + return ai < bi + } + return ar[i] < br[i] + } + return len(ar) < len(br) + } // keyFloat returns a float value for v if it is a number/bool + // and whether it is a number/bool or not. + func keyFloat(v reflect.Value) (f float64, ok bool) { + switch v.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return float64(v.Int()), true + case reflect.Float32, reflect.Float64: + return v.Float(), true + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return float64(v.Uint()), true + case reflect.Bool: + if v.Bool() { + return 1, true + } + return 0, true + } + return 0, false + } // numLess returns whether a < b. + // a and b must necessarily have the same kind. + func numLess(a, b reflect.Value) bool { + switch a.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return a.Int() < b.Int() + case reflect.Float32, reflect.Float64: + return a.Float() < b.Float() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return a.Uint() < b.Uint() + case reflect.Bool: + return !a.Bool() && b.Bool() + } + panic("not a number") + } diff --git a/vendor/gopkg.in/yaml.v3/yaml.go b/vendor/gopkg.in/yaml.v3/yaml.go index f0bedf3..7cdbb53 100644 --- a/vendor/gopkg.in/yaml.v3/yaml.go +++ b/vendor/gopkg.in/yaml.v3/yaml.go @@ -1,23 +1,41 @@ // + // Copyright (c) 2011-2019 Canonical Ltd + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. // Package yaml implements YAML support for the Go language. + // + // Source code and other details for the project are available at GitHub: + // + // https://github.com/go-yaml/yaml + package yaml import ( @@ -31,7 +49,9 @@ import ( ) // The Unmarshaler interface may be implemented by types to customize their + // behavior when being unmarshaled from a YAML document. + type Unmarshaler interface { UnmarshalYAML(value *Node) error } @@ -41,256 +61,469 @@ type obsoleteUnmarshaler interface { } // The Marshaler interface may be implemented by types to customize their + // behavior when being marshaled into a YAML document. The returned value + // is marshaled in place of the original value implementing Marshaler. + // + // If an error is returned by MarshalYAML, the marshaling procedure stops + // and returns with the provided error. + type Marshaler interface { MarshalYAML() (interface{}, error) } // Unmarshal decodes the first document found within the in byte slice + // and assigns decoded values into the out value. + // + // Maps and pointers (to a struct, string, int, etc) are accepted as out + // values. If an internal pointer within a struct is not initialized, + // the yaml package will initialize it if necessary for unmarshalling + // the provided data. The out parameter must not be nil. + // + // The type of the decoded values should be compatible with the respective + // values in out. If one or more values cannot be decoded due to a type + // mismatches, decoding continues partially until the end of the YAML + // content, and a *yaml.TypeError is returned with details for all + // missed values. + // + // Struct fields are only unmarshalled if they are exported (have an + // upper case first letter), and are unmarshalled using the field name + // lowercased as the default key. Custom keys may be defined via the + // "yaml" name in the field tag: the content preceding the first comma + // is used as the key, and the following comma-separated options are + // used to tweak the marshalling process (see Marshal). + // Conflicting names result in a runtime error. + // + // For example: + // + // type T struct { + // F int `yaml:"a,omitempty"` + // B int + // } + // var t T + // yaml.Unmarshal([]byte("a: 1\nb: 2"), &t) + // + // See the documentation of Marshal for the format of tags and a list of + // supported tag options. + func Unmarshal(in []byte, out interface{}) (err error) { + return unmarshal(in, out, false) + } // A Decoder reads and decodes YAML values from an input stream. + type Decoder struct { - parser *parser + parser *parser + knownFields bool } // NewDecoder returns a new decoder that reads from r. + // + // The decoder introduces its own buffering and may read + // data from r beyond the YAML values requested. + func NewDecoder(r io.Reader) *Decoder { + return &Decoder{ + parser: newParserFromReader(r), } + } // KnownFields ensures that the keys in decoded mappings to + // exist as fields in the struct being decoded into. + func (dec *Decoder) KnownFields(enable bool) { + dec.knownFields = enable + } // Decode reads the next YAML-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 YAML into a Go value. + func (dec *Decoder) Decode(v interface{}) (err error) { + d := newDecoder() + d.knownFields = dec.knownFields + defer handleErr(&err) + node := dec.parser.parse() + if node == nil { + return io.EOF + } + out := reflect.ValueOf(v) + if out.Kind() == reflect.Ptr && !out.IsNil() { + out = out.Elem() + } + d.unmarshal(node, out) + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil + } // Decode decodes the node and stores its data into the value pointed to by v. + // + // See the documentation for Unmarshal for details about the + // conversion of YAML into a Go value. + func (n *Node) Decode(v interface{}) (err error) { + d := newDecoder() + defer handleErr(&err) + out := reflect.ValueOf(v) + if out.Kind() == reflect.Ptr && !out.IsNil() { + out = out.Elem() + } + d.unmarshal(n, out) + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil + } func unmarshal(in []byte, out interface{}, strict bool) (err error) { + defer handleErr(&err) + d := newDecoder() + p := newParser(in) + defer p.destroy() + node := p.parse() + if node != nil { + v := reflect.ValueOf(out) + if v.Kind() == reflect.Ptr && !v.IsNil() { + v = v.Elem() + } + d.unmarshal(node, v) + } + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil + } // Marshal serializes the value provided into a YAML document. The structure + // of the generated document will reflect the structure of the value itself. + // Maps and pointers (to struct, string, int, etc) are accepted as the in value. + // + // Struct fields are only marshalled if they are exported (have an upper case + // first letter), and are marshalled using the field name lowercased as the + // default key. Custom keys may be defined via the "yaml" name in the field + // tag: the content preceding the first comma is used as the key, and the + // following comma-separated options are used to tweak the marshalling process. + // Conflicting names result in a runtime error. + // + // The field tag format accepted is: + // + // `(...) yaml:"[][,[,]]" (...)` + // + // The following flags are currently supported: + // + // omitempty Only include the field if it's not set to the zero + // value for the type or to empty slices or maps. + // Zero valued structs will be omitted if all their public + // fields are zero, unless they implement an IsZero + // method (see the IsZeroer interface type), in which + // case the field will be excluded if IsZero returns true. + // + // flow Marshal using a flow style (useful for structs, + // sequences and maps). + // + // inline Inline the field, which must be a struct or a map, + // causing all of its fields or keys to be processed as if + // they were part of the outer struct. For maps, keys must + // not conflict with the yaml keys of other struct fields. + // + // In addition, if the key is "-", the field is ignored. + // + // For example: + // + // type T struct { + // F int `yaml:"a,omitempty"` + // B int + // } + // yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" + // yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n" + func Marshal(in interface{}) (out []byte, err error) { + defer handleErr(&err) + e := newEncoder() + defer e.destroy() + e.marshalDoc("", reflect.ValueOf(in)) + e.finish() + out = e.out + return + } // An Encoder writes YAML values to an output stream. + type Encoder struct { encoder *encoder } // NewEncoder returns a new encoder that writes to w. + // The Encoder should be closed after use to flush all data + // to w. + func NewEncoder(w io.Writer) *Encoder { + return &Encoder{ + encoder: newEncoderWithWriter(w), } + } // Encode writes the YAML encoding of v to the stream. + // If multiple items are encoded to the stream, the + // second and subsequent document will be preceded + // with a "---" document separator, but the first will not. + // + // See the documentation for Marshal for details about the conversion of Go + // values to YAML. + func (e *Encoder) Encode(v interface{}) (err error) { + defer handleErr(&err) + e.encoder.marshalDoc("", reflect.ValueOf(v)) + return nil + } // Encode encodes value v and stores its representation in n. + // + // See the documentation for Marshal for details about the + // conversion of Go values into YAML. + func (n *Node) Encode(v interface{}) (err error) { + defer handleErr(&err) + e := newEncoder() + defer e.destroy() + e.marshalDoc("", reflect.ValueOf(v)) + e.finish() + p := newParser(e.out) + p.textless = true + defer p.destroy() + doc := p.parse() + *n = *doc.Content[0] + return nil + } // SetIndent changes the used indentation used when encoding. + func (e *Encoder) SetIndent(spaces int) { + if spaces < 0 { + panic("yaml: cannot indent to a negative number of spaces") + } + e.encoder.indent = spaces + } // Close closes the encoder by writing any remaining data. + // It does not write a stream terminating string "...". + func (e *Encoder) Close() (err error) { + defer handleErr(&err) + e.encoder.finish() + return nil + } func handleErr(err *error) { + if v := recover(); v != nil { + if e, ok := v.(yamlError); ok { + *err = e.err + } else { + panic(v) + } + } + } type yamlError struct { @@ -298,32 +531,46 @@ type yamlError struct { } func fail(err error) { + panic(yamlError{err}) + } func failf(format string, args ...interface{}) { + panic(yamlError{fmt.Errorf("yaml: "+format, args...)}) + } // A TypeError is returned by Unmarshal when one or more fields in + // the YAML document cannot be properly decoded into the requested + // types. When this error is returned, the value is still + // unmarshaled partially. + type TypeError struct { Errors []string } func (e *TypeError) Error() string { + return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n ")) + } type Kind uint32 const ( DocumentNode Kind = 1 << iota + SequenceNode + MappingNode + ScalarNode + AliasNode ) @@ -331,363 +578,638 @@ type Style uint32 const ( TaggedStyle Style = 1 << iota + DoubleQuotedStyle + SingleQuotedStyle + LiteralStyle + FoldedStyle + FlowStyle ) // Node represents an element in the YAML document hierarchy. While documents + // are typically encoded and decoded into higher level types, such as structs + // and maps, Node is an intermediate representation that allows detailed + // control over the content being decoded or encoded. + // + // It's worth noting that although Node offers access into details such as + // line numbers, colums, and comments, the content when re-encoded will not + // have its original textual representation preserved. An effort is made to + // render the data plesantly, and to preserve comments near the data they + // describe, though. + // + // Values that make use of the Node type interact with the yaml package in the + // same way any other type would do, by encoding and decoding yaml data + // directly or indirectly into them. + // + // For example: + // + // var person struct { + // Name string + // Address yaml.Node + // } + // err := yaml.Unmarshal(data, &person) + // + // Or by itself: + // + // var person Node + // err := yaml.Unmarshal(data, &person) + type Node struct { + // Kind defines whether the node is a document, a mapping, a sequence, + // a scalar value, or an alias to another node. The specific data type of + // scalar nodes may be obtained via the ShortTag and LongTag methods. + Kind Kind // Style allows customizing the apperance of the node in the tree. + Style Style // Tag holds the YAML tag defining the data type for the value. + // When decoding, this field will always be set to the resolved tag, + // even when it wasn't explicitly provided in the YAML content. + // When encoding, if this field is unset the value type will be + // implied from the node properties, and if it is set, it will only + // be serialized into the representation if TaggedStyle is used or + // the implicit tag diverges from the provided one. + Tag string // Value holds the unescaped and unquoted represenation of the value. + Value string // Anchor holds the anchor name for this node, which allows aliases to point to it. + Anchor string // Alias holds the node that this alias points to. Only valid when Kind is AliasNode. + Alias *Node // Content holds contained nodes for documents, mappings, and sequences. + Content []*Node // HeadComment holds any comments in the lines preceding the node and + // not separated by an empty line. + HeadComment string // LineComment holds any comments at the end of the line where the node is in. + LineComment string // FootComment holds any comments following the node and before empty lines. + FootComment string // Line and Column hold the node position in the decoded YAML text. + // These fields are not respected when encoding the node. - Line int + + Line int + Column int } // IsZero returns whether the node has all of its fields unset. + func (n *Node) IsZero() bool { + return n.Kind == 0 && n.Style == 0 && n.Tag == "" && n.Value == "" && n.Anchor == "" && n.Alias == nil && n.Content == nil && + n.HeadComment == "" && n.LineComment == "" && n.FootComment == "" && n.Line == 0 && n.Column == 0 + } // LongTag returns the long form of the tag that indicates the data type for + // the node. If the Tag field isn't explicitly defined, one will be computed + // based on the node properties. + func (n *Node) LongTag() string { + return longTag(n.ShortTag()) + } // ShortTag returns the short form of the YAML tag that indicates data type for + // the node. If the Tag field isn't explicitly defined, one will be computed + // based on the node properties. + func (n *Node) ShortTag() string { + if n.indicatedString() { + return strTag + } + if n.Tag == "" || n.Tag == "!" { + switch n.Kind { + case MappingNode: + return mapTag + case SequenceNode: + return seqTag + case AliasNode: + if n.Alias != nil { + return n.Alias.ShortTag() + } + case ScalarNode: + tag, _ := resolve("", n.Value) + return tag + case 0: + // Special case to make the zero value convenient. + if n.IsZero() { + return nullTag + } + } + return "" + } + return shortTag(n.Tag) + } func (n *Node) indicatedString() bool { + return n.Kind == ScalarNode && + (shortTag(n.Tag) == strTag || + (n.Tag == "" || n.Tag == "!") && n.Style&(SingleQuotedStyle|DoubleQuotedStyle|LiteralStyle|FoldedStyle) != 0) + } // SetString is a convenience function that sets the node to a string value + // and defines its style in a pleasant way depending on its content. + func (n *Node) SetString(s string) { + n.Kind = ScalarNode + if utf8.ValidString(s) { + n.Value = s + n.Tag = strTag + } else { + n.Value = encodeBase64(s) + n.Tag = binaryTag + } + if strings.Contains(n.Value, "\n") { + n.Style = LiteralStyle + } + } // -------------------------------------------------------------------------- + // Maintain a mapping of keys to structure field indexes // The code in this section was copied from mgo/bson. // structInfo holds details for the serialization of fields of + // a given struct. + type structInfo struct { - FieldsMap map[string]fieldInfo + FieldsMap map[string]fieldInfo + FieldsList []fieldInfo // InlineMap is the number of the field in the struct that + // contains an ,inline map, or -1 if there's none. + InlineMap int // InlineUnmarshalers holds indexes to inlined fields that + // contain unmarshaler values. + InlineUnmarshalers [][]int } type fieldInfo struct { - Key string - Num int + Key string + + Num int + OmitEmpty bool - Flow bool + + Flow bool + // Id holds the unique field identifier, so we can cheaply + // check for field duplicates without maintaining an extra map. + Id int // Inline holds the field index if the field is part of an inlined struct. + Inline []int } var structMap = make(map[reflect.Type]*structInfo) + var fieldMapMutex sync.RWMutex + var unmarshalerType reflect.Type func init() { + var v Unmarshaler + unmarshalerType = reflect.ValueOf(&v).Elem().Type() + } func getStructInfo(st reflect.Type) (*structInfo, error) { + fieldMapMutex.RLock() + sinfo, found := structMap[st] + fieldMapMutex.RUnlock() + if found { + return sinfo, nil + } n := st.NumField() + fieldsMap := make(map[string]fieldInfo) + fieldsList := make([]fieldInfo, 0, n) + inlineMap := -1 + inlineUnmarshalers := [][]int(nil) + for i := 0; i != n; i++ { + field := st.Field(i) + if field.PkgPath != "" && !field.Anonymous { + continue // Private field + } info := fieldInfo{Num: i} tag := field.Tag.Get("yaml") + if tag == "" && strings.Index(string(field.Tag), ":") < 0 { + tag = string(field.Tag) + } + if tag == "-" { + continue + } inline := false + fields := strings.Split(tag, ",") + if len(fields) > 1 { + for _, flag := range fields[1:] { + switch flag { + case "omitempty": + info.OmitEmpty = true + case "flow": + info.Flow = true + case "inline": + inline = true + default: + return nil, errors.New(fmt.Sprintf("unsupported flag %q in tag %q of type %s", flag, tag, st)) + } + } + tag = fields[0] + } if inline { + switch field.Type.Kind() { + case reflect.Map: + if inlineMap >= 0 { + return nil, errors.New("multiple ,inline maps in struct " + st.String()) + } + if field.Type.Key() != reflect.TypeOf("") { + return nil, errors.New("option ,inline needs a map with string keys in struct " + st.String()) + } + inlineMap = info.Num + case reflect.Struct, reflect.Ptr: + ftype := field.Type + for ftype.Kind() == reflect.Ptr { + ftype = ftype.Elem() + } + if ftype.Kind() != reflect.Struct { + return nil, errors.New("option ,inline may only be used on a struct or map field") + } + if reflect.PtrTo(ftype).Implements(unmarshalerType) { + inlineUnmarshalers = append(inlineUnmarshalers, []int{i}) + } else { + sinfo, err := getStructInfo(ftype) + if err != nil { + return nil, err + } + for _, index := range sinfo.InlineUnmarshalers { + inlineUnmarshalers = append(inlineUnmarshalers, append([]int{i}, index...)) + } + for _, finfo := range sinfo.FieldsList { + if _, found := fieldsMap[finfo.Key]; found { + msg := "duplicated key '" + finfo.Key + "' in struct " + st.String() + return nil, errors.New(msg) + } + if finfo.Inline == nil { + finfo.Inline = []int{i, finfo.Num} + } else { + finfo.Inline = append([]int{i}, finfo.Inline...) + } + finfo.Id = len(fieldsList) + fieldsMap[finfo.Key] = finfo + fieldsList = append(fieldsList, finfo) + } + } + default: + return nil, errors.New("option ,inline may only be used on a struct or map field") + } + continue + } if tag != "" { + info.Key = tag + } else { + info.Key = strings.ToLower(field.Name) + } if _, found = fieldsMap[info.Key]; found { + msg := "duplicated key '" + info.Key + "' in struct " + st.String() + return nil, errors.New(msg) + } info.Id = len(fieldsList) + fieldsList = append(fieldsList, info) + fieldsMap[info.Key] = info + } sinfo = &structInfo{ - FieldsMap: fieldsMap, - FieldsList: fieldsList, - InlineMap: inlineMap, + + FieldsMap: fieldsMap, + + FieldsList: fieldsList, + + InlineMap: inlineMap, + InlineUnmarshalers: inlineUnmarshalers, } fieldMapMutex.Lock() + structMap[st] = sinfo + fieldMapMutex.Unlock() + return sinfo, nil + } // IsZeroer is used to check whether an object is zero to + // determine whether it should be omitted when marshaling + // with the omitempty flag. One notable implementation + // is time.Time. + type IsZeroer interface { IsZero() bool } func isZero(v reflect.Value) bool { + kind := v.Kind() + if z, ok := v.Interface().(IsZeroer); ok { + if (kind == reflect.Ptr || kind == reflect.Interface) && v.IsNil() { + return true + } + return z.IsZero() + } + switch kind { + case reflect.String: + return len(v.String()) == 0 + case reflect.Interface, reflect.Ptr: + return v.IsNil() + case reflect.Slice: + return v.Len() == 0 + case reflect.Map: + return v.Len() == 0 + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Struct: + vt := v.Type() + for i := v.NumField() - 1; i >= 0; i-- { + if vt.Field(i).PkgPath != "" { + continue // Private field + } + if !isZero(v.Field(i)) { + return false + } + } + return true + } + return false + } diff --git a/vendor/gopkg.in/yaml.v3/yamlh.go b/vendor/gopkg.in/yaml.v3/yamlh.go index ddcd551..d913d0f 100644 --- a/vendor/gopkg.in/yaml.v3/yamlh.go +++ b/vendor/gopkg.in/yaml.v3/yamlh.go @@ -1,23 +1,43 @@ // + // Copyright (c) 2011-2019 Canonical Ltd + // Copyright (c) 2006-2010 Kirill Simonov + // + // Permission is hereby granted, free of charge, to any person obtaining a copy of + // this software and associated documentation files (the "Software"), to deal in + // the Software without restriction, including without limitation the rights to + // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + // of the Software, and to permit persons to whom the Software is furnished to do + // so, subject to the following conditions: + // + // The above copyright notice and this permission notice shall be included in all + // copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + // SOFTWARE. package yaml @@ -28,62 +48,94 @@ import ( ) // The version directive data. + type yaml_version_directive_t struct { major int8 // The major version number. + minor int8 // The minor version number. + } // The tag directive data. + type yaml_tag_directive_t struct { handle []byte // The tag handle. + prefix []byte // The tag prefix. + } type yaml_encoding_t int // The stream encoding. + const ( + // Let the parser choose the encoding. + yaml_ANY_ENCODING yaml_encoding_t = iota - yaml_UTF8_ENCODING // The default UTF-8 encoding. + yaml_UTF8_ENCODING // The default UTF-8 encoding. + yaml_UTF16LE_ENCODING // The UTF-16-LE encoding with BOM. + yaml_UTF16BE_ENCODING // The UTF-16-BE encoding with BOM. + ) type yaml_break_t int // Line break types. + const ( + // Let the parser choose the break type. + yaml_ANY_BREAK yaml_break_t = iota - yaml_CR_BREAK // Use CR for line breaks (Mac style). - yaml_LN_BREAK // Use LN for line breaks (Unix style). + yaml_CR_BREAK // Use CR for line breaks (Mac style). + + yaml_LN_BREAK // Use LN for line breaks (Unix style). + yaml_CRLN_BREAK // Use CR LN for line breaks (DOS style). + ) type yaml_error_type_t int // Many bad things could happen with the parser and emitter. + const ( + // No error is produced. + yaml_NO_ERROR yaml_error_type_t = iota - yaml_MEMORY_ERROR // Cannot allocate or reallocate a block of memory. - yaml_READER_ERROR // Cannot read or decode the input stream. - yaml_SCANNER_ERROR // Cannot scan the input stream. - yaml_PARSER_ERROR // Cannot parse the input stream. + yaml_MEMORY_ERROR // Cannot allocate or reallocate a block of memory. + + yaml_READER_ERROR // Cannot read or decode the input stream. + + yaml_SCANNER_ERROR // Cannot scan the input stream. + + yaml_PARSER_ERROR // Cannot parse the input stream. + yaml_COMPOSER_ERROR // Cannot compose a YAML document. - yaml_WRITER_ERROR // Cannot write to the output stream. - yaml_EMITTER_ERROR // Cannot emit a YAML stream. + + yaml_WRITER_ERROR // Cannot write to the output stream. + + yaml_EMITTER_ERROR // Cannot emit a YAML stream. + ) // The pointer position. + type yaml_mark_t struct { - index int // The position index. - line int // The position line. + index int // The position index. + + line int // The position line. + column int // The position column. + } // Node Styles @@ -93,37 +145,55 @@ type yaml_style_t int8 type yaml_scalar_style_t yaml_style_t // Scalar styles. + const ( + // Let the emitter choose the style. + yaml_ANY_SCALAR_STYLE yaml_scalar_style_t = 0 - yaml_PLAIN_SCALAR_STYLE yaml_scalar_style_t = 1 << iota // The plain scalar style. - yaml_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style. - yaml_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style. - yaml_LITERAL_SCALAR_STYLE // The literal scalar style. - yaml_FOLDED_SCALAR_STYLE // The folded scalar style. + yaml_PLAIN_SCALAR_STYLE yaml_scalar_style_t = 1 << iota // The plain scalar style. + + yaml_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style. + + yaml_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style. + + yaml_LITERAL_SCALAR_STYLE // The literal scalar style. + + yaml_FOLDED_SCALAR_STYLE // The folded scalar style. + ) type yaml_sequence_style_t yaml_style_t // Sequence styles. + const ( + // Let the emitter choose the style. + yaml_ANY_SEQUENCE_STYLE yaml_sequence_style_t = iota yaml_BLOCK_SEQUENCE_STYLE // The block sequence style. - yaml_FLOW_SEQUENCE_STYLE // The flow sequence style. + + yaml_FLOW_SEQUENCE_STYLE // The flow sequence style. + ) type yaml_mapping_style_t yaml_style_t // Mapping styles. + const ( + // Let the emitter choose the style. + yaml_ANY_MAPPING_STYLE yaml_mapping_style_t = iota yaml_BLOCK_MAPPING_STYLE // The block mapping style. - yaml_FLOW_MAPPING_STYLE // The flow mapping style. + + yaml_FLOW_MAPPING_STYLE // The flow mapping style. + ) // Tokens @@ -131,113 +201,191 @@ const ( type yaml_token_type_t int // Token types. + const ( + // An empty token. + yaml_NO_TOKEN yaml_token_type_t = iota yaml_STREAM_START_TOKEN // A STREAM-START token. - yaml_STREAM_END_TOKEN // A STREAM-END token. + + yaml_STREAM_END_TOKEN // A STREAM-END token. yaml_VERSION_DIRECTIVE_TOKEN // A VERSION-DIRECTIVE token. - yaml_TAG_DIRECTIVE_TOKEN // A TAG-DIRECTIVE token. - yaml_DOCUMENT_START_TOKEN // A DOCUMENT-START token. - yaml_DOCUMENT_END_TOKEN // A DOCUMENT-END token. + + yaml_TAG_DIRECTIVE_TOKEN // A TAG-DIRECTIVE token. + + yaml_DOCUMENT_START_TOKEN // A DOCUMENT-START token. + + yaml_DOCUMENT_END_TOKEN // A DOCUMENT-END token. yaml_BLOCK_SEQUENCE_START_TOKEN // A BLOCK-SEQUENCE-START token. - yaml_BLOCK_MAPPING_START_TOKEN // A BLOCK-SEQUENCE-END token. - yaml_BLOCK_END_TOKEN // A BLOCK-END token. + + yaml_BLOCK_MAPPING_START_TOKEN // A BLOCK-SEQUENCE-END token. + + yaml_BLOCK_END_TOKEN // A BLOCK-END token. yaml_FLOW_SEQUENCE_START_TOKEN // A FLOW-SEQUENCE-START token. - yaml_FLOW_SEQUENCE_END_TOKEN // A FLOW-SEQUENCE-END token. - yaml_FLOW_MAPPING_START_TOKEN // A FLOW-MAPPING-START token. - yaml_FLOW_MAPPING_END_TOKEN // A FLOW-MAPPING-END token. + + yaml_FLOW_SEQUENCE_END_TOKEN // A FLOW-SEQUENCE-END token. + + yaml_FLOW_MAPPING_START_TOKEN // A FLOW-MAPPING-START token. + + yaml_FLOW_MAPPING_END_TOKEN // A FLOW-MAPPING-END token. yaml_BLOCK_ENTRY_TOKEN // A BLOCK-ENTRY token. - yaml_FLOW_ENTRY_TOKEN // A FLOW-ENTRY token. - yaml_KEY_TOKEN // A KEY token. - yaml_VALUE_TOKEN // A VALUE token. - yaml_ALIAS_TOKEN // An ALIAS token. + yaml_FLOW_ENTRY_TOKEN // A FLOW-ENTRY token. + + yaml_KEY_TOKEN // A KEY token. + + yaml_VALUE_TOKEN // A VALUE token. + + yaml_ALIAS_TOKEN // An ALIAS token. + yaml_ANCHOR_TOKEN // An ANCHOR token. - yaml_TAG_TOKEN // A TAG token. + + yaml_TAG_TOKEN // A TAG token. + yaml_SCALAR_TOKEN // A SCALAR token. + ) func (tt yaml_token_type_t) String() string { + switch tt { + case yaml_NO_TOKEN: + return "yaml_NO_TOKEN" + case yaml_STREAM_START_TOKEN: + return "yaml_STREAM_START_TOKEN" + case yaml_STREAM_END_TOKEN: + return "yaml_STREAM_END_TOKEN" + case yaml_VERSION_DIRECTIVE_TOKEN: + return "yaml_VERSION_DIRECTIVE_TOKEN" + case yaml_TAG_DIRECTIVE_TOKEN: + return "yaml_TAG_DIRECTIVE_TOKEN" + case yaml_DOCUMENT_START_TOKEN: + return "yaml_DOCUMENT_START_TOKEN" + case yaml_DOCUMENT_END_TOKEN: + return "yaml_DOCUMENT_END_TOKEN" + case yaml_BLOCK_SEQUENCE_START_TOKEN: + return "yaml_BLOCK_SEQUENCE_START_TOKEN" + case yaml_BLOCK_MAPPING_START_TOKEN: + return "yaml_BLOCK_MAPPING_START_TOKEN" + case yaml_BLOCK_END_TOKEN: + return "yaml_BLOCK_END_TOKEN" + case yaml_FLOW_SEQUENCE_START_TOKEN: + return "yaml_FLOW_SEQUENCE_START_TOKEN" + case yaml_FLOW_SEQUENCE_END_TOKEN: + return "yaml_FLOW_SEQUENCE_END_TOKEN" + case yaml_FLOW_MAPPING_START_TOKEN: + return "yaml_FLOW_MAPPING_START_TOKEN" + case yaml_FLOW_MAPPING_END_TOKEN: + return "yaml_FLOW_MAPPING_END_TOKEN" + case yaml_BLOCK_ENTRY_TOKEN: + return "yaml_BLOCK_ENTRY_TOKEN" + case yaml_FLOW_ENTRY_TOKEN: + return "yaml_FLOW_ENTRY_TOKEN" + case yaml_KEY_TOKEN: + return "yaml_KEY_TOKEN" + case yaml_VALUE_TOKEN: + return "yaml_VALUE_TOKEN" + case yaml_ALIAS_TOKEN: + return "yaml_ALIAS_TOKEN" + case yaml_ANCHOR_TOKEN: + return "yaml_ANCHOR_TOKEN" + case yaml_TAG_TOKEN: + return "yaml_TAG_TOKEN" + case yaml_SCALAR_TOKEN: + return "yaml_SCALAR_TOKEN" + } + return "" + } // The token structure. + type yaml_token_t struct { + // The token type. + typ yaml_token_type_t // The start/end of the token. + start_mark, end_mark yaml_mark_t // The stream encoding (for yaml_STREAM_START_TOKEN). + encoding yaml_encoding_t // The alias/anchor/scalar value or tag/tag directive handle + // (for yaml_ALIAS_TOKEN, yaml_ANCHOR_TOKEN, yaml_SCALAR_TOKEN, yaml_TAG_TOKEN, yaml_TAG_DIRECTIVE_TOKEN). + value []byte // The tag suffix (for yaml_TAG_TOKEN). + suffix []byte // The tag directive prefix (for yaml_TAG_DIRECTIVE_TOKEN). + prefix []byte // The scalar style (for yaml_SCALAR_TOKEN). + style yaml_scalar_style_t // The version directive major/minor (for yaml_VERSION_DIRECTIVE_TOKEN). + major, minor int8 } @@ -246,314 +394,514 @@ type yaml_token_t struct { type yaml_event_type_t int8 // Event types. + const ( + // An empty event. + yaml_NO_EVENT yaml_event_type_t = iota - yaml_STREAM_START_EVENT // A STREAM-START event. - yaml_STREAM_END_EVENT // A STREAM-END event. + yaml_STREAM_START_EVENT // A STREAM-START event. + + yaml_STREAM_END_EVENT // A STREAM-END event. + yaml_DOCUMENT_START_EVENT // A DOCUMENT-START event. - yaml_DOCUMENT_END_EVENT // A DOCUMENT-END event. - yaml_ALIAS_EVENT // An ALIAS event. - yaml_SCALAR_EVENT // A SCALAR event. + + yaml_DOCUMENT_END_EVENT // A DOCUMENT-END event. + + yaml_ALIAS_EVENT // An ALIAS event. + + yaml_SCALAR_EVENT // A SCALAR event. + yaml_SEQUENCE_START_EVENT // A SEQUENCE-START event. - yaml_SEQUENCE_END_EVENT // A SEQUENCE-END event. - yaml_MAPPING_START_EVENT // A MAPPING-START event. - yaml_MAPPING_END_EVENT // A MAPPING-END event. + + yaml_SEQUENCE_END_EVENT // A SEQUENCE-END event. + + yaml_MAPPING_START_EVENT // A MAPPING-START event. + + yaml_MAPPING_END_EVENT // A MAPPING-END event. + yaml_TAIL_COMMENT_EVENT ) var eventStrings = []string{ - yaml_NO_EVENT: "none", - yaml_STREAM_START_EVENT: "stream start", - yaml_STREAM_END_EVENT: "stream end", + + yaml_NO_EVENT: "none", + + yaml_STREAM_START_EVENT: "stream start", + + yaml_STREAM_END_EVENT: "stream end", + yaml_DOCUMENT_START_EVENT: "document start", - yaml_DOCUMENT_END_EVENT: "document end", - yaml_ALIAS_EVENT: "alias", - yaml_SCALAR_EVENT: "scalar", + + yaml_DOCUMENT_END_EVENT: "document end", + + yaml_ALIAS_EVENT: "alias", + + yaml_SCALAR_EVENT: "scalar", + yaml_SEQUENCE_START_EVENT: "sequence start", - yaml_SEQUENCE_END_EVENT: "sequence end", - yaml_MAPPING_START_EVENT: "mapping start", - yaml_MAPPING_END_EVENT: "mapping end", - yaml_TAIL_COMMENT_EVENT: "tail comment", + + yaml_SEQUENCE_END_EVENT: "sequence end", + + yaml_MAPPING_START_EVENT: "mapping start", + + yaml_MAPPING_END_EVENT: "mapping end", + + yaml_TAIL_COMMENT_EVENT: "tail comment", } func (e yaml_event_type_t) String() string { + if e < 0 || int(e) >= len(eventStrings) { + return fmt.Sprintf("unknown event %d", e) + } + return eventStrings[e] + } // The event structure. + type yaml_event_t struct { // The event type. + typ yaml_event_type_t // The start and end of the event. + start_mark, end_mark yaml_mark_t // The document encoding (for yaml_STREAM_START_EVENT). + encoding yaml_encoding_t // The version directive (for yaml_DOCUMENT_START_EVENT). + version_directive *yaml_version_directive_t // The list of tag directives (for yaml_DOCUMENT_START_EVENT). + tag_directives []yaml_tag_directive_t // The comments + head_comment []byte + line_comment []byte + foot_comment []byte + tail_comment []byte // The anchor (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_ALIAS_EVENT). + anchor []byte // The tag (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). + tag []byte // The scalar value (for yaml_SCALAR_EVENT). + value []byte // Is the document start/end indicator implicit, or the tag optional? + // (for yaml_DOCUMENT_START_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_SCALAR_EVENT). + implicit bool // Is the tag optional for any non-plain style? (for yaml_SCALAR_EVENT). + quoted_implicit bool // The style (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). + style yaml_style_t } -func (e *yaml_event_t) scalar_style() yaml_scalar_style_t { return yaml_scalar_style_t(e.style) } +func (e *yaml_event_t) scalar_style() yaml_scalar_style_t { return yaml_scalar_style_t(e.style) } + func (e *yaml_event_t) sequence_style() yaml_sequence_style_t { return yaml_sequence_style_t(e.style) } -func (e *yaml_event_t) mapping_style() yaml_mapping_style_t { return yaml_mapping_style_t(e.style) } + +func (e *yaml_event_t) mapping_style() yaml_mapping_style_t { return yaml_mapping_style_t(e.style) } // Nodes const ( - yaml_NULL_TAG = "tag:yaml.org,2002:null" // The tag !!null with the only possible value: null. - yaml_BOOL_TAG = "tag:yaml.org,2002:bool" // The tag !!bool with the values: true and false. - yaml_STR_TAG = "tag:yaml.org,2002:str" // The tag !!str for string values. - yaml_INT_TAG = "tag:yaml.org,2002:int" // The tag !!int for integer values. - yaml_FLOAT_TAG = "tag:yaml.org,2002:float" // The tag !!float for float values. + yaml_NULL_TAG = "tag:yaml.org,2002:null" // The tag !!null with the only possible value: null. + + yaml_BOOL_TAG = "tag:yaml.org,2002:bool" // The tag !!bool with the values: true and false. + + yaml_STR_TAG = "tag:yaml.org,2002:str" // The tag !!str for string values. + + yaml_INT_TAG = "tag:yaml.org,2002:int" // The tag !!int for integer values. + + yaml_FLOAT_TAG = "tag:yaml.org,2002:float" // The tag !!float for float values. + yaml_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp" // The tag !!timestamp for date and time values. yaml_SEQ_TAG = "tag:yaml.org,2002:seq" // The tag !!seq is used to denote sequences. + yaml_MAP_TAG = "tag:yaml.org,2002:map" // The tag !!map is used to denote mapping. // Not in original libyaml. - yaml_BINARY_TAG = "tag:yaml.org,2002:binary" - yaml_MERGE_TAG = "tag:yaml.org,2002:merge" - yaml_DEFAULT_SCALAR_TAG = yaml_STR_TAG // The default scalar tag is !!str. + yaml_BINARY_TAG = "tag:yaml.org,2002:binary" + + yaml_MERGE_TAG = "tag:yaml.org,2002:merge" + + yaml_DEFAULT_SCALAR_TAG = yaml_STR_TAG // The default scalar tag is !!str. + yaml_DEFAULT_SEQUENCE_TAG = yaml_SEQ_TAG // The default sequence tag is !!seq. - yaml_DEFAULT_MAPPING_TAG = yaml_MAP_TAG // The default mapping tag is !!map. + + yaml_DEFAULT_MAPPING_TAG = yaml_MAP_TAG // The default mapping tag is !!map. + ) type yaml_node_type_t int // Node types. + const ( + // An empty node. + yaml_NO_NODE yaml_node_type_t = iota - yaml_SCALAR_NODE // A scalar node. + yaml_SCALAR_NODE // A scalar node. + yaml_SEQUENCE_NODE // A sequence node. - yaml_MAPPING_NODE // A mapping node. + + yaml_MAPPING_NODE // A mapping node. + ) // An element of a sequence node. + type yaml_node_item_t int // An element of a mapping node. + type yaml_node_pair_t struct { - key int // The key of the element. + key int // The key of the element. + value int // The value of the element. + } // The node structure. + type yaml_node_t struct { typ yaml_node_type_t // The node type. - tag []byte // The node tag. + + tag []byte // The node tag. // The node data. // The scalar parameters (for yaml_SCALAR_NODE). + scalar struct { - value []byte // The scalar value. - length int // The length of the scalar value. - style yaml_scalar_style_t // The scalar style. + value []byte // The scalar value. + + length int // The length of the scalar value. + + style yaml_scalar_style_t // The scalar style. + } // The sequence parameters (for YAML_SEQUENCE_NODE). + sequence struct { - items_data []yaml_node_item_t // The stack of sequence items. - style yaml_sequence_style_t // The sequence style. + items_data []yaml_node_item_t // The stack of sequence items. + + style yaml_sequence_style_t // The sequence style. + } // The mapping parameters (for yaml_MAPPING_NODE). + mapping struct { - pairs_data []yaml_node_pair_t // The stack of mapping pairs (key, value). - pairs_start *yaml_node_pair_t // The beginning of the stack. - pairs_end *yaml_node_pair_t // The end of the stack. - pairs_top *yaml_node_pair_t // The top of the stack. - style yaml_mapping_style_t // The mapping style. + pairs_data []yaml_node_pair_t // The stack of mapping pairs (key, value). + + pairs_start *yaml_node_pair_t // The beginning of the stack. + + pairs_end *yaml_node_pair_t // The end of the stack. + + pairs_top *yaml_node_pair_t // The top of the stack. + + style yaml_mapping_style_t // The mapping style. + } start_mark yaml_mark_t // The beginning of the node. - end_mark yaml_mark_t // The end of the node. + + end_mark yaml_mark_t // The end of the node. } // The document structure. + type yaml_document_t struct { // The document nodes. + nodes []yaml_node_t // The version directive. + version_directive *yaml_version_directive_t // The list of tag directives. - tag_directives_data []yaml_tag_directive_t + + tag_directives_data []yaml_tag_directive_t + tag_directives_start int // The beginning of the tag directives list. - tag_directives_end int // The end of the tag directives list. + + tag_directives_end int // The end of the tag directives list. start_implicit int // Is the document start indicator implicit? - end_implicit int // Is the document end indicator implicit? + + end_implicit int // Is the document end indicator implicit? // The start/end of the document. + start_mark, end_mark yaml_mark_t } // The prototype of a read handler. + // + // The read handler is called when the parser needs to read more bytes from the + // source. The handler should write not more than size bytes to the buffer. + // The number of written bytes should be set to the size_read variable. + // + // [in,out] data A pointer to an application data specified by + // + // yaml_parser_set_input(). + // + // [out] buffer The buffer to write the data from the source. + // [in] size The size of the buffer. + // [out] size_read The actual number of bytes read from the source. + // + // On success, the handler should return 1. If the handler failed, + // the returned value should be 0. On EOF, the handler should set the + // size_read to 0 and return 1. + type yaml_read_handler_t func(parser *yaml_parser_t, buffer []byte) (n int, err error) // This structure holds information about a potential simple key. + type yaml_simple_key_t struct { - possible bool // Is a simple key possible? - required bool // Is a simple key required? - token_number int // The number of the token. - mark yaml_mark_t // The position mark. + possible bool // Is a simple key possible? + + required bool // Is a simple key required? + + token_number int // The number of the token. + + mark yaml_mark_t // The position mark. + } // The states of the parser. + type yaml_parser_state_t int const ( yaml_PARSE_STREAM_START_STATE yaml_parser_state_t = iota - yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE // Expect the beginning of an implicit document. - yaml_PARSE_DOCUMENT_START_STATE // Expect DOCUMENT-START. - yaml_PARSE_DOCUMENT_CONTENT_STATE // Expect the content of a document. - yaml_PARSE_DOCUMENT_END_STATE // Expect DOCUMENT-END. - yaml_PARSE_BLOCK_NODE_STATE // Expect a block node. + yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE // Expect the beginning of an implicit document. + + yaml_PARSE_DOCUMENT_START_STATE // Expect DOCUMENT-START. + + yaml_PARSE_DOCUMENT_CONTENT_STATE // Expect the content of a document. + + yaml_PARSE_DOCUMENT_END_STATE // Expect DOCUMENT-END. + + yaml_PARSE_BLOCK_NODE_STATE // Expect a block node. + yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE // Expect a block node or indentless sequence. - yaml_PARSE_FLOW_NODE_STATE // Expect a flow node. - yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a block sequence. - yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE // Expect an entry of a block sequence. - yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE // Expect an entry of an indentless sequence. - yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. - yaml_PARSE_BLOCK_MAPPING_KEY_STATE // Expect a block mapping key. - yaml_PARSE_BLOCK_MAPPING_VALUE_STATE // Expect a block mapping value. - yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a flow sequence. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE // Expect an entry of a flow sequence. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE // Expect a key of an ordered mapping. + + yaml_PARSE_FLOW_NODE_STATE // Expect a flow node. + + yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a block sequence. + + yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE // Expect an entry of a block sequence. + + yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE // Expect an entry of an indentless sequence. + + yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. + + yaml_PARSE_BLOCK_MAPPING_KEY_STATE // Expect a block mapping key. + + yaml_PARSE_BLOCK_MAPPING_VALUE_STATE // Expect a block mapping value. + + yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a flow sequence. + + yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE // Expect an entry of a flow sequence. + + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE // Expect a key of an ordered mapping. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE // Expect a value of an ordered mapping. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE // Expect the and of an ordered mapping entry. - yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. - yaml_PARSE_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. - yaml_PARSE_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. - yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE // Expect an empty value of a flow mapping. - yaml_PARSE_END_STATE // Expect nothing. + + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE // Expect the and of an ordered mapping entry. + + yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. + + yaml_PARSE_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. + + yaml_PARSE_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. + + yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE // Expect an empty value of a flow mapping. + + yaml_PARSE_END_STATE // Expect nothing. + ) func (ps yaml_parser_state_t) String() string { + switch ps { + case yaml_PARSE_STREAM_START_STATE: + return "yaml_PARSE_STREAM_START_STATE" + case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: + return "yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE" + case yaml_PARSE_DOCUMENT_START_STATE: + return "yaml_PARSE_DOCUMENT_START_STATE" + case yaml_PARSE_DOCUMENT_CONTENT_STATE: + return "yaml_PARSE_DOCUMENT_CONTENT_STATE" + case yaml_PARSE_DOCUMENT_END_STATE: + return "yaml_PARSE_DOCUMENT_END_STATE" + case yaml_PARSE_BLOCK_NODE_STATE: + return "yaml_PARSE_BLOCK_NODE_STATE" + case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: + return "yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE" + case yaml_PARSE_FLOW_NODE_STATE: + return "yaml_PARSE_FLOW_NODE_STATE" + case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: + return "yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE" + case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: + return "yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE" + case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: + return "yaml_PARSE_BLOCK_MAPPING_KEY_STATE" + case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: + return "yaml_PARSE_BLOCK_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE" + case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: + return "yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE" + case yaml_PARSE_FLOW_MAPPING_KEY_STATE: + return "yaml_PARSE_FLOW_MAPPING_KEY_STATE" + case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: + return "yaml_PARSE_FLOW_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: + return "yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE" + case yaml_PARSE_END_STATE: + return "yaml_PARSE_END_STATE" + } + return "" + } // This structure holds aliases data. + type yaml_alias_data_t struct { - anchor []byte // The anchor. - index int // The node id. - mark yaml_mark_t // The anchor mark. + anchor []byte // The anchor. + + index int // The node id. + + mark yaml_mark_t // The anchor mark. + } // The parser structure. + // + // All members are internal. Manage the structure using the + // yaml_parser_ family of functions. + type yaml_parser_t struct { // Error handling @@ -563,12 +911,17 @@ type yaml_parser_t struct { problem string // Error description. // The byte about which the problem occurred. + problem_offset int - problem_value int - problem_mark yaml_mark_t + + problem_value int + + problem_mark yaml_mark_t // The error context. - context string + + context string + context_mark yaml_mark_t // Reader stuff @@ -576,61 +929,81 @@ type yaml_parser_t struct { read_handler yaml_read_handler_t // Read handler. input_reader io.Reader // File input data. - input []byte // String input data. - input_pos int + + input []byte // String input data. + + input_pos int eof bool // EOF flag - buffer []byte // The working buffer. - buffer_pos int // The current position of the buffer. + buffer []byte // The working buffer. + + buffer_pos int // The current position of the buffer. unread int // The number of unread characters in the buffer. newlines int // The number of line breaks since last non-break/non-blank character - raw_buffer []byte // The raw buffer. - raw_buffer_pos int // The current position of the buffer. + raw_buffer []byte // The raw buffer. + + raw_buffer_pos int // The current position of the buffer. encoding yaml_encoding_t // The input encoding. - offset int // The offset of the current position (in bytes). - mark yaml_mark_t // The mark of the current position. + offset int // The offset of the current position (in bytes). + + mark yaml_mark_t // The mark of the current position. // Comments head_comment []byte // The current head comments + line_comment []byte // The current line comments + foot_comment []byte // The current foot comments + tail_comment []byte // Foot comment that happens at the end of a block. + stem_comment []byte // Comment in item preceding a nested structure (list inside list item, etc) - comments []yaml_comment_t // The folded comments for all parsed tokens + comments []yaml_comment_t // The folded comments for all parsed tokens + comments_head int // Scanner stuff stream_start_produced bool // Have we started to scan the input stream? - stream_end_produced bool // Have we reached the end of the input stream? + + stream_end_produced bool // Have we reached the end of the input stream? flow_level int // The number of unclosed '[' and '{' indicators. - tokens []yaml_token_t // The tokens queue. - tokens_head int // The head of the tokens queue. - tokens_parsed int // The number of tokens fetched from the queue. - token_available bool // Does the tokens queue contain a token ready for dequeueing. + tokens []yaml_token_t // The tokens queue. + + tokens_head int // The head of the tokens queue. + + tokens_parsed int // The number of tokens fetched from the queue. + + token_available bool // Does the tokens queue contain a token ready for dequeueing. + + indent int // The current indentation level. - indent int // The current indentation level. indents []int // The indentation levels stack. - simple_key_allowed bool // May a simple key occur at the current position? - simple_keys []yaml_simple_key_t // The stack of simple keys. - simple_keys_by_tok map[int]int // possible simple_key indexes indexed by token_number + simple_key_allowed bool // May a simple key occur at the current position? + + simple_keys []yaml_simple_key_t // The stack of simple keys. + + simple_keys_by_tok map[int]int // possible simple_key indexes indexed by token_number // Parser stuff - state yaml_parser_state_t // The current parser state. - states []yaml_parser_state_t // The parser states stack. - marks []yaml_mark_t // The stack of marks. + state yaml_parser_state_t // The current parser state. + + states []yaml_parser_state_t // The parser states stack. + + marks []yaml_mark_t // The stack of marks. + tag_directives []yaml_tag_directive_t // The list of TAG directives. // Dumper stuff @@ -638,105 +1011,162 @@ type yaml_parser_t struct { aliases []yaml_alias_data_t // The alias data. document *yaml_document_t // The currently parsed document. + } type yaml_comment_t struct { - scan_mark yaml_mark_t // Position where scanning for comments started + scan_mark yaml_mark_t // Position where scanning for comments started + token_mark yaml_mark_t // Position after which tokens will be associated with this comment + start_mark yaml_mark_t // Position of '#' comment mark - end_mark yaml_mark_t // Position where comment terminated + + end_mark yaml_mark_t // Position where comment terminated head []byte + line []byte + foot []byte } // Emitter Definitions // The prototype of a write handler. + // + // The write handler is called when the emitter needs to flush the accumulated + // characters to the output. The handler should write @a size bytes of the + // @a buffer to the output. + // + // @param[in,out] data A pointer to an application data specified by + // + // yaml_emitter_set_output(). + // + // @param[in] buffer The buffer with bytes to be written. + // @param[in] size The size of the buffer. + // + // @returns On success, the handler should return @c 1. If the handler failed, + // the returned value should be @c 0. + type yaml_write_handler_t func(emitter *yaml_emitter_t, buffer []byte) error type yaml_emitter_state_t int // The emitter states. + const ( + // Expect STREAM-START. + yaml_EMIT_STREAM_START_STATE yaml_emitter_state_t = iota - yaml_EMIT_FIRST_DOCUMENT_START_STATE // Expect the first DOCUMENT-START or STREAM-END. - yaml_EMIT_DOCUMENT_START_STATE // Expect DOCUMENT-START or STREAM-END. - yaml_EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document. - yaml_EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END. - yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence. - yaml_EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE // Expect the next item of a flow sequence, with the comma already written out - yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence. - yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_TRAIL_KEY_STATE // Expect the next key of a flow mapping, with the comma already written out - yaml_EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. - yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a block sequence. - yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE // Expect an item of a block sequence. - yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. - yaml_EMIT_BLOCK_MAPPING_KEY_STATE // Expect the key of a block mapping. + yaml_EMIT_FIRST_DOCUMENT_START_STATE // Expect the first DOCUMENT-START or STREAM-END. + + yaml_EMIT_DOCUMENT_START_STATE // Expect DOCUMENT-START or STREAM-END. + + yaml_EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document. + + yaml_EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END. + + yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence. + + yaml_EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE // Expect the next item of a flow sequence, with the comma already written out + + yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence. + + yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. + + yaml_EMIT_FLOW_MAPPING_TRAIL_KEY_STATE // Expect the next key of a flow mapping, with the comma already written out + + yaml_EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. + + yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping. + + yaml_EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. + + yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a block sequence. + + yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE // Expect an item of a block sequence. + + yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. + + yaml_EMIT_BLOCK_MAPPING_KEY_STATE // Expect the key of a block mapping. + yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a block mapping. - yaml_EMIT_BLOCK_MAPPING_VALUE_STATE // Expect a value of a block mapping. - yaml_EMIT_END_STATE // Expect nothing. + + yaml_EMIT_BLOCK_MAPPING_VALUE_STATE // Expect a value of a block mapping. + + yaml_EMIT_END_STATE // Expect nothing. + ) // The emitter structure. + // + // All members are internal. Manage the structure using the @c yaml_emitter_ + // family of functions. + type yaml_emitter_t struct { // Error handling - error yaml_error_type_t // Error type. - problem string // Error description. + error yaml_error_type_t // Error type. + + problem string // Error description. // Writer stuff write_handler yaml_write_handler_t // Write handler. - output_buffer *[]byte // String output data. + output_buffer *[]byte // String output data. + output_writer io.Writer // File output data. - buffer []byte // The working buffer. - buffer_pos int // The current position of the buffer. + buffer []byte // The working buffer. - raw_buffer []byte // The raw buffer. - raw_buffer_pos int // The current position of the buffer. + buffer_pos int // The current position of the buffer. + + raw_buffer []byte // The raw buffer. + + raw_buffer_pos int // The current position of the buffer. encoding yaml_encoding_t // The stream encoding. // Emitter stuff - canonical bool // If the output is in the canonical style? - best_indent int // The number of indentation spaces. - best_width int // The preferred width of the output lines. - unicode bool // Allow unescaped non-ASCII characters? - line_break yaml_break_t // The preferred line break. + canonical bool // If the output is in the canonical style? + + best_indent int // The number of indentation spaces. + + best_width int // The preferred width of the output lines. + + unicode bool // Allow unescaped non-ASCII characters? + + line_break yaml_break_t // The preferred line break. + + state yaml_emitter_state_t // The current emitter state. - state yaml_emitter_state_t // The current emitter state. states []yaml_emitter_state_t // The stack of states. - events []yaml_event_t // The event queue. - events_head int // The head of the event queue. + events []yaml_event_t // The event queue. + + events_head int // The head of the event queue. indents []int // The stack of indentation levels. @@ -746,47 +1176,73 @@ type yaml_emitter_t struct { flow_level int // The current flow level. - root_context bool // Is it the document root context? - sequence_context bool // Is it a sequence context? - mapping_context bool // Is it a mapping context? + root_context bool // Is it the document root context? + + sequence_context bool // Is it a sequence context? + + mapping_context bool // Is it a mapping context? + simple_key_context bool // Is it a simple mapping key context? - line int // The current line. - column int // The current column. + line int // The current line. + + column int // The current column. + whitespace bool // If the last character was a whitespace? - indention bool // If the last character was an indentation character (' ', '-', '?', ':')? + + indention bool // If the last character was an indentation character (' ', '-', '?', ':')? + open_ended bool // If an explicit document end is required? space_above bool // Is there's an empty line above? - foot_indent int // The indent used to write the foot comment above, or -1 if none. + + foot_indent int // The indent used to write the foot comment above, or -1 if none. // Anchor analysis. + anchor_data struct { anchor []byte // The anchor value. - alias bool // Is it an alias? + + alias bool // Is it an alias? + } // Tag analysis. + tag_data struct { handle []byte // The tag handle. + suffix []byte // The tag suffix. + } // Scalar analysis. + scalar_data struct { - value []byte // The scalar value. - multiline bool // Does the scalar contain line breaks? - flow_plain_allowed bool // Can the scalar be expessed in the flow plain style? - block_plain_allowed bool // Can the scalar be expressed in the block plain style? - single_quoted_allowed bool // Can the scalar be expressed in the single quoted style? - block_allowed bool // Can the scalar be expressed in the literal or folded styles? - style yaml_scalar_style_t // The output style. + value []byte // The scalar value. + + multiline bool // Does the scalar contain line breaks? + + flow_plain_allowed bool // Can the scalar be expessed in the flow plain style? + + block_plain_allowed bool // Can the scalar be expressed in the block plain style? + + single_quoted_allowed bool // Can the scalar be expressed in the single quoted style? + + block_allowed bool // Can the scalar be expressed in the literal or folded styles? + + style yaml_scalar_style_t // The output style. + } // Comments + head_comment []byte + line_comment []byte + foot_comment []byte + tail_comment []byte key_line_comment []byte @@ -794,16 +1250,22 @@ type yaml_emitter_t struct { // Dumper stuff opened bool // If the stream was already opened? + closed bool // If the stream was already closed? // The information associated with the document nodes. + anchors *struct { - references int // The number of references. - anchor int // The anchor id. + references int // The number of references. + + anchor int // The anchor id. + serialized bool // If the node has been emitted? + } last_anchor_id int // The last assigned anchor id. document *yaml_document_t // The currently emitted document. + }