github.com/liloew/wireguard-go@v0.0.0-20220224014633-9cd745e6f114/tun/alignment_windows_test.go (about) 1 /* SPDX-License-Identifier: MIT 2 * 3 * Copyright (C) 2017-2021 WireGuard LLC. All Rights Reserved. 4 */ 5 6 package tun 7 8 import ( 9 "reflect" 10 "testing" 11 "unsafe" 12 ) 13 14 func checkAlignment(t *testing.T, name string, offset uintptr) { 15 t.Helper() 16 if offset%8 != 0 { 17 t.Errorf("offset of %q within struct is %d bytes, which does not align to 64-bit word boundaries (missing %d bytes). Atomic operations will crash on 32-bit systems.", name, offset, 8-(offset%8)) 18 } 19 } 20 21 // TestRateJugglerAlignment checks that atomically-accessed fields are 22 // aligned to 64-bit boundaries, as required by the atomic package. 23 // 24 // Unfortunately, violating this rule on 32-bit platforms results in a 25 // hard segfault at runtime. 26 func TestRateJugglerAlignment(t *testing.T) { 27 var r rateJuggler 28 29 typ := reflect.TypeOf(&r).Elem() 30 t.Logf("Peer type size: %d, with fields:", typ.Size()) 31 for i := 0; i < typ.NumField(); i++ { 32 field := typ.Field(i) 33 t.Logf("\t%30s\toffset=%3v\t(type size=%3d, align=%d)", 34 field.Name, 35 field.Offset, 36 field.Type.Size(), 37 field.Type.Align(), 38 ) 39 } 40 41 checkAlignment(t, "rateJuggler.current", unsafe.Offsetof(r.current)) 42 checkAlignment(t, "rateJuggler.nextByteCount", unsafe.Offsetof(r.nextByteCount)) 43 checkAlignment(t, "rateJuggler.nextStartTime", unsafe.Offsetof(r.nextStartTime)) 44 } 45 46 // TestNativeTunAlignment checks that atomically-accessed fields are 47 // aligned to 64-bit boundaries, as required by the atomic package. 48 // 49 // Unfortunately, violating this rule on 32-bit platforms results in a 50 // hard segfault at runtime. 51 func TestNativeTunAlignment(t *testing.T) { 52 var tun NativeTun 53 54 typ := reflect.TypeOf(&tun).Elem() 55 t.Logf("Peer type size: %d, with fields:", typ.Size()) 56 for i := 0; i < typ.NumField(); i++ { 57 field := typ.Field(i) 58 t.Logf("\t%30s\toffset=%3v\t(type size=%3d, align=%d)", 59 field.Name, 60 field.Offset, 61 field.Type.Size(), 62 field.Type.Align(), 63 ) 64 } 65 66 checkAlignment(t, "NativeTun.rate", unsafe.Offsetof(tun.rate)) 67 }