From f9d00d04367c32db3007c64320c9e95aa485b392 Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Fri, 6 Sep 2024 00:14:39 +0100 Subject: [PATCH 1/4] feat: support CGO_ENABLED=0 - see notes users now required to set PACT_LD_LIBRARY_PATH env var with location of download pact ffi lib. It can exist anywhere on the filesystem --- go.mod | 3 +- go.sum | 2 + internal/native/c_types_unix.go | 2 +- internal/native/c_types_win.go | 2 +- internal/native/ffi_cgo.go | 451 ++++++++++++++++++++++++++ internal/native/ffi_dynamic.go | 293 +++++++++++++++++ internal/native/ffi_purego.go | 34 ++ internal/native/ffi_purego_unix.go | 9 + internal/native/ffi_purego_windows.go | 11 + internal/native/ffi_types.go | 65 ++++ internal/native/interaction_given.go | 39 +-- internal/native/lib.go | 2 + internal/native/message_server.go | 186 +++-------- internal/native/mock_server.go | 184 +++-------- internal/native/verifier.go | 150 ++------- 15 files changed, 994 insertions(+), 439 deletions(-) create mode 100644 internal/native/ffi_cgo.go create mode 100644 internal/native/ffi_dynamic.go create mode 100644 internal/native/ffi_purego.go create mode 100644 internal/native/ffi_purego_unix.go create mode 100644 internal/native/ffi_purego_windows.go create mode 100644 internal/native/ffi_types.go diff --git a/go.mod b/go.mod index bd9ab6551..d78c1977e 100644 --- a/go.mod +++ b/go.mod @@ -16,6 +16,7 @@ require ( ) require ( + github.com/ebitengine/purego v0.11.3 github.com/golang/snappy v0.0.4 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/kr/pretty v0.3.0 // indirect @@ -23,7 +24,7 @@ require ( github.com/spf13/pflag v1.0.9 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect golang.org/x/net v0.60.0 // indirect - golang.org/x/sys v0.48.0 // indirect + golang.org/x/sys v0.48.0 golang.org/x/text v0.42.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260817212433-ac3dfec99bb1 // indirect google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.6.2 // indirect diff --git a/go.sum b/go.sum index 9eb270f08..64b24e4c4 100644 --- a/go.sum +++ b/go.sum @@ -2,6 +2,8 @@ github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6N github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/ebitengine/purego v0.11.3 h1:OB+JLpdm7ioymhyA+6s5kbb/uOuYycAgL8NNTFc5MLg= +github.com/ebitengine/purego v0.11.3/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= diff --git a/internal/native/c_types_unix.go b/internal/native/c_types_unix.go index fde508865..1be9c4ac3 100644 --- a/internal/native/c_types_unix.go +++ b/internal/native/c_types_unix.go @@ -1,4 +1,4 @@ -//go:build darwin || linux +//go:build (darwin || linux) && cgo && !pact_purego && !pact_goffi package native diff --git a/internal/native/c_types_win.go b/internal/native/c_types_win.go index 386d6aabc..b0842ad70 100644 --- a/internal/native/c_types_win.go +++ b/internal/native/c_types_win.go @@ -1,4 +1,4 @@ -//go:build windows +//go:build windows && cgo && !pact_purego && !pact_goffi package native diff --git a/internal/native/ffi_cgo.go b/internal/native/ffi_cgo.go new file mode 100644 index 000000000..b9d1a7d4c --- /dev/null +++ b/internal/native/ffi_cgo.go @@ -0,0 +1,451 @@ +//go:build cgo && !pact_purego && !pact_goffi + +package native + +/* +#include +#include "pact.h" +*/ +import "C" + +import "unsafe" + +// ffiBackend names the binding in use, see ffi_types.go. +const ffiBackend = "cgo" + +// cStringArray converts inputs into a C array of C strings, and returns it +// with a function that frees it. It returns nil for an empty array. +func cStringArray(inputs []string) (unsafe.Pointer, func()) { + if len(inputs) == 0 { + return nil, func() {} + } + + output := make([]*C.char, len(inputs)) + for i, input := range inputs { + output[i] = C.CString(input) + } + + freeOutput := func() { + for _, s := range output { + C.free(unsafe.Pointer(s)) + } + } + + return unsafe.Pointer(&output[0]), freeOutput +} + +func pactffi_with_multipart_file(interaction uint32, part int32, contentType string, file string, partName string) { + cContentType := C.CString(contentType) + defer C.free(unsafe.Pointer(cContentType)) + cFile := C.CString(file) + defer C.free(unsafe.Pointer(cFile)) + cPartName := C.CString(partName) + defer C.free(unsafe.Pointer(cPartName)) + C.pactffi_with_multipart_file(C.InteractionHandle(interaction), C.int(part), cContentType, cFile, cPartName) +} + +func pactffi_version() unsafe.Pointer { + return unsafe.Pointer(C.pactffi_version()) +} + +func pactffi_free_string(s unsafe.Pointer) { + C.pactffi_free_string((*C.char)(s)) +} + +func pactffi_log_to_stdout(level int32) int32 { + return int32(C.pactffi_log_to_stdout(C.int(level))) +} + +func pactffi_log_to_file(file string, level int32) int32 { + cFile := C.CString(file) + defer C.free(unsafe.Pointer(cFile)) + return int32(C.pactffi_log_to_file(cFile, C.int(level))) +} + +func pactffi_new_pact(consumer string, provider string) uint16 { + cConsumer := C.CString(consumer) + defer C.free(unsafe.Pointer(cConsumer)) + cProvider := C.CString(provider) + defer C.free(unsafe.Pointer(cProvider)) + return uint16(C.pactffi_new_pact(cConsumer, cProvider)) +} + +func pactffi_with_specification(pact uint16, version int32) bool { + return bool(C.pactffi_with_specification(C.PactHandle(pact), C.int(version))) +} + +func pactffi_with_pact_metadata(pact uint16, namespace string, name string, value string) bool { + cNamespace := C.CString(namespace) + defer C.free(unsafe.Pointer(cNamespace)) + cName := C.CString(name) + defer C.free(unsafe.Pointer(cName)) + cValue := C.CString(value) + defer C.free(unsafe.Pointer(cValue)) + return bool(C.pactffi_with_pact_metadata(C.PactHandle(pact), cNamespace, cName, cValue)) +} + +func pactffi_using_plugin(pact uint16, name string, version string) uint32 { + cName := C.CString(name) + defer C.free(unsafe.Pointer(cName)) + cVersion := C.CString(version) + defer C.free(unsafe.Pointer(cVersion)) + return uint32(C.pactffi_using_plugin(C.PactHandle(pact), cName, cVersion)) +} + +func pactffi_cleanup_plugins(pact uint16) { + C.pactffi_cleanup_plugins(C.PactHandle(pact)) +} + +func pactffi_new_interaction(pact uint16, description string) uint32 { + cDescription := C.CString(description) + defer C.free(unsafe.Pointer(cDescription)) + return uint32(C.pactffi_new_interaction(C.PactHandle(pact), cDescription)) +} + +func pactffi_new_message_interaction(pact uint16, description string) uint32 { + cDescription := C.CString(description) + defer C.free(unsafe.Pointer(cDescription)) + return uint32(C.pactffi_new_message_interaction(C.PactHandle(pact), cDescription)) +} + +func pactffi_new_sync_message_interaction(pact uint16, description string) uint32 { + cDescription := C.CString(description) + defer C.free(unsafe.Pointer(cDescription)) + return uint32(C.pactffi_new_sync_message_interaction(C.PactHandle(pact), cDescription)) +} + +func pactffi_interaction_contents(interaction uint32, part int32, contentType string, contents string) uint32 { + cContentType := C.CString(contentType) + defer C.free(unsafe.Pointer(cContentType)) + cContents := C.CString(contents) + defer C.free(unsafe.Pointer(cContents)) + return uint32(C.pactffi_interaction_contents(C.InteractionHandle(interaction), C.int(part), cContentType, cContents)) +} + +func pactffi_upon_receiving(interaction uint32, description string) bool { + cDescription := C.CString(description) + defer C.free(unsafe.Pointer(cDescription)) + return bool(C.pactffi_upon_receiving(C.InteractionHandle(interaction), cDescription)) +} + +func pactffi_given(interaction uint32, description string) bool { + cDescription := C.CString(description) + defer C.free(unsafe.Pointer(cDescription)) + return bool(C.pactffi_given(C.InteractionHandle(interaction), cDescription)) +} + +func pactffi_given_with_param(interaction uint32, description string, name string, value string) bool { + cDescription := C.CString(description) + defer C.free(unsafe.Pointer(cDescription)) + cName := C.CString(name) + defer C.free(unsafe.Pointer(cName)) + cValue := C.CString(value) + defer C.free(unsafe.Pointer(cValue)) + return bool(C.pactffi_given_with_param(C.InteractionHandle(interaction), cDescription, cName, cValue)) +} + +func pactffi_with_request(interaction uint32, method string, path string) bool { + cMethod := C.CString(method) + defer C.free(unsafe.Pointer(cMethod)) + cPath := C.CString(path) + defer C.free(unsafe.Pointer(cPath)) + return bool(C.pactffi_with_request(C.InteractionHandle(interaction), cMethod, cPath)) +} + +func pactffi_with_query_parameter_v2(interaction uint32, name string, index uintptr, value string) bool { + cName := C.CString(name) + defer C.free(unsafe.Pointer(cName)) + cValue := C.CString(value) + defer C.free(unsafe.Pointer(cValue)) + return bool(C.pactffi_with_query_parameter_v2(C.InteractionHandle(interaction), cName, CUlong(index), cValue)) +} + +func pactffi_with_header_v2(interaction uint32, part int32, name string, index uintptr, value string) bool { + cName := C.CString(name) + defer C.free(unsafe.Pointer(cName)) + cValue := C.CString(value) + defer C.free(unsafe.Pointer(cValue)) + return bool(C.pactffi_with_header_v2(C.InteractionHandle(interaction), C.int(part), cName, CUlong(index), cValue)) +} + +func pactffi_with_body(interaction uint32, part int32, contentType string, body string) bool { + cContentType := C.CString(contentType) + defer C.free(unsafe.Pointer(cContentType)) + cBody := C.CString(body) + defer C.free(unsafe.Pointer(cBody)) + return bool(C.pactffi_with_body(C.InteractionHandle(interaction), C.int(part), cContentType, cBody)) +} + +func pactffi_with_binary_file(interaction uint32, part int32, contentType string, body unsafe.Pointer, size uintptr) bool { + cContentType := C.CString(contentType) + defer C.free(unsafe.Pointer(cContentType)) + return bool(C.pactffi_with_binary_file(C.InteractionHandle(interaction), C.int(part), cContentType, (*C.uint8_t)(body), CUlong(size))) +} + +func pactffi_response_status(interaction uint32, status uint16) bool { + return bool(C.pactffi_response_status(C.InteractionHandle(interaction), C.ushort(status))) +} + +func pactffi_add_interaction_reference(interaction uint32, group string, name string, value string) bool { + cGroup := C.CString(group) + defer C.free(unsafe.Pointer(cGroup)) + cName := C.CString(name) + defer C.free(unsafe.Pointer(cName)) + cValue := C.CString(value) + defer C.free(unsafe.Pointer(cValue)) + return bool(C.pactffi_add_interaction_reference(C.InteractionHandle(interaction), cGroup, cName, cValue)) +} + +func pactffi_with_metadata(interaction uint32, key string, value string, part int32) bool { + cKey := C.CString(key) + defer C.free(unsafe.Pointer(cKey)) + cValue := C.CString(value) + defer C.free(unsafe.Pointer(cValue)) + return bool(C.pactffi_with_metadata(C.InteractionHandle(interaction), cKey, cValue, C.int(part))) +} + +func pactffi_create_mock_server_for_transport(pact uint16, addr string, port uint16, transport string, config *byte) int32 { + cAddr := C.CString(addr) + defer C.free(unsafe.Pointer(cAddr)) + cTransport := C.CString(transport) + defer C.free(unsafe.Pointer(cTransport)) + return int32(C.pactffi_create_mock_server_for_transport(C.PactHandle(pact), cAddr, C.uint16_t(port), cTransport, (*C.char)(unsafe.Pointer(config)))) +} + +func pactffi_mock_server_mismatches(port int32) unsafe.Pointer { + return unsafe.Pointer(C.pactffi_mock_server_mismatches(C.int32_t(port))) +} + +func pactffi_mock_server_matched(port int32) bool { + return bool(C.pactffi_mock_server_matched(C.int32_t(port))) +} + +func pactffi_cleanup_mock_server(port int32) bool { + return bool(C.pactffi_cleanup_mock_server(C.int32_t(port))) +} + +func pactffi_write_pact_file(port int32, dir string, overwrite bool) int32 { + cDir := C.CString(dir) + defer C.free(unsafe.Pointer(cDir)) + return int32(C.pactffi_write_pact_file(C.int32_t(port), cDir, C.bool(overwrite))) +} + +func pactffi_get_tls_ca_certificate() unsafe.Pointer { + return unsafe.Pointer(C.pactffi_get_tls_ca_certificate()) +} + +func pactffi_new_message_pact(consumer string, provider string) uint16 { + cConsumer := C.CString(consumer) + defer C.free(unsafe.Pointer(cConsumer)) + cProvider := C.CString(provider) + defer C.free(unsafe.Pointer(cProvider)) + return uint16(C.pactffi_new_message_pact(cConsumer, cProvider)) +} + +func pactffi_with_message_pact_metadata(pact uint16, namespace string, name string, value string) { + cNamespace := C.CString(namespace) + defer C.free(unsafe.Pointer(cNamespace)) + cName := C.CString(name) + defer C.free(unsafe.Pointer(cName)) + cValue := C.CString(value) + defer C.free(unsafe.Pointer(cValue)) + C.pactffi_with_message_pact_metadata(C.MessagePactHandle(pact), cNamespace, cName, cValue) +} + +func pactffi_message_expects_to_receive(message uint32, description string) { + cDescription := C.CString(description) + defer C.free(unsafe.Pointer(cDescription)) + C.pactffi_message_expects_to_receive(C.MessageHandle(message), cDescription) +} + +func pactffi_message_with_metadata(message uint32, key string, value string) { + cKey := C.CString(key) + defer C.free(unsafe.Pointer(cKey)) + cValue := C.CString(value) + defer C.free(unsafe.Pointer(cValue)) + C.pactffi_message_with_metadata(C.MessageHandle(message), cKey, cValue) +} + +func pactffi_write_message_pact_file(pact uint16, dir string, overwrite bool) int32 { + cDir := C.CString(dir) + defer C.free(unsafe.Pointer(cDir)) + return int32(C.pactffi_write_message_pact_file(C.MessagePactHandle(pact), cDir, C.bool(overwrite))) +} + +func pactffi_pact_handle_get_message_iter(pact uint16) unsafe.Pointer { + return unsafe.Pointer(C.pactffi_pact_handle_get_message_iter(C.PactHandle(pact))) +} + +func pactffi_pact_message_iter_next(iter unsafe.Pointer) unsafe.Pointer { + return unsafe.Pointer(C.pactffi_pact_message_iter_next((*C.struct_PactMessageIterator)(iter))) +} + +func pactffi_pact_message_iter_delete(iter unsafe.Pointer) { + C.pactffi_pact_message_iter_delete((*C.struct_PactMessageIterator)(iter)) +} + +func pactffi_message_get_contents_length(message unsafe.Pointer) uintptr { + return uintptr(C.pactffi_message_get_contents_length((*C.struct_Message)(message))) +} + +func pactffi_message_get_contents_bin(message unsafe.Pointer) unsafe.Pointer { + return unsafe.Pointer(C.pactffi_message_get_contents_bin((*C.struct_Message)(message))) +} + +func pactffi_pact_handle_get_sync_message_iter(pact uint16) unsafe.Pointer { + return unsafe.Pointer(C.pactffi_pact_handle_get_sync_message_iter(C.PactHandle(pact))) +} + +func pactffi_pact_sync_message_iter_next(iter unsafe.Pointer) unsafe.Pointer { + return unsafe.Pointer(C.pactffi_pact_sync_message_iter_next((*C.struct_PactSyncMessageIterator)(iter))) +} + +func pactffi_pact_sync_message_iter_delete(iter unsafe.Pointer) { + C.pactffi_pact_sync_message_iter_delete((*C.struct_PactSyncMessageIterator)(iter)) +} + +func pactffi_sync_message_get_request_contents_length(message unsafe.Pointer) uintptr { + return uintptr(C.pactffi_sync_message_get_request_contents_length((*C.struct_SynchronousMessage)(message))) +} + +func pactffi_sync_message_get_request_contents_bin(message unsafe.Pointer) unsafe.Pointer { + return unsafe.Pointer(C.pactffi_sync_message_get_request_contents_bin((*C.struct_SynchronousMessage)(message))) +} + +func pactffi_sync_message_get_response_contents_length(message unsafe.Pointer, index uintptr) uintptr { + return uintptr(C.pactffi_sync_message_get_response_contents_length((*C.struct_SynchronousMessage)(message), CUlong(index))) +} + +func pactffi_sync_message_get_response_contents_bin(message unsafe.Pointer, index uintptr) unsafe.Pointer { + return unsafe.Pointer(C.pactffi_sync_message_get_response_contents_bin((*C.struct_SynchronousMessage)(message), CUlong(index))) +} + +func pactffi_verifier_new_for_application(name string, version string) unsafe.Pointer { + cName := C.CString(name) + defer C.free(unsafe.Pointer(cName)) + cVersion := C.CString(version) + defer C.free(unsafe.Pointer(cVersion)) + return unsafe.Pointer(C.pactffi_verifier_new_for_application(cName, cVersion)) +} + +func pactffi_verifier_shutdown(handle unsafe.Pointer) { + C.pactffi_verifier_shutdown((*C.struct_VerifierHandle)(handle)) +} + +func pactffi_verifier_set_provider_info(handle unsafe.Pointer, name string, scheme string, host string, port uint16, path string) { + cName := C.CString(name) + defer C.free(unsafe.Pointer(cName)) + cScheme := C.CString(scheme) + defer C.free(unsafe.Pointer(cScheme)) + cHost := C.CString(host) + defer C.free(unsafe.Pointer(cHost)) + cPath := C.CString(path) + defer C.free(unsafe.Pointer(cPath)) + C.pactffi_verifier_set_provider_info((*C.struct_VerifierHandle)(handle), cName, cScheme, cHost, C.ushort(port), cPath) +} + +func pactffi_verifier_add_provider_transport(handle unsafe.Pointer, protocol string, port uint16, path string, scheme string) { + cProtocol := C.CString(protocol) + defer C.free(unsafe.Pointer(cProtocol)) + cPath := C.CString(path) + defer C.free(unsafe.Pointer(cPath)) + cScheme := C.CString(scheme) + defer C.free(unsafe.Pointer(cScheme)) + C.pactffi_verifier_add_provider_transport((*C.struct_VerifierHandle)(handle), cProtocol, C.ushort(port), cPath, cScheme) +} + +func pactffi_verifier_set_filter_info(handle unsafe.Pointer, description string, state string, noState uint8) { + cDescription := C.CString(description) + defer C.free(unsafe.Pointer(cDescription)) + cState := C.CString(state) + defer C.free(unsafe.Pointer(cState)) + C.pactffi_verifier_set_filter_info((*C.struct_VerifierHandle)(handle), cDescription, cState, C.uchar(noState)) +} + +func pactffi_verifier_set_provider_state(handle unsafe.Pointer, sourceURL string, teardown uint8, body uint8) { + cSourceURL := C.CString(sourceURL) + defer C.free(unsafe.Pointer(cSourceURL)) + C.pactffi_verifier_set_provider_state((*C.struct_VerifierHandle)(handle), cSourceURL, C.uchar(teardown), C.uchar(body)) +} + +func pactffi_verifier_set_verification_options(handle unsafe.Pointer, disableSSLVerification uint8, requestTimeout uint64) int32 { + return int32(C.pactffi_verifier_set_verification_options((*C.struct_VerifierHandle)(handle), C.uchar(disableSSLVerification), C.ulong(requestTimeout))) +} + +func pactffi_verifier_set_consumer_filters(handle unsafe.Pointer, filters unsafe.Pointer, filtersLen uint16) { + C.pactffi_verifier_set_consumer_filters((*C.struct_VerifierHandle)(handle), (**C.char)(filters), C.ushort(filtersLen)) +} + +func pactffi_verifier_add_custom_header(handle unsafe.Pointer, name string, value string) { + cName := C.CString(name) + defer C.free(unsafe.Pointer(cName)) + cValue := C.CString(value) + defer C.free(unsafe.Pointer(cValue)) + C.pactffi_verifier_add_custom_header((*C.struct_VerifierHandle)(handle), cName, cValue) +} + +func pactffi_verifier_add_file_source(handle unsafe.Pointer, file string) { + cFile := C.CString(file) + defer C.free(unsafe.Pointer(cFile)) + C.pactffi_verifier_add_file_source((*C.struct_VerifierHandle)(handle), cFile) +} + +func pactffi_verifier_add_directory_source(handle unsafe.Pointer, directory string) { + cDirectory := C.CString(directory) + defer C.free(unsafe.Pointer(cDirectory)) + C.pactffi_verifier_add_directory_source((*C.struct_VerifierHandle)(handle), cDirectory) +} + +func pactffi_verifier_url_source(handle unsafe.Pointer, sourceURL string, username string, password string, token string) { + cSourceURL := C.CString(sourceURL) + defer C.free(unsafe.Pointer(cSourceURL)) + cUsername := C.CString(username) + defer C.free(unsafe.Pointer(cUsername)) + cPassword := C.CString(password) + defer C.free(unsafe.Pointer(cPassword)) + cToken := C.CString(token) + defer C.free(unsafe.Pointer(cToken)) + C.pactffi_verifier_url_source((*C.struct_VerifierHandle)(handle), cSourceURL, cUsername, cPassword, cToken) +} + +func pactffi_verifier_broker_source_with_selectors(handle unsafe.Pointer, sourceURL string, username string, password string, token string, enablePending uint8, includeWipPactsSince string, providerTags unsafe.Pointer, providerTagsLen uint16, providerBranch string, selectors unsafe.Pointer, selectorsLen uint16, consumerVersionTags unsafe.Pointer, consumerVersionTagsLen uint16) int32 { + cSourceURL := C.CString(sourceURL) + defer C.free(unsafe.Pointer(cSourceURL)) + cUsername := C.CString(username) + defer C.free(unsafe.Pointer(cUsername)) + cPassword := C.CString(password) + defer C.free(unsafe.Pointer(cPassword)) + cToken := C.CString(token) + defer C.free(unsafe.Pointer(cToken)) + cIncludeWipPactsSince := C.CString(includeWipPactsSince) + defer C.free(unsafe.Pointer(cIncludeWipPactsSince)) + cProviderBranch := C.CString(providerBranch) + defer C.free(unsafe.Pointer(cProviderBranch)) + return int32(C.pactffi_verifier_broker_source_with_selectors((*C.struct_VerifierHandle)(handle), cSourceURL, cUsername, cPassword, cToken, C.uchar(enablePending), cIncludeWipPactsSince, (**C.char)(providerTags), C.ushort(providerTagsLen), cProviderBranch, (**C.char)(selectors), C.ushort(selectorsLen), (**C.char)(consumerVersionTags), C.ushort(consumerVersionTagsLen))) +} + +func pactffi_verifier_set_publish_options(handle unsafe.Pointer, providerVersion string, buildURL string, providerTags unsafe.Pointer, providerTagsLen uint16, providerBranch string) int32 { + cProviderVersion := C.CString(providerVersion) + defer C.free(unsafe.Pointer(cProviderVersion)) + cBuildURL := C.CString(buildURL) + defer C.free(unsafe.Pointer(cBuildURL)) + cProviderBranch := C.CString(providerBranch) + defer C.free(unsafe.Pointer(cProviderBranch)) + return int32(C.pactffi_verifier_set_publish_options((*C.struct_VerifierHandle)(handle), cProviderVersion, cBuildURL, (**C.char)(providerTags), C.ushort(providerTagsLen), cProviderBranch)) +} + +func pactffi_verifier_execute(handle unsafe.Pointer) int32 { + return int32(C.pactffi_verifier_execute((*C.struct_VerifierHandle)(handle))) +} + +func pactffi_verifier_set_no_pacts_is_error(handle unsafe.Pointer, isError uint8) int32 { + return int32(C.pactffi_verifier_set_no_pacts_is_error((*C.struct_VerifierHandle)(handle), C.uchar(isError))) +} + +func pactffi_verifier_set_coloured_output(handle unsafe.Pointer, colouredOutput uint8) int32 { + return int32(C.pactffi_verifier_set_coloured_output((*C.struct_VerifierHandle)(handle), C.uchar(colouredOutput))) +} + +func pactffi_verifier_json(handle unsafe.Pointer) unsafe.Pointer { + return unsafe.Pointer(C.pactffi_verifier_json((*C.struct_VerifierHandle)(handle))) +} diff --git a/internal/native/ffi_dynamic.go b/internal/native/ffi_dynamic.go new file mode 100644 index 000000000..c85f60727 --- /dev/null +++ b/internal/native/ffi_dynamic.go @@ -0,0 +1,293 @@ +//go:build !cgo || pact_purego || pact_goffi + +package native + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "unsafe" +) + +// The pact_ffi functions, bound at runtime by the purego or goffi backend +// (see ffi_types.go). Only the functions this package calls are bound. +var ( + pactffi_version func() unsafe.Pointer + pactffi_free_string func(s unsafe.Pointer) + pactffi_log_to_stdout func(level int32) int32 + pactffi_log_to_file func(file string, level int32) int32 + pactffi_new_pact func(consumer string, provider string) uint16 + pactffi_with_specification func(pact uint16, version int32) bool + pactffi_with_pact_metadata func(pact uint16, namespace string, name string, value string) bool + pactffi_using_plugin func(pact uint16, name string, version string) uint32 + pactffi_cleanup_plugins func(pact uint16) + pactffi_new_interaction func(pact uint16, description string) uint32 + pactffi_new_message_interaction func(pact uint16, description string) uint32 + pactffi_new_sync_message_interaction func(pact uint16, description string) uint32 + pactffi_interaction_contents func(interaction uint32, part int32, contentType string, contents string) uint32 + pactffi_upon_receiving func(interaction uint32, description string) bool + pactffi_given func(interaction uint32, description string) bool + pactffi_given_with_param func(interaction uint32, description string, name string, value string) bool + pactffi_with_request func(interaction uint32, method string, path string) bool + pactffi_with_query_parameter_v2 func(interaction uint32, name string, index uintptr, value string) bool + pactffi_with_header_v2 func(interaction uint32, part int32, name string, index uintptr, value string) bool + pactffi_with_body func(interaction uint32, part int32, contentType string, body string) bool + pactffi_with_binary_file func(interaction uint32, part int32, contentType string, body unsafe.Pointer, size uintptr) bool + pactffi_response_status func(interaction uint32, status uint16) bool + pactffi_add_interaction_reference func(interaction uint32, group string, name string, value string) bool + pactffi_with_metadata func(interaction uint32, key string, value string, part int32) bool + pactffi_create_mock_server_for_transport func(pact uint16, addr string, port uint16, transport string, config *byte) int32 + pactffi_mock_server_mismatches func(port int32) unsafe.Pointer + pactffi_mock_server_matched func(port int32) bool + pactffi_cleanup_mock_server func(port int32) bool + pactffi_write_pact_file func(port int32, dir string, overwrite bool) int32 + pactffi_get_tls_ca_certificate func() unsafe.Pointer + pactffi_new_message_pact func(consumer string, provider string) uint16 + pactffi_with_message_pact_metadata func(pact uint16, namespace string, name string, value string) + pactffi_message_expects_to_receive func(message uint32, description string) + pactffi_message_with_metadata func(message uint32, key string, value string) + pactffi_write_message_pact_file func(pact uint16, dir string, overwrite bool) int32 + pactffi_pact_handle_get_message_iter func(pact uint16) unsafe.Pointer + pactffi_pact_message_iter_next func(iter unsafe.Pointer) unsafe.Pointer + pactffi_pact_message_iter_delete func(iter unsafe.Pointer) + pactffi_message_get_contents_length func(message unsafe.Pointer) uintptr + pactffi_message_get_contents_bin func(message unsafe.Pointer) unsafe.Pointer + pactffi_pact_handle_get_sync_message_iter func(pact uint16) unsafe.Pointer + pactffi_pact_sync_message_iter_next func(iter unsafe.Pointer) unsafe.Pointer + pactffi_pact_sync_message_iter_delete func(iter unsafe.Pointer) + pactffi_sync_message_get_request_contents_length func(message unsafe.Pointer) uintptr + pactffi_sync_message_get_request_contents_bin func(message unsafe.Pointer) unsafe.Pointer + pactffi_sync_message_get_response_contents_length func(message unsafe.Pointer, index uintptr) uintptr + pactffi_sync_message_get_response_contents_bin func(message unsafe.Pointer, index uintptr) unsafe.Pointer + pactffi_verifier_new_for_application func(name string, version string) unsafe.Pointer + pactffi_verifier_shutdown func(handle unsafe.Pointer) + pactffi_verifier_set_provider_info func(handle unsafe.Pointer, name string, scheme string, host string, port uint16, path string) + pactffi_verifier_add_provider_transport func(handle unsafe.Pointer, protocol string, port uint16, path string, scheme string) + pactffi_verifier_set_filter_info func(handle unsafe.Pointer, description string, state string, noState uint8) + pactffi_verifier_set_provider_state func(handle unsafe.Pointer, sourceURL string, teardown uint8, body uint8) + pactffi_verifier_set_verification_options func(handle unsafe.Pointer, disableSSLVerification uint8, requestTimeout uint64) int32 + pactffi_verifier_set_consumer_filters func(handle unsafe.Pointer, filters unsafe.Pointer, filtersLen uint16) + pactffi_verifier_add_custom_header func(handle unsafe.Pointer, name string, value string) + pactffi_verifier_add_file_source func(handle unsafe.Pointer, file string) + pactffi_verifier_add_directory_source func(handle unsafe.Pointer, directory string) + pactffi_verifier_url_source func(handle unsafe.Pointer, sourceURL string, username string, password string, token string) + pactffi_verifier_broker_source_with_selectors func(handle unsafe.Pointer, sourceURL string, username string, password string, token string, enablePending uint8, includeWipPactsSince string, providerTags unsafe.Pointer, providerTagsLen uint16, providerBranch string, selectors unsafe.Pointer, selectorsLen uint16, consumerVersionTags unsafe.Pointer, consumerVersionTagsLen uint16) int32 + pactffi_verifier_set_publish_options func(handle unsafe.Pointer, providerVersion string, buildURL string, providerTags unsafe.Pointer, providerTagsLen uint16, providerBranch string) int32 + pactffi_verifier_execute func(handle unsafe.Pointer) int32 + pactffi_verifier_set_no_pacts_is_error func(handle unsafe.Pointer, isError uint8) int32 + pactffi_verifier_set_coloured_output func(handle unsafe.Pointer, colouredOutput uint8) int32 + pactffi_verifier_json func(handle unsafe.Pointer) unsafe.Pointer + + // pactffi_with_multipart_file returns a 16 byte struct by value, which + // is not read. On the System V and AAPCS64 ABIs it comes back in + // registers and can be ignored; on Windows x64 the caller must pass a + // buffer for it as a hidden first argument. + withMultipartFileRegs func(interaction uint32, part int32, contentType string, file string, partName string) + withMultipartFileMem func(result unsafe.Pointer, interaction uint32, part int32, contentType string, file string, partName string) unsafe.Pointer +) + +func pactffi_with_multipart_file(interaction uint32, part int32, contentType string, file string, partName string) { + if runtime.GOOS != "windows" { + withMultipartFileRegs(interaction, part, contentType, file, partName) + + return + } + + var result [2]uintptr + withMultipartFileMem(unsafe.Pointer(&result), interaction, part, contentType, file, partName) +} + +// ffiSymbol pairs the name of a pact_ffi function with a pointer to the Go +// func variable it is bound to. +type ffiSymbol struct { + name string + fptr any +} + +func ffiSymbols() []ffiSymbol { + symbols := []ffiSymbol{ + {"pactffi_version", &pactffi_version}, + {"pactffi_free_string", &pactffi_free_string}, + {"pactffi_log_to_stdout", &pactffi_log_to_stdout}, + {"pactffi_log_to_file", &pactffi_log_to_file}, + {"pactffi_new_pact", &pactffi_new_pact}, + {"pactffi_with_specification", &pactffi_with_specification}, + {"pactffi_with_pact_metadata", &pactffi_with_pact_metadata}, + {"pactffi_using_plugin", &pactffi_using_plugin}, + {"pactffi_cleanup_plugins", &pactffi_cleanup_plugins}, + {"pactffi_new_interaction", &pactffi_new_interaction}, + {"pactffi_new_message_interaction", &pactffi_new_message_interaction}, + {"pactffi_new_sync_message_interaction", &pactffi_new_sync_message_interaction}, + {"pactffi_interaction_contents", &pactffi_interaction_contents}, + {"pactffi_upon_receiving", &pactffi_upon_receiving}, + {"pactffi_given", &pactffi_given}, + {"pactffi_given_with_param", &pactffi_given_with_param}, + {"pactffi_with_request", &pactffi_with_request}, + {"pactffi_with_query_parameter_v2", &pactffi_with_query_parameter_v2}, + {"pactffi_with_header_v2", &pactffi_with_header_v2}, + {"pactffi_with_body", &pactffi_with_body}, + {"pactffi_with_binary_file", &pactffi_with_binary_file}, + {"pactffi_response_status", &pactffi_response_status}, + {"pactffi_add_interaction_reference", &pactffi_add_interaction_reference}, + {"pactffi_with_metadata", &pactffi_with_metadata}, + {"pactffi_create_mock_server_for_transport", &pactffi_create_mock_server_for_transport}, + {"pactffi_mock_server_mismatches", &pactffi_mock_server_mismatches}, + {"pactffi_mock_server_matched", &pactffi_mock_server_matched}, + {"pactffi_cleanup_mock_server", &pactffi_cleanup_mock_server}, + {"pactffi_write_pact_file", &pactffi_write_pact_file}, + {"pactffi_get_tls_ca_certificate", &pactffi_get_tls_ca_certificate}, + {"pactffi_new_message_pact", &pactffi_new_message_pact}, + {"pactffi_with_message_pact_metadata", &pactffi_with_message_pact_metadata}, + {"pactffi_message_expects_to_receive", &pactffi_message_expects_to_receive}, + {"pactffi_message_with_metadata", &pactffi_message_with_metadata}, + {"pactffi_write_message_pact_file", &pactffi_write_message_pact_file}, + {"pactffi_pact_handle_get_message_iter", &pactffi_pact_handle_get_message_iter}, + {"pactffi_pact_message_iter_next", &pactffi_pact_message_iter_next}, + {"pactffi_pact_message_iter_delete", &pactffi_pact_message_iter_delete}, + {"pactffi_message_get_contents_length", &pactffi_message_get_contents_length}, + {"pactffi_message_get_contents_bin", &pactffi_message_get_contents_bin}, + {"pactffi_pact_handle_get_sync_message_iter", &pactffi_pact_handle_get_sync_message_iter}, + {"pactffi_pact_sync_message_iter_next", &pactffi_pact_sync_message_iter_next}, + {"pactffi_pact_sync_message_iter_delete", &pactffi_pact_sync_message_iter_delete}, + {"pactffi_sync_message_get_request_contents_length", &pactffi_sync_message_get_request_contents_length}, + {"pactffi_sync_message_get_request_contents_bin", &pactffi_sync_message_get_request_contents_bin}, + {"pactffi_sync_message_get_response_contents_length", &pactffi_sync_message_get_response_contents_length}, + {"pactffi_sync_message_get_response_contents_bin", &pactffi_sync_message_get_response_contents_bin}, + {"pactffi_verifier_new_for_application", &pactffi_verifier_new_for_application}, + {"pactffi_verifier_shutdown", &pactffi_verifier_shutdown}, + {"pactffi_verifier_set_provider_info", &pactffi_verifier_set_provider_info}, + {"pactffi_verifier_add_provider_transport", &pactffi_verifier_add_provider_transport}, + {"pactffi_verifier_set_filter_info", &pactffi_verifier_set_filter_info}, + {"pactffi_verifier_set_provider_state", &pactffi_verifier_set_provider_state}, + {"pactffi_verifier_set_verification_options", &pactffi_verifier_set_verification_options}, + {"pactffi_verifier_set_consumer_filters", &pactffi_verifier_set_consumer_filters}, + {"pactffi_verifier_add_custom_header", &pactffi_verifier_add_custom_header}, + {"pactffi_verifier_add_file_source", &pactffi_verifier_add_file_source}, + {"pactffi_verifier_add_directory_source", &pactffi_verifier_add_directory_source}, + {"pactffi_verifier_url_source", &pactffi_verifier_url_source}, + {"pactffi_verifier_broker_source_with_selectors", &pactffi_verifier_broker_source_with_selectors}, + {"pactffi_verifier_set_publish_options", &pactffi_verifier_set_publish_options}, + {"pactffi_verifier_execute", &pactffi_verifier_execute}, + {"pactffi_verifier_set_no_pacts_is_error", &pactffi_verifier_set_no_pacts_is_error}, + {"pactffi_verifier_set_coloured_output", &pactffi_verifier_set_coloured_output}, + {"pactffi_verifier_json", &pactffi_verifier_json}, + } + + if runtime.GOOS == "windows" { + return append(symbols, ffiSymbol{"pactffi_with_multipart_file", &withMultipartFileMem}) + } + + return append(symbols, ffiSymbol{"pactffi_with_multipart_file", &withMultipartFileRegs}) +} + +// libEnvVar names a directory to load the pact_ffi library from, ahead of +// the default locations. +const libEnvVar = "PACT_LD_LIBRARY_PATH" + +// libDownloadEnvVar names the directory `pact-go install` downloads the +// library to, see the installer package. +const libDownloadEnvVar = "PACT_GO_LIB_DOWNLOAD_PATH" + +// errLibNotLoaded is the reason the pact_ffi library is unusable, or nil +// if it was loaded and every function was bound. +var errLibNotLoaded error + +// LibraryLoadError returns the reason the pact_ffi library could not be +// loaded at startup, or nil if it is ready for use. With the cgo backend +// the library is linked at build time and this is always nil. +func LibraryLoadError() error { + return errLibNotLoaded +} + +func libFileName() string { + switch runtime.GOOS { + case "windows": + return "pact_ffi.dll" + case "darwin": + return "libpact_ffi.dylib" + default: + return "libpact_ffi.so" + } +} + +// libCandidates lists where to look for the pact_ffi library, in order: +// $PACT_LD_LIBRARY_PATH, $PACT_GO_LIB_DOWNLOAD_PATH, the directories the cgo backend links against +// (see lib.go), and finally the bare file name, which leaves the search +// to the system loader (LD_LIBRARY_PATH, DYLD_LIBRARY_PATH, PATH, ...). +func libCandidates() []string { + name := libFileName() + + var candidates []string + for _, env := range []string{libEnvVar, libDownloadEnvVar} { + if dir := os.Getenv(env); dir != "" { + candidates = append(candidates, filepath.Join(dir, name)) + } + } + if runtime.GOOS != "windows" { + for _, dir := range []string{"/tmp", "/opt/pact/lib", "/usr/local/lib"} { + candidates = append(candidates, filepath.Join(dir, name)) + } + } + + return append(candidates, name) +} + +// The package must be importable without the library: `pact-go install`, +// which downloads it, imports this package. So a failure to load is not +// fatal here; instead every pact_ffi function panics with the reason when +// it is first called. +func init() { + symbols := ffiSymbols() + + errLibNotLoaded = loadLibrary(symbols) + if errLibNotLoaded == nil { + return + } + + errLibNotLoaded = fmt.Errorf("pact-go: the pact_ffi library is not available to the %s backend (run `pact-go install`, or set %s to the directory containing %s): %w", ffiBackend, libEnvVar, libFileName(), errLibNotLoaded) + for _, s := range symbols { + fn := reflect.ValueOf(s.fptr).Elem() + fn.Set(reflect.MakeFunc(fn.Type(), func([]reflect.Value) []reflect.Value { + panic(errLibNotLoaded) + })) + } +} + +// loadLibrary opens the first candidate library that exists and binds +// every symbol from it. +func loadLibrary(symbols []ffiSymbol) error { + var errs []error + for _, path := range libCandidates() { + if filepath.IsAbs(path) { + if _, err := os.Stat(path); err != nil { + continue + } + } + + err := bindLibrary(path, symbols) + if err == nil { + return nil + } + errs = append(errs, fmt.Errorf("%s: %w", path, err)) + } + + return errors.Join(errs...) +} + +// cStringArray converts inputs into a C array of C strings, and returns it +// with a function that releases it. It returns nil for an empty array. +func cStringArray(inputs []string) (unsafe.Pointer, func()) { + if len(inputs) == 0 { + return nil, func() {} + } + + output := make([]*byte, len(inputs)) + for i, input := range inputs { + output[i] = cstr(input) + } + + return unsafe.Pointer(&output[0]), func() { runtime.KeepAlive(output) } +} diff --git a/internal/native/ffi_purego.go b/internal/native/ffi_purego.go new file mode 100644 index 000000000..672f45517 --- /dev/null +++ b/internal/native/ffi_purego.go @@ -0,0 +1,34 @@ +//go:build (!cgo || pact_purego) && !pact_goffi + +package native + +import ( + "fmt" + + "github.com/ebitengine/purego" +) + +// ffiBackend names the binding in use, see ffi_types.go. +const ffiBackend = "purego" + +// bindLibrary loads the pact_ffi library at path and binds every symbol +// to its Go func variable. +func bindLibrary(path string, symbols []ffiSymbol) error { + lib, err := openLibrary(path) + if err != nil { + return err + } + + // RegisterLibFunc panics on a missing symbol, so check them all first. + for _, s := range symbols { + _, err := purego.Dlsym(lib, s.name) + if err != nil { + return fmt.Errorf("symbol %s: %w", s.name, err) + } + } + for _, s := range symbols { + purego.RegisterLibFunc(s.fptr, lib, s.name) + } + + return nil +} diff --git a/internal/native/ffi_purego_unix.go b/internal/native/ffi_purego_unix.go new file mode 100644 index 000000000..04a3202a1 --- /dev/null +++ b/internal/native/ffi_purego_unix.go @@ -0,0 +1,9 @@ +//go:build (!cgo || pact_purego) && !pact_goffi && !windows + +package native + +import "github.com/ebitengine/purego" + +func openLibrary(path string) (uintptr, error) { + return purego.Dlopen(path, purego.RTLD_NOW|purego.RTLD_GLOBAL) +} diff --git a/internal/native/ffi_purego_windows.go b/internal/native/ffi_purego_windows.go new file mode 100644 index 000000000..07a7c9c24 --- /dev/null +++ b/internal/native/ffi_purego_windows.go @@ -0,0 +1,11 @@ +//go:build (!cgo || pact_purego) && !pact_goffi && windows + +package native + +import "golang.org/x/sys/windows" + +func openLibrary(path string) (uintptr, error) { + handle, err := windows.LoadLibrary(path) + + return uintptr(handle), err +} diff --git a/internal/native/ffi_types.go b/internal/native/ffi_types.go new file mode 100644 index 000000000..aaa785454 --- /dev/null +++ b/internal/native/ffi_types.go @@ -0,0 +1,65 @@ +package native + +import "unsafe" + +// The pact_ffi library can be bound in three ways, selected at build time: +// +// - cgo (ffi_cgo.go): the default when cgo is enabled. Links libpact_ffi +// at build time, exactly as pact-go has always done. +// - purego (ffi_purego.go): the default when cgo is disabled +// (CGO_ENABLED=0), or forced with -tags pact_purego. Loads libpact_ffi +// at runtime with github.com/ebitengine/purego; no C toolchain needed. +// - goffi (ffi_goffi.go): opt-in with -tags pact_goffi. Loads libpact_ffi +// at runtime with github.com/go-webgpu/goffi; no C toolchain needed. +// +// Every backend provides the same set of pactffi_* functions with the same +// Go signatures, so the rest of this package does not know which is in use. +// The mapping from the C prototypes in pact.h is: +// +// const char * (in) string (copied, NUL terminated for the call) +// const char * (nullable) *byte, see cstr +// char * (returned) unsafe.Pointer, see goString and libRustFree +// opaque pointers unsafe.Pointer +// PactHandle uint16 +// InteractionHandle uint32 +// int, int32_t int32 +// unsigned short uint16 +// size_t uintptr +// unsigned char uint8 +// bool bool + +// goString copies the NUL-terminated C string at p into a Go string. It +// returns "" if p is nil. The C string is not freed. +func goString(p unsafe.Pointer) string { + if p == nil { + return "" + } + + n := 0 + for *(*byte)(unsafe.Add(p, n)) != 0 { + n++ + } + + return string(unsafe.Slice((*byte)(p), n)) +} + +// goBytes copies n bytes of C memory starting at p into a Go slice. +func goBytes(p unsafe.Pointer, n int) []byte { + if p == nil || n <= 0 { + return []byte{} + } + + out := make([]byte, n) + copy(out, unsafe.Slice((*byte)(p), n)) + + return out +} + +// cstr returns a pointer to a NUL-terminated copy of s, for the C string +// arguments that may also be passed as NULL (a nil *byte). +func cstr(s string) *byte { + b := make([]byte, len(s)+1) + copy(b, s) + + return &b[0] +} diff --git a/internal/native/interaction_given.go b/internal/native/interaction_given.go index e9d9980cc..5400de199 100644 --- a/internal/native/interaction_given.go +++ b/internal/native/interaction_given.go @@ -1,39 +1,14 @@ package native -/* -#include "pact.h" -*/ -import "C" - -// interactionGiven wraps pactffi_given so that it is only referenced from a -// single CGo compilation unit. Go 1.24+ performs cross-file consistency checks -// for CGo symbols, and having the same C function (especially one returning -// bool) referenced from multiple files can trigger "inconsistent definitions" -// errors. By centralising the call here, mock_server.go and message_server.go -// can both invoke this Go-level wrapper without directly referencing the C -// symbol. -func interactionGiven(handle C.InteractionHandle, state string) { - cState := C.CString(state) - defer free(cState) - - C.pactffi_given(handle, cState) +// interactionGiven adds a provider state to the interaction. +func interactionGiven(handle uint32, state string) { + pactffi_given(handle, state) } -// interactionGivenWithParams wraps pactffi_given_with_param for the same -// reason as interactionGiven above. It handles the full params map in one call -// so that the state C string is allocated only once, matching the performance -// of the original inline implementation. -func interactionGivenWithParams(handle C.InteractionHandle, state string, params map[string]any) { - cState := C.CString(state) - defer free(cState) - +// interactionGivenWithParams adds a provider state to the interaction, +// once for each of its parameters. +func interactionGivenWithParams(handle uint32, state string, params map[string]any) { for k, v := range params { - cKey := C.CString(k) - cValue := C.CString(stringFromInterface(v)) - - C.pactffi_given_with_param(handle, cState, cKey, cValue) - - free(cValue) - free(cKey) + pactffi_given_with_param(handle, state, k, stringFromInterface(v)) } } diff --git a/internal/native/lib.go b/internal/native/lib.go index 68971ca1f..5eefff98c 100644 --- a/internal/native/lib.go +++ b/internal/native/lib.go @@ -1,3 +1,5 @@ +//go:build cgo && !pact_purego && !pact_goffi + // Package native contains the c bindings into the Pact Reference types. package native diff --git a/internal/native/message_server.go b/internal/native/message_server.go index 07268cb3a..9e5910578 100644 --- a/internal/native/message_server.go +++ b/internal/native/message_server.go @@ -1,10 +1,5 @@ package native -/* -#include "pact.h" -*/ -import "C" - import ( "encoding/json" "errors" @@ -15,7 +10,7 @@ import ( // MessagePact is a Go representation of the message-based PactHandle struct. type MessagePact struct { - handle C.PactHandle + handle uint16 } type messageType int @@ -30,7 +25,7 @@ const ( // Message is a single message interaction on a MessageServer, either // asynchronous (one body) or synchronous (a request/response pair). type Message struct { - handle C.InteractionHandle + handle uint32 messageType messageType pact *MessagePact index int @@ -46,26 +41,14 @@ type MessageServer struct { // NewMessageServer creates a new message-based Pact for a given // consumer/provider. func NewMessageServer(consumer string, provider string) *MessageServer { - cConsumer := C.CString(consumer) - cProvider := C.CString(provider) - defer free(cConsumer) - defer free(cProvider) - - return &MessageServer{messagePact: &MessagePact{handle: C.pactffi_new_message_pact(cConsumer, cProvider)}} + return &MessageServer{messagePact: &MessagePact{handle: pactffi_new_message_pact(consumer, provider)}} } // WithMetadata sets additional metadata on the Pact file, grouped under // namespace. Common uses are to add client library details such as the // name and version. func (m *MessageServer) WithMetadata(namespace, k, v string) *MessageServer { - cNamespace := C.CString(namespace) - defer free(cNamespace) - cName := C.CString(k) - defer free(cName) - cValue := C.CString(v) - defer free(cValue) - - C.pactffi_with_message_pact_metadata(m.messagePact.handle, cNamespace, cName, cValue) + pactffi_with_message_pact_metadata(m.messagePact.handle, namespace, k, v) return m } @@ -80,11 +63,8 @@ func (m *MessageServer) NewMessage() *Message { // NewSyncMessageInteraction initialises a new synchronous message interaction for the current contract. func (m *MessageServer) NewSyncMessageInteraction(description string) *Message { - cDescription := C.CString(description) - defer free(cDescription) - i := &Message{ - handle: C.pactffi_new_sync_message_interaction(m.messagePact.handle, cDescription), + handle: pactffi_new_sync_message_interaction(m.messagePact.handle, description), messageType: MESSAGE_TYPE_SYNC, pact: m.messagePact, index: len(m.messages), @@ -97,11 +77,8 @@ func (m *MessageServer) NewSyncMessageInteraction(description string) *Message { // NewAsyncMessageInteraction initialises a new asynchronous message interaction for the current contract. func (m *MessageServer) NewAsyncMessageInteraction(description string) *Message { - cDescription := C.CString(description) - defer free(cDescription) - i := &Message{ - handle: C.pactffi_new_message_interaction(m.messagePact.handle, cDescription), + handle: pactffi_new_message_interaction(m.messagePact.handle, description), messageType: MESSAGE_TYPE_ASYNC, pact: m.messagePact, index: len(m.messages), @@ -115,7 +92,7 @@ func (m *MessageServer) NewAsyncMessageInteraction(description string) *Message // WithSpecificationVersion sets the Pact specification version this // message pact is written and verified against. func (m *MessageServer) WithSpecificationVersion(version specificationVersion) { - C.pactffi_with_specification(m.messagePact.handle, C.int(version)) + pactffi_with_specification(m.messagePact.handle, int32(version)) } // Given adds a provider state that must hold for this message. @@ -139,10 +116,7 @@ func (m *Message) GivenWithParameter(state string, params map[string]any) *Messa // ExpectsToReceive sets the description of this message interaction. func (m *Message) ExpectsToReceive(description string) *Message { - cDescription := C.CString(description) - defer free(cDescription) - - C.pactffi_message_expects_to_receive(m.handle, cDescription) + pactffi_message_expects_to_receive(m.handle, description) return m } @@ -151,18 +125,12 @@ func (m *Message) ExpectsToReceive(description string) *Message { // message's contents. func (m *Message) WithMetadata(valueOrMatcher map[string]string) *Message { for k, v := range valueOrMatcher { - cName := C.CString(k) - // TODO: check if matching rules allowed here // value := stringFromInterface(v) // fmt.Printf("withheaders, sending: %+v \n\n", value) // cValue := C.CString(value) - cValue := C.CString(v) - - C.pactffi_message_with_metadata(m.handle, cName, cValue) - free(cValue) - free(cName) + pactffi_message_with_metadata(m.handle, k, v) } return m @@ -172,13 +140,7 @@ func (m *Message) WithMetadata(valueOrMatcher map[string]string) *Message { // request half of this synchronous message. func (m *Message) WithRequestMetadata(valueOrMatcher map[string]string) *Message { for k, v := range valueOrMatcher { - cName := C.CString(k) - cValue := C.CString(v) - - C.pactffi_with_metadata(m.handle, cName, cValue, 0) - - free(cValue) - free(cName) + pactffi_with_metadata(m.handle, k, v, 0) } return m @@ -188,13 +150,7 @@ func (m *Message) WithRequestMetadata(valueOrMatcher map[string]string) *Message // response half of this synchronous message. func (m *Message) WithResponseMetadata(valueOrMatcher map[string]string) *Message { for k, v := range valueOrMatcher { - cName := C.CString(k) - cValue := C.CString(v) - - C.pactffi_with_metadata(m.handle, cName, cValue, 1) - - free(cValue) - free(cName) + pactffi_with_metadata(m.handle, k, v, 1) } return m @@ -203,13 +159,10 @@ func (m *Message) WithResponseMetadata(valueOrMatcher map[string]string) *Messag // WithRequestBinaryContents sets the request contents of this message to // body, with an application/octet-stream content type. func (m *Message) WithRequestBinaryContents(body []byte) *Message { - cHeader := C.CString("application/octet-stream") - defer free(cHeader) - // TODO: handle response - res := C.pactffi_with_binary_file(m.handle, C.int(INTERACTION_PART_REQUEST), cHeader, (*C.uchar)(unsafe.Pointer(&body[0])), CUlong(len(body))) + res := pactffi_with_binary_file(m.handle, int32(INTERACTION_PART_REQUEST), "application/octet-stream", unsafe.Pointer(&body[0]), uintptr(len(body))) - log.Println("[DEBUG] WithRequestBinaryContents - pactffi_with_binary_file returned", bool(res)) + log.Println("[DEBUG] WithRequestBinaryContents - pactffi_with_binary_file returned", res) return m } @@ -217,11 +170,8 @@ func (m *Message) WithRequestBinaryContents(body []byte) *Message { // WithRequestBinaryContentType sets the request contents of this message // to body, with the given content type. func (m *Message) WithRequestBinaryContentType(contentType string, body []byte) *Message { - cHeader := C.CString(contentType) - defer free(cHeader) - // TODO: handle response - res := C.pactffi_with_binary_file(m.handle, C.int(INTERACTION_PART_REQUEST), cHeader, (*C.uchar)(unsafe.Pointer(&body[0])), CUlong(len(body))) + res := pactffi_with_binary_file(m.handle, int32(INTERACTION_PART_REQUEST), contentType, unsafe.Pointer(&body[0]), uintptr(len(body))) log.Println("[DEBUG] WithRequestBinaryContents - pactffi_with_binary_file returned", res) @@ -242,11 +192,8 @@ func (m *Message) WithRequestJSONContents(body any) *Message { // synchronous message to body, with an application/octet-stream content // type. func (m *Message) WithResponseBinaryContents(body []byte) *Message { - cHeader := C.CString("application/octet-stream") - defer free(cHeader) - // TODO: handle response - C.pactffi_with_binary_file(m.handle, C.int(INTERACTION_PART_RESPONSE), cHeader, (*C.uchar)(unsafe.Pointer(&body[0])), CUlong(len(body))) + pactffi_with_binary_file(m.handle, int32(INTERACTION_PART_RESPONSE), "application/octet-stream", unsafe.Pointer(&body[0]), uintptr(len(body))) return m } @@ -265,14 +212,8 @@ func (m *Message) WithResponseJSONContents(body any) *Message { // body with the given content type. Note that string values here must be // NUL terminated. func (m *Message) WithContents(part interactionPart, contentType string, body []byte) *Message { - cHeader := C.CString(contentType) - defer free(cHeader) - - cBody := C.CString(string(body)) - defer free(cBody) - - res := C.pactffi_with_body(m.handle, C.int(part), cHeader, cBody) - log.Println("[DEBUG] response from pactffi_interaction_contents", bool(res)) + res := pactffi_with_body(m.handle, int32(part), contentType, string(body)) + log.Println("[DEBUG] response from pactffi_interaction_contents", res) return m } @@ -283,12 +224,7 @@ func (m *Message) WithContents(part interactionPart, contentType string, body [] // messages on this pact can use plugin-provided matchers and content // types (e.g. protobuf, gRPC). func (m *MessageServer) UsingPlugin(pluginName string, pluginVersion string) error { - cPluginName := C.CString(pluginName) - defer free(cPluginName) - cPluginVersion := C.CString(pluginVersion) - defer free(cPluginVersion) - - r := C.pactffi_using_plugin(m.messagePact.handle, cPluginName, cPluginVersion) + r := pactffi_using_plugin(m.messagePact.handle, pluginName, pluginVersion) // 1 - A general panic was caught. // 2 - Failed to load the plugin. @@ -314,12 +250,7 @@ func (m *MessageServer) UsingPlugin(pluginName string, pluginVersion string) err // this message from a plugin-provided contentType (e.g. a protobuf // message type), delegating the encoding to the loaded plugin. func (m *Message) WithPluginInteractionContents(part interactionPart, contentType string, contents string) error { - cContentType := C.CString(contentType) - defer free(cContentType) - cContents := C.CString(contents) - defer free(cContents) - - r := C.pactffi_interaction_contents(m.handle, C.int(part), cContentType, cContents) + r := pactffi_interaction_contents(m.handle, int32(part), contentType, contents) // 1 - A general panic was caught. // 2 - The mock server has already been started. @@ -371,28 +302,27 @@ func (m *Message) GetMessageResponseContents() ([][]byte, error) { if m.messageType == MESSAGE_TYPE_ASYNC { return nil, errors.New("invalid request: asynchronous messages do not have response") } - iter := C.pactffi_pact_handle_get_sync_message_iter(m.pact.handle) + iter := pactffi_pact_handle_get_sync_message_iter(m.pact.handle) if iter == nil { return nil, errors.New("unable to get a message iterator") } - defer C.pactffi_pact_sync_message_iter_delete(iter) + defer pactffi_pact_sync_message_iter_delete(iter) for i := range len(m.server.messages) { - message := C.pactffi_pact_sync_message_iter_next(iter) + message := pactffi_pact_sync_message_iter_next(iter) if message == nil { return nil, errors.New("retrieved a null message pointer") } // Get Response body - contentsLen := C.pactffi_sync_message_get_response_contents_length(message, C.size_t(i)) + contentsLen := pactffi_sync_message_get_response_contents_length(message, uintptr(i)) if contentsLen != 0 { - data := C.pactffi_sync_message_get_response_contents_bin(message, C.size_t(i)) + data := pactffi_sync_message_get_response_contents_bin(message, uintptr(i)) if data == nil { return nil, errors.New("retrieved an empty pointer to the message contents") } - ptr := unsafe.Pointer(data) - bytes := C.GoBytes(ptr, C.int(contentsLen)) + bytes := goBytes(data, int(contentsLen)) responses[i] = bytes } } @@ -408,17 +338,10 @@ func (m *MessageServer) StartTransport(transport string, address string, port in } log.Println("[DEBUG] mock server starting on address:", address, port) - cAddress := C.CString(address) - defer free(cAddress) - - cTransport := C.CString(transport) - defer free(cTransport) configJSON := stringFromInterface(config) - cConfig := C.CString(configJSON) - defer free(cConfig) - p := C.pactffi_create_mock_server_for_transport(m.messagePact.handle, cAddress, C.ushort(port), cTransport, cConfig) + p := pactffi_create_mock_server_for_transport(m.messagePact.handle, address, uint16(port), transport, cstr(configJSON)) // | Error | Description // |-------|------------- @@ -451,7 +374,7 @@ func (m *MessageServer) StartTransport(transport string, address string, port in // CleanupPlugins releases the plugins loaded on this pact via UsingPlugin. func (m *MessageServer) CleanupPlugins() { - C.pactffi_cleanup_plugins(m.messagePact.handle) + pactffi_cleanup_plugins(m.messagePact.handle) } // CleanupMockServer frees the memory from the previous mock server. @@ -460,9 +383,9 @@ func (m *MessageServer) CleanupMockServer(port int) bool { return true } log.Println("[DEBUG] mock server cleaning up port:", port) - res := C.pactffi_cleanup_mock_server(C.int(port)) + res := pactffi_cleanup_mock_server(int32(port)) - return bool(res) + return res } // MockServerMismatchedRequests returns a JSON object containing any mismatches from @@ -471,7 +394,7 @@ func (m *MessageServer) MockServerMismatchedRequests(port int) []MismatchedReque log.Println("[DEBUG] mock server determining mismatches:", port) var res []MismatchedRequest - mismatches := C.pactffi_mock_server_mismatches(C.int(port)) + mismatches := pactffi_mock_server_mismatches(int32(port)) // This method can return a nil pointer, in which case, it // should be considered a failure (or at least, an issue) // converting it to a string might also do nasty things here! @@ -480,7 +403,7 @@ func (m *MessageServer) MockServerMismatchedRequests(port int) []MismatchedReque return []MismatchedRequest{} } - err := json.Unmarshal([]byte(C.GoString(mismatches)), &res) + err := json.Unmarshal([]byte(goString(mismatches)), &res) if err != nil { log.Println("[ERROR] failed to unmarshal mismatches response, returning empty list of mismatches") return []MismatchedRequest{} @@ -494,24 +417,22 @@ func (m *MessageServer) MockServerMismatchedRequests(port int) []MismatchedReque func (m *MessageServer) MockServerMatched(port int) bool { log.Println("[DEBUG] mock server determining mismatches:", port) - res := C.pactffi_mock_server_matched(C.int(port)) + res := pactffi_mock_server_matched(int32(port)) // TODO: why this number is so big and not a bool? Type def wrong? Port value wrong? // log.Println("MATCHED RES?") // log.Println(int(res)) - return bool(res) + return res } // WritePactFile writes the Pact to file. func (m *MessageServer) WritePactFile(dir string, overwrite bool) error { log.Println("[DEBUG] writing pact file for message pact at dir:", dir) - cDir := C.CString(dir) - defer free(cDir) overwritePact := overwrite - res := int(C.pactffi_write_message_pact_file(m.messagePact.handle, cDir, C.bool(overwritePact))) + res := int(pactffi_write_message_pact_file(m.messagePact.handle, dir, overwritePact)) /// | Error | Description | /// |-------|-------------| @@ -533,12 +454,10 @@ func (m *MessageServer) WritePactFile(dir string, overwrite bool) error { // port to dir, optionally overwriting an existing file. func (m *MessageServer) WritePactFileForServer(port int, dir string, overwrite bool) error { log.Println("[DEBUG] writing pact file for message pact at dir:", dir) - cDir := C.CString(dir) - defer free(cDir) overwritePact := overwrite - res := int(C.pactffi_write_pact_file(C.int(port), cDir, C.bool(overwritePact))) + res := int(pactffi_write_pact_file(int32(port), dir, overwritePact)) /// | Error | Description | /// |-------|-------------| @@ -562,14 +481,7 @@ func (m *MessageServer) WritePactFileForServer(port int, dir string, overwrite b // against the interaction. References are stored under comments.references[group][name] // in the Pact file. This is a V4-only feature. func (m *Message) WithReference(group, name, value string) *Message { - cGroup := C.CString(group) - defer free(cGroup) - cName := C.CString(name) - defer free(cName) - cValue := C.CString(value) - defer free(cValue) - - C.pactffi_add_interaction_reference(m.handle, cGroup, cName, cValue) + pactffi_add_interaction_reference(m.handle, group, name, value) return m } @@ -577,12 +489,12 @@ func (m *Message) WithReference(group, name, value string) *Message { // getAsyncMessageRequestContents is the MESSAGE_TYPE_ASYNC branch of // GetMessageRequestContents, split out to keep both branches readable. func (m *Message) getAsyncMessageRequestContents() ([]byte, error) { - iter := C.pactffi_pact_handle_get_message_iter(m.pact.handle) + iter := pactffi_pact_handle_get_message_iter(m.pact.handle) log.Println("[DEBUG] pactffi_pact_handle_get_message_iter") if iter == nil { return nil, errors.New("unable to get a message iterator") } - defer C.pactffi_pact_message_iter_delete(iter) + defer pactffi_pact_message_iter_delete(iter) log.Println("[DEBUG] pactffi_pact_handle_get_message_iter - OK") /////// @@ -593,7 +505,7 @@ func (m *Message) getAsyncMessageRequestContents() ([]byte, error) { for i := range len(m.server.messages) { log.Println("[DEBUG] pactffi_pact_handle_get_message_iter - index", i) - message := C.pactffi_pact_message_iter_next(iter) + message := pactffi_pact_message_iter_next(iter) log.Println("[DEBUG] pactffi_pact_message_iter_next - message", message) if i != m.index { @@ -605,22 +517,21 @@ func (m *Message) getAsyncMessageRequestContents() ([]byte, error) { return nil, errors.New("retrieved a null message pointer") } - contentsLen := C.pactffi_message_get_contents_length(message) + contentsLen := pactffi_message_get_contents_length(message) log.Println("[DEBUG] pactffi_message_get_contents_length - len", contentsLen) if contentsLen == 0 { // You can have empty bodies log.Println("[DEBUG] message body is empty") return nil, nil } - data := C.pactffi_message_get_contents_bin(message) + data := pactffi_message_get_contents_bin(message) log.Println("[DEBUG] pactffi_message_get_contents_bin - data", data) if data == nil { // You can have empty bodies log.Println("[DEBUG] message binary contents are empty") return nil, nil } - ptr := unsafe.Pointer(data) - bytes := C.GoBytes(ptr, C.int(contentsLen)) + bytes := goBytes(data, int(contentsLen)) return bytes, nil } @@ -631,14 +542,14 @@ func (m *Message) getAsyncMessageRequestContents() ([]byte, error) { // getSyncMessageRequestContents is the synchronous-message branch of // GetMessageRequestContents, split out to keep both branches readable. func (m *Message) getSyncMessageRequestContents() ([]byte, error) { - iter := C.pactffi_pact_handle_get_sync_message_iter(m.pact.handle) + iter := pactffi_pact_handle_get_sync_message_iter(m.pact.handle) if iter == nil { return nil, errors.New("unable to get a message iterator") } - defer C.pactffi_pact_sync_message_iter_delete(iter) + defer pactffi_pact_sync_message_iter_delete(iter) for i := range len(m.server.messages) { - message := C.pactffi_pact_sync_message_iter_next(iter) + message := pactffi_pact_sync_message_iter_next(iter) if i != m.index { continue @@ -648,18 +559,17 @@ func (m *Message) getSyncMessageRequestContents() ([]byte, error) { return nil, errors.New("retrieved a null message pointer") } - contentsLen := C.pactffi_sync_message_get_request_contents_length(message) + contentsLen := pactffi_sync_message_get_request_contents_length(message) if contentsLen == 0 { log.Println("[DEBUG] message body is empty") return nil, nil } - data := C.pactffi_sync_message_get_request_contents_bin(message) + data := pactffi_sync_message_get_request_contents_bin(message) if data == nil { log.Println("[DEBUG] message binary contents are empty") return nil, nil } - ptr := unsafe.Pointer(data) - bytes := C.GoBytes(ptr, C.int(contentsLen)) + bytes := goBytes(data, int(contentsLen)) return bytes, nil } diff --git a/internal/native/mock_server.go b/internal/native/mock_server.go index ab59b4e5a..add490d92 100644 --- a/internal/native/mock_server.go +++ b/internal/native/mock_server.go @@ -1,10 +1,5 @@ package native -/* -#include "pact.h" -*/ -import "C" - import ( "crypto/tls" "crypto/x509" @@ -22,7 +17,7 @@ import ( type interactionPart int // Which half of an interaction pactffi_interaction_contents (and the -// C.int(part) calls throughout this file) applies to. +// int32(part) calls throughout this file) applies to. const ( INTERACTION_PART_REQUEST interactionPart = iota INTERACTION_PART_RESPONSE @@ -70,19 +65,19 @@ var logLevelStringToInt = map[string]logLevel{ // Pact is a Go representation of the PactHandle struct. type Pact struct { - handle C.PactHandle + handle uint16 } // Interaction is a Go representation of the InteractionHandle struct. type Interaction struct { - handle C.InteractionHandle + handle uint32 } // Version returns the current semver FFI interface version. func Version() string { - v := C.pactffi_version() + v := pactffi_version() - return C.GoString(v) + return goString(v) } var loggingInitialised string @@ -128,12 +123,7 @@ type MockServer struct { // NewHTTPPact creates a new HTTP mock server for a given consumer/provider. func NewHTTPPact(consumer string, provider string) *MockServer { - cConsumer := C.CString(consumer) - cProvider := C.CString(provider) - defer free(cConsumer) - defer free(cProvider) - - return &MockServer{pact: &Pact{handle: C.pactffi_new_pact(cConsumer, cProvider)}} + return &MockServer{pact: &Pact{handle: pactffi_new_pact(consumer, provider)}} } // Version returns the current semver FFI interface version. @@ -144,7 +134,7 @@ func (m *MockServer) Version() string { // WithSpecificationVersion sets the Pact specification version the mock // server writes and verifies interactions against. func (m *MockServer) WithSpecificationVersion(version specificationVersion) { - C.pactffi_with_specification(m.pact.handle, C.int(version)) + pactffi_with_specification(m.pact.handle, int32(version)) } // Verify verifies that all interactions were successful. If not, returns a slice @@ -162,7 +152,7 @@ func (m *MockServer) MockServerMismatchedRequests(port int) []MismatchedRequest log.Println("[DEBUG] mock server determining mismatches:", port) var res []MismatchedRequest - mismatches := C.pactffi_mock_server_mismatches(C.int(port)) + mismatches := pactffi_mock_server_mismatches(int32(port)) // This method can return a nil pointer, in which case, it // should be considered a failure (or at least, an issue) // converting it to a string might also do nasty things here! @@ -171,7 +161,7 @@ func (m *MockServer) MockServerMismatchedRequests(port int) []MismatchedRequest return []MismatchedRequest{} } - err := json.Unmarshal([]byte(C.GoString(mismatches)), &res) + err := json.Unmarshal([]byte(goString(mismatches)), &res) if err != nil { log.Println("[ERROR] failed to unmarshal mismatches response, returning empty list of mismatches") return []MismatchedRequest{} @@ -185,25 +175,23 @@ func (m *MockServer) CleanupMockServer(port int) bool { return true } log.Println("[DEBUG] mock server cleaning up port:", port) - res := C.pactffi_cleanup_mock_server(C.int(port)) + res := pactffi_cleanup_mock_server(int32(port)) - return bool(res) + return res } // WritePactFile writes the Pact to file. // TODO: expose overwrite. func (m *MockServer) WritePactFile(port int, dir string) error { log.Println("[DEBUG] writing pact file for mock server on port:", port, ", dir:", dir) - cDir := C.CString(dir) - defer free(cDir) // overwritePact := 0 // if overwrite { // overwritePact = 1 // } - // res := int(C.pactffi_write_pact_file(C.int(port), cDir, C.int(overwritePact))) - res := int(C.pactffi_write_pact_file(C.int(port), cDir, C.bool(false))) + // res := int(pactffi_write_pact_file(int32(port), dir, int32(overwritePact))) + res := int(pactffi_write_pact_file(int32(port), dir, false)) // | Error | Description | // |-------|-------------| @@ -227,10 +215,10 @@ func (m *MockServer) WritePactFile(port int, dir string) error { // GetTLSConfig returns a tls.Config compatible with the TLS // mock server. func GetTLSConfig() *tls.Config { - cert := C.pactffi_get_tls_ca_certificate() + cert := pactffi_get_tls_ca_certificate() defer libRustFree(cert) - goCert := C.GoString(cert) + goCert := goString(cert) certPool := x509.NewCertPool() certPool.AppendCertsFromPEM([]byte(goCert)) @@ -239,12 +227,8 @@ func GetTLSConfig() *tls.Config { } } -func free(str *C.char) { - C.free(unsafe.Pointer(str)) -} - -func libRustFree(str *C.char) { - C.pactffi_free_string(str) +func libRustFree(str unsafe.Pointer) { + pactffi_free_string(str) } // Start starts up the mock HTTP server on the given address:port and TLS config @@ -264,20 +248,14 @@ func (m *MockServer) Start(address string, tls bool) (int, error) { if err != nil { return 0, ErrInvalidAddress } - cHost := C.CString(host) - defer free(cHost) var transport string if tls { transport = "https" } else { transport = "http" } - cTransport := C.CString(transport) - defer free(cTransport) - - cConfig := (*C.char)(nil) - msPort := int(C.pactffi_create_mock_server_for_transport(m.pact.handle, cHost, C.ushort(requestedPort), cTransport, cConfig)) + msPort := int(pactffi_create_mock_server_for_transport(m.pact.handle, host, uint16(requestedPort), transport, nil)) // | Error | Description | // |-------|-------------| @@ -315,17 +293,10 @@ func (m *MockServer) StartTransport(transport string, address string, port int, } log.Println("[DEBUG] mock server starting on address:", address, port) - cAddress := C.CString(address) - defer free(cAddress) - - cTransport := C.CString(transport) - defer free(cTransport) configJSON := stringFromInterface(config) - cConfig := C.CString(configJSON) - defer free(cConfig) - p := C.pactffi_create_mock_server_for_transport(m.pact.handle, cAddress, C.ushort(port), cTransport, cConfig) + p := pactffi_create_mock_server_for_transport(m.pact.handle, address, uint16(port), transport, cstr(configJSON)) // | Error | Description // |-------|------------- @@ -360,14 +331,7 @@ func (m *MockServer) StartTransport(transport string, address string, port int, // namespace. Common uses are to add client library details such as the // name and version. func (m *MockServer) WithMetadata(namespace, k, v string) *MockServer { - cNamespace := C.CString(namespace) - defer free(cNamespace) - cName := C.CString(k) - defer free(cName) - cValue := C.CString(v) - defer free(cValue) - - C.pactffi_with_pact_metadata(m.pact.handle, cNamespace, cName, cValue) + pactffi_with_pact_metadata(m.pact.handle, namespace, k, v) return m } @@ -376,12 +340,7 @@ func (m *MockServer) WithMetadata(namespace, k, v string) *MockServer { // interactions on this pact can use plugin-provided matchers and content // types (e.g. protobuf, gRPC). func (m *MockServer) UsingPlugin(pluginName string, pluginVersion string) error { - cPluginName := C.CString(pluginName) - defer free(cPluginName) - cPluginVersion := C.CString(pluginVersion) - defer free(cPluginVersion) - - r := C.pactffi_using_plugin(m.pact.handle, cPluginName, cPluginVersion) + r := pactffi_using_plugin(m.pact.handle, pluginName, pluginVersion) // 1 - A general panic was caught. // 2 - Failed to load the plugin. @@ -405,16 +364,13 @@ func (m *MockServer) UsingPlugin(pluginName string, pluginVersion string) error // CleanupPlugins releases the plugins loaded on this pact via UsingPlugin. func (m *MockServer) CleanupPlugins() { - C.pactffi_cleanup_plugins(m.pact.handle) + pactffi_cleanup_plugins(m.pact.handle) } // NewInteraction initialises a new interaction for the current contract. func (m *MockServer) NewInteraction(description string) *Interaction { - cDescription := C.CString(description) - defer free(cDescription) - i := &Interaction{ - handle: C.pactffi_new_interaction(m.pact.handle, cDescription), + handle: pactffi_new_interaction(m.pact.handle, description), } m.interactions = append(m.interactions, i) @@ -425,12 +381,7 @@ func (m *MockServer) NewInteraction(description string) *Interaction { // this interaction from a plugin-provided contentType (e.g. a protobuf // message type), delegating the encoding to the loaded plugin. func (i *Interaction) WithPluginInteractionContents(part interactionPart, contentType string, contents string) error { - cContentType := C.CString(contentType) - defer free(cContentType) - cContents := C.CString(contents) - defer free(cContents) - - r := C.pactffi_interaction_contents(i.handle, C.int(part), cContentType, cContents) + r := pactffi_interaction_contents(i.handle, int32(part), contentType, contents) // 1 - A general panic was caught. // 2 - The mock server has already been started. @@ -464,10 +415,7 @@ func (i *Interaction) WithPluginInteractionContents(part interactionPart, conten // UponReceiving sets the description of the request that triggers this // interaction. func (i *Interaction) UponReceiving(description string) *Interaction { - cDescription := C.CString(description) - defer free(cDescription) - - C.pactffi_upon_receiving(i.handle, cDescription) + pactffi_upon_receiving(i.handle, description) return i } @@ -490,14 +438,9 @@ func (i *Interaction) GivenWithParameter(state string, params map[string]any) *I // WithRequest sets the request method and path (or path matcher) that // this interaction expects. func (i *Interaction) WithRequest(method string, pathOrMatcher any) *Interaction { - cMethod := C.CString(method) - defer free(cMethod) - path := stringFromInterface(pathOrMatcher) - cPath := C.CString(path) - defer free(cPath) - C.pactffi_with_request(i.handle, cMethod, cPath) + pactffi_with_request(i.handle, method, path) return i } @@ -518,18 +461,11 @@ func (i *Interaction) WithResponseHeaders(valueOrMatcher map[string][]any) *Inte // keyed by parameter name, with each value optionally a matcher. func (i *Interaction) WithQuery(valueOrMatcher map[string][]any) *Interaction { for k, values := range valueOrMatcher { - cName := C.CString(k) - for idx, v := range values { value := stringFromInterface(v) - cValue := C.CString(value) - C.pactffi_with_query_parameter_v2(i.handle, cName, CUlong(idx), cValue) - - free(cValue) + pactffi_with_query_parameter_v2(i.handle, k, uintptr(idx), value) } - - free(cName) } return i @@ -583,7 +519,7 @@ func (i *Interaction) WithResponseMultipartFile(contentType string, filename str // WithStatus sets the expected HTTP response status. func (i *Interaction) WithStatus(status int) *Interaction { - C.pactffi_response_status(i.handle, C.ushort(status)) + pactffi_response_status(i.handle, uint16(status)) return i } @@ -592,82 +528,45 @@ func (i *Interaction) WithStatus(status int) *Interaction { // against the interaction. References are stored under comments.references[group][name] // in the Pact file. This is a V4-only feature. func (i *Interaction) WithReference(group, name, value string) *Interaction { - cGroup := C.CString(group) - defer free(cGroup) - cName := C.CString(name) - defer free(cName) - cValue := C.CString(value) - defer free(cValue) - - C.pactffi_add_interaction_reference(i.handle, cGroup, cName, cValue) + pactffi_add_interaction_reference(i.handle, group, name, value) return i } func (i *Interaction) withHeaders(part interactionPart, valueOrMatcher map[string][]any) *Interaction { for k, v := range valueOrMatcher { - cName := C.CString(k) - for idx, header := range v { value := stringFromInterface(header) - cValue := C.CString(value) - C.pactffi_with_header_v2(i.handle, C.int(part), cName, CUlong(idx), cValue) - - free(cValue) + pactffi_with_header_v2(i.handle, int32(part), k, uintptr(idx), value) } - - free(cName) } return i } func (i *Interaction) withJSONBody(body any, part interactionPart) *Interaction { - cHeader := C.CString("application/json") - defer free(cHeader) - jsonBody := stringFromInterface(body) - cBody := C.CString(jsonBody) - defer free(cBody) - C.pactffi_with_body(i.handle, C.int(part), cHeader, cBody) + pactffi_with_body(i.handle, int32(part), "application/json", jsonBody) return i } func (i *Interaction) withBody(contentType string, body []byte, part interactionPart) *Interaction { - cHeader := C.CString(contentType) - defer free(cHeader) - - cBody := C.CString(string(body)) - defer free(cBody) - - C.pactffi_with_body(i.handle, C.int(part), cHeader, cBody) + pactffi_with_body(i.handle, int32(part), contentType, string(body)) return i } func (i *Interaction) withBinaryBody(contentType string, body []byte, part interactionPart) *Interaction { - cHeader := C.CString(contentType) - defer free(cHeader) - - C.pactffi_with_binary_file(i.handle, C.int(part), cHeader, (*C.uchar)(unsafe.Pointer(&body[0])), CUlong(len(body))) + pactffi_with_binary_file(i.handle, int32(part), contentType, unsafe.Pointer(&body[0]), uintptr(len(body))) return i } func (i *Interaction) withMultipartFile(contentType string, filename string, mimePartName string, part interactionPart) *Interaction { - cHeader := C.CString(contentType) - defer free(cHeader) - - cPartName := C.CString(mimePartName) - defer free(cPartName) - - cFilename := C.CString(filename) - defer free(cFilename) - - C.pactffi_with_multipart_file(i.handle, C.int(part), cHeader, cFilename, cPartName) + pactffi_with_multipart_file(i.handle, int32(part), contentType, filename, mimePartName) return i } @@ -710,39 +609,36 @@ func quotedString(s string) string { // cMessage := C.CString(message) // defer free(cMessage) -// res := C.pactffi_log_message(cPkg, cLevel, cMessage) +// res := pactffi_log_message(cPkg, cLevel, cMessage) // log.Println("[DEBUG] log_to_buffer res", res) // } // func logToBuffer(level logLevel) error { -// res := C.pactffi_log_to_buffer(C.int(level)) +// res := pactffi_log_to_buffer(int32(level)) // log.Println("[DEBUG] log_to_buffer res", res) // return logResultToError(int(res)) // } func logToStdout(level logLevel) error { - res := C.pactffi_log_to_stdout(C.int(level)) + res := pactffi_log_to_stdout(int32(level)) log.Println("[DEBUG] log_to_stdout res", res) return logResultToError(int(res)) } func logToFile(file string, level logLevel) error { - cFile := C.CString(file) - defer free(cFile) - - res := C.pactffi_log_to_file(cFile, C.int(level)) + res := pactffi_log_to_file(file, int32(level)) log.Println("[DEBUG] log_to_file res", res) return logResultToError(int(res)) } // func getLogBuffer() string { -// buf := C.pactffi_fetch_log_buffer() +// buf := pactffi_fetch_log_buffer() // defer free(buf) -// return C.GoString(buf) +// return goString(buf) // } func logResultToError(res int) error { diff --git a/internal/native/verifier.go b/internal/native/verifier.go index 10fa642bb..1e01a7309 100644 --- a/internal/native/verifier.go +++ b/internal/native/verifier.go @@ -1,10 +1,5 @@ package native -/* -#include "pact.h" -*/ -import "C" - import ( "encoding/json" "errors" @@ -17,7 +12,7 @@ import ( // Verifier is a Go representation of the pact_ffi VerifierHandle, used to // verify a provider against one or more consumer pacts. type Verifier struct { - handle *C.VerifierHandle + handle unsafe.Pointer } // NewVerifier creates a new provider verifier, identifying the calling @@ -25,12 +20,7 @@ type Verifier struct { // and this module's own version). The caller is responsible for calling // Shutdown when done with it, to free the underlying resources. func NewVerifier(name string, version string) *Verifier { - cName := C.CString(name) - cVersion := C.CString(version) - defer free(cName) - defer free(cVersion) - - h := C.pactffi_verifier_new_for_application(cName, cVersion) + h := pactffi_verifier_new_for_application(name, version) return &Verifier{ handle: h, @@ -60,50 +50,27 @@ var ( // Shutdown releases the resources held by this verifier. func (v *Verifier) Shutdown() { - C.pactffi_verifier_shutdown(v.handle) + pactffi_verifier_shutdown(v.handle) } // SetProviderInfo sets the name and network location of the provider // under verification. func (v *Verifier) SetProviderInfo(name string, scheme string, host string, port uint16, path string) { - cName := C.CString(name) - defer free(cName) - cScheme := C.CString(scheme) - defer free(cScheme) - cHost := C.CString(host) - defer free(cHost) - cPort := C.ushort(port) - cPath := C.CString(path) - defer free(cPath) - - C.pactffi_verifier_set_provider_info(v.handle, cName, cScheme, cHost, cPort, cPath) + pactffi_verifier_set_provider_info(v.handle, name, scheme, host, port, path) } // AddTransport registers an additional transport (e.g. a message queue // alongside HTTP) that the provider exposes for verification. func (v *Verifier) AddTransport(protocol string, port uint16, path string, scheme string) { log.Println("[DEBUG] Adding transport with protocol:", protocol, "port:", port, "path:", path, "scheme:", scheme) - cProtocol := C.CString(protocol) - defer free(cProtocol) - cPort := C.ushort(port) - cPath := C.CString(path) - defer free(cPath) - cScheme := C.CString(scheme) - defer free(cScheme) - - C.pactffi_verifier_add_provider_transport(v.handle, cProtocol, cPort, cPath, cScheme) + pactffi_verifier_add_provider_transport(v.handle, protocol, port, path, scheme) } // SetFilterInfo restricts verification to interactions matching // description and/or state; noState additionally restricts to // interactions with no provider state. func (v *Verifier) SetFilterInfo(description string, state string, noState bool) { - cFilterDescription := C.CString(description) - defer free(cFilterDescription) - cFilterState := C.CString(state) - defer free(cFilterState) - - C.pactffi_verifier_set_filter_info(v.handle, cFilterDescription, cFilterState, boolToCUchar(noState)) + pactffi_verifier_set_filter_info(v.handle, description, state, boolToCUchar(noState)) } // SetProviderState sets the URL the verifier calls to set up (and, if @@ -111,17 +78,14 @@ func (v *Verifier) SetFilterInfo(description string, state string, noState bool) // If body is set, state parameters are sent as a JSON request body rather // than query parameters. func (v *Verifier) SetProviderState(url string, teardown bool, body bool) { - cURL := C.CString(url) - defer free(cURL) - - C.pactffi_verifier_set_provider_state(v.handle, cURL, boolToCUchar(teardown), boolToCUchar(body)) + pactffi_verifier_set_provider_state(v.handle, url, boolToCUchar(teardown), boolToCUchar(body)) } // SetVerificationOptions sets the options used by the verifier when // calling the provider. func (v *Verifier) SetVerificationOptions(disableSSLVerification bool, requestTimeout int64) { // TODO: this returns an int and therefore can error. We should have all of these functions return values?? - C.pactffi_verifier_set_verification_options(v.handle, boolToCUchar(disableSSLVerification), C.ulong(requestTimeout)) + pactffi_verifier_set_verification_options(v.handle, boolToCUchar(disableSSLVerification), uint64(requestTimeout)) } // SetConsumerFilters is intended to restrict verification to pacts from @@ -129,53 +93,33 @@ func (v *Verifier) SetVerificationOptions(disableSSLVerification bool, requestTi func (v *Verifier) SetConsumerFilters(consumers []string) { // TODO: check if this actually works! It is untested and its effect // on the underlying pact_ffi call has not been confirmed. - cConsumers, freeConsumers := stringArrayToCStringArray(consumers) + cConsumers, freeConsumers := cStringArray(consumers) defer freeConsumers() - C.pactffi_verifier_set_consumer_filters(v.handle, cConsumers, C.ushort(len(consumers))) + pactffi_verifier_set_consumer_filters(v.handle, cConsumers, uint16(len(consumers))) } // AddCustomHeader adds a header to be sent with every request made to the // provider during verification. func (v *Verifier) AddCustomHeader(name string, value string) { - cHeaderName := C.CString(name) - defer free(cHeaderName) - cHeaderValue := C.CString(value) - defer free(cHeaderValue) - - C.pactffi_verifier_add_custom_header(v.handle, cHeaderName, cHeaderValue) + pactffi_verifier_add_custom_header(v.handle, name, value) } // AddFileSource adds a single Pact file as a source to verify. func (v *Verifier) AddFileSource(file string) { - cFile := C.CString(file) - defer free(cFile) - - C.pactffi_verifier_add_file_source(v.handle, cFile) + pactffi_verifier_add_file_source(v.handle, file) } // AddDirectorySource adds a directory as a source to verify: every pact // file in it that matches the provider name is verified. func (v *Verifier) AddDirectorySource(directory string) { - cDirectory := C.CString(directory) - defer free(cDirectory) - - C.pactffi_verifier_add_directory_source(v.handle, cDirectory) + pactffi_verifier_add_directory_source(v.handle, directory) } // AddURLSource adds a URL as a source to verify: the pact file is fetched // from url, using basic auth if username and password are set, or bearer // token auth if token is set. func (v *Verifier) AddURLSource(url string, username string, password string, token string) { - cURL := C.CString(url) - defer free(cURL) - cUsername := C.CString(username) - defer free(cUsername) - cPassword := C.CString(password) - defer free(cPassword) - cToken := C.CString(token) - defer free(cToken) - - C.pactffi_verifier_url_source(v.handle, cURL, cUsername, cPassword, cToken) + pactffi_verifier_url_source(v.handle, url, username, password, token) } // BrokerSourceWithSelectors adds a Pact Broker as a source to verify, @@ -184,42 +128,24 @@ func (v *Verifier) AddURLSource(url string, username string, password string, to // https://docs.pact.io/pact_broker/advanced_topics/consumer_version_selectors/). // Authentication follows the same rules as AddURLSource. func (v *Verifier) BrokerSourceWithSelectors(url string, username string, password string, token string, enablePending bool, includeWipPactsSince string, providerTags []string, providerBranch string, selectors []string, consumerVersionTags []string) { - cURL := C.CString(url) - defer free(cURL) - cUsername := C.CString(username) - defer free(cUsername) - cPassword := C.CString(password) - defer free(cPassword) - cToken := C.CString(token) - defer free(cToken) - cIncludeWipPactsSince := C.CString(includeWipPactsSince) - defer free(cIncludeWipPactsSince) - cProviderBranch := C.CString(providerBranch) - defer free(cProviderBranch) - cProviderTags, freeProviderTags := stringArrayToCStringArray(providerTags) + cProviderTags, freeProviderTags := cStringArray(providerTags) defer freeProviderTags() - cSelectors, freeSelectors := stringArrayToCStringArray(selectors) + cSelectors, freeSelectors := cStringArray(selectors) defer freeSelectors() - cConsumerVersionTags, freeConsumerVersionTags := stringArrayToCStringArray(consumerVersionTags) + cConsumerVersionTags, freeConsumerVersionTags := cStringArray(consumerVersionTags) defer freeConsumerVersionTags() - C.pactffi_verifier_broker_source_with_selectors(v.handle, cURL, cUsername, cPassword, cToken, boolToCUchar(enablePending), cIncludeWipPactsSince, cProviderTags, C.ushort(len(providerTags)), cProviderBranch, cSelectors, C.ushort(len(selectors)), cConsumerVersionTags, C.ushort(len(consumerVersionTags))) + pactffi_verifier_broker_source_with_selectors(v.handle, url, username, password, token, boolToCUchar(enablePending), includeWipPactsSince, cProviderTags, uint16(len(providerTags)), providerBranch, cSelectors, uint16(len(selectors)), cConsumerVersionTags, uint16(len(consumerVersionTags))) } // SetPublishOptions sets the values needed to publish verification // results back to the Pact Broker: providerVersion is required, the rest // are optional and pass as "" or nil to omit. func (v *Verifier) SetPublishOptions(providerVersion string, buildURL string, providerTags []string, providerBranch string) { - cProviderVersion := C.CString(providerVersion) - defer free(cProviderVersion) - cBuildURL := C.CString(buildURL) - defer free(cBuildURL) - cProviderBranch := C.CString(providerBranch) - defer free(cProviderBranch) - cProviderTags, freeProviderTags := stringArrayToCStringArray(providerTags) + cProviderTags, freeProviderTags := cStringArray(providerTags) defer freeProviderTags() - C.pactffi_verifier_set_publish_options(v.handle, cProviderVersion, cBuildURL, cProviderTags, C.ushort(len(providerTags)), cProviderBranch) + pactffi_verifier_set_publish_options(v.handle, providerVersion, buildURL, cProviderTags, uint16(len(providerTags)), providerBranch) } // Execute runs the verification against every source and option @@ -227,7 +153,7 @@ func (v *Verifier) SetPublishOptions(providerVersion string, buildURL string, pr // not run. func (v *Verifier) Execute() error { // TODO: Validate - result := C.pactffi_verifier_execute(v.handle) + result := pactffi_verifier_execute(v.handle) /// | Error | Description | /// |-------|-------------| @@ -249,25 +175,25 @@ func (v *Verifier) Execute() error { // SetNoPactsIsError controls whether finding no pacts to verify is // treated as a verification error. func (v *Verifier) SetNoPactsIsError(isError bool) { - C.pactffi_verifier_set_no_pacts_is_error(v.handle, boolToCUchar(isError)) + pactffi_verifier_set_no_pacts_is_error(v.handle, boolToCUchar(isError)) } // SetColoredOutput enables or disables ANSI colour codes in the verifier // output; colour is enabled by default. func (v *Verifier) SetColoredOutput(isColoredOutput bool) { - C.pactffi_verifier_set_coloured_output(v.handle, boolToCUchar(isColoredOutput)) + pactffi_verifier_set_coloured_output(v.handle, boolToCUchar(isColoredOutput)) } // resultJSON returns the verification result of the last Execute as JSON, // or "" if the FFI could not produce it. func (v *Verifier) resultJSON() string { - cJSON := C.pactffi_verifier_json(v.handle) + cJSON := pactffi_verifier_json(v.handle) if cJSON == nil { return "" } defer libRustFree(cJSON) - return C.GoString(cJSON) + return goString(cJSON) } // verificationResult is the part of the pactffi_verifier_json document @@ -309,29 +235,9 @@ func classifyVerifierFailure(resultJSON string) error { return ErrVerifierFailed } -func stringArrayToCStringArray(inputs []string) (**C.char, func()) { - if len(inputs) == 0 { - return nil, func() {} - } - - output := make([]*C.char, len(inputs)) - - for i, consumer := range inputs { - output[i] = C.CString(consumer) - } - - freeOutput := func() { - for _, consumer := range output { - free(consumer) - } - } - - return (**C.char)(unsafe.Pointer(&output[0])), freeOutput -} - -func boolToCUchar(val bool) C.uchar { +func boolToCUchar(val bool) uint8 { if val { - return C.uchar(1) + return 1 } - return C.uchar(0) + return 0 } From 9c310e08034bd007010bfd98ce7e8b3a5b5c8c37 Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Fri, 31 Oct 2025 02:18:06 +0000 Subject: [PATCH 2/4] feat: pact-go test wrapper around go test to automatically set PACT_LD_LIBRARY_PATH --- command/install.go | 6 +++++ command/test.go | 60 ++++++++++++++++++++++++++++++++++++++++++ installer/installer.go | 22 ++++++++++++++++ 3 files changed, 88 insertions(+) create mode 100644 command/test.go diff --git a/command/install.go b/command/install.go index 5ed59e06e..92bd04995 100644 --- a/command/install.go +++ b/command/install.go @@ -38,6 +38,12 @@ var ( log.Println("[ERROR] Your Pact library installation is out of date and we were unable to download a newer one for you:", err) os.Exit(1) } + + // Record where the libraries are, for `pact-go test`. + err = i.SetConfigLibDir(i.GetActualLibDir()) + if err != nil { + log.Println("[WARN] unable to record the library directory in the pact-go config:", err) + } }, } ) diff --git a/command/test.go b/command/test.go new file mode 100644 index 000000000..1e684ef28 --- /dev/null +++ b/command/test.go @@ -0,0 +1,60 @@ +package command + +import ( + "errors" + "log" + "os" + "os/exec" + + "github.com/spf13/cobra" + + "github.com/pact-foundation/pact-go/v2/installer" +) + +// libPathEnvVar names the directory the purego and goffi backends load the +// pact_ffi library from at runtime. +const libPathEnvVar = "PACT_LD_LIBRARY_PATH" + +var testCmd = &cobra.Command{ + Use: "test", + Short: "Run go test with the Pact library path configured", + Long: "Wrapper for 'go test' that sets " + libPathEnvVar + " to the directory the Pact libraries " + + "were installed to, for builds that load them at runtime (CGO_ENABLED=0, or the pact_purego and pact_goffi build tags)", + DisableFlagParsing: true, + Run: func(_ *cobra.Command, args []string) { + // An explicit environment setting wins over the recorded directory. + libDir := os.Getenv(libPathEnvVar) + if libDir == "" { + libDir = installer.GetConfigLibDir() + } + if libDir == "" { + log.Println("[ERROR] no library directory is configured: run `pact-go install`, or set", libPathEnvVar) + os.Exit(1) + } + + log.Printf("[INFO] running go test with %s=%s", libPathEnvVar, libDir) + + goCmd := exec.Command("go", append([]string{"test"}, args...)...) // #nosec G204 -- runs go test with the caller's own arguments + goCmd.Env = append(os.Environ(), libPathEnvVar+"="+libDir) + goCmd.Stdout = os.Stdout + goCmd.Stderr = os.Stderr + goCmd.Stdin = os.Stdin + + err := goCmd.Run() + if err == nil { + return + } + + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + os.Exit(exitErr.ExitCode()) + } + + log.Printf("[ERROR] failed to run go test: %v", err) + os.Exit(1) + }, +} + +func init() { + RootCmd.AddCommand(testCmd) +} diff --git a/installer/installer.go b/installer/installer.go index a2e7140f1..2a924cbc6 100644 --- a/installer/installer.go +++ b/installer/installer.go @@ -94,6 +94,27 @@ func (i *Installer) SetLibDir(dir string) { i.libDir = dir } +// SetConfigLibDir records dir in the pact-go configuration file as the +// directory the libraries were installed to, for `pact-go test` to use. +func (i *Installer) SetConfigLibDir(dir string) error { + log.Printf("[DEBUG] setting config lib dir to %s", dir) + c := i.config.readConfig() + c.LibDir = dir + + return i.config.writeConfig(c) +} + +// GetConfigLibDir returns the directory the libraries were last installed +// to, as recorded in the pact-go configuration file, or "" if none is. +func GetConfigLibDir() string { + return configuration{}.readConfig().LibDir +} + +// GetActualLibDir returns the directory the libraries are installed to. +func (i *Installer) GetActualLibDir() string { + return i.getLibDir() +} + // Force installs over the top. func (i *Installer) Force(force bool) { i.force = force @@ -746,6 +767,7 @@ type packageMetadata struct { type pactConfig struct { Libraries map[string]packageMetadata `yaml:"libraries"` + LibDir string `yaml:"libDir,omitempty"` } type configReader interface { From 0141f90cdc77269f78a639656beab5b6ecb4caa4 Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Sun, 15 Nov 2026 09:19:40 +0000 Subject: [PATCH 3/4] feat: goffi backend alongside cgo and purego Add a third libpact_ffi backend built on github.com/go-webgpu/goffi, selected with -tags pact_goffi. It shares the symbol table, library search and stub-on-failure behaviour of the purego backend (ffi_dynamic.go) and binds each symbol through reflection. Backends are mutually exclusive by build tag: cgo cgo && !pact_purego && !pact_goffi (default, CGO_ENABLED=1) purego (!cgo || pact_purego) && !pact_goffi (default, CGO_ENABLED=0) goffi pact_goffi Also: - purego: look symbols up through a per-platform helper, so the backend builds on Windows (purego.Dlsym is unix only) - wrap loader errors, drop unused declarations, keep the package comment in an untagged file - golangci: scope gosec G103/G115 out of internal/native, the FFI boundary, where cgo conversions previously hid the same narrowing --- .golangci.yml | 9 ++ go.mod | 1 + go.sum | 2 + internal/native/ffi_dynamic.go | 14 ++- internal/native/ffi_goffi.go | 166 ++++++++++++++++++++++++++ internal/native/ffi_purego.go | 2 +- internal/native/ffi_purego_unix.go | 22 +++- internal/native/ffi_purego_windows.go | 20 +++- internal/native/ffi_types.go | 4 +- internal/native/lib.go | 1 - internal/native/mock_server.go | 7 +- internal/native/verifier_test.go | 4 +- 12 files changed, 232 insertions(+), 20 deletions(-) create mode 100644 internal/native/ffi_goffi.go diff --git a/.golangci.yml b/.golangci.yml index 0b8d32cd4..049abdd60 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -133,6 +133,15 @@ linters: linters: - revive text: "var-naming" + # internal/native is the FFI boundary: handing pointers to pact_ffi (G103) + # and narrowing Go ints to the fixed-width C types in its signatures + # (G115) is what the package is for. cgo's C.int(x) conversions hid the + # same narrowing from gosec; the backend-neutral call sites spell it in + # Go types. Scoped to these two rules, and to this package. + - path: internal/native/ + linters: + - gosec + text: "G103|G115" # internal/native's switch statements match pact_ffi's C return codes, # each documented in a comment table directly above the switch; the # numbers are FFI enum values, not tunable magic numbers. Scoped to diff --git a/go.mod b/go.mod index d78c1977e..ede18e50c 100644 --- a/go.mod +++ b/go.mod @@ -17,6 +17,7 @@ require ( require ( github.com/ebitengine/purego v0.11.3 + github.com/go-webgpu/goffi v0.6.8 github.com/golang/snappy v0.0.4 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/kr/pretty v0.3.0 // indirect diff --git a/go.sum b/go.sum index 64b24e4c4..7bb0fb79d 100644 --- a/go.sum +++ b/go.sum @@ -4,6 +4,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/ebitengine/purego v0.11.3 h1:OB+JLpdm7ioymhyA+6s5kbb/uOuYycAgL8NNTFc5MLg= github.com/ebitengine/purego v0.11.3/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= +github.com/go-webgpu/goffi v0.6.8 h1:FjNYbHf+zvJXxbRM/PaTqwuhlgzypBNgA12Vo1updQk= +github.com/go-webgpu/goffi v0.6.8/go.mod h1:wfoxNsJkU+5RFbV1kNN1kunhc1lFHuJKK3zpgx08/uM= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= diff --git a/internal/native/ffi_dynamic.go b/internal/native/ffi_dynamic.go index c85f60727..b1489b446 100644 --- a/internal/native/ffi_dynamic.go +++ b/internal/native/ffi_dynamic.go @@ -90,7 +90,7 @@ var ( ) func pactffi_with_multipart_file(interaction uint32, part int32, contentType string, file string, partName string) { - if runtime.GOOS != "windows" { + if runtime.GOOS != goosWindows { withMultipartFileRegs(interaction, part, contentType, file, partName) return @@ -176,7 +176,7 @@ func ffiSymbols() []ffiSymbol { {"pactffi_verifier_json", &pactffi_verifier_json}, } - if runtime.GOOS == "windows" { + if runtime.GOOS == goosWindows { return append(symbols, ffiSymbol{"pactffi_with_multipart_file", &withMultipartFileMem}) } @@ -185,6 +185,9 @@ func ffiSymbols() []ffiSymbol { // libEnvVar names a directory to load the pact_ffi library from, ahead of // the default locations. +// goosWindows is the runtime.GOOS value on Windows. +const goosWindows = "windows" + const libEnvVar = "PACT_LD_LIBRARY_PATH" // libDownloadEnvVar names the directory `pact-go install` downloads the @@ -204,7 +207,7 @@ func LibraryLoadError() error { func libFileName() string { switch runtime.GOOS { - case "windows": + case goosWindows: return "pact_ffi.dll" case "darwin": return "libpact_ffi.dylib" @@ -226,7 +229,7 @@ func libCandidates() []string { candidates = append(candidates, filepath.Join(dir, name)) } } - if runtime.GOOS != "windows" { + if runtime.GOOS != goosWindows { for _, dir := range []string{"/tmp", "/opt/pact/lib", "/usr/local/lib"} { candidates = append(candidates, filepath.Join(dir, name)) } @@ -262,7 +265,8 @@ func loadLibrary(symbols []ffiSymbol) error { var errs []error for _, path := range libCandidates() { if filepath.IsAbs(path) { - if _, err := os.Stat(path); err != nil { + _, err := os.Stat(path) + if err != nil { continue } } diff --git a/internal/native/ffi_goffi.go b/internal/native/ffi_goffi.go new file mode 100644 index 000000000..2415bd6f9 --- /dev/null +++ b/internal/native/ffi_goffi.go @@ -0,0 +1,166 @@ +//go:build pact_goffi + +package native + +import ( + "fmt" + "math" + "reflect" + "runtime" + "unsafe" + + "github.com/go-webgpu/goffi/ffi" + "github.com/go-webgpu/goffi/types" +) + +// ffiBackend names the binding in use, see ffi_types.go. +const ffiBackend = "goffi" + +// bindLibrary loads the pact_ffi library at path and binds every symbol +// to its Go func variable. +func bindLibrary(path string, symbols []ffiSymbol) error { + lib, err := ffi.LoadLibrary(path) + if err != nil { + return fmt.Errorf("load %s: %w", path, err) + } + + // Resolve and prepare everything before binding anything, so that a + // failure leaves no function half bound. + bound := make([]reflect.Value, len(symbols)) + for i, s := range symbols { + addr, err := ffi.GetSymbol(lib, s.name) + if err != nil { + return fmt.Errorf("symbol %s: %w", s.name, err) + } + + bound[i], err = goffiFunc(reflect.TypeOf(s.fptr).Elem(), addr) + if err != nil { + return fmt.Errorf("symbol %s: %w", s.name, err) + } + } + for i, s := range symbols { + reflect.ValueOf(s.fptr).Elem().Set(bound[i]) + } + + return nil +} + +// goffiType maps a Go parameter or result type to its C type, following +// the table in ffi_types.go. +func goffiType(t reflect.Type) (*types.TypeDescriptor, error) { + switch t.Kind() { //nolint:exhaustive // only the kinds in the ffi_types.go table are bound; goffiType rejects the rest + case reflect.String, reflect.UnsafePointer, reflect.Pointer: + return types.PointerTypeDescriptor, nil + case reflect.Bool, reflect.Uint8: + return types.UInt8TypeDescriptor, nil + case reflect.Uint16: + return types.UInt16TypeDescriptor, nil + case reflect.Uint32: + return types.UInt32TypeDescriptor, nil + case reflect.Int32: + return types.SInt32TypeDescriptor, nil + case reflect.Uint64, reflect.Uintptr: + return types.UInt64TypeDescriptor, nil + default: + return nil, fmt.Errorf("unsupported type %s", t) + } +} + +// goffiFunc returns a Go func of type t that calls the C function at addr. +func goffiFunc(t reflect.Type, addr unsafe.Pointer) (reflect.Value, error) { + argTypes := make([]*types.TypeDescriptor, t.NumIn()) + for i := range argTypes { + var err error + argTypes[i], err = goffiType(t.In(i)) + if err != nil { + return reflect.Value{}, fmt.Errorf("argument %d: %w", i, err) + } + } + + retType := types.VoidTypeDescriptor + if t.NumOut() == 1 { + var err error + retType, err = goffiType(t.Out(0)) + if err != nil { + return reflect.Value{}, fmt.Errorf("result: %w", err) + } + } + + cif := &types.CallInterface{} + err := ffi.PrepareCallInterface(cif, types.DefaultCall, retType, argTypes) + if err != nil { + return reflect.Value{}, fmt.Errorf("prepare call: %w", err) + } + + return reflect.MakeFunc(t, func(args []reflect.Value) []reflect.Value { + // goffi takes a pointer to each argument. Pointers and scalars are + // kept in separate slots so that the garbage collector sees the + // pointers; scalars are little-endian, so the C type can be read + // from the start of a 64 bit slot. + ptrs := make([]unsafe.Pointer, len(args)) + vals := make([]uint64, len(args)) + avalue := make([]unsafe.Pointer, len(args)) + for i, arg := range args { + avalue[i] = unsafe.Pointer(&vals[i]) + + switch arg.Kind() { //nolint:exhaustive // only the kinds in the ffi_types.go table are bound; goffiType rejects the rest + case reflect.String: + ptrs[i] = unsafe.Pointer(cstr(arg.String())) + avalue[i] = unsafe.Pointer(&ptrs[i]) + case reflect.UnsafePointer, reflect.Pointer: + ptrs[i] = arg.UnsafePointer() + avalue[i] = unsafe.Pointer(&ptrs[i]) + case reflect.Bool: + if arg.Bool() { + vals[i] = 1 + } + case reflect.Int32: + vals[i] = uint64(arg.Int()) // #nosec G115 -- sign extension is intended + default: + vals[i] = arg.Uint() + } + } + + var ( + retVal uint64 + retPtr unsafe.Pointer + rvalue unsafe.Pointer + ) + isPtr := t.NumOut() == 1 && t.Out(0).Kind() == reflect.UnsafePointer + switch { + case isPtr: + rvalue = unsafe.Pointer(&retPtr) + case t.NumOut() == 1: + rvalue = unsafe.Pointer(&retVal) + } + + _, err := ffi.CallFunction(cif, addr, rvalue, avalue) + runtime.KeepAlive(ptrs) + runtime.KeepAlive(vals) + if err != nil { + panic(fmt.Errorf("pact-go: goffi call failed: %w", err)) + } + + if t.NumOut() == 0 { + return nil + } + + out := reflect.New(t.Out(0)).Elem() + switch out.Kind() { //nolint:exhaustive // only the kinds in the ffi_types.go table are bound; goffiType rejects the rest + case reflect.UnsafePointer: + out.SetPointer(retPtr) + case reflect.Bool: + out.SetBool(uint8(retVal) != 0) + case reflect.Int32: + out.SetInt(int64(int32(retVal))) // #nosec G115 -- truncation to the C type is intended + case reflect.Uint16: + out.SetUint(retVal & math.MaxUint16) + case reflect.Uint32: + out.SetUint(retVal & math.MaxUint32) + default: + out.SetUint(retVal) + } + + return []reflect.Value{out} + }), nil +} diff --git a/internal/native/ffi_purego.go b/internal/native/ffi_purego.go index 672f45517..c1c3d6024 100644 --- a/internal/native/ffi_purego.go +++ b/internal/native/ffi_purego.go @@ -21,7 +21,7 @@ func bindLibrary(path string, symbols []ffiSymbol) error { // RegisterLibFunc panics on a missing symbol, so check them all first. for _, s := range symbols { - _, err := purego.Dlsym(lib, s.name) + err := lookupSymbol(lib, s.name) if err != nil { return fmt.Errorf("symbol %s: %w", s.name, err) } diff --git a/internal/native/ffi_purego_unix.go b/internal/native/ffi_purego_unix.go index 04a3202a1..cde08bfd3 100644 --- a/internal/native/ffi_purego_unix.go +++ b/internal/native/ffi_purego_unix.go @@ -2,8 +2,26 @@ package native -import "github.com/ebitengine/purego" +import ( + "fmt" + + "github.com/ebitengine/purego" +) func openLibrary(path string) (uintptr, error) { - return purego.Dlopen(path, purego.RTLD_NOW|purego.RTLD_GLOBAL) + lib, err := purego.Dlopen(path, purego.RTLD_NOW|purego.RTLD_GLOBAL) + if err != nil { + return 0, fmt.Errorf("dlopen %s: %w", path, err) + } + + return lib, nil +} + +func lookupSymbol(lib uintptr, name string) error { + _, err := purego.Dlsym(lib, name) + if err != nil { + return fmt.Errorf("dlsym: %w", err) + } + + return nil } diff --git a/internal/native/ffi_purego_windows.go b/internal/native/ffi_purego_windows.go index 07a7c9c24..7daef95a1 100644 --- a/internal/native/ffi_purego_windows.go +++ b/internal/native/ffi_purego_windows.go @@ -2,10 +2,26 @@ package native -import "golang.org/x/sys/windows" +import ( + "fmt" + + "golang.org/x/sys/windows" +) func openLibrary(path string) (uintptr, error) { handle, err := windows.LoadLibrary(path) + if err != nil { + return 0, fmt.Errorf("load %s: %w", path, err) + } + + return uintptr(handle), nil +} + +func lookupSymbol(lib uintptr, name string) error { + _, err := windows.GetProcAddress(windows.Handle(lib), name) + if err != nil { + return fmt.Errorf("lookup %s: %w", name, err) + } - return uintptr(handle), err + return nil } diff --git a/internal/native/ffi_types.go b/internal/native/ffi_types.go index aaa785454..644a434bd 100644 --- a/internal/native/ffi_types.go +++ b/internal/native/ffi_types.go @@ -1,3 +1,5 @@ +// Package native contains the bindings into the Pact Reference (pact_ffi) +// library. package native import "unsafe" @@ -26,7 +28,7 @@ import "unsafe" // unsigned short uint16 // size_t uintptr // unsigned char uint8 -// bool bool +// bool (stdbool.h) bool // goString copies the NUL-terminated C string at p into a Go string. It // returns "" if p is nil. The C string is not freed. diff --git a/internal/native/lib.go b/internal/native/lib.go index 5eefff98c..56f898ea5 100644 --- a/internal/native/lib.go +++ b/internal/native/lib.go @@ -1,6 +1,5 @@ //go:build cgo && !pact_purego && !pact_goffi -// Package native contains the c bindings into the Pact Reference types. package native /* diff --git a/internal/native/mock_server.go b/internal/native/mock_server.go index add490d92..0845c701d 100644 --- a/internal/native/mock_server.go +++ b/internal/native/mock_server.go @@ -117,7 +117,6 @@ func Init(logLevel string) { // MockServer is the public interface for managing the HTTP mock server. type MockServer struct { pact *Pact - messagePact *MessagePact interactions []*Interaction } @@ -571,10 +570,6 @@ func (i *Interaction) withMultipartFile(contentType string, filename string, mim return i } -type stringLike interface { - String() string -} - func stringFromInterface(obj any) string { switch t := obj.(type) { case string: @@ -629,7 +624,7 @@ func logToStdout(level logLevel) error { func logToFile(file string, level logLevel) error { res := pactffi_log_to_file(file, int32(level)) - log.Println("[DEBUG] log_to_file res", res) + log.Println("[DEBUG] log_to_file res", res) // #nosec G706 -- res is an integer result code return logResultToError(int(res)) } diff --git a/internal/native/verifier_test.go b/internal/native/verifier_test.go index 6ddd87cdf..a3b53de96 100644 --- a/internal/native/verifier_test.go +++ b/internal/native/verifier_test.go @@ -50,14 +50,14 @@ func TestVerifier_SetConsumerFilters(_ *testing.T) { func TestStringArrayToCStringArray(t *testing.T) { t.Run("empty", func(t *testing.T) { - array, release := stringArrayToCStringArray(nil) + array, release := cStringArray(nil) assert.Nil(t, array) assert.NotNil(t, release) release() }) t.Run("values", func(t *testing.T) { - array, release := stringArrayToCStringArray([]string{"consumer1", "consumer2"}) + array, release := cStringArray([]string{"consumer1", "consumer2"}) assert.NotNil(t, array) assert.NotNil(t, release) release() From de7f384ef0706bf0295b0f6e25cbd01f79283533 Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Sun, 15 Nov 2026 14:12:09 +0000 Subject: [PATCH 4/4] fix: run the verifier on a thread with an 8 MiB stack on Linux pactffi_verifier_execute runs the verification on the calling thread and needs more stack than a Go-created thread has on musl (Alpine), where the default is 128 KiB. The provider tests crashed with SIGSEGV intermittently, and almost always under -race. On Linux, every backend (cgo, purego, goffi) now calls it on a pthread created with an 8 MiB stack and waits for it, falling back to a direct call if the thread cannot be created. Other platforms are unchanged. --- internal/native/ffi_cgo.go | 36 +++++++++- internal/native/ffi_dynamic.go | 10 ++- internal/native/ffi_goffi.go | 6 ++ internal/native/ffi_purego.go | 12 +++- internal/native/ffi_purego_unix.go | 8 +-- internal/native/ffi_purego_windows.go | 8 +-- internal/native/ffi_verifier_thread.go | 20 ++++++ internal/native/ffi_verifier_thread_linux.go | 70 ++++++++++++++++++++ internal/native/ffi_verifier_thread_other.go | 10 +++ 9 files changed, 167 insertions(+), 13 deletions(-) create mode 100644 internal/native/ffi_verifier_thread.go create mode 100644 internal/native/ffi_verifier_thread_linux.go create mode 100644 internal/native/ffi_verifier_thread_other.go diff --git a/internal/native/ffi_cgo.go b/internal/native/ffi_cgo.go index b9d1a7d4c..e439b383c 100644 --- a/internal/native/ffi_cgo.go +++ b/internal/native/ffi_cgo.go @@ -4,7 +4,41 @@ package native /* #include +#include #include "pact.h" + +// pact_go_verifier_execute calls pactffi_verifier_execute on a thread with +// an 8 MiB stack, see ffi_verifier_thread.go for why. +#if defined(__linux__) +#include + +static void *pact_go_verifier_thread(void *handle) { + return (void *)(intptr_t)pactffi_verifier_execute((struct VerifierHandle *)handle); +} + +static int pact_go_verifier_execute(struct VerifierHandle *handle) { + pthread_attr_t attr; + pthread_t thread; + void *result = NULL; + + if (pthread_attr_init(&attr) != 0) { + return pactffi_verifier_execute(handle); + } + if (pthread_attr_setstacksize(&attr, 8 * 1024 * 1024) != 0 || + pthread_create(&thread, &attr, pact_go_verifier_thread, handle) != 0) { + pthread_attr_destroy(&attr); + return pactffi_verifier_execute(handle); + } + pthread_attr_destroy(&attr); + pthread_join(thread, &result); + + return (int)(intptr_t)result; +} +#else +static int pact_go_verifier_execute(struct VerifierHandle *handle) { + return pactffi_verifier_execute(handle); +} +#endif */ import "C" @@ -435,7 +469,7 @@ func pactffi_verifier_set_publish_options(handle unsafe.Pointer, providerVersion } func pactffi_verifier_execute(handle unsafe.Pointer) int32 { - return int32(C.pactffi_verifier_execute((*C.struct_VerifierHandle)(handle))) + return int32(C.pact_go_verifier_execute((*C.struct_VerifierHandle)(handle))) } func pactffi_verifier_set_no_pacts_is_error(handle unsafe.Pointer, isError uint8) int32 { diff --git a/internal/native/ffi_dynamic.go b/internal/native/ffi_dynamic.go index b1489b446..baa6e745b 100644 --- a/internal/native/ffi_dynamic.go +++ b/internal/native/ffi_dynamic.go @@ -101,7 +101,8 @@ func pactffi_with_multipart_file(interaction uint32, part int32, contentType str } // ffiSymbol pairs the name of a pact_ffi function with a pointer to the Go -// func variable it is bound to. +// func variable it is bound to. If fptr is a *uintptr instead, the symbol +// is not bound: its address is stored there. type ffiSymbol struct { name string fptr any @@ -176,6 +177,8 @@ func ffiSymbols() []ffiSymbol { {"pactffi_verifier_json", &pactffi_verifier_json}, } + symbols = append(symbols, verifierThreadSymbols()...) + if runtime.GOOS == goosWindows { return append(symbols, ffiSymbol{"pactffi_with_multipart_file", &withMultipartFileMem}) } @@ -247,12 +250,17 @@ func init() { errLibNotLoaded = loadLibrary(symbols) if errLibNotLoaded == nil { + useVerifierThread() + return } errLibNotLoaded = fmt.Errorf("pact-go: the pact_ffi library is not available to the %s backend (run `pact-go install`, or set %s to the directory containing %s): %w", ffiBackend, libEnvVar, libFileName(), errLibNotLoaded) for _, s := range symbols { fn := reflect.ValueOf(s.fptr).Elem() + if fn.Kind() != reflect.Func { + continue + } fn.Set(reflect.MakeFunc(fn.Type(), func([]reflect.Value) []reflect.Value { panic(errLibNotLoaded) })) diff --git a/internal/native/ffi_goffi.go b/internal/native/ffi_goffi.go index 2415bd6f9..5f5523d39 100644 --- a/internal/native/ffi_goffi.go +++ b/internal/native/ffi_goffi.go @@ -33,6 +33,12 @@ func bindLibrary(path string, symbols []ffiSymbol) error { return fmt.Errorf("symbol %s: %w", s.name, err) } + if _, ok := s.fptr.(*uintptr); ok { + bound[i] = reflect.ValueOf(uintptr(addr)) + + continue + } + bound[i], err = goffiFunc(reflect.TypeOf(s.fptr).Elem(), addr) if err != nil { return fmt.Errorf("symbol %s: %w", s.name, err) diff --git a/internal/native/ffi_purego.go b/internal/native/ffi_purego.go index c1c3d6024..7e470f879 100644 --- a/internal/native/ffi_purego.go +++ b/internal/native/ffi_purego.go @@ -20,13 +20,19 @@ func bindLibrary(path string, symbols []ffiSymbol) error { } // RegisterLibFunc panics on a missing symbol, so check them all first. - for _, s := range symbols { - err := lookupSymbol(lib, s.name) + addrs := make([]uintptr, len(symbols)) + for i, s := range symbols { + addrs[i], err = lookupSymbol(lib, s.name) if err != nil { return fmt.Errorf("symbol %s: %w", s.name, err) } } - for _, s := range symbols { + for i, s := range symbols { + if addr, ok := s.fptr.(*uintptr); ok { + *addr = addrs[i] + + continue + } purego.RegisterLibFunc(s.fptr, lib, s.name) } diff --git a/internal/native/ffi_purego_unix.go b/internal/native/ffi_purego_unix.go index cde08bfd3..3949ad668 100644 --- a/internal/native/ffi_purego_unix.go +++ b/internal/native/ffi_purego_unix.go @@ -17,11 +17,11 @@ func openLibrary(path string) (uintptr, error) { return lib, nil } -func lookupSymbol(lib uintptr, name string) error { - _, err := purego.Dlsym(lib, name) +func lookupSymbol(lib uintptr, name string) (uintptr, error) { + addr, err := purego.Dlsym(lib, name) if err != nil { - return fmt.Errorf("dlsym: %w", err) + return 0, fmt.Errorf("dlsym: %w", err) } - return nil + return addr, nil } diff --git a/internal/native/ffi_purego_windows.go b/internal/native/ffi_purego_windows.go index 7daef95a1..32e3ec130 100644 --- a/internal/native/ffi_purego_windows.go +++ b/internal/native/ffi_purego_windows.go @@ -17,11 +17,11 @@ func openLibrary(path string) (uintptr, error) { return uintptr(handle), nil } -func lookupSymbol(lib uintptr, name string) error { - _, err := windows.GetProcAddress(windows.Handle(lib), name) +func lookupSymbol(lib uintptr, name string) (uintptr, error) { + addr, err := windows.GetProcAddress(windows.Handle(lib), name) if err != nil { - return fmt.Errorf("lookup %s: %w", name, err) + return 0, fmt.Errorf("lookup %s: %w", name, err) } - return nil + return addr, nil } diff --git a/internal/native/ffi_verifier_thread.go b/internal/native/ffi_verifier_thread.go new file mode 100644 index 000000000..775579110 --- /dev/null +++ b/internal/native/ffi_verifier_thread.go @@ -0,0 +1,20 @@ +package native + +// Why the verification runs on a thread of its own on Linux. +// +// pactffi_verifier_execute drives the whole verification on the thread that +// calls it, and needs more stack than that thread may have. Go creates its +// threads with the default pthread attributes, so their stack is the +// platform's default: 8 MiB with glibc, but 128 KiB with musl (Alpine), +// which the verification overflows, crashing the process with SIGSEGV. The +// crash was intermittent, as a call that happened to land on the main thread +// had the main thread's 8 MiB. +// +// So on Linux every backend calls pactffi_verifier_execute on a thread it +// creates with an 8 MiB stack, and waits for it: the cgo backend in the C +// preamble of ffi_cgo.go, the purego and goffi backends in +// ffi_verifier_thread_linux.go. With glibc this changes nothing but the +// thread, and other platforms call the function directly, as before. +// +// Versions of pact_ffi that do this themselves make it redundant, but +// harmless. diff --git a/internal/native/ffi_verifier_thread_linux.go b/internal/native/ffi_verifier_thread_linux.go new file mode 100644 index 000000000..b94ce5b0b --- /dev/null +++ b/internal/native/ffi_verifier_thread_linux.go @@ -0,0 +1,70 @@ +//go:build (!cgo || pact_purego || pact_goffi) && linux + +package native + +import ( + "fmt" + "unsafe" +) + +// verifierStackSize is the stack size of the thread a verification runs on. +const verifierStackSize = 8 << 20 + +// The pthread functions needed to run the verification on a thread with a +// stack size of our choosing, see ffi_verifier_thread.go. They are looked +// up through the pact_ffi library, which depends on the C library that +// defines them. +var ( + pthread_attr_init func(attr unsafe.Pointer) int32 + pthread_attr_setstacksize func(attr unsafe.Pointer, size uintptr) int32 + pthread_attr_destroy func(attr unsafe.Pointer) int32 + pthread_create func(thread unsafe.Pointer, attr unsafe.Pointer, start uintptr, arg unsafe.Pointer) int32 + pthread_join func(thread uintptr, result unsafe.Pointer) int32 + + // verifierExecuteAddr is the address of pactffi_verifier_execute, which + // is the new thread's start routine. + verifierExecuteAddr uintptr +) + +func verifierThreadSymbols() []ffiSymbol { + return []ffiSymbol{ + {"pthread_attr_init", &pthread_attr_init}, + {"pthread_attr_setstacksize", &pthread_attr_setstacksize}, + {"pthread_attr_destroy", &pthread_attr_destroy}, + {"pthread_create", &pthread_create}, + {"pthread_join", &pthread_join}, + {"pactffi_verifier_execute", &verifierExecuteAddr}, + } +} + +// useVerifierThread makes pactffi_verifier_execute run on a thread with a +// large stack. If that thread cannot be created, the call is made on the +// calling thread, as it would be otherwise. +func useVerifierThread() { + direct := pactffi_verifier_execute + + pactffi_verifier_execute = func(handle unsafe.Pointer) int32 { + // pthread_attr_t is 64 bytes or fewer in every Linux C library. + var attr [16]uint64 + if pthread_attr_init(unsafe.Pointer(&attr)) != 0 { + return direct(handle) + } + + var thread uintptr // pthread_t is the size of a pointer + started := pthread_attr_setstacksize(unsafe.Pointer(&attr), verifierStackSize) == 0 && + pthread_create(unsafe.Pointer(&thread), unsafe.Pointer(&attr), verifierExecuteAddr, handle) == 0 + pthread_attr_destroy(unsafe.Pointer(&attr)) + if !started { + return direct(handle) + } + + // The start routine returns a C int where a pointer is expected, so + // only the low 32 bits of the result are meaningful. + var result uintptr + if errno := pthread_join(thread, unsafe.Pointer(&result)); errno != 0 { + panic(fmt.Errorf("pact-go: could not wait for the verifier thread: pthread_join failed with %d", errno)) + } + + return int32(result) // #nosec G115 -- truncation to the C int is intended + } +} diff --git a/internal/native/ffi_verifier_thread_other.go b/internal/native/ffi_verifier_thread_other.go new file mode 100644 index 000000000..6890e2649 --- /dev/null +++ b/internal/native/ffi_verifier_thread_other.go @@ -0,0 +1,10 @@ +//go:build (!cgo || pact_purego || pact_goffi) && !linux + +package native + +// Only Linux runs the verification on a thread of its own, see +// ffi_verifier_thread.go. + +func verifierThreadSymbols() []ffiSymbol { return nil } + +func useVerifierThread() {}