github.com/goshafaq/sonic@v0.0.0-20231026082336-871835fb94c6/loader/wrapper_test.go (about) 1 /** 2 * Copyright 2023 ByteDance Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package loader 18 19 import ( 20 "os" 21 "runtime" 22 "runtime/debug" 23 "testing" 24 "time" 25 26 "github.com/stretchr/testify/require" 27 ) 28 29 var ( 30 debugAsyncGC = os.Getenv("SONIC_NO_ASYNC_GC") == "" 31 ) 32 33 func TestMain(m *testing.M) { 34 go func() { 35 if !debugAsyncGC { 36 return 37 } 38 println("Begin GC looping...") 39 for { 40 runtime.GC() 41 debug.FreeOSMemory() 42 } 43 println("stop GC looping!") 44 }() 45 time.Sleep(time.Millisecond * 100) 46 m.Run() 47 } 48 49 func TestWrapC(t *testing.T) { 50 var stub func(a int64, val *int64) (ret int64) 51 ct := []byte{ 52 0x55, // pushq %rbp 53 0x48, 0x89, 0xe5, // movq %rsp, %rbp 54 0x48, 0x89, 0x7d, 0xf8, // movq %rdi, -8(%rbp) 55 0x48, 0x89, 0x75, 0xf0, // movq %rsi, -16(%rbp) 56 0x48, 0x8b, 0x75, 0xf8, // movq -8(%rbp), %rsi 57 0x48, 0x8b, 0x7d, 0xf0, // movq -16(%rbp), %rdi 58 0x48, 0x03, 0x37, // addq (%rdi), %rsi 59 0x48, 0x89, 0xf0, // movq %rsi, %rax 60 0x5d, // popq %rbp 61 0xc3, // ret 62 } 63 64 WrapGoC(ct, []CFunc{{ 65 Name: "add", 66 EntryOff: 0, 67 TextSize: uint32(len(ct)), 68 MaxStack: uintptr(16), 69 Pcsp: [][2]uint32{ 70 {1, 8}, 71 }, 72 }}, []GoC{{ 73 CName: "add", 74 GoFunc: &stub, 75 }}, "dummy/native", "dummy/native.c") 76 77 // defer func(){ 78 // if err := recover(); err!= nil { 79 // println("panic:", err) 80 // } else { 81 // t.Fatal("not panic") 82 // } 83 // }() 84 85 f := stub 86 b := int64(2) 87 println("b : ", &b) 88 var c *int64 = &b 89 runtime.SetFinalizer(c, func(x *int64) { 90 println("c got GC: ", x) 91 }) 92 runtime.GC() 93 println("before") 94 act := f(1, c) 95 println("after") 96 runtime.GC() 97 require.Equal(t, int64(3), act) 98 }