github.com/matrixorigin/matrixone@v1.2.0/pkg/util/stack/stack.go (about)

     1  // Copyright 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  package stack
    16  
    17  import (
    18  	"fmt"
    19  	"io"
    20  	"runtime"
    21  
    22  	pkgErr "github.com/pkg/errors"
    23  )
    24  
    25  type StackTrace = pkgErr.StackTrace
    26  
    27  type Frame = pkgErr.Frame
    28  
    29  type Stack []uintptr
    30  
    31  // Callers makes the depth customizable.
    32  func Callers(depth int) *Stack {
    33  	const numFrames = 32
    34  	var pcs [numFrames]uintptr
    35  	n := runtime.Callers(2+depth, pcs[:])
    36  	var st Stack = pcs[0:n]
    37  	return &st
    38  }
    39  
    40  // Caller return only one Frame
    41  func Caller(depth int) Frame {
    42  	const numFrames = 1
    43  	var pcs [numFrames]uintptr
    44  	_ = runtime.Callers(2+depth, pcs[:])
    45  	return Frame(pcs[0])
    46  }
    47  
    48  func (s *Stack) Format(st fmt.State, verb rune) {
    49  	for _, pc := range *s {
    50  		f := Frame(pc)
    51  		io.WriteString(st, "\n")
    52  		f.Format(st, verb)
    53  	}
    54  }
    55  
    56  func (s *Stack) StackTrace() pkgErr.StackTrace {
    57  	f := make([]pkgErr.Frame, len(*s))
    58  	for i := 0; i < len(f); i++ {
    59  		f[i] = pkgErr.Frame((*s)[i])
    60  	}
    61  	return f
    62  }