cl: switch debug symbols with LLGO_DEBUG

This commit is contained in:
Li Jie
2024-09-21 21:09:16 +08:00
parent 88b980ac17
commit dad22b1686
11 changed files with 43 additions and 68 deletions

View File

@@ -3,15 +3,17 @@
### Build with debug info ### Build with debug info
```shell ```shell
llgo build -o cl/_testdata/debug/out -dbg ./cl/_testdata/debug LLGO_DEBUG=1 llgo build -o cl/_testdata/debug/out ./cl/_testdata/debug
``` ```
### Debug with lldb ### Debug with lldb
```shell ```shell
lldb -O "command script import _lldb/llgo_plugin.py" ./cl/_testdata/debug/out _lldb/runlldb.sh ./cl/_testdata/debug/out
``` ```
or
```shell ```shell
/opt/homebrew/bin/lldb -O "command script import _lldb/llgo_plugin.py" ./cl/_testdata/debug/out /opt/homebrew/bin/lldb -O "command script import _lldb/llgo_plugin.py" ./cl/_testdata/debug/out
# github.com/goplus/llgo/cl/_testdata/debug # github.com/goplus/llgo/cl/_testdata/debug

View File

@@ -11,7 +11,8 @@ find_lldb() {
for lldb_path in "${lldb_paths[@]}"; do for lldb_path in "${lldb_paths[@]}"; do
if command -v "$lldb_path" >/dev/null 2>&1; then if command -v "$lldb_path" >/dev/null 2>&1; then
local version=$("$lldb_path" --version | grep -oE '[0-9]+' | head -1) local version
version=$("$lldb_path" --version | grep -oE '[0-9]+' | head -1)
if [ "$version" -ge 18 ]; then if [ "$version" -ge 18 ]; then
echo "$lldb_path" echo "$lldb_path"
return 0 return 0
@@ -25,12 +26,13 @@ find_lldb() {
# Find LLDB 18+ # Find LLDB 18+
LLDB_PATH=$(find_lldb) LLDB_PATH=$(find_lldb)
export LLDB_PATH
# Default package path # Default package path
DEFAULT_PACKAGE_PATH="./cl/_testdata/debug" export DEFAULT_PACKAGE_PATH="./cl/_testdata/debug"
# Function to build the project # Function to build the project
build_project() { build_project() {
local package_path="$1" local package_path="$1"
go run ./cmd/llgo build -o "${package_path}/out" -dbg "${package_path}" LLGO_DEBUG=1 go run ./cmd/llgo build -o "${package_path}/out" "${package_path}"
} }

View File

@@ -3,16 +3,10 @@
set -e set -e
# Source common functions and variables # Source common functions and variables
# shellcheck source=./_lldb/common.sh
source "$(dirname "$0")/common.sh" source "$(dirname "$0")/common.sh"
# Check if a package path is provided as an argument executable="$1"
package_path="$DEFAULT_PACKAGE_PATH"
if [ $# -eq 1 ]; then
package_path="$1"
fi
# Build the project
build_project "$package_path"
# Run LLDB # Run LLDB
"$LLDB_PATH" "${package_path}/out" "$LLDB_PATH" "$executable"

View File

@@ -91,7 +91,7 @@ class LLDBDebugger:
bp = self.target.BreakpointCreateByLocation(file_spec, line_number) bp = self.target.BreakpointCreateByLocation(file_spec, line_number)
if not bp.IsValid(): if not bp.IsValid():
raise LLDBTestException(f"Failed to set breakpoint at { raise LLDBTestException(f"Failed to set breakpoint at {
file_spec}:{line_number}") file_spec}: {line_number}")
return bp return bp
def run_to_breakpoint(self) -> None: def run_to_breakpoint(self) -> None:
@@ -225,7 +225,7 @@ def execute_tests(executable_path: str, test_cases: List[TestCase], verbose: boo
try: try:
if verbose: if verbose:
log(f"Setting breakpoint at { log(f"Setting breakpoint at {
test_case.source_file}:{test_case.end_line}") test_case.source_file}: {test_case.end_line}")
debugger.setup() debugger.setup()
debugger.set_breakpoint(test_case.source_file, test_case.end_line) debugger.set_breakpoint(test_case.source_file, test_case.end_line)
debugger.run_to_breakpoint() debugger.run_to_breakpoint()
@@ -269,6 +269,7 @@ def run_tests(executable_path: str, source_files: List[str], verbose: bool, inte
results = execute_tests(executable_path, test_cases, results = execute_tests(executable_path, test_cases,
verbose, interactive, plugin_path) verbose, interactive, plugin_path)
print_test_results(results)
if results.total != results.passed: if results.total != results.passed:
os._exit(1) os._exit(1)
@@ -331,14 +332,7 @@ def execute_single_variable_test(debugger: LLDBDebugger, test: Test) -> TestResu
) )
def print_test_results(results: TestResults, verbose: bool) -> None: def print_test_results(results: TestResults) -> None:
for case_result in results.case_results:
case = case_result.test_case
loc = f"{case.source_file}:{case.start_line}-{case.end_line}"
log(f"\nTest case: {loc} in function '{case_result.function}'")
for result in case_result.results:
print_test_result(result, verbose)
log("\nTest results:") log("\nTest results:")
log(f" Total tests: {results.total}") log(f" Total tests: {results.total}")
log(f" Passed tests: {results.passed}") log(f" Passed tests: {results.passed}")

View File

@@ -66,13 +66,9 @@ func llgenDir(dir string, pkgPath ...string) {
} }
testDir := dir + "/" + name testDir := dir + "/" + name
fmt.Fprintln(os.Stderr, "llgen", testDir) fmt.Fprintln(os.Stderr, "llgen", testDir)
os.Chdir(testDir) check(os.Chdir(testDir))
dbg := isDbgSymEnabled("flags.txt") dbg := isDbgSymEnabled("flags.txt")
if dbg { cl.EnableDebugSymbols(dbg)
cl.EnableDebugSymbols()
} else {
cl.DisableDebugSymbols()
}
llgen.SmartDoFile("in.go", pkgPath...) llgen.SmartDoFile("in.go", pkgPath...)
} }

View File

@@ -17,24 +17,19 @@
package main package main
import ( import (
"flag"
"fmt" "fmt"
"os" "os"
"github.com/goplus/llgo/internal/build"
"github.com/goplus/llgo/internal/llgen" "github.com/goplus/llgo/internal/llgen"
) )
var (
enableDbg = flag.Bool("dbg", false, "enable debug symbols")
)
func main() { func main() {
flag.Parse() if len(os.Args) < 2 {
if len(flag.Args()) < 1 {
fmt.Fprintln(os.Stderr, "Usage: llgen [flags] <pkg> [pkgPath]") fmt.Fprintln(os.Stderr, "Usage: llgen [flags] <pkg> [pkgPath]")
return return
} }
llgen.Init(*enableDbg) llgen.Init(build.IsDebugEnabled())
args := flag.Args() args := os.Args[1:]
llgen.SmartDoFile(args[0], args[1:]...) llgen.SmartDoFile(args[0], args[1:]...)
} }

View File

@@ -130,10 +130,10 @@ func testFrom(t *testing.T, pkgDir, sel string, byLLGen bool) {
out := pkgDir + "/out.ll" out := pkgDir + "/out.ll"
dbg := isDbgSymEnabled(pkgDir + "/flags.txt") dbg := isDbgSymEnabled(pkgDir + "/flags.txt")
if dbg { if dbg {
cl.EnableDebugSymbols() cl.EnableDebugSymbols(true)
defer cl.EnableDebugSymbols(false)
cl.DebugSymbols() // just for coverage cl.DebugSymbols() // just for coverage
} }
defer cl.DisableDebugSymbols()
b, err := os.ReadFile(out) b, err := os.ReadFile(out)
if err != nil { if err != nil {
t.Fatal("ReadFile failed:", err) t.Fatal("ReadFile failed:", err)

View File

@@ -58,12 +58,8 @@ func SetDebug(dbgFlags dbgFlags) {
} }
// EnableDebugSymbols enables debug symbols. // EnableDebugSymbols enables debug symbols.
func EnableDebugSymbols() { func EnableDebugSymbols(b bool) {
debugSymbols = true debugSymbols = b
}
func DisableDebugSymbols() {
debugSymbols = false
} }
func DebugSymbols() bool { func DebugSymbols() bool {

View File

@@ -120,10 +120,8 @@ const (
) )
func Do(args []string, conf *Config) { func Do(args []string, conf *Config) {
flags, patterns, verbose, dbg := ParseArgs(args, buildFlags) flags, patterns, verbose := ParseArgs(args, buildFlags)
if dbg { cl.EnableDebugSymbols(IsDebugEnabled())
cl.EnableDebugSymbols()
}
flags = append(flags, "-tags", "llgo") flags = append(flags, "-tags", "llgo")
cfg := &packages.Config{ cfg := &packages.Config{
Mode: loadSyntax | packages.NeedDeps | packages.NeedModule | packages.NeedExportFile, Mode: loadSyntax | packages.NeedDeps | packages.NeedModule | packages.NeedExportFile,
@@ -602,7 +600,6 @@ var (
"-cover": false, // -cover: enable coverage analysis "-cover": false, // -cover: enable coverage analysis
"-covermode": true, // -covermode mode: set the mode for coverage analysis "-covermode": true, // -covermode mode: set the mode for coverage analysis
"-v": false, // -v: print the names of packages as they are compiled "-v": false, // -v: print the names of packages as they are compiled
"-dbg": false, // -dbg: build with debug symbols (temporarily)
"-work": false, // -work: print the name of the temporary work directory and do not delete it when exiting "-work": false, // -work: print the name of the temporary work directory and do not delete it when exiting
"-x": false, // -x: print the commands "-x": false, // -x: print the commands
"-tags": true, // -tags 'tag,list': a space-separated list of build tags to consider satisfied during the build "-tags": true, // -tags 'tag,list': a space-separated list of build tags to consider satisfied during the build
@@ -611,19 +608,22 @@ var (
} }
) )
func ParseArgs(args []string, swflags map[string]bool) (flags, patterns []string, verbose, dbg bool) { const llgoDebug = "LLGO_DEBUG"
func IsDebugEnabled() bool {
llgoDbgVal := strings.ToLower(os.Getenv(llgoDebug))
return llgoDbgVal == "1" || llgoDbgVal == "true" || llgoDbgVal == "on"
}
func ParseArgs(args []string, swflags map[string]bool) (flags, patterns []string, verbose bool) {
n := len(args) n := len(args)
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
arg := args[i] arg := args[i]
if strings.HasPrefix(arg, "-") { if strings.HasPrefix(arg, "-") {
checkFlag(arg, &i, &verbose, &dbg, swflags) checkFlag(arg, &i, &verbose, swflags)
} else { } else {
patterns = args[i:] patterns = args[i:]
for _, arg := range args[:i] { flags = args[:i]
if arg != "-dbg" {
flags = append(flags, arg)
}
}
return return
} }
} }
@@ -635,7 +635,7 @@ func SkipFlagArgs(args []string) int {
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
arg := args[i] arg := args[i]
if strings.HasPrefix(arg, "-") { if strings.HasPrefix(arg, "-") {
checkFlag(arg, &i, nil, nil, buildFlags) checkFlag(arg, &i, nil, buildFlags)
} else { } else {
return i return i
} }
@@ -643,7 +643,7 @@ func SkipFlagArgs(args []string) int {
return -1 return -1
} }
func checkFlag(arg string, i *int, verbose, dbg *bool, swflags map[string]bool) { func checkFlag(arg string, i *int, verbose *bool, swflags map[string]bool) {
if pos := strings.IndexByte(arg, '='); pos > 0 { if pos := strings.IndexByte(arg, '='); pos > 0 {
if verbose != nil && arg == "-v=true" { if verbose != nil && arg == "-v=true" {
*verbose = true *verbose = true
@@ -653,8 +653,6 @@ func checkFlag(arg string, i *int, verbose, dbg *bool, swflags map[string]bool)
*i++ *i++
} else if verbose != nil && arg == "-v" { } else if verbose != nil && arg == "-v" {
*verbose = true *verbose = true
} else if dbg != nil && arg == "-dbg" {
*dbg = true
} }
} else { } else {
panic("unknown flag: " + arg) panic("unknown flag: " + arg)

View File

@@ -33,7 +33,7 @@ var (
) )
func Clean(args []string, conf *Config) { func Clean(args []string, conf *Config) {
flags, patterns, verbose, _ := ParseArgs(args, cleanFlags) flags, patterns, verbose := ParseArgs(args, cleanFlags)
cfg := &packages.Config{ cfg := &packages.Config{
Mode: loadSyntax | packages.NeedExportFile, Mode: loadSyntax | packages.NeedExportFile,
BuildFlags: flags, BuildFlags: flags,

View File

@@ -29,9 +29,7 @@ func Init(enableDbg bool) {
llssa.Initialize(llssa.InitAll) llssa.Initialize(llssa.InitAll)
llssa.SetDebug(llssa.DbgFlagAll) llssa.SetDebug(llssa.DbgFlagAll)
cl.SetDebug(cl.DbgFlagAll) cl.SetDebug(cl.DbgFlagAll)
if enableDbg { cl.EnableDebugSymbols(enableDbg)
cl.EnableDebugSymbols()
}
} }
func PkgPath(dir string) string { func PkgPath(dir string) string {