1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
|
package goja
import (
"errors"
"io"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/google/pprof/profile"
)
const profInterval = 10 * time.Millisecond
const profMaxStackDepth = 64
const (
profReqNone int32 = iota
profReqDoSample
profReqSampleReady
profReqStop
)
type _globalProfiler struct {
p profiler
w io.Writer
enabled int32
}
var globalProfiler _globalProfiler
type profTracker struct {
req, finished int32
start, stop time.Time
numFrames int
frames [profMaxStackDepth]StackFrame
}
type profiler struct {
mu sync.Mutex
trackers []*profTracker
buf *profBuffer
running bool
}
type profFunc struct {
f profile.Function
locs map[int32]*profile.Location
}
type profSampleNode struct {
loc *profile.Location
sample *profile.Sample
parent *profSampleNode
children map[*profile.Location]*profSampleNode
}
type profBuffer struct {
funcs map[*Program]*profFunc
root profSampleNode
}
func (pb *profBuffer) addSample(pt *profTracker) {
sampleFrames := pt.frames[:pt.numFrames]
n := &pb.root
for j := len(sampleFrames) - 1; j >= 0; j-- {
frame := sampleFrames[j]
if frame.prg == nil {
continue
}
var f *profFunc
if f = pb.funcs[frame.prg]; f == nil {
f = &profFunc{
locs: make(map[int32]*profile.Location),
}
if pb.funcs == nil {
pb.funcs = make(map[*Program]*profFunc)
}
pb.funcs[frame.prg] = f
}
var loc *profile.Location
if loc = f.locs[int32(frame.pc)]; loc == nil {
loc = &profile.Location{}
f.locs[int32(frame.pc)] = loc
}
if nn := n.children[loc]; nn == nil {
if n.children == nil {
n.children = make(map[*profile.Location]*profSampleNode, 1)
}
nn = &profSampleNode{
parent: n,
loc: loc,
}
n.children[loc] = nn
n = nn
} else {
n = nn
}
}
smpl := n.sample
if smpl == nil {
locs := make([]*profile.Location, 0, len(sampleFrames))
for n1 := n; n1.loc != nil; n1 = n1.parent {
locs = append(locs, n1.loc)
}
smpl = &profile.Sample{
Location: locs,
Value: make([]int64, 2),
}
n.sample = smpl
}
smpl.Value[0]++
smpl.Value[1] += int64(pt.stop.Sub(pt.start))
}
func (pb *profBuffer) profile() *profile.Profile {
pr := profile.Profile{}
pr.SampleType = []*profile.ValueType{
{Type: "samples", Unit: "count"},
{Type: "cpu", Unit: "nanoseconds"},
}
pr.PeriodType = pr.SampleType[1]
pr.Period = int64(profInterval)
mapping := &profile.Mapping{
ID: 1,
File: "[ECMAScript code]",
}
pr.Mapping = make([]*profile.Mapping, 1, len(pb.funcs)+1)
pr.Mapping[0] = mapping
pr.Function = make([]*profile.Function, 0, len(pb.funcs))
funcNames := make(map[string]struct{})
var funcId, locId uint64
for prg, f := range pb.funcs {
fileName := prg.src.Name()
funcId++
f.f.ID = funcId
f.f.Filename = fileName
var funcName string
if prg.funcName != "" {
funcName = prg.funcName.String()
} else {
funcName = "<anonymous>"
}
// Make sure the function name is unique, otherwise the graph display merges them into one node, even
// if they are in different mappings.
if _, exists := funcNames[funcName]; exists {
funcName += "." + strconv.FormatUint(f.f.ID, 10)
} else {
funcNames[funcName] = struct{}{}
}
f.f.Name = funcName
pr.Function = append(pr.Function, &f.f)
for pc, loc := range f.locs {
locId++
loc.ID = locId
pos := prg.src.Position(prg.sourceOffset(int(pc)))
loc.Line = []profile.Line{
{
Function: &f.f,
Line: int64(pos.Line),
},
}
loc.Mapping = mapping
pr.Location = append(pr.Location, loc)
}
}
pb.addSamples(&pr, &pb.root)
return &pr
}
func (pb *profBuffer) addSamples(p *profile.Profile, n *profSampleNode) {
if n.sample != nil {
p.Sample = append(p.Sample, n.sample)
}
for _, child := range n.children {
pb.addSamples(p, child)
}
}
func (p *profiler) run() {
ticker := time.NewTicker(profInterval)
counter := 0
for ts := range ticker.C {
p.mu.Lock()
left := len(p.trackers)
if left == 0 {
break
}
for {
// This loop runs until either one of the VMs is signalled or all of the VMs are scanned and found
// busy or deleted.
if counter >= len(p.trackers) {
counter = 0
}
tracker := p.trackers[counter]
req := atomic.LoadInt32(&tracker.req)
if req == profReqSampleReady {
p.buf.addSample(tracker)
}
if atomic.LoadInt32(&tracker.finished) != 0 {
p.trackers[counter] = p.trackers[len(p.trackers)-1]
p.trackers[len(p.trackers)-1] = nil
p.trackers = p.trackers[:len(p.trackers)-1]
} else {
counter++
if req != profReqDoSample {
// signal the VM to take a sample
tracker.start = ts
atomic.StoreInt32(&tracker.req, profReqDoSample)
break
}
}
left--
if left <= 0 {
// all VMs are busy
break
}
}
p.mu.Unlock()
}
ticker.Stop()
p.running = false
p.mu.Unlock()
}
func (p *profiler) registerVm() *profTracker {
pt := new(profTracker)
p.mu.Lock()
if p.buf != nil {
p.trackers = append(p.trackers, pt)
if !p.running {
go p.run()
p.running = true
}
} else {
pt.req = profReqStop
}
p.mu.Unlock()
return pt
}
func (p *profiler) start() error {
p.mu.Lock()
if p.buf != nil {
p.mu.Unlock()
return errors.New("profiler is already active")
}
p.buf = new(profBuffer)
p.mu.Unlock()
return nil
}
func (p *profiler) stop() *profile.Profile {
p.mu.Lock()
trackers, buf := p.trackers, p.buf
p.trackers, p.buf = nil, nil
p.mu.Unlock()
if buf != nil {
k := 0
for i, tracker := range trackers {
req := atomic.LoadInt32(&tracker.req)
if req == profReqSampleReady {
buf.addSample(tracker)
} else if req == profReqDoSample {
// In case the VM is requested to do a sample, there is a small chance of a race
// where we set profReqStop in between the read and the write, so that the req
// ends up being set to profReqSampleReady. It's no such a big deal if we do nothing,
// it just means the VM remains in tracing mode until it finishes the current run,
// but we do an extra cleanup step later just in case.
if i != k {
trackers[k] = trackers[i]
}
k++
}
atomic.StoreInt32(&tracker.req, profReqStop)
}
if k > 0 {
trackers = trackers[:k]
go func() {
// Make sure all VMs are requested to stop tracing.
for {
k := 0
for i, tracker := range trackers {
req := atomic.LoadInt32(&tracker.req)
if req != profReqStop {
atomic.StoreInt32(&tracker.req, profReqStop)
if i != k {
trackers[k] = trackers[i]
}
k++
}
}
if k == 0 {
return
}
trackers = trackers[:k]
time.Sleep(100 * time.Millisecond)
}
}()
}
return buf.profile()
}
return nil
}
/*
StartProfile enables execution time profiling for all Runtimes within the current process.
This works similar to pprof.StartCPUProfile and produces the same format which can be consumed by `go tool pprof`.
There are, however, a few notable differences. Firstly, it's not a CPU profile, rather "execution time" profile.
It measures the time the VM spends executing an instruction. If this instruction happens to be a call to a
blocking Go function, the waiting time will be measured. Secondly, the 'cpu' sample isn't simply `count*period`,
it's the time interval between when sampling was requested and when the instruction has finished. If a VM is still
executing the same instruction when the time comes for the next sample, the sampling is skipped (i.e. `count` doesn't
grow).
If there are multiple functions with the same name, their names get a '.N' suffix, where N is a unique number,
because otherwise the graph view merges them together (even if they are in different mappings). This includes
"<anonymous>" functions.
The sampling period is set to 10ms.
It returns an error if profiling is already active.
*/
func StartProfile(w io.Writer) error {
err := globalProfiler.p.start()
if err != nil {
return err
}
globalProfiler.w = w
atomic.StoreInt32(&globalProfiler.enabled, 1)
return nil
}
/*
StopProfile stops the current profile initiated by StartProfile, if any.
*/
func StopProfile() {
atomic.StoreInt32(&globalProfiler.enabled, 0)
pr := globalProfiler.p.stop()
if pr != nil {
_ = pr.Write(globalProfiler.w)
}
globalProfiler.w = nil
}
|