# Unless explicitly stated otherwise all files in this repository are licensed
# under the Apache License Version 2.0.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2023-present Datadog, Inc.
---
# yaml-language-server: $schema=https://datadoghq.dev/orchestrion/schema.json
meta:
  name: github.com/DataDog/dd-trace-go/v2/internal/orchestrion
  description: Operations that interact with Go's runtime system.
  caveats: |-
    This configuration introduces a way to access the Goroutine Local Storage (GLS), which is not
    meant to be used directly by end-users. This is intended to be used only by tracer internals to
    enable trace context forwarding in places where a {{<godoc import-path="context" name="Context">}}
    value is not available.

aspects:
  - id: __dd_gls_v2
    join-point:
      struct-definition: runtime.g
    advice:
      - add-struct-field:
          name: __dd_gls_v2
          type: any
      - add-blank-import: unsafe # Needed for go:linkname
      - inject-declarations:
          # Reference: https://github.com/golang/go/blob/6d89b38ed86e0bfa0ddaba08dc4071e6bb300eea/src/runtime/HACKING.md?plain=1#L44-L54
          template: |-
            //go:linkname __dd_orchestrion_gls_get __dd_orchestrion_gls_get.V2
            var __dd_orchestrion_gls_get = func() any {
              return getg().m.curg.__dd_gls_v2
            }

            //go:linkname __dd_orchestrion_gls_set __dd_orchestrion_gls_set.V2
            var __dd_orchestrion_gls_set = func(val any) {
              getg().m.curg.__dd_gls_v2 = val
            }
  - id: goexit1
    join-point:
      all-of:
        - import-path: runtime
        - function-body:
            function:
              # This is the function that finishes the execution of a goroutine.
              # See: https://github.com/golang/go/blob/f38d42f2c4c6ad0d7cbdad5e1417cac3be2a5dcb/src/runtime/proc.go#L4264
              - name: goexit1
    advice:
      - prepend-statements:
          template: getg().__dd_gls_v2 = nil
