github.com/matrixorigin/matrixone@v1.2.0/pkg/common/mpool/alloc_tracing.go (about)

     1  // Copyright 2021 - 2022 Matrix Origin
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  //go:build race
    16  // +build race
    17  
    18  package mpool
    19  
    20  import (
    21  	"runtime/debug"
    22  	"time"
    23  	"unsafe"
    24  )
    25  
    26  const (
    27  	DefaultGCInterval = 1 * time.Second
    28  )
    29  
    30  func init() {
    31  	go func() {
    32  		ticker := time.Tick(DefaultGCInterval)
    33  		for {
    34  			<-ticker
    35  			debug.FreeOSMemory()
    36  		}
    37  	}()
    38  }
    39  
    40  func alloc(sz, requiredSpaceWithoutHeader int, mp *MPool) []byte {
    41  	bs := make([]byte, requiredSpaceWithoutHeader+kMemHdrSz)
    42  	hdr := unsafe.Pointer(&bs[0])
    43  	pHdr := (*memHdr)(hdr)
    44  	pHdr.poolId = mp.id
    45  	pHdr.fixedPoolIdx = NumFixedPool
    46  	pHdr.allocSz = int32(sz)
    47  	pHdr.SetGuard()
    48  	if mp.details != nil {
    49  		mp.details.recordAlloc(int64(pHdr.allocSz))
    50  	}
    51  	b := pHdr.ToSlice(sz, requiredSpaceWithoutHeader)
    52  	// stack := string(debug.Stack())
    53  	// runtime.SetFinalizer(&b, func(ptr *[]byte) {
    54  	// 	d := *ptr
    55  	// 	hdr := unsafe.Add((unsafe.Pointer)(&d[0]), -kMemHdrSz)
    56  	// 	pHdr := (*memHdr)(unsafe.Pointer(hdr))
    57  	// 	if allocSz := atomic.LoadInt32(&pHdr.allocSz); allocSz >= 0 {
    58  	// 		logutil.Error("memory leak detected",
    59  	// 			zap.Any("ptr", pHdr),
    60  	// 			zap.Int("size", int(allocSz)),
    61  	// 			zap.String("stack", stack),
    62  	// 		)
    63  	// 	}
    64  	// })
    65  	return b
    66  }