github.com/liloew/wireguard-go@v0.0.0-20220224014633-9cd745e6f114/device/alignment_test.go (about)

     1  /* SPDX-License-Identifier: MIT
     2   *
     3   * Copyright (C) 2017-2021 WireGuard LLC. All Rights Reserved.
     4   */
     5  
     6  package device
     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  // TestPeerAlignment 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 TestPeerAlignment(t *testing.T) {
    27  	var p Peer
    28  
    29  	typ := reflect.TypeOf(&p).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, "Peer.stats", unsafe.Offsetof(p.stats))
    42  	checkAlignment(t, "Peer.isRunning", unsafe.Offsetof(p.isRunning))
    43  }
    44  
    45  // TestDeviceAlignment checks that atomically-accessed fields are
    46  // aligned to 64-bit boundaries, as required by the atomic package.
    47  //
    48  // Unfortunately, violating this rule on 32-bit platforms results in a
    49  // hard segfault at runtime.
    50  func TestDeviceAlignment(t *testing.T) {
    51  	var d Device
    52  
    53  	typ := reflect.TypeOf(&d).Elem()
    54  	t.Logf("Device type size: %d, with fields:", typ.Size())
    55  	for i := 0; i < typ.NumField(); i++ {
    56  		field := typ.Field(i)
    57  		t.Logf("\t%30s\toffset=%3v\t(type size=%3d, align=%d)",
    58  			field.Name,
    59  			field.Offset,
    60  			field.Type.Size(),
    61  			field.Type.Align(),
    62  		)
    63  	}
    64  	checkAlignment(t, "Device.rate.underLoadUntil", unsafe.Offsetof(d.rate)+unsafe.Offsetof(d.rate.underLoadUntil))
    65  }