// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// This file implements conversion from old (Go 1.11–Go 1.21) traces to the Go
// 1.22 format.
//
// Most events have direct equivalents in 1.22, at worst requiring arguments to
// be reordered. Some events, such as GoWaiting need to look ahead for follow-up
// events to determine the correct translation. GoSyscall, which is an
// instantaneous event, gets turned into a 1 ns long pair of
// GoSyscallStart+GoSyscallEnd, unless we observe a GoSysBlock, in which case we
// emit a GoSyscallStart+GoSyscallEndBlocked pair with the correct duration
// (i.e. starting at the original GoSyscall).
//
// The resulting trace treats the old trace as a single, large generation,
// sharing a single evTable for all events.
//
// We use a new (compared to what was used for 'go tool trace' in earlier
// versions of Go) parser for old traces that is optimized for speed, low memory
// usage, and minimal GC pressure. It allocates events in batches so that even
// though we have to load the entire trace into memory, the conversion process
// shouldn't result in a doubling of memory usage, even if all converted events
// are kept alive, as we free batches once we're done with them.
//
// The conversion process is lossless.

package trace

import (
	
	
	
	
	
	
)

type oldTraceConverter struct {
	trace          oldtrace.Trace
	evt            *evTable
	preInit        bool
	createdPreInit map[GoID]struct{}
	events         oldtrace.Events
	extra          []Event
	extraArr       [3]Event
	tasks          map[TaskID]taskState
	seenProcs      map[ProcID]struct{}
	lastTs         Time
	procMs         map[ProcID]ThreadID
	lastStwReason  uint64

	inlineToStringID  []uint64
	builtinToStringID []uint64
}

const (
	// Block reasons
	sForever = iota
	sPreempted
	sGosched
	sSleep
	sChanSend
	sChanRecv
	sNetwork
	sSync
	sSyncCond
	sSelect
	sEmpty
	sMarkAssistWait

	// STW kinds
	sSTWUnknown
	sSTWGCMarkTermination
	sSTWGCSweepTermination
	sSTWWriteHeapDump
	sSTWGoroutineProfile
	sSTWGoroutineProfileCleanup
	sSTWAllGoroutinesStackTrace
	sSTWReadMemStats
	sSTWAllThreadsSyscall
	sSTWGOMAXPROCS
	sSTWStartTrace
	sSTWStopTrace
	sSTWCountPagesInUse
	sSTWReadMetricsSlow
	sSTWReadMemStatsSlow
	sSTWPageCachePagesLeaked
	sSTWResetDebugLog

	sLast
)

func ( *oldTraceConverter) ( oldtrace.Trace) error {
	.trace = 
	.preInit = true
	.createdPreInit = make(map[GoID]struct{})
	.evt = &evTable{pcs: make(map[uint64]frame)}
	.events = .Events
	.extra = .extraArr[:0]
	.tasks = make(map[TaskID]taskState)
	.seenProcs = make(map[ProcID]struct{})
	.procMs = make(map[ProcID]ThreadID)
	.lastTs = -1

	 := .evt

	// Convert from oldtracer's Strings map to our dataTable.
	var  uint64
	for ,  := range .Strings {
		.strings.insert(stringID(), )
		if  >  {
			 = 
		}
	}
	.Strings = nil

	// Add all strings used for UserLog. In the old trace format, these were
	// stored inline and didn't have IDs. We generate IDs for them.
	if +uint64(len(.InlineStrings)) <  {
		return errors.New("trace contains too many strings")
	}
	var  error
	 := func( stringID,  string) {
		if  := .strings.insert(, );  != nil &&  == nil {
			 = 
		}
	}
	for ,  := range .InlineStrings {
		 :=  + 1 + uint64()
		.inlineToStringID = append(.inlineToStringID, )
		(stringID(), )
	}
	 += uint64(len(.InlineStrings))
	.InlineStrings = nil

	// Add strings that the converter emits explicitly.
	if +uint64(sLast) <  {
		return errors.New("trace contains too many strings")
	}
	.builtinToStringID = make([]uint64, sLast)
	 := func( int,  string) {
		 :=  + 1 + uint64()
		.builtinToStringID[] = 
		(stringID(), )
	}
	(sForever, "forever")
	(sPreempted, "preempted")
	(sGosched, "runtime.Gosched")
	(sSleep, "sleep")
	(sChanSend, "chan send")
	(sChanRecv, "chan receive")
	(sNetwork, "network")
	(sSync, "sync")
	(sSyncCond, "sync.(*Cond).Wait")
	(sSelect, "select")
	(sEmpty, "")
	(sMarkAssistWait, "GC mark assist wait for work")
	(sSTWUnknown, "")
	(sSTWGCMarkTermination, "GC mark termination")
	(sSTWGCSweepTermination, "GC sweep termination")
	(sSTWWriteHeapDump, "write heap dump")
	(sSTWGoroutineProfile, "goroutine profile")
	(sSTWGoroutineProfileCleanup, "goroutine profile cleanup")
	(sSTWAllGoroutinesStackTrace, "all goroutine stack trace")
	(sSTWReadMemStats, "read mem stats")
	(sSTWAllThreadsSyscall, "AllThreadsSyscall")
	(sSTWGOMAXPROCS, "GOMAXPROCS")
	(sSTWStartTrace, "start trace")
	(sSTWStopTrace, "stop trace")
	(sSTWCountPagesInUse, "CountPagesInUse (test)")
	(sSTWReadMetricsSlow, "ReadMetricsSlow (test)")
	(sSTWReadMemStatsSlow, "ReadMemStatsSlow (test)")
	(sSTWPageCachePagesLeaked, "PageCachePagesLeaked (test)")
	(sSTWResetDebugLog, "ResetDebugLog (test)")

	if  != nil {
		// This should be impossible but let's be safe.
		return fmt.Errorf("couldn't add strings: %w", )
	}

	.evt.strings.compactify()

	// Convert stacks.
	for ,  := range .Stacks {
		.stacks.insert(stackID(), stack{pcs: })
	}

	// OPT(dh): if we could share the frame type between this package and
	// oldtrace we wouldn't have to copy the map.
	for ,  := range .PCs {
		.pcs[] = frame{
			pc:     ,
			funcID: stringID(.Fn),
			fileID: stringID(.File),
			line:   uint64(.Line),
		}
	}
	.Stacks = nil
	.PCs = nil
	.stacks.compactify()
	return nil
}

// next returns the next event, io.EOF if there are no more events, or a
// descriptive error for invalid events.
func ( *oldTraceConverter) () (Event, error) {
	if len(.extra) > 0 {
		 := .extra[0]
		.extra = .extra[1:]

		if len(.extra) == 0 {
			.extra = .extraArr[:0]
		}
		// Two events aren't allowed to fall on the same timestamp in the new API,
		// but this may happen when we produce EvGoStatus events
		if .base.time <= .lastTs {
			.base.time = .lastTs + 1
		}
		.lastTs = .base.time
		return , nil
	}

	,  := .events.Pop()
	if ! {
		return Event{}, io.EOF
	}

	,  := .convertEvent()

	if  == errSkip {
		return .()
	} else if  != nil {
		return Event{}, 
	}

	// Two events aren't allowed to fall on the same timestamp in the new API,
	// but this may happen when we produce EvGoStatus events
	if .base.time <= .lastTs {
		.base.time = .lastTs + 1
	}
	.lastTs = .base.time
	return , nil
}

var errSkip = errors.New("skip event")

// convertEvent converts an event from the old trace format to zero or more
// events in the new format. Most events translate 1 to 1. Some events don't
// result in an event right away, in which case convertEvent returns errSkip.
// Some events result in more than one new event; in this case, convertEvent
// returns the first event and stores additional events in it.extra. When
// encountering events that oldtrace shouldn't be able to emit, ocnvertEvent
// returns a descriptive error.
func ( *oldTraceConverter) ( *oldtrace.Event) ( Event,  error) {
	var  event.Type
	var  timedEventArgs
	copy([:], .Args[:])

	switch .Type {
	case oldtrace.EvGomaxprocs:
		 = go122.EvProcsChange
		if .preInit {
			// The first EvGomaxprocs signals the end of trace initialization. At this point we've seen
			// all goroutines that already existed at trace begin.
			.preInit = false
			for  := range .createdPreInit {
				// These are goroutines that already existed when tracing started but for which we
				// received neither GoWaiting, GoInSyscall, or GoStart. These are goroutines that are in
				// the states _Gidle or _Grunnable.
				.extra = append(.extra, Event{
					ctx: schedCtx{
						// G: GoID(gid),
						G: NoGoroutine,
						P: NoProc,
						M: NoThread,
					},
					table: .evt,
					base: baseEvent{
						typ:  go122.EvGoStatus,
						time: Time(.Ts),
						args: timedEventArgs{uint64(), ^uint64(0), uint64(go122.GoRunnable)},
					},
				})
			}
			.createdPreInit = nil
			return Event{}, errSkip
		}
	case oldtrace.EvProcStart:
		.procMs[ProcID(.P)] = ThreadID(.Args[0])
		if ,  := .seenProcs[ProcID(.P)];  {
			 = go122.EvProcStart
			 = timedEventArgs{uint64(.P)}
		} else {
			.seenProcs[ProcID(.P)] = struct{}{}
			 = go122.EvProcStatus
			 = timedEventArgs{uint64(.P), uint64(go122.ProcRunning)}
		}
	case oldtrace.EvProcStop:
		if ,  := .seenProcs[ProcID(.P)];  {
			 = go122.EvProcStop
			 = timedEventArgs{uint64(.P)}
		} else {
			.seenProcs[ProcID(.P)] = struct{}{}
			 = go122.EvProcStatus
			 = timedEventArgs{uint64(.P), uint64(go122.ProcIdle)}
		}
	case oldtrace.EvGCStart:
		 = go122.EvGCBegin
	case oldtrace.EvGCDone:
		 = go122.EvGCEnd
	case oldtrace.EvSTWStart:
		 := .builtinToStringID[sSTWUnknown+.trace.STWReason(.Args[0])]
		.lastStwReason = 
		 = go122.EvSTWBegin
		 = timedEventArgs{uint64()}
	case oldtrace.EvSTWDone:
		 = go122.EvSTWEnd
		 = timedEventArgs{.lastStwReason}
	case oldtrace.EvGCSweepStart:
		 = go122.EvGCSweepBegin
	case oldtrace.EvGCSweepDone:
		 = go122.EvGCSweepEnd
	case oldtrace.EvGoCreate:
		if .preInit {
			.createdPreInit[GoID(.Args[0])] = struct{}{}
			return Event{}, errSkip
		}
		 = go122.EvGoCreate
	case oldtrace.EvGoStart:
		if .preInit {
			 = go122.EvGoStatus
			 = timedEventArgs{.Args[0], ^uint64(0), uint64(go122.GoRunning)}
			delete(.createdPreInit, GoID(.Args[0]))
		} else {
			 = go122.EvGoStart
		}
	case oldtrace.EvGoStartLabel:
		.extra = []Event{{
			ctx: schedCtx{
				G: GoID(.G),
				P: ProcID(.P),
				M: .procMs[ProcID(.P)],
			},
			table: .evt,
			base: baseEvent{
				typ:  go122.EvGoLabel,
				time: Time(.Ts),
				args: timedEventArgs{.Args[2]},
			},
		}}
		return Event{
			ctx: schedCtx{
				G: GoID(.G),
				P: ProcID(.P),
				M: .procMs[ProcID(.P)],
			},
			table: .evt,
			base: baseEvent{
				typ:  go122.EvGoStart,
				time: Time(.Ts),
				args: ,
			},
		}, nil
	case oldtrace.EvGoEnd:
		 = go122.EvGoDestroy
	case oldtrace.EvGoStop:
		 = go122.EvGoBlock
		 = timedEventArgs{uint64(.builtinToStringID[sForever]), uint64(.StkID)}
	case oldtrace.EvGoSched:
		 = go122.EvGoStop
		 = timedEventArgs{uint64(.builtinToStringID[sGosched]), uint64(.StkID)}
	case oldtrace.EvGoPreempt:
		 = go122.EvGoStop
		 = timedEventArgs{uint64(.builtinToStringID[sPreempted]), uint64(.StkID)}
	case oldtrace.EvGoSleep:
		 = go122.EvGoBlock
		 = timedEventArgs{uint64(.builtinToStringID[sSleep]), uint64(.StkID)}
	case oldtrace.EvGoBlock:
		 = go122.EvGoBlock
		 = timedEventArgs{uint64(.builtinToStringID[sEmpty]), uint64(.StkID)}
	case oldtrace.EvGoUnblock:
		 = go122.EvGoUnblock
	case oldtrace.EvGoBlockSend:
		 = go122.EvGoBlock
		 = timedEventArgs{uint64(.builtinToStringID[sChanSend]), uint64(.StkID)}
	case oldtrace.EvGoBlockRecv:
		 = go122.EvGoBlock
		 = timedEventArgs{uint64(.builtinToStringID[sChanRecv]), uint64(.StkID)}
	case oldtrace.EvGoBlockSelect:
		 = go122.EvGoBlock
		 = timedEventArgs{uint64(.builtinToStringID[sSelect]), uint64(.StkID)}
	case oldtrace.EvGoBlockSync:
		 = go122.EvGoBlock
		 = timedEventArgs{uint64(.builtinToStringID[sSync]), uint64(.StkID)}
	case oldtrace.EvGoBlockCond:
		 = go122.EvGoBlock
		 = timedEventArgs{uint64(.builtinToStringID[sSyncCond]), uint64(.StkID)}
	case oldtrace.EvGoBlockNet:
		 = go122.EvGoBlock
		 = timedEventArgs{uint64(.builtinToStringID[sNetwork]), uint64(.StkID)}
	case oldtrace.EvGoBlockGC:
		 = go122.EvGoBlock
		 = timedEventArgs{uint64(.builtinToStringID[sMarkAssistWait]), uint64(.StkID)}
	case oldtrace.EvGoSysCall:
		// Look for the next event for the same G to determine if the syscall
		// blocked.
		 := false
		.events.All()(func( *oldtrace.Event) bool {
			if .G != .G {
				return true
			}
			// After an EvGoSysCall, the next event on the same G will either be
			// EvGoSysBlock to denote a blocking syscall, or some other event
			// (or the end of the trace) if the syscall didn't block.
			if .Type == oldtrace.EvGoSysBlock {
				 = true
			}
			return false
		})
		if  {
			 = go122.EvGoSyscallBegin
			 = timedEventArgs{1: uint64(.StkID)}
		} else {
			// Convert the old instantaneous syscall event to a pair of syscall
			// begin and syscall end and give it the shortest possible duration,
			// 1ns.
			 := Event{
				ctx: schedCtx{
					G: GoID(.G),
					P: ProcID(.P),
					M: .procMs[ProcID(.P)],
				},
				table: .evt,
				base: baseEvent{
					typ:  go122.EvGoSyscallBegin,
					time: Time(.Ts),
					args: timedEventArgs{1: uint64(.StkID)},
				},
			}

			 := Event{
				ctx:   .ctx,
				table: .evt,
				base: baseEvent{
					typ:  go122.EvGoSyscallEnd,
					time: Time(.Ts + 1),
					args: timedEventArgs{},
				},
			}

			.extra = append(.extra, )
			return , nil
		}

	case oldtrace.EvGoSysExit:
		 = go122.EvGoSyscallEndBlocked
	case oldtrace.EvGoSysBlock:
		return Event{}, errSkip
	case oldtrace.EvGoWaiting:
		 = go122.EvGoStatus
		 = timedEventArgs{.Args[0], ^uint64(0), uint64(go122.GoWaiting)}
		delete(.createdPreInit, GoID(.Args[0]))
	case oldtrace.EvGoInSyscall:
		 = go122.EvGoStatus
		// In the new tracer, GoStatus with GoSyscall knows what thread the
		// syscall is on. In the old tracer, EvGoInSyscall doesn't contain that
		// information and all we can do here is specify NoThread.
		 = timedEventArgs{.Args[0], ^uint64(0), uint64(go122.GoSyscall)}
		delete(.createdPreInit, GoID(.Args[0]))
	case oldtrace.EvHeapAlloc:
		 = go122.EvHeapAlloc
	case oldtrace.EvHeapGoal:
		 = go122.EvHeapGoal
	case oldtrace.EvGCMarkAssistStart:
		 = go122.EvGCMarkAssistBegin
	case oldtrace.EvGCMarkAssistDone:
		 = go122.EvGCMarkAssistEnd
	case oldtrace.EvUserTaskCreate:
		 = go122.EvUserTaskBegin
		 := .Args[1]
		if  == 0 {
			 = uint64(NoTask)
		}
		 = timedEventArgs{.Args[0], , .Args[2], uint64(.StkID)}
		,  := .evt.strings.get(stringID(.Args[2]))
		.tasks[TaskID(.Args[0])] = taskState{name: , parentID: TaskID(.Args[1])}
	case oldtrace.EvUserTaskEnd:
		 = go122.EvUserTaskEnd
		// Event.Task expects the parent and name to be smuggled in extra args
		// and as extra strings.
		,  := .tasks[TaskID(.Args[0])]
		if  {
			delete(.tasks, TaskID(.Args[0]))
			 = timedEventArgs{
				.Args[0],
				.Args[1],
				uint64(.parentID),
				uint64(.evt.addExtraString(.name)),
			}
		} else {
			 = timedEventArgs{.Args[0], .Args[1], uint64(NoTask), uint64(.evt.addExtraString(""))}
		}
	case oldtrace.EvUserRegion:
		switch .Args[1] {
		case 0: // start
			 = go122.EvUserRegionBegin
		case 1: // end
			 = go122.EvUserRegionEnd
		}
		 = timedEventArgs{.Args[0], .Args[2], uint64(.StkID)}
	case oldtrace.EvUserLog:
		 = go122.EvUserLog
		 = timedEventArgs{.Args[0], .Args[1], .inlineToStringID[.Args[3]], uint64(.StkID)}
	case oldtrace.EvCPUSample:
		 = go122.EvCPUSample
		// When emitted by the Go 1.22 tracer, CPU samples have 5 arguments:
		// timestamp, M, P, G, stack. However, after they get turned into Event,
		// they have the arguments stack, M, P, G.
		//
		// In Go 1.21, CPU samples did not have Ms.
		 = timedEventArgs{uint64(.StkID), ^uint64(0), uint64(.P), .G}
	default:
		return Event{}, fmt.Errorf("unexpected event type %v", .Type)
	}

	if oldtrace.EventDescriptions[.Type].Stack {
		if  := go122.Specs()[].StackIDs; len() > 0 {
			[[0]-1] = uint64(.StkID)
		}
	}

	 := NoThread
	if .P != -1 && .Type != oldtrace.EvCPUSample {
		if ,  := .procMs[ProcID(.P)];  {
			 = ThreadID()
		}
	}
	if .Type == oldtrace.EvProcStop {
		delete(.procMs, ProcID(.P))
	}
	 := GoID(.G)
	if  == 0 {
		 = NoGoroutine
	}
	 := Event{
		ctx: schedCtx{
			G: GoID(),
			P: ProcID(.P),
			M: ,
		},
		table: .evt,
		base: baseEvent{
			typ:  ,
			time: Time(.Ts),
			args: ,
		},
	}
	return , nil
}

// convertOldFormat takes a fully loaded trace in the old trace format and
// returns an iterator over events in the new format.
func convertOldFormat( oldtrace.Trace) *oldTraceConverter {
	 := &oldTraceConverter{}
	.init()
	return 
}