stack_tags_js.go 1.5 KB
Newer Older
W
wangkang101 已提交
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
// +build js

package gls

// This file is used for GopherJS builds, which don't have normal runtime
// stack trace support

import (
	"strconv"
	"strings"

	"github.com/gopherjs/gopherjs/js"
)

const (
	jsFuncNamePrefix = "github_com_jtolds_gls_mark"
)

func jsMarkStack() (f []uintptr) {
	lines := strings.Split(
		js.Global.Get("Error").New().Get("stack").String(), "\n")
	f = make([]uintptr, 0, len(lines))
	for i, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}
		if i == 0 {
			if line != "Error" {
				panic("didn't understand js stack trace")
			}
			continue
		}
		fields := strings.Fields(line)
		if len(fields) < 2 || fields[0] != "at" {
			panic("didn't understand js stack trace")
		}

		pos := strings.Index(fields[1], jsFuncNamePrefix)
		if pos < 0 {
			continue
		}
		pos += len(jsFuncNamePrefix)
		if pos >= len(fields[1]) {
			panic("didn't understand js stack trace")
		}
		char := string(fields[1][pos])
		switch char {
		case "S":
			f = append(f, uintptr(0))
		default:
			val, err := strconv.ParseUint(char, 16, 8)
			if err != nil {
				panic("didn't understand js stack trace")
			}
			f = append(f, uintptr(val)+1)
		}
	}
	return f
}

// variables to prevent inlining
var (
	findPtr = func() uintptr {
		funcs := jsMarkStack()
		if len(funcs) == 0 {
			panic("failed to find function pointer")
		}
		return funcs[0]
	}

	getStack = func(offset, amount int) (stack []uintptr, next_offset int) {
		return jsMarkStack(), 0
	}
)