// 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 v1 (Go 1.11–Go 1.21) traces to the v2
// format (Go 1.22+).
//
// Most events have direct equivalents in v2, 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 trace v1 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 v1 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 traceV1Converter struct {
	trace          tracev1.Trace
	evt            *evTable
	preInit        bool
	createdPreInit map[GoID]struct{}
	events         tracev1.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 ( *traceV1Converter) ( tracev1.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 trace v1'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 trace v1 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
	// tracev1 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 ( *traceV1Converter) () (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 trace v1 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 tracev1 shouldn't be able to emit, ocnvertEvent
// returns a descriptive error.
func ( *traceV1Converter) ( *tracev1.Event) ( Event,  error) {
	var  tracev2.EventType
	var  timedEventArgs
	copy([:], .Args[:])

	switch .Type {
	case tracev1.EvGomaxprocs:
		 = tracev2.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:  tracev2.EvGoStatus,
						time: Time(.Ts),
						args: timedEventArgs{uint64(), ^uint64(0), uint64(tracev2.GoRunnable)},
					},
				})
			}
			.createdPreInit = nil
			return Event{}, errSkip
		}
	case tracev1.EvProcStart:
		.procMs[ProcID(.P)] = ThreadID(.Args[0])
		if ,  := .seenProcs[ProcID(.P)];  {
			 = tracev2.EvProcStart
			 = timedEventArgs{uint64(.P)}
		} else {
			.seenProcs[ProcID(.P)] = struct{}{}
			 = tracev2.EvProcStatus
			 = timedEventArgs{uint64(.P), uint64(tracev2.ProcRunning)}
		}
	case tracev1.EvProcStop:
		if ,  := .seenProcs[ProcID(.P)];  {
			 = tracev2.EvProcStop
			 = timedEventArgs{uint64(.P)}
		} else {
			.seenProcs[ProcID(.P)] = struct{}{}
			 = tracev2.EvProcStatus
			 = timedEventArgs{uint64(.P), uint64(tracev2.ProcIdle)}
		}
	case tracev1.EvGCStart:
		 = tracev2.EvGCBegin
	case tracev1.EvGCDone:
		 = tracev2.EvGCEnd
	case tracev1.EvSTWStart:
		 := .builtinToStringID[sSTWUnknown+.trace.STWReason(.Args[0])]
		.lastStwReason = 
		 = tracev2.EvSTWBegin
		 = timedEventArgs{uint64()}
	case tracev1.EvSTWDone:
		 = tracev2.EvSTWEnd
		 = timedEventArgs{.lastStwReason}
	case tracev1.EvGCSweepStart:
		 = tracev2.EvGCSweepBegin
	case tracev1.EvGCSweepDone:
		 = tracev2.EvGCSweepEnd
	case tracev1.EvGoCreate:
		if .preInit {
			.createdPreInit[GoID(.Args[0])] = struct{}{}
			return Event{}, errSkip
		}
		 = tracev2.EvGoCreate
	case tracev1.EvGoStart:
		if .preInit {
			 = tracev2.EvGoStatus
			 = timedEventArgs{.Args[0], ^uint64(0), uint64(tracev2.GoRunning)}
			delete(.createdPreInit, GoID(.Args[0]))
		} else {
			 = tracev2.EvGoStart
		}
	case tracev1.EvGoStartLabel:
		.extra = []Event{{
			ctx: schedCtx{
				G: GoID(.G),
				P: ProcID(.P),
				M: .procMs[ProcID(.P)],
			},
			table: .evt,
			base: baseEvent{
				typ:  tracev2.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:  tracev2.EvGoStart,
				time: Time(.Ts),
				args: ,
			},
		}, nil
	case tracev1.EvGoEnd:
		 = tracev2.EvGoDestroy
	case tracev1.EvGoStop:
		 = tracev2.EvGoBlock
		 = timedEventArgs{uint64(.builtinToStringID[sForever]), uint64(.StkID)}
	case tracev1.EvGoSched:
		 = tracev2.EvGoStop
		 = timedEventArgs{uint64(.builtinToStringID[sGosched]), uint64(.StkID)}
	case tracev1.EvGoPreempt:
		 = tracev2.EvGoStop
		 = timedEventArgs{uint64(.builtinToStringID[sPreempted]), uint64(.StkID)}
	case tracev1.EvGoSleep:
		 = tracev2.EvGoBlock
		 = timedEventArgs{uint64(.builtinToStringID[sSleep]), uint64(.StkID)}
	case tracev1.EvGoBlock:
		 = tracev2.EvGoBlock
		 = timedEventArgs{uint64(.builtinToStringID[sEmpty]), uint64(.StkID)}
	case tracev1.EvGoUnblock:
		 = tracev2.EvGoUnblock
	case tracev1.EvGoBlockSend:
		 = tracev2.EvGoBlock
		 = timedEventArgs{uint64(.builtinToStringID[sChanSend]), uint64(.StkID)}
	case tracev1.EvGoBlockRecv:
		 = tracev2.EvGoBlock
		 = timedEventArgs{uint64(.builtinToStringID[sChanRecv]), uint64(.StkID)}
	case tracev1.EvGoBlockSelect:
		 = tracev2.EvGoBlock
		 = timedEventArgs{uint64(.builtinToStringID[sSelect]), uint64(.StkID)}
	case tracev1.EvGoBlockSync:
		 = tracev2.EvGoBlock
		 = timedEventArgs{uint64(.builtinToStringID[sSync]), uint64(.StkID)}
	case tracev1.EvGoBlockCond:
		 = tracev2.EvGoBlock
		 = timedEventArgs{uint64(.builtinToStringID[sSyncCond]), uint64(.StkID)}
	case tracev1.EvGoBlockNet:
		 = tracev2.EvGoBlock
		 = timedEventArgs{uint64(.builtinToStringID[sNetwork]), uint64(.StkID)}
	case tracev1.EvGoBlockGC:
		 = tracev2.EvGoBlock
		 = timedEventArgs{uint64(.builtinToStringID[sMarkAssistWait]), uint64(.StkID)}
	case tracev1.EvGoSysCall:
		// Look for the next event for the same G to determine if the syscall
		// blocked.
		 := false
		.events.All()(func( *tracev1.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 == tracev1.EvGoSysBlock {
				 = true
			}
			return false
		})
		if  {
			 = tracev2.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:  tracev2.EvGoSyscallBegin,
					time: Time(.Ts),
					args: timedEventArgs{1: uint64(.StkID)},
				},
			}

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

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

	case tracev1.EvGoSysExit:
		 = tracev2.EvGoSyscallEndBlocked
	case tracev1.EvGoSysBlock:
		return Event{}, errSkip
	case tracev1.EvGoWaiting:
		 = tracev2.EvGoStatus
		 = timedEventArgs{.Args[0], ^uint64(0), uint64(tracev2.GoWaiting)}
		delete(.createdPreInit, GoID(.Args[0]))
	case tracev1.EvGoInSyscall:
		 = tracev2.EvGoStatus
		// In the new tracer, GoStatus with GoSyscall knows what thread the
		// syscall is on. In trace v1, EvGoInSyscall doesn't contain that
		// information and all we can do here is specify NoThread.
		 = timedEventArgs{.Args[0], ^uint64(0), uint64(tracev2.GoSyscall)}
		delete(.createdPreInit, GoID(.Args[0]))
	case tracev1.EvHeapAlloc:
		 = tracev2.EvHeapAlloc
	case tracev1.EvHeapGoal:
		 = tracev2.EvHeapGoal
	case tracev1.EvGCMarkAssistStart:
		 = tracev2.EvGCMarkAssistBegin
	case tracev1.EvGCMarkAssistDone:
		 = tracev2.EvGCMarkAssistEnd
	case tracev1.EvUserTaskCreate:
		 = tracev2.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 tracev1.EvUserTaskEnd:
		 = tracev2.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 tracev1.EvUserRegion:
		switch .Args[1] {
		case 0: // start
			 = tracev2.EvUserRegionBegin
		case 1: // end
			 = tracev2.EvUserRegionEnd
		}
		 = timedEventArgs{.Args[0], .Args[2], uint64(.StkID)}
	case tracev1.EvUserLog:
		 = tracev2.EvUserLog
		 = timedEventArgs{.Args[0], .Args[1], .inlineToStringID[.Args[3]], uint64(.StkID)}
	case tracev1.EvCPUSample:
		 = tracev2.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 tracev1.EventDescriptions[.Type].Stack {
		if  := tracev2.Specs()[].StackIDs; len() > 0 {
			[[0]-1] = uint64(.StkID)
		}
	}

	 := NoThread
	if .P != -1 && .Type != tracev1.EvCPUSample {
		if ,  := .procMs[ProcID(.P)];  {
			 = ThreadID()
		}
	}
	if .Type == tracev1.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
}

// convertV1Trace takes a fully loaded trace in the v1 trace format and
// returns an iterator over events in the new format.
func convertV1Trace( tracev1.Trace) *traceV1Converter {
	 := &traceV1Converter{}
	.init()
	return 
}