Skip to content

Commit

Permalink
Fix to/from array conversions for windows
Browse files Browse the repository at this point in the history
uint is at least 32 bit integer, according to the standard.
on windows, the uint has 64 bits, as in linux, but:
C.sizeof_ulong is 0x4 on windows.
ASAN does not like that.
but even if the value is stored, the code can't read it properly,
because bytesToUlong checks
if sliceSize > C.sizeof_ulong
  • Loading branch information
droppingin committed May 21, 2023
1 parent db3e080 commit b748786
Showing 1 changed file with 21 additions and 18 deletions.
39 changes: 21 additions & 18 deletions common.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,35 +24,38 @@ package crypto11
import (
"C"
"encoding/asn1"
"encoding/binary"
"math"
"math/big"
"unsafe"

"github.com/miekg/pkcs11"
"github.com/pkg/errors"
)

const uint64Sz = 8
const uint32Sz = 4

// **little-endian** order
func ulongToBytes(n uint) []byte {
return C.GoBytes(unsafe.Pointer(&n), C.sizeof_ulong) // ugh!
if n > math.MaxUint32 {
bytes := make([]byte, uint64Sz)
binary.LittleEndian.PutUint64(bytes, uint64(n))
return bytes
}
bytes := make([]byte, uint32Sz)
binary.LittleEndian.PutUint32(bytes, uint32(n))
return bytes
}

// assuming **little-endian** storage order
func bytesToUlong(bs []byte) (n uint) {
sliceSize := len(bs)
if sliceSize == 0 {
return 0
}

value := *(*uint)(unsafe.Pointer(&bs[0]))
if sliceSize > C.sizeof_ulong {
return value
}

// truncate the value to the # of bits present in the byte slice since
// the unsafe pointer will always grab/convert ULONG # of bytes
var mask uint
for i := 0; i < sliceSize; i++ {
mask |= 0xff << uint(i * 8)
if len(bs) < uint64Sz {
placeholder := make([]byte, uint64Sz)
copy(placeholder, bs)
bs = placeholder
}
return value & mask
nn := binary.LittleEndian.Uint64(bs)
return uint(nn)
}

func concat(slices ...[]byte) []byte {
Expand Down

0 comments on commit b748786

Please sign in to comment.