text
stringlengths
2
1.1M
id
stringlengths
11
117
metadata
dict
__index_level_0__
int64
0
885
// Copyright 2017 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. package trace import ( "container/heap" "math" "sort" "strings" "time" ) // MutatorUtil is a change in mutator utilization at a particular // time. Mutator utilization functions are represented as a // time-ordered []MutatorUtil. type MutatorUtil struct { Time int64 // Util is the mean mutator utilization starting at Time. This // is in the range [0, 1]. Util float64 } // UtilFlags controls the behavior of MutatorUtilization. type UtilFlags int const ( // UtilSTW means utilization should account for STW events. // This includes non-GC STW events, which are typically user-requested. UtilSTW UtilFlags = 1 << iota // UtilBackground means utilization should account for // background mark workers. UtilBackground // UtilAssist means utilization should account for mark // assists. UtilAssist // UtilSweep means utilization should account for sweeping. UtilSweep // UtilPerProc means each P should be given a separate // utilization function. Otherwise, there is a single function // and each P is given a fraction of the utilization. UtilPerProc ) // MutatorUtilizationV2 returns a set of mutator utilization functions // for the given v2 trace, passed as an io.Reader. Each function will // always end with 0 utilization. The bounds of each function are implicit // in the first and last event; outside of these bounds each function is // undefined. // // If the UtilPerProc flag is not given, this always returns a single // utilization function. Otherwise, it returns one function per P. func MutatorUtilizationV2(events []Event, flags UtilFlags) [][]MutatorUtil { // Set up a bunch of analysis state. type perP struct { // gc > 0 indicates that GC is active on this P. gc int // series the logical series number for this P. This // is necessary because Ps may be removed and then // re-added, and then the new P needs a new series. series int } type procsCount struct { // time at which procs changed. time int64 // n is the number of procs at that point. n int } out := [][]MutatorUtil{} stw := 0 ps := []perP{} inGC := make(map[GoID]bool) states := make(map[GoID]GoState) bgMark := make(map[GoID]bool) procs := []procsCount{} seenSync := false // Helpers. handleSTW := func(r Range) bool { return flags&UtilSTW != 0 && isGCSTW(r) } handleMarkAssist := func(r Range) bool { return flags&UtilAssist != 0 && isGCMarkAssist(r) } handleSweep := func(r Range) bool { return flags&UtilSweep != 0 && isGCSweep(r) } // Iterate through the trace, tracking mutator utilization. var lastEv *Event for i := range events { ev := &events[i] lastEv = ev // Process the event. switch ev.Kind() { case EventSync: seenSync = true case EventMetric: m := ev.Metric() if m.Name != "/sched/gomaxprocs:threads" { break } gomaxprocs := int(m.Value.Uint64()) if len(ps) > gomaxprocs { if flags&UtilPerProc != 0 { // End each P's series. for _, p := range ps[gomaxprocs:] { out[p.series] = addUtil(out[p.series], MutatorUtil{int64(ev.Time()), 0}) } } ps = ps[:gomaxprocs] } for len(ps) < gomaxprocs { // Start new P's series. series := 0 if flags&UtilPerProc != 0 || len(out) == 0 { series = len(out) out = append(out, []MutatorUtil{{int64(ev.Time()), 1}}) } ps = append(ps, perP{series: series}) } if len(procs) == 0 || gomaxprocs != procs[len(procs)-1].n { procs = append(procs, procsCount{time: int64(ev.Time()), n: gomaxprocs}) } } if len(ps) == 0 { // We can't start doing any analysis until we see what GOMAXPROCS is. // It will show up very early in the trace, but we need to be robust to // something else being emitted beforehand. continue } switch ev.Kind() { case EventRangeActive: if seenSync { // If we've seen a sync, then we can be sure we're not finding out about // something late; we have complete information after that point, and these // active events will just be redundant. break } // This range is active back to the start of the trace. We're failing to account // for this since we just found out about it now. Fix up the mutator utilization. // // N.B. A trace can't start during a STW, so we don't handle it here. r := ev.Range() switch { case handleMarkAssist(r): if !states[ev.Goroutine()].Executing() { // If the goroutine isn't executing, then the fact that it was in mark // assist doesn't actually count. break } // This G has been in a mark assist *and running on its P* since the start // of the trace. fallthrough case handleSweep(r): // This P has been in sweep (or mark assist, from above) in the start of the trace. // // We don't need to do anything if UtilPerProc is set. If we get an event like // this for a running P, it must show up the first time a P is mentioned. Therefore, // this P won't actually have any MutatorUtils on its list yet. // // However, if UtilPerProc isn't set, then we probably have data from other procs // and from previous events. We need to fix that up. if flags&UtilPerProc != 0 { break } // Subtract out 1/gomaxprocs mutator utilization for all time periods // from the beginning of the trace until now. mi, pi := 0, 0 for mi < len(out[0]) { if pi < len(procs)-1 && procs[pi+1].time < out[0][mi].Time { pi++ continue } out[0][mi].Util -= float64(1) / float64(procs[pi].n) if out[0][mi].Util < 0 { out[0][mi].Util = 0 } mi++ } } // After accounting for the portion we missed, this just acts like the // beginning of a new range. fallthrough case EventRangeBegin: r := ev.Range() if handleSTW(r) { stw++ } else if handleSweep(r) { ps[ev.Proc()].gc++ } else if handleMarkAssist(r) { ps[ev.Proc()].gc++ if g := r.Scope.Goroutine(); g != NoGoroutine { inGC[g] = true } } case EventRangeEnd: r := ev.Range() if handleSTW(r) { stw-- } else if handleSweep(r) { ps[ev.Proc()].gc-- } else if handleMarkAssist(r) { ps[ev.Proc()].gc-- if g := r.Scope.Goroutine(); g != NoGoroutine { delete(inGC, g) } } case EventStateTransition: st := ev.StateTransition() if st.Resource.Kind != ResourceGoroutine { break } old, new := st.Goroutine() g := st.Resource.Goroutine() if inGC[g] || bgMark[g] { if !old.Executing() && new.Executing() { // Started running while doing GC things. ps[ev.Proc()].gc++ } else if old.Executing() && !new.Executing() { // Stopped running while doing GC things. ps[ev.Proc()].gc-- } } states[g] = new case EventLabel: l := ev.Label() if flags&UtilBackground != 0 && strings.HasPrefix(l.Label, "GC ") && l.Label != "GC (idle)" { // Background mark worker. // // If we're in per-proc mode, we don't // count dedicated workers because // they kick all of the goroutines off // that P, so don't directly // contribute to goroutine latency. if !(flags&UtilPerProc != 0 && l.Label == "GC (dedicated)") { bgMark[ev.Goroutine()] = true ps[ev.Proc()].gc++ } } } if flags&UtilPerProc == 0 { // Compute the current average utilization. if len(ps) == 0 { continue } gcPs := 0 if stw > 0 { gcPs = len(ps) } else { for i := range ps { if ps[i].gc > 0 { gcPs++ } } } mu := MutatorUtil{int64(ev.Time()), 1 - float64(gcPs)/float64(len(ps))} // Record the utilization change. (Since // len(ps) == len(out), we know len(out) > 0.) out[0] = addUtil(out[0], mu) } else { // Check for per-P utilization changes. for i := range ps { p := &ps[i] util := 1.0 if stw > 0 || p.gc > 0 { util = 0.0 } out[p.series] = addUtil(out[p.series], MutatorUtil{int64(ev.Time()), util}) } } } // No events in the stream. if lastEv == nil { return nil } // Add final 0 utilization event to any remaining series. This // is important to mark the end of the trace. The exact value // shouldn't matter since no window should extend beyond this, // but using 0 is symmetric with the start of the trace. mu := MutatorUtil{int64(lastEv.Time()), 0} for i := range ps { out[ps[i].series] = addUtil(out[ps[i].series], mu) } return out } func addUtil(util []MutatorUtil, mu MutatorUtil) []MutatorUtil { if len(util) > 0 { if mu.Util == util[len(util)-1].Util { // No change. return util } if mu.Time == util[len(util)-1].Time { // Take the lowest utilization at a time stamp. if mu.Util < util[len(util)-1].Util { util[len(util)-1] = mu } return util } } return append(util, mu) } // totalUtil is total utilization, measured in nanoseconds. This is a // separate type primarily to distinguish it from mean utilization, // which is also a float64. type totalUtil float64 func totalUtilOf(meanUtil float64, dur int64) totalUtil { return totalUtil(meanUtil * float64(dur)) } // mean returns the mean utilization over dur. func (u totalUtil) mean(dur time.Duration) float64 { return float64(u) / float64(dur) } // An MMUCurve is the minimum mutator utilization curve across // multiple window sizes. type MMUCurve struct { series []mmuSeries } type mmuSeries struct { util []MutatorUtil // sums[j] is the cumulative sum of util[:j]. sums []totalUtil // bands summarizes util in non-overlapping bands of duration // bandDur. bands []mmuBand // bandDur is the duration of each band. bandDur int64 } type mmuBand struct { // minUtil is the minimum instantaneous mutator utilization in // this band. minUtil float64 // cumUtil is the cumulative total mutator utilization between // time 0 and the left edge of this band. cumUtil totalUtil // integrator is the integrator for the left edge of this // band. integrator integrator } // NewMMUCurve returns an MMU curve for the given mutator utilization // function. func NewMMUCurve(utils [][]MutatorUtil) *MMUCurve { series := make([]mmuSeries, len(utils)) for i, util := range utils { series[i] = newMMUSeries(util) } return &MMUCurve{series} } // bandsPerSeries is the number of bands to divide each series into. // This is only changed by tests. var bandsPerSeries = 1000 func newMMUSeries(util []MutatorUtil) mmuSeries { // Compute cumulative sum. sums := make([]totalUtil, len(util)) var prev MutatorUtil var sum totalUtil for j, u := range util { sum += totalUtilOf(prev.Util, u.Time-prev.Time) sums[j] = sum prev = u } // Divide the utilization curve up into equal size // non-overlapping "bands" and compute a summary for each of // these bands. // // Compute the duration of each band. numBands := bandsPerSeries if numBands > len(util) { // There's no point in having lots of bands if there // aren't many events. numBands = len(util) } dur := util[len(util)-1].Time - util[0].Time bandDur := (dur + int64(numBands) - 1) / int64(numBands) if bandDur < 1 { bandDur = 1 } // Compute the bands. There are numBands+1 bands in order to // record the final cumulative sum. bands := make([]mmuBand, numBands+1) s := mmuSeries{util, sums, bands, bandDur} leftSum := integrator{&s, 0} for i := range bands { startTime, endTime := s.bandTime(i) cumUtil := leftSum.advance(startTime) predIdx := leftSum.pos minUtil := 1.0 for i := predIdx; i < len(util) && util[i].Time < endTime; i++ { minUtil = math.Min(minUtil, util[i].Util) } bands[i] = mmuBand{minUtil, cumUtil, leftSum} } return s } func (s *mmuSeries) bandTime(i int) (start, end int64) { start = int64(i)*s.bandDur + s.util[0].Time end = start + s.bandDur return } type bandUtil struct { // Utilization series index series int // Band index i int // Lower bound of mutator utilization for all windows // with a left edge in this band. utilBound float64 } type bandUtilHeap []bandUtil func (h bandUtilHeap) Len() int { return len(h) } func (h bandUtilHeap) Less(i, j int) bool { return h[i].utilBound < h[j].utilBound } func (h bandUtilHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *bandUtilHeap) Push(x any) { *h = append(*h, x.(bandUtil)) } func (h *bandUtilHeap) Pop() any { x := (*h)[len(*h)-1] *h = (*h)[:len(*h)-1] return x } // UtilWindow is a specific window at Time. type UtilWindow struct { Time int64 // MutatorUtil is the mean mutator utilization in this window. MutatorUtil float64 } type utilHeap []UtilWindow func (h utilHeap) Len() int { return len(h) } func (h utilHeap) Less(i, j int) bool { if h[i].MutatorUtil != h[j].MutatorUtil { return h[i].MutatorUtil > h[j].MutatorUtil } return h[i].Time > h[j].Time } func (h utilHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *utilHeap) Push(x any) { *h = append(*h, x.(UtilWindow)) } func (h *utilHeap) Pop() any { x := (*h)[len(*h)-1] *h = (*h)[:len(*h)-1] return x } // An accumulator takes a windowed mutator utilization function and // tracks various statistics for that function. type accumulator struct { mmu float64 // bound is the mutator utilization bound where adding any // mutator utilization above this bound cannot affect the // accumulated statistics. bound float64 // Worst N window tracking nWorst int wHeap utilHeap // Mutator utilization distribution tracking mud *mud // preciseMass is the distribution mass that must be precise // before accumulation is stopped. preciseMass float64 // lastTime and lastMU are the previous point added to the // windowed mutator utilization function. lastTime int64 lastMU float64 } // resetTime declares a discontinuity in the windowed mutator // utilization function by resetting the current time. func (acc *accumulator) resetTime() { // This only matters for distribution collection, since that's // the only thing that depends on the progression of the // windowed mutator utilization function. acc.lastTime = math.MaxInt64 } // addMU adds a point to the windowed mutator utilization function at // (time, mu). This must be called for monotonically increasing values // of time. // // It returns true if further calls to addMU would be pointless. func (acc *accumulator) addMU(time int64, mu float64, window time.Duration) bool { if mu < acc.mmu { acc.mmu = mu } acc.bound = acc.mmu if acc.nWorst == 0 { // If the minimum has reached zero, it can't go any // lower, so we can stop early. return mu == 0 } // Consider adding this window to the n worst. if len(acc.wHeap) < acc.nWorst || mu < acc.wHeap[0].MutatorUtil { // This window is lower than the K'th worst window. // // Check if there's any overlapping window // already in the heap and keep whichever is // worse. for i, ui := range acc.wHeap { if time+int64(window) > ui.Time && ui.Time+int64(window) > time { if ui.MutatorUtil <= mu { // Keep the first window. goto keep } else { // Replace it with this window. heap.Remove(&acc.wHeap, i) break } } } heap.Push(&acc.wHeap, UtilWindow{time, mu}) if len(acc.wHeap) > acc.nWorst { heap.Pop(&acc.wHeap) } keep: } if len(acc.wHeap) < acc.nWorst { // We don't have N windows yet, so keep accumulating. acc.bound = 1.0 } else { // Anything above the least worst window has no effect. acc.bound = math.Max(acc.bound, acc.wHeap[0].MutatorUtil) } if acc.mud != nil { if acc.lastTime != math.MaxInt64 { // Update distribution. acc.mud.add(acc.lastMU, mu, float64(time-acc.lastTime)) } acc.lastTime, acc.lastMU = time, mu if _, mudBound, ok := acc.mud.approxInvCumulativeSum(); ok { acc.bound = math.Max(acc.bound, mudBound) } else { // We haven't accumulated enough total precise // mass yet to even reach our goal, so keep // accumulating. acc.bound = 1 } // It's not worth checking percentiles every time, so // just keep accumulating this band. return false } // If we've found enough 0 utilizations, we can stop immediately. return len(acc.wHeap) == acc.nWorst && acc.wHeap[0].MutatorUtil == 0 } // MMU returns the minimum mutator utilization for the given time // window. This is the minimum utilization for all windows of this // duration across the execution. The returned value is in the range // [0, 1]. func (c *MMUCurve) MMU(window time.Duration) (mmu float64) { acc := accumulator{mmu: 1.0, bound: 1.0} c.mmu(window, &acc) return acc.mmu } // Examples returns n specific examples of the lowest mutator // utilization for the given window size. The returned windows will be // disjoint (otherwise there would be a huge number of // mostly-overlapping windows at the single lowest point). There are // no guarantees on which set of disjoint windows this returns. func (c *MMUCurve) Examples(window time.Duration, n int) (worst []UtilWindow) { acc := accumulator{mmu: 1.0, bound: 1.0, nWorst: n} c.mmu(window, &acc) sort.Sort(sort.Reverse(acc.wHeap)) return ([]UtilWindow)(acc.wHeap) } // MUD returns mutator utilization distribution quantiles for the // given window size. // // The mutator utilization distribution is the distribution of mean // mutator utilization across all windows of the given window size in // the trace. // // The minimum mutator utilization is the minimum (0th percentile) of // this distribution. (However, if only the minimum is desired, it's // more efficient to use the MMU method.) func (c *MMUCurve) MUD(window time.Duration, quantiles []float64) []float64 { if len(quantiles) == 0 { return []float64{} } // Each unrefined band contributes a known total mass to the // distribution (bandDur except at the end), but in an unknown // way. However, we know that all the mass it contributes must // be at or above its worst-case mean mutator utilization. // // Hence, we refine bands until the highest desired // distribution quantile is less than the next worst-case mean // mutator utilization. At this point, all further // contributions to the distribution must be beyond the // desired quantile and hence cannot affect it. // // First, find the highest desired distribution quantile. maxQ := quantiles[0] for _, q := range quantiles { if q > maxQ { maxQ = q } } // The distribution's mass is in units of time (it's not // normalized because this would make it more annoying to // account for future contributions of unrefined bands). The // total final mass will be the duration of the trace itself // minus the window size. Using this, we can compute the mass // corresponding to quantile maxQ. var duration int64 for _, s := range c.series { duration1 := s.util[len(s.util)-1].Time - s.util[0].Time if duration1 >= int64(window) { duration += duration1 - int64(window) } } qMass := float64(duration) * maxQ // Accumulate the MUD until we have precise information for // everything to the left of qMass. acc := accumulator{mmu: 1.0, bound: 1.0, preciseMass: qMass, mud: new(mud)} acc.mud.setTrackMass(qMass) c.mmu(window, &acc) // Evaluate the quantiles on the accumulated MUD. out := make([]float64, len(quantiles)) for i := range out { mu, _ := acc.mud.invCumulativeSum(float64(duration) * quantiles[i]) if math.IsNaN(mu) { // There are a few legitimate ways this can // happen: // // 1. If the window is the full trace // duration, then the windowed MU function is // only defined at a single point, so the MU // distribution is not well-defined. // // 2. If there are no events, then the MU // distribution has no mass. // // Either way, all of the quantiles will have // converged toward the MMU at this point. mu = acc.mmu } out[i] = mu } return out } func (c *MMUCurve) mmu(window time.Duration, acc *accumulator) { if window <= 0 { acc.mmu = 0 return } var bandU bandUtilHeap windows := make([]time.Duration, len(c.series)) for i, s := range c.series { windows[i] = window if max := time.Duration(s.util[len(s.util)-1].Time - s.util[0].Time); window > max { windows[i] = max } bandU1 := bandUtilHeap(s.mkBandUtil(i, windows[i])) if bandU == nil { bandU = bandU1 } else { bandU = append(bandU, bandU1...) } } // Process bands from lowest utilization bound to highest. heap.Init(&bandU) // Refine each band into a precise window and MMU until // refining the next lowest band can no longer affect the MMU // or windows. for len(bandU) > 0 && bandU[0].utilBound < acc.bound { i := bandU[0].series c.series[i].bandMMU(bandU[0].i, windows[i], acc) heap.Pop(&bandU) } } func (c *mmuSeries) mkBandUtil(series int, window time.Duration) []bandUtil { // For each band, compute the worst-possible total mutator // utilization for all windows that start in that band. // minBands is the minimum number of bands a window can span // and maxBands is the maximum number of bands a window can // span in any alignment. minBands := int((int64(window) + c.bandDur - 1) / c.bandDur) maxBands := int((int64(window) + 2*(c.bandDur-1)) / c.bandDur) if window > 1 && maxBands < 2 { panic("maxBands < 2") } tailDur := int64(window) % c.bandDur nUtil := len(c.bands) - maxBands + 1 if nUtil < 0 { nUtil = 0 } bandU := make([]bandUtil, nUtil) for i := range bandU { // To compute the worst-case MU, we assume the minimum // for any bands that are only partially overlapped by // some window and the mean for any bands that are // completely covered by all windows. var util totalUtil // Find the lowest and second lowest of the partial // bands. l := c.bands[i].minUtil r1 := c.bands[i+minBands-1].minUtil r2 := c.bands[i+maxBands-1].minUtil minBand := math.Min(l, math.Min(r1, r2)) // Assume the worst window maximally overlaps the // worst minimum and then the rest overlaps the second // worst minimum. if minBands == 1 { util += totalUtilOf(minBand, int64(window)) } else { util += totalUtilOf(minBand, c.bandDur) midBand := 0.0 switch { case minBand == l: midBand = math.Min(r1, r2) case minBand == r1: midBand = math.Min(l, r2) case minBand == r2: midBand = math.Min(l, r1) } util += totalUtilOf(midBand, tailDur) } // Add the total mean MU of bands that are completely // overlapped by all windows. if minBands > 2 { util += c.bands[i+minBands-1].cumUtil - c.bands[i+1].cumUtil } bandU[i] = bandUtil{series, i, util.mean(window)} } return bandU } // bandMMU computes the precise minimum mutator utilization for // windows with a left edge in band bandIdx. func (c *mmuSeries) bandMMU(bandIdx int, window time.Duration, acc *accumulator) { util := c.util // We think of the mutator utilization over time as the // box-filtered utilization function, which we call the // "windowed mutator utilization function". The resulting // function is continuous and piecewise linear (unless // window==0, which we handle elsewhere), where the boundaries // between segments occur when either edge of the window // encounters a change in the instantaneous mutator // utilization function. Hence, the minimum of this function // will always occur when one of the edges of the window // aligns with a utilization change, so these are the only // points we need to consider. // // We compute the mutator utilization function incrementally // by tracking the integral from t=0 to the left edge of the // window and to the right edge of the window. left := c.bands[bandIdx].integrator right := left time, endTime := c.bandTime(bandIdx) if utilEnd := util[len(util)-1].Time - int64(window); utilEnd < endTime { endTime = utilEnd } acc.resetTime() for { // Advance edges to time and time+window. mu := (right.advance(time+int64(window)) - left.advance(time)).mean(window) if acc.addMU(time, mu, window) { break } if time == endTime { break } // The maximum slope of the windowed mutator // utilization function is 1/window, so we can always // advance the time by at least (mu - mmu) * window // without dropping below mmu. minTime := time + int64((mu-acc.bound)*float64(window)) // Advance the window to the next time where either // the left or right edge of the window encounters a // change in the utilization curve. if t1, t2 := left.next(time), right.next(time+int64(window))-int64(window); t1 < t2 { time = t1 } else { time = t2 } if time < minTime { time = minTime } if time >= endTime { // For MMUs we could stop here, but for MUDs // it's important that we span the entire // band. time = endTime } } } // An integrator tracks a position in a utilization function and // integrates it. type integrator struct { u *mmuSeries // pos is the index in u.util of the current time's non-strict // predecessor. pos int } // advance returns the integral of the utilization function from 0 to // time. advance must be called on monotonically increasing values of // times. func (in *integrator) advance(time int64) totalUtil { util, pos := in.u.util, in.pos // Advance pos until pos+1 is time's strict successor (making // pos time's non-strict predecessor). // // Very often, this will be nearby, so we optimize that case, // but it may be arbitrarily far away, so we handled that // efficiently, too. const maxSeq = 8 if pos+maxSeq < len(util) && util[pos+maxSeq].Time > time { // Nearby. Use a linear scan. for pos+1 < len(util) && util[pos+1].Time <= time { pos++ } } else { // Far. Binary search for time's strict successor. l, r := pos, len(util) for l < r { h := int(uint(l+r) >> 1) if util[h].Time <= time { l = h + 1 } else { r = h } } pos = l - 1 // Non-strict predecessor. } in.pos = pos var partial totalUtil if time != util[pos].Time { partial = totalUtilOf(util[pos].Util, time-util[pos].Time) } return in.u.sums[pos] + partial } // next returns the smallest time t' > time of a change in the // utilization function. func (in *integrator) next(time int64) int64 { for _, u := range in.u.util[in.pos:] { if u.Time > time { return u.Time } } return 1<<63 - 1 } func isGCSTW(r Range) bool { return strings.HasPrefix(r.Name, "stop-the-world") && strings.Contains(r.Name, "GC") } func isGCMarkAssist(r Range) bool { return r.Name == "GC mark assist" } func isGCSweep(r Range) bool { return r.Name == "GC incremental sweep" }
go/src/internal/trace/gc.go/0
{ "file_path": "go/src/internal/trace/gc.go", "repo_id": "go", "token_count": 9854 }
300
// Copyright 2023 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. package trace import ( "bufio" "fmt" "io" "slices" "strings" "internal/trace/event/go122" "internal/trace/internal/oldtrace" "internal/trace/version" ) // Reader reads a byte stream, validates it, and produces trace events. type Reader struct { r *bufio.Reader lastTs Time gen *generation spill *spilledBatch spillErr error // error from reading spill frontier []*batchCursor cpuSamples []cpuSample order ordering emittedSync bool go121Events *oldTraceConverter } // NewReader creates a new trace reader. func NewReader(r io.Reader) (*Reader, error) { br := bufio.NewReader(r) v, err := version.ReadHeader(br) if err != nil { return nil, err } switch v { case version.Go111, version.Go119, version.Go121: tr, err := oldtrace.Parse(br, v) if err != nil { return nil, err } return &Reader{ go121Events: convertOldFormat(tr), }, nil case version.Go122, version.Go123: return &Reader{ r: br, order: ordering{ mStates: make(map[ThreadID]*mState), pStates: make(map[ProcID]*pState), gStates: make(map[GoID]*gState), activeTasks: make(map[TaskID]taskState), }, // Don't emit a sync event when we first go to emit events. emittedSync: true, }, nil default: return nil, fmt.Errorf("unknown or unsupported version go 1.%d", v) } } // ReadEvent reads a single event from the stream. // // If the stream has been exhausted, it returns an invalid // event and io.EOF. func (r *Reader) ReadEvent() (e Event, err error) { if r.go121Events != nil { ev, err := r.go121Events.next() if err != nil { // XXX do we have to emit an EventSync when the trace is done? return Event{}, err } return ev, nil } // Go 1.22+ trace parsing algorithm. // // (1) Read in all the batches for the next generation from the stream. // (a) Use the size field in the header to quickly find all batches. // (2) Parse out the strings, stacks, CPU samples, and timestamp conversion data. // (3) Group each event batch by M, sorted by timestamp. (batchCursor contains the groups.) // (4) Organize batchCursors in a min-heap, ordered by the timestamp of the next event for each M. // (5) Try to advance the next event for the M at the top of the min-heap. // (a) On success, select that M. // (b) On failure, sort the min-heap and try to advance other Ms. Select the first M that advances. // (c) If there's nothing left to advance, goto (1). // (6) Select the latest event for the selected M and get it ready to be returned. // (7) Read the next event for the selected M and update the min-heap. // (8) Return the selected event, goto (5) on the next call. // Set us up to track the last timestamp and fix up // the timestamp of any event that comes through. defer func() { if err != nil { return } if err = e.validateTableIDs(); err != nil { return } if e.base.time <= r.lastTs { e.base.time = r.lastTs + 1 } r.lastTs = e.base.time }() // Consume any events in the ordering first. if ev, ok := r.order.Next(); ok { return ev, nil } // Check if we need to refresh the generation. if len(r.frontier) == 0 && len(r.cpuSamples) == 0 { if !r.emittedSync { r.emittedSync = true return syncEvent(r.gen.evTable, r.lastTs), nil } if r.spillErr != nil { return Event{}, r.spillErr } if r.gen != nil && r.spill == nil { // If we have a generation from the last read, // and there's nothing left in the frontier, and // there's no spilled batch, indicating that there's // no further generation, it means we're done. // Return io.EOF. return Event{}, io.EOF } // Read the next generation. var err error r.gen, r.spill, err = readGeneration(r.r, r.spill) if r.gen == nil { return Event{}, err } r.spillErr = err // Reset CPU samples cursor. r.cpuSamples = r.gen.cpuSamples // Reset frontier. for _, m := range r.gen.batchMs { batches := r.gen.batches[m] bc := &batchCursor{m: m} ok, err := bc.nextEvent(batches, r.gen.freq) if err != nil { return Event{}, err } if !ok { // Turns out there aren't actually any events in these batches. continue } r.frontier = heapInsert(r.frontier, bc) } // Reset emittedSync. r.emittedSync = false } tryAdvance := func(i int) (bool, error) { bc := r.frontier[i] if ok, err := r.order.Advance(&bc.ev, r.gen.evTable, bc.m, r.gen.gen); !ok || err != nil { return ok, err } // Refresh the cursor's event. ok, err := bc.nextEvent(r.gen.batches[bc.m], r.gen.freq) if err != nil { return false, err } if ok { // If we successfully refreshed, update the heap. heapUpdate(r.frontier, i) } else { // There's nothing else to read. Delete this cursor from the frontier. r.frontier = heapRemove(r.frontier, i) } return true, nil } // Inject a CPU sample if it comes next. if len(r.cpuSamples) != 0 { if len(r.frontier) == 0 || r.cpuSamples[0].time < r.frontier[0].ev.time { e := r.cpuSamples[0].asEvent(r.gen.evTable) r.cpuSamples = r.cpuSamples[1:] return e, nil } } // Try to advance the head of the frontier, which should have the minimum timestamp. // This should be by far the most common case if len(r.frontier) == 0 { return Event{}, fmt.Errorf("broken trace: frontier is empty:\n[gen=%d]\n\n%s\n%s\n", r.gen.gen, dumpFrontier(r.frontier), dumpOrdering(&r.order)) } if ok, err := tryAdvance(0); err != nil { return Event{}, err } else if !ok { // Try to advance the rest of the frontier, in timestamp order. // // To do this, sort the min-heap. A sorted min-heap is still a // min-heap, but now we can iterate over the rest and try to // advance in order. This path should be rare. slices.SortFunc(r.frontier, (*batchCursor).compare) success := false for i := 1; i < len(r.frontier); i++ { if ok, err = tryAdvance(i); err != nil { return Event{}, err } else if ok { success = true break } } if !success { return Event{}, fmt.Errorf("broken trace: failed to advance: frontier:\n[gen=%d]\n\n%s\n%s\n", r.gen.gen, dumpFrontier(r.frontier), dumpOrdering(&r.order)) } } // Pick off the next event on the queue. At this point, one must exist. ev, ok := r.order.Next() if !ok { panic("invariant violation: advance successful, but queue is empty") } return ev, nil } func dumpFrontier(frontier []*batchCursor) string { var sb strings.Builder for _, bc := range frontier { spec := go122.Specs()[bc.ev.typ] fmt.Fprintf(&sb, "M %d [%s time=%d", bc.m, spec.Name, bc.ev.time) for i, arg := range spec.Args[1:] { fmt.Fprintf(&sb, " %s=%d", arg, bc.ev.args[i]) } fmt.Fprintf(&sb, "]\n") } return sb.String() }
go/src/internal/trace/reader.go/0
{ "file_path": "go/src/internal/trace/reader.go", "repo_id": "go", "token_count": 2698 }
301
go test fuzz v1 []byte("go 1.22 trace\x00\x00\x00\x01000\x85\x00\b0000")
go/src/internal/trace/testdata/fuzz/FuzzReader/aeb749b6bc317b66/0
{ "file_path": "go/src/internal/trace/testdata/fuzz/FuzzReader/aeb749b6bc317b66", "repo_id": "go", "token_count": 37 }
302
// Copyright 2023 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. // Tests increasing and decreasing GOMAXPROCS to try and // catch issues with stale proc state. //go:build ignore package main import ( "log" "os" "runtime" "runtime/trace" "time" ) func main() { // Start a goroutine that calls runtime.GC to try and // introduce some interesting events in between the // GOMAXPROCS calls. go func() { for { runtime.GC() time.Sleep(1 * time.Millisecond) } }() // Start tracing. if err := trace.Start(os.Stdout); err != nil { log.Fatalf("failed to start tracing: %v", err) } // Run GOMAXPROCS a bunch of times, up and down. for i := 1; i <= 16; i *= 2 { runtime.GOMAXPROCS(i) time.Sleep(1 * time.Millisecond) } for i := 16; i >= 1; i /= 2 { runtime.GOMAXPROCS(i) time.Sleep(1 * time.Millisecond) } // Stop tracing. trace.Stop() }
go/src/internal/trace/testdata/testprog/gomaxprocs.go/0
{ "file_path": "go/src/internal/trace/testdata/testprog/gomaxprocs.go", "repo_id": "go", "token_count": 370 }
303
// Copyright 2020 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. // Package traceviewer provides definitions of the JSON data structures // used by the Chrome trace viewer. // // The official description of the format is in this file: // https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview // // Note: This can't be part of the parent traceviewer package as that would // throw. go_bootstrap cannot depend on the cgo version of package net in ./make.bash. package format type Data struct { Events []*Event `json:"traceEvents"` Frames map[string]Frame `json:"stackFrames"` TimeUnit string `json:"displayTimeUnit"` } type Event struct { Name string `json:"name,omitempty"` Phase string `json:"ph"` Scope string `json:"s,omitempty"` Time float64 `json:"ts"` Dur float64 `json:"dur,omitempty"` PID uint64 `json:"pid"` TID uint64 `json:"tid"` ID uint64 `json:"id,omitempty"` BindPoint string `json:"bp,omitempty"` Stack int `json:"sf,omitempty"` EndStack int `json:"esf,omitempty"` Arg any `json:"args,omitempty"` Cname string `json:"cname,omitempty"` Category string `json:"cat,omitempty"` } type Frame struct { Name string `json:"name"` Parent int `json:"parent,omitempty"` } type NameArg struct { Name string `json:"name"` } type BlockedArg struct { Blocked string `json:"blocked"` } type SortIndexArg struct { Index int `json:"sort_index"` } type HeapCountersArg struct { Allocated uint64 NextGC uint64 } const ( ProcsSection = 0 // where Goroutines or per-P timelines are presented. StatsSection = 1 // where counters are presented. TasksSection = 2 // where Task hierarchy & timeline is presented. ) type GoroutineCountersArg struct { Running uint64 Runnable uint64 GCWaiting uint64 } type ThreadCountersArg struct { Running int64 InSyscall int64 } type ThreadIDArg struct { ThreadID uint64 }
go/src/internal/trace/traceviewer/format/format.go/0
{ "file_path": "go/src/internal/trace/traceviewer/format/format.go", "repo_id": "go", "token_count": 786 }
304
// Copyright 2012 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. // builtin calls package builtins import "unsafe" func f0() {} func append1() { var b byte var x int var s []byte _ = append() // ERROR "not enough arguments" _ = append("foo" /* ERROR "must be a slice" */ ) _ = append(nil /* ERROR "must be a slice" */ , s) _ = append(x /* ERROR "must be a slice" */ , s) _ = append(s) _ = append(s, nil...) append /* ERROR "not used" */ (s) _ = append(s, b) _ = append(s, x /* ERROR "cannot use x" */ ) _ = append(s, s /* ERROR "cannot use s" */ ) _ = append(s...) /* ERROR "not enough arguments" */ _ = append(s, b, s /* ERROR "too many arguments" */ ...) _ = append(s, 1, 2, 3) _ = append(s, 1, 2, 3, x /* ERROR "cannot use x" */ , 5, 6, 6) _ = append(s, 1, 2 /* ERROR "too many arguments" */, s...) _ = append([]interface{}(nil), 1, 2, "foo", x, 3.1425, false) type S []byte type T string var t T _ = append(s, "foo" /* ERRORx `cannot use .* in argument to append` */ ) _ = append(s, "foo"...) _ = append(S(s), "foo" /* ERRORx `cannot use .* in argument to append` */ ) _ = append(S(s), "foo"...) _ = append(s, t /* ERROR "cannot use t" */ ) _ = append(s, t...) _ = append(s, T("foo")...) _ = append(S(s), t /* ERROR "cannot use t" */ ) _ = append(S(s), t...) _ = append(S(s), T("foo")...) _ = append([]string{}, t /* ERROR "cannot use t" */ , "foo") _ = append([]T{}, t, "foo") } // from the spec func append2() { s0 := []int{0, 0} s1 := append(s0, 2) // append a single element s1 == []int{0, 0, 2} s2 := append(s1, 3, 5, 7) // append multiple elements s2 == []int{0, 0, 2, 3, 5, 7} s3 := append(s2, s0...) // append a slice s3 == []int{0, 0, 2, 3, 5, 7, 0, 0} s4 := append(s3[3:6], s3[2:]...) // append overlapping slice s4 == []int{3, 5, 7, 2, 3, 5, 7, 0, 0} var t []interface{} t = append(t, 42, 3.1415, "foo") // t == []interface{}{42, 3.1415, "foo"} var b []byte b = append(b, "bar"...) // append string contents b == []byte{'b', 'a', 'r' } _ = s4 } func append3() { f1 := func() (s []int) { return } f2 := func() (s []int, x int) { return } f3 := func() (s []int, x, y int) { return } f5 := func() (s []interface{}, x int, y float32, z string, b bool) { return } ff := func() (int, float32) { return 0, 0 } _ = append(f0 /* ERROR "used as value" */ ()) _ = append(f1()) _ = append(f2()) _ = append(f3()) _ = append(f5()) _ = append(ff /* ERROR "must be a slice" */ ()) // TODO(gri) better error message } func cap1() { var a [10]bool var p *[20]int var c chan string _ = cap() // ERROR "not enough arguments" _ = cap(1, 2) // ERROR "too many arguments" _ = cap(42 /* ERROR "invalid" */) const _3 = cap(a) assert(_3 == 10) const _4 = cap(p) assert(_4 == 20) _ = cap(c) cap /* ERROR "not used" */ (c) // issue 4744 type T struct{ a [10]int } const _ = cap(((*T)(nil)).a) var s [][]byte _ = cap(s) _ = cap(s... /* ERROR "invalid use of ... with built-in cap" */ ) var x int _ = cap(x /* ERROR "invalid argument: x (variable of type int) for built-in cap" */ ) } func cap2() { f1a := func() (a [10]int) { return } f1s := func() (s []int) { return } f2 := func() (s []int, x int) { return } _ = cap(f0 /* ERROR "used as value" */ ()) _ = cap(f1a()) _ = cap(f1s()) _ = cap(f2()) // ERROR "too many arguments" } // test cases for issue 7387 func cap3() { var f = func() int { return 0 } var x = f() const ( _ = cap([4]int{}) _ = cap([4]int{x}) _ = cap /* ERROR "not constant" */ ([4]int{f()}) _ = cap /* ERROR "not constant" */ ([4]int{cap([]int{})}) _ = cap([4]int{cap([4]int{})}) ) var y float64 var z complex128 const ( _ = cap([4]float64{}) _ = cap([4]float64{y}) _ = cap([4]float64{real(2i)}) _ = cap /* ERROR "not constant" */ ([4]float64{real(z)}) ) var ch chan [10]int const ( _ = cap /* ERROR "not constant" */ (<-ch) _ = cap /* ERROR "not constant" */ ([4]int{(<-ch)[0]}) ) } func clear1() { var a [10]int var m map[float64]string var s []byte clear(a /* ERROR "cannot clear a" */) clear(&/* ERROR "cannot clear &a" */a) clear(m) clear(s) clear([]int{}) } func close1() { var c chan int var r <-chan int close() // ERROR "not enough arguments" close(1, 2) // ERROR "too many arguments" close(42 /* ERROR "cannot close non-channel" */) close(r /* ERROR "receive-only channel" */) close(c) _ = close /* ERROR "used as value" */ (c) var s []chan int close(s... /* ERROR "invalid use of ..." */ ) } func close2() { f1 := func() (ch chan int) { return } f2 := func() (ch chan int, x int) { return } close(f0 /* ERROR "used as value" */ ()) close(f1()) close(f2()) // ERROR "too many arguments" } func complex1() { var i32 int32 var f32 float32 var f64 float64 var c64 complex64 var c128 complex128 _ = complex() // ERROR "not enough arguments" _ = complex(1) // ERROR "not enough arguments" _ = complex(true /* ERROR "mismatched types" */ , 0) _ = complex(i32 /* ERROR "expected floating-point" */ , 0) _ = complex("foo" /* ERROR "mismatched types" */ , 0) _ = complex(c64 /* ERROR "expected floating-point" */ , 0) _ = complex(0 /* ERROR "mismatched types" */ , true) _ = complex(0 /* ERROR "expected floating-point" */ , i32) _ = complex(0 /* ERROR "mismatched types" */ , "foo") _ = complex(0 /* ERROR "expected floating-point" */ , c64) _ = complex(f32, f32) _ = complex(f32, 1) _ = complex(f32, 1.0) _ = complex(f32, 'a') _ = complex(f64, f64) _ = complex(f64, 1) _ = complex(f64, 1.0) _ = complex(f64, 'a') _ = complex(f32 /* ERROR "mismatched types" */ , f64) _ = complex(f64 /* ERROR "mismatched types" */ , f32) _ = complex(1, 1) _ = complex(1, 1.1) _ = complex(1, 'a') complex /* ERROR "not used" */ (1, 2) var _ complex64 = complex(f32, f32) var _ complex64 = complex /* ERRORx `cannot use .* in variable declaration` */ (f64, f64) var _ complex128 = complex /* ERRORx `cannot use .* in variable declaration` */ (f32, f32) var _ complex128 = complex(f64, f64) // untyped constants const _ int = complex(1, 0) const _ float32 = complex(1, 0) const _ complex64 = complex(1, 0) const _ complex128 = complex(1, 0) const _ = complex(0i, 0i) const _ = complex(0i, 0) const _ int = 1.0 + complex(1, 0i) const _ int = complex /* ERROR "int" */ (1.1, 0) const _ float32 = complex /* ERROR "float32" */ (1, 2) // untyped values var s uint _ = complex(1 /* ERROR "integer" */ <<s, 0) const _ = complex /* ERROR "not constant" */ (1 /* ERROR "integer" */ <<s, 0) var _ int = complex /* ERRORx `cannot use .* in variable declaration` */ (1 /* ERROR "integer" */ <<s, 0) // floating-point argument types must be identical type F32 float32 type F64 float64 var x32 F32 var x64 F64 c64 = complex(x32, x32) _ = complex(x32 /* ERROR "mismatched types" */ , f32) _ = complex(f32 /* ERROR "mismatched types" */ , x32) c128 = complex(x64, x64) _ = c128 _ = complex(x64 /* ERROR "mismatched types" */ , f64) _ = complex(f64 /* ERROR "mismatched types" */ , x64) var t []float32 _ = complex(t... /* ERROR "invalid use of ..." */ ) } func complex2() { f1 := func() (x float32) { return } f2 := func() (x, y float32) { return } f3 := func() (x, y, z float32) { return } _ = complex(f0 /* ERROR "used as value" */ ()) _ = complex(f1()) // ERROR "not enough arguments" _ = complex(f2()) _ = complex(f3()) // ERROR "too many arguments" } func copy1() { copy() // ERROR "not enough arguments" copy("foo") // ERROR "not enough arguments" copy([ /* ERROR "copy expects slice arguments" */ ...]int{}, []int{}) copy([ /* ERROR "copy expects slice arguments" */ ]int{}, [...]int{}) copy([ /* ERROR "different element types" */ ]int8{}, "foo") // spec examples var a = [...]int{0, 1, 2, 3, 4, 5, 6, 7} var s = make([]int, 6) var b = make([]byte, 5) n1 := copy(s, a[0:]) // n1 == 6, s == []int{0, 1, 2, 3, 4, 5} n2 := copy(s, s[2:]) // n2 == 4, s == []int{2, 3, 4, 5, 4, 5} n3 := copy(b, "Hello, World!") // n3 == 5, b == []byte("Hello") _, _, _ = n1, n2, n3 var t [][]int copy(t, t) copy(t /* ERROR "copy expects slice arguments" */ , nil) copy(nil /* ERROR "copy expects slice arguments" */ , t) copy(nil /* ERROR "copy expects slice arguments" */ , nil) copy(t... /* ERROR "invalid use of ..." */ ) } func copy2() { f1 := func() (a []int) { return } f2 := func() (a, b []int) { return } f3 := func() (a, b, c []int) { return } copy(f0 /* ERROR "used as value" */ ()) copy(f1()) // ERROR "not enough arguments" copy(f2()) copy(f3()) // ERROR "too many arguments" } func delete1() { var m map[string]int var s string delete() // ERROR "not enough arguments" delete(1) // ERROR "not enough arguments" delete(1, 2, 3) // ERROR "too many arguments" delete(m, 0 /* ERROR "cannot use" */) delete(m, s) _ = delete /* ERROR "used as value" */ (m, s) var t []map[string]string delete(t... /* ERROR "invalid use of ..." */ ) } func delete2() { f1 := func() (m map[string]int) { return } f2 := func() (m map[string]int, k string) { return } f3 := func() (m map[string]int, k string, x float32) { return } delete(f0 /* ERROR "used as value" */ ()) delete(f1()) // ERROR "not enough arguments" delete(f2()) delete(f3()) // ERROR "too many arguments" } func imag1() { var f32 float32 var f64 float64 var c64 complex64 var c128 complex128 _ = imag() // ERROR "not enough arguments" _ = imag(1, 2) // ERROR "too many arguments" _ = imag(10) _ = imag(2.7182818) _ = imag("foo" /* ERROR "expected complex" */) _ = imag('a') const _5 = imag(1 + 2i) assert(_5 == 2) f32 = _5 f64 = _5 const _6 = imag(0i) assert(_6 == 0) f32 = imag(c64) f64 = imag(c128) f32 = imag /* ERRORx `cannot use .* in assignment` */ (c128) f64 = imag /* ERRORx `cannot use .* in assignment` */ (c64) imag /* ERROR "not used" */ (c64) _, _ = f32, f64 // complex type may not be predeclared type C64 complex64 type C128 complex128 var x64 C64 var x128 C128 f32 = imag(x64) f64 = imag(x128) var a []complex64 _ = imag(a... /* ERROR "invalid use of ..." */ ) // if argument is untyped, result is untyped const _ byte = imag(1.2 + 3i) const _ complex128 = imag(1.2 + 3i) // lhs constant shift operands are typed as complex128 var s uint _ = imag(1 /* ERROR "must be integer" */ << s) } func imag2() { f1 := func() (x complex128) { return } f2 := func() (x, y complex128) { return } _ = imag(f0 /* ERROR "used as value" */ ()) _ = imag(f1()) _ = imag(f2()) // ERROR "too many arguments" } func len1() { const c = "foobar" var a [10]bool var p *[20]int var m map[string]complex128 _ = len() // ERROR "not enough arguments" _ = len(1, 2) // ERROR "too many arguments" _ = len(42 /* ERROR "invalid" */) const _3 = len(c) assert(_3 == 6) const _4 = len(a) assert(_4 == 10) const _5 = len(p) assert(_5 == 20) _ = len(m) len /* ERROR "not used" */ (c) // esoteric case var t string var hash map[interface{}][]*[10]int const n = len /* ERROR "not constant" */ (hash[recover()][len(t)]) assert(n == 10) // ok because n has unknown value and no error is reported var ch <-chan int const nn = len /* ERROR "not constant" */ (hash[<-ch][len(t)]) // issue 4744 type T struct{ a [10]int } const _ = len(((*T)(nil)).a) var s [][]byte _ = len(s) _ = len(s... /* ERROR "invalid use of ..." */ ) } func len2() { f1 := func() (x []int) { return } f2 := func() (x, y []int) { return } _ = len(f0 /* ERROR "used as value" */ ()) _ = len(f1()) _ = len(f2()) // ERROR "too many arguments" } // test cases for issue 7387 func len3() { var f = func() int { return 0 } var x = f() const ( _ = len([4]int{}) _ = len([4]int{x}) _ = len /* ERROR "not constant" */ ([4]int{f()}) _ = len /* ERROR "not constant" */ ([4]int{len([]int{})}) _ = len([4]int{len([4]int{})}) ) var y float64 var z complex128 const ( _ = len([4]float64{}) _ = len([4]float64{y}) _ = len([4]float64{real(2i)}) _ = len /* ERROR "not constant" */ ([4]float64{real(z)}) ) var ch chan [10]int const ( _ = len /* ERROR "not constant" */ (<-ch) _ = len /* ERROR "not constant" */ ([4]int{(<-ch)[0]}) ) } func make1() { var n int var m float32 var s uint _ = make() // ERROR "not enough arguments" _ = make(1 /* ERROR "not a type" */) _ = make(int /* ERROR "cannot make" */) // slices _ = make/* ERROR "arguments" */ ([]int) _ = make/* ERROR "arguments" */ ([]int, 2, 3, 4) _ = make([]int, int /* ERROR "not an expression" */) _ = make([]int, 10, float32 /* ERROR "not an expression" */) _ = make([]int, "foo" /* ERROR "cannot convert" */) _ = make([]int, 10, 2.3 /* ERROR "truncated" */) _ = make([]int, 5, 10.0) _ = make([]int, 0i) _ = make([]int, 1.0) _ = make([]int, 1.0<<s) _ = make([]int, 1.1 /* ERROR "int" */ <<s) _ = make([]int, - /* ERROR "must not be negative" */ 1, 10) _ = make([]int, 0, - /* ERROR "must not be negative" */ 1) _ = make([]int, - /* ERROR "must not be negative" */ 1, - /* ERROR "must not be negative" */ 1) _ = make([]int, 1 /* ERROR "overflows" */ <<100, 1 /* ERROR "overflows" */ <<100) _ = make([]int, 10 /* ERROR "length and capacity swapped" */ , 9) _ = make([]int, 1 /* ERROR "overflows" */ <<100, 12345) _ = make([]int, m /* ERROR "must be integer" */ ) _ = &make /* ERROR "cannot take address" */ ([]int, 0) // maps _ = make /* ERROR "arguments" */ (map[int]string, 10, 20) _ = make(map[int]float32, int /* ERROR "not an expression" */) _ = make(map[int]float32, "foo" /* ERROR "cannot convert" */) _ = make(map[int]float32, 10) _ = make(map[int]float32, n) _ = make(map[int]float32, int64(n)) _ = make(map[string]bool, 10.0) _ = make(map[string]bool, 10.0<<s) _ = &make /* ERROR "cannot take address" */ (map[string]bool) // channels _ = make /* ERROR "arguments" */ (chan int, 10, 20) _ = make(chan int, int /* ERROR "not an expression" */) _ = make(chan<- int, "foo" /* ERROR "cannot convert" */) _ = make(chan int, - /* ERROR "must not be negative" */ 10) _ = make(<-chan float64, 10) _ = make(chan chan int, n) _ = make(chan string, int64(n)) _ = make(chan bool, 10.0) _ = make(chan bool, 10.0<<s) _ = &make /* ERROR "cannot take address" */ (chan bool) make /* ERROR "not used" */ ([]int, 10) var t []int _ = make([]int, t[0], t[1]) _ = make([]int, t... /* ERROR "invalid use of ..." */ ) } func make2() { f1 := func() (x []int) { return } _ = make(f0 /* ERROR "not a type" */ ()) _ = make(f1 /* ERROR "not a type" */ ()) } func max1() { var b bool var c complex128 var x int var s string type myint int var m myint _ = max() /* ERROR "not enough arguments" */ _ = max(b /* ERROR "cannot be ordered" */ ) _ = max(c /* ERROR "cannot be ordered" */ ) _ = max(x) _ = max(s) _ = max(x, x) _ = max(x, x, x, x, x) var _ int = max /* ERROR "cannot use max(m) (value of type myint) as int value" */ (m) _ = max(x, m /* ERROR "invalid argument: mismatched types int (previous argument) and myint (type of m)" */ , x) _ = max(1, x) _ = max(1.0, x) _ = max(1.2 /* ERROR "1.2 (untyped float constant) truncated to int" */ , x) _ = max(-10, 1.0, c /* ERROR "cannot be ordered" */ ) const ( _ = max /* ERROR "max(x) (value of type int) is not constant" */ (x) _ = max(true /* ERROR "invalid argument: true (untyped bool constant) cannot be ordered" */ ) _ = max(1) _ = max(1, 2.3, 'a') _ = max(1, "foo" /* ERROR "mismatched types" */ ) _ = max(1, 0i /* ERROR "cannot be ordered" */ ) _ = max(1, 2 /* ERROR "cannot be ordered" */ + 3i ) ) } func max2() { _ = assert(max(0) == 0) _ = assert(max(0, 1) == 1) _ = assert(max(0, -10, 123456789) == 123456789) _ = assert(max(-12345678901234567890, 0) == 0) _ = assert(max(1, 2.3) == 2.3) _ = assert(max(1, 2.3, 'a') == 'a') _ = assert(max("", "a") == "a") _ = assert(max("abcde", "xyz", "foo", "bar") == "xyz") const ( _ int = max(1.0) _ float32 = max(1, 2) _ int = max /* ERROR "cannot use max(1, 2.3) (untyped float constant 2.3) as int value" */ (1, 2.3) _ int = max(1.2, 3) // ok! _ byte = max(1, 'a') ) } func min1() { var b bool var c complex128 var x int var s string type myint int var m myint _ = min() /* ERROR "not enough arguments" */ _ = min(b /* ERROR "cannot be ordered" */ ) _ = min(c /* ERROR "cannot be ordered" */ ) _ = min(x) _ = min(s) _ = min(x, x) _ = min(x, x, x, x, x) var _ int = min /* ERROR "cannot use min(m) (value of type myint) as int value" */ (m) _ = min(x, m /* ERROR "invalid argument: mismatched types int (previous argument) and myint (type of m)" */ , x) _ = min(1, x) _ = min(1.0, x) _ = min(1.2 /* ERROR "1.2 (untyped float constant) truncated to int" */ , x) _ = min(-10, 1.0, c /* ERROR "cannot be ordered" */ ) const ( _ = min /* ERROR "min(x) (value of type int) is not constant" */ (x) _ = min(true /* ERROR "invalid argument: true (untyped bool constant) cannot be ordered" */ ) _ = min(1) _ = min(1, 2.3, 'a') _ = min(1, "foo" /* ERROR "mismatched types" */ ) _ = min(1, 0i /* ERROR "cannot be ordered" */ ) _ = min(1, 2 /* ERROR "cannot be ordered" */ + 3i ) ) } func min2() { _ = assert(min(0) == 0) _ = assert(min(0, 1) == 0) _ = assert(min(0, -10, 123456789) == -10) _ = assert(min(-12345678901234567890, 0) == -12345678901234567890) _ = assert(min(1, 2.3) == 1) _ = assert(min(1, 2.3, 'a') == 1) _ = assert(min("", "a") == "") _ = assert(min("abcde", "xyz", "foo", "bar") == "abcde") const ( _ int = min(1.0) _ float32 = min(1, 2) _ int = min(1, 2.3) // ok! _ int = min /* ERROR "cannot use min(1.2, 3) (untyped float constant 1.2) as int value" */ (1.2, 3) _ byte = min(1, 'a') ) } func new1() { _ = new() // ERROR "not enough arguments" _ = new(1, 2) // ERROR "too many arguments" _ = new("foo" /* ERROR "not a type" */) p := new(float64) _ = new(struct{ x, y int }) q := new(*float64) _ = *p == **q new /* ERROR "not used" */ (int) _ = &new /* ERROR "cannot take address" */ (int) _ = new(int... /* ERROR "invalid use of ..." */ ) } func new2() { f1 := func() (x []int) { return } _ = new(f0 /* ERROR "not a type" */ ()) _ = new(f1 /* ERROR "not a type" */ ()) } func panic1() { panic() // ERROR "not enough arguments" panic(1, 2) // ERROR "too many arguments" panic(0) panic("foo") panic(false) panic(1<<10) panic(1 << /* ERROR "constant shift overflow" */ 1000) _ = panic /* ERROR "used as value" */ (0) var s []byte panic(s) panic(s... /* ERROR "invalid use of ..." */ ) } func panic2() { f1 := func() (x int) { return } f2 := func() (x, y int) { return } panic(f0 /* ERROR "used as value" */ ()) panic(f1()) panic(f2()) // ERROR "too many arguments" } func print1() { print() print(1) print(1, 2) print("foo") print(2.718281828) print(false) print(1<<10) print(1 << /* ERROR "constant shift overflow" */ 1000) println(nil /* ERROR "untyped nil" */ ) var s []int print(s... /* ERROR "invalid use of ..." */ ) _ = print /* ERROR "used as value" */ () } func print2() { f1 := func() (x int) { return } f2 := func() (x, y int) { return } f3 := func() (x int, y float32, z string) { return } print(f0 /* ERROR "used as value" */ ()) print(f1()) print(f2()) print(f3()) } func println1() { println() println(1) println(1, 2) println("foo") println(2.718281828) println(false) println(1<<10) println(1 << /* ERROR "constant shift overflow" */ 1000) println(nil /* ERROR "untyped nil" */ ) var s []int println(s... /* ERROR "invalid use of ..." */ ) _ = println /* ERROR "used as value" */ () } func println2() { f1 := func() (x int) { return } f2 := func() (x, y int) { return } f3 := func() (x int, y float32, z string) { return } println(f0 /* ERROR "used as value" */ ()) println(f1()) println(f2()) println(f3()) } func real1() { var f32 float32 var f64 float64 var c64 complex64 var c128 complex128 _ = real() // ERROR "not enough arguments" _ = real(1, 2) // ERROR "too many arguments" _ = real(10) _ = real(2.7182818) _ = real("foo" /* ERROR "expected complex" */) const _5 = real(1 + 2i) assert(_5 == 1) f32 = _5 f64 = _5 const _6 = real(0i) assert(_6 == 0) f32 = real(c64) f64 = real(c128) f32 = real /* ERRORx `cannot use .* in assignment` */ (c128) f64 = real /* ERRORx `cannot use .* in assignment` */ (c64) real /* ERROR "not used" */ (c64) // complex type may not be predeclared type C64 complex64 type C128 complex128 var x64 C64 var x128 C128 f32 = imag(x64) f64 = imag(x128) _, _ = f32, f64 var a []complex64 _ = real(a... /* ERROR "invalid use of ..." */ ) // if argument is untyped, result is untyped const _ byte = real(1 + 2.3i) const _ complex128 = real(1 + 2.3i) // lhs constant shift operands are typed as complex128 var s uint _ = real(1 /* ERROR "must be integer" */ << s) } func real2() { f1 := func() (x complex128) { return } f2 := func() (x, y complex128) { return } _ = real(f0 /* ERROR "used as value" */ ()) _ = real(f1()) _ = real(f2()) // ERROR "too many arguments" } func recover1() { _ = recover() _ = recover(10) // ERROR "too many arguments" recover() var s []int recover(s... /* ERROR "invalid use of ..." */ ) } func recover2() { f1 := func() (x int) { return } f2 := func() (x, y int) { return } _ = recover(f0 /* ERROR "used as value" */ ()) _ = recover(f1()) // ERROR "too many arguments" _ = recover(f2()) // ERROR "too many arguments" } // assuming types.DefaultPtrSize == 8 type S0 struct{ // offset a bool // 0 b rune // 4 c *int // 8 d bool // 16 e complex128 // 24 } // 40 type S1 struct{ // offset x float32 // 0 y string // 8 z *S1 // 24 S0 // 32 } // 72 type S2 struct{ // offset *S1 // 0 } // 8 type S3 struct { // offset a int64 // 0 b int32 // 8 } // 16 type S4 struct { // offset S3 // 0 int32 // 12 } // 24 type S5 struct { // offset a [3]int32 // 0 b int32 // 16 } // 16 func (S2) m() {} func Alignof1() { var x int _ = unsafe.Alignof() // ERROR "not enough arguments" _ = unsafe.Alignof(1, 2) // ERROR "too many arguments" _ = unsafe.Alignof(int /* ERROR "not an expression" */) _ = unsafe.Alignof(42) _ = unsafe.Alignof(new(struct{})) _ = unsafe.Alignof(1<<10) _ = unsafe.Alignof(1 << /* ERROR "constant shift overflow" */ 1000) _ = unsafe.Alignof(nil /* ERROR "untyped nil" */ ) unsafe /* ERROR "not used" */ .Alignof(x) var y S0 assert(unsafe.Alignof(y.a) == 1) assert(unsafe.Alignof(y.b) == 4) assert(unsafe.Alignof(y.c) == 8) assert(unsafe.Alignof(y.d) == 1) assert(unsafe.Alignof(y.e) == 8) var s []byte _ = unsafe.Alignof(s) _ = unsafe.Alignof(s... /* ERROR "invalid use of ..." */ ) } func Alignof2() { f1 := func() (x int32) { return } f2 := func() (x, y int32) { return } _ = unsafe.Alignof(f0 /* ERROR "used as value" */ ()) assert(unsafe.Alignof(f1()) == 4) _ = unsafe.Alignof(f2()) // ERROR "too many arguments" } func Offsetof1() { var x struct{ f int } _ = unsafe.Offsetof() // ERROR "not enough arguments" _ = unsafe.Offsetof(1, 2) // ERROR "too many arguments" _ = unsafe.Offsetof(int /* ERROR "not a selector expression" */ ) _ = unsafe.Offsetof(x /* ERROR "not a selector expression" */ ) _ = unsafe.Offsetof(nil /* ERROR "not a selector expression" */ ) _ = unsafe.Offsetof(x.f) _ = unsafe.Offsetof((x.f)) _ = unsafe.Offsetof((((((((x))).f))))) unsafe /* ERROR "not used" */ .Offsetof(x.f) var y0 S0 assert(unsafe.Offsetof(y0.a) == 0) assert(unsafe.Offsetof(y0.b) == 4) assert(unsafe.Offsetof(y0.c) == 8) assert(unsafe.Offsetof(y0.d) == 16) assert(unsafe.Offsetof(y0.e) == 24) var y1 S1 assert(unsafe.Offsetof(y1.x) == 0) assert(unsafe.Offsetof(y1.y) == 8) assert(unsafe.Offsetof(y1.z) == 24) assert(unsafe.Offsetof(y1.S0) == 32) assert(unsafe.Offsetof(y1.S0.a) == 0) // relative to S0 assert(unsafe.Offsetof(y1.a) == 32) // relative to S1 assert(unsafe.Offsetof(y1.b) == 36) // relative to S1 assert(unsafe.Offsetof(y1.c) == 40) // relative to S1 assert(unsafe.Offsetof(y1.d) == 48) // relative to S1 assert(unsafe.Offsetof(y1.e) == 56) // relative to S1 var y1p *S1 assert(unsafe.Offsetof(y1p.S0) == 32) type P *S1 var p P = y1p assert(unsafe.Offsetof(p.S0) == 32) var y2 S2 assert(unsafe.Offsetof(y2.S1) == 0) _ = unsafe.Offsetof(y2 /* ERROR "embedded via a pointer" */ .x) _ = unsafe.Offsetof(y2 /* ERROR "method value" */ .m) var s []byte _ = unsafe.Offsetof(s... /* ERROR "invalid use of ..." */ ) } func Offsetof2() { f1 := func() (x int32) { return } f2 := func() (x, y int32) { return } _ = unsafe.Offsetof(f0 /* ERROR "not a selector expression" */ ()) _ = unsafe.Offsetof(f1 /* ERROR "not a selector expression" */ ()) _ = unsafe.Offsetof(f2 /* ERROR "not a selector expression" */ ()) } func Sizeof1() { var x int _ = unsafe.Sizeof() // ERROR "not enough arguments" _ = unsafe.Sizeof(1, 2) // ERROR "too many arguments" _ = unsafe.Sizeof(int /* ERROR "not an expression" */) _ = unsafe.Sizeof(42) _ = unsafe.Sizeof(new(complex128)) _ = unsafe.Sizeof(1<<10) _ = unsafe.Sizeof(1 << /* ERROR "constant shift overflow" */ 1000) _ = unsafe.Sizeof(nil /* ERROR "untyped nil" */ ) unsafe /* ERROR "not used" */ .Sizeof(x) // basic types have size guarantees assert(unsafe.Sizeof(byte(0)) == 1) assert(unsafe.Sizeof(uint8(0)) == 1) assert(unsafe.Sizeof(int8(0)) == 1) assert(unsafe.Sizeof(uint16(0)) == 2) assert(unsafe.Sizeof(int16(0)) == 2) assert(unsafe.Sizeof(uint32(0)) == 4) assert(unsafe.Sizeof(int32(0)) == 4) assert(unsafe.Sizeof(float32(0)) == 4) assert(unsafe.Sizeof(uint64(0)) == 8) assert(unsafe.Sizeof(int64(0)) == 8) assert(unsafe.Sizeof(float64(0)) == 8) assert(unsafe.Sizeof(complex64(0)) == 8) assert(unsafe.Sizeof(complex128(0)) == 16) var y0 S0 assert(unsafe.Sizeof(y0.a) == 1) assert(unsafe.Sizeof(y0.b) == 4) assert(unsafe.Sizeof(y0.c) == 8) assert(unsafe.Sizeof(y0.d) == 1) assert(unsafe.Sizeof(y0.e) == 16) assert(unsafe.Sizeof(y0) == 40) var y1 S1 assert(unsafe.Sizeof(y1) == 72) var y2 S2 assert(unsafe.Sizeof(y2) == 8) var y3 S3 assert(unsafe.Sizeof(y3) == 16) var y4 S4 assert(unsafe.Sizeof(y4) == 24) var y5 S5 assert(unsafe.Sizeof(y5) == 16) var a3 [10]S3 assert(unsafe.Sizeof(a3) == 160) // test case for issue 5670 type T struct { a int32 _ int32 c int32 } assert(unsafe.Sizeof(T{}) == 12) var s []byte _ = unsafe.Sizeof(s) _ = unsafe.Sizeof(s... /* ERROR "invalid use of ..." */ ) } func Sizeof2() { f1 := func() (x int64) { return } f2 := func() (x, y int64) { return } _ = unsafe.Sizeof(f0 /* ERROR "used as value" */ ()) assert(unsafe.Sizeof(f1()) == 8) _ = unsafe.Sizeof(f2()) // ERROR "too many arguments" } func Slice1() { var x int unsafe.Slice() // ERROR "not enough arguments" unsafe.Slice(1, 2, 3) // ERROR "too many arguments" unsafe.Slice(1 /* ERROR "is not a pointer" */ , 2) unsafe.Slice(nil /* ERROR "nil is not a pointer" */ , 0) unsafe.Slice(&x, "foo" /* ERRORx `cannot convert .* to type int` */ ) unsafe.Slice(&x, 1.2 /* ERROR "truncated to int" */ ) unsafe.Slice(&x, - /* ERROR "must not be negative" */ 1) unsafe /* ERROR "not used" */ .Slice(&x, 0) var _ []byte = unsafe /* ERROR "value of type []int" */ .Slice(&x, 0) var _ []int = unsafe.Slice(&x, 0) _ = unsafe.Slice(&x, 1.0) _ = unsafe.Slice((*int)(nil), 0) } func SliceData1() { var s []int unsafe.SliceData(0 /* ERROR "not a slice" */) unsafe /* ERROR "not used" */ .SliceData(s) type S []int _ = unsafe.SliceData(s) _ = unsafe.SliceData(S{}) } func String1() { var b byte unsafe.String() // ERROR "not enough arguments" unsafe.String(1, 2, 3) // ERROR "too many arguments" unsafe.String(1 /* ERROR "cannot use 1" */ , 2) unsafe.String(&b, "foo" /* ERRORx `cannot convert .* to type int` */ ) unsafe.String(&b, 1.2 /* ERROR "truncated to int" */ ) unsafe.String(&b, - /* ERROR "must not be negative" */ 1) unsafe /* ERROR "not used" */ .String(&b, 0) var _ []byte = unsafe /* ERROR "value of type string" */ .String(&b, 0) var _ string = unsafe.String(&b, 0) _ = unsafe.String(&b, 1.0) _ = unsafe.String(nil, 0) // here we allow nil as ptr argument (in contrast to unsafe.Slice) } func StringData1() { var s string type S string unsafe.StringData(0 /* ERROR "cannot use 0" */) unsafe.StringData(S /* ERROR "cannot use S" */ ("foo")) unsafe /* ERROR "not used" */ .StringData(s) _ = unsafe.StringData(s) _ = unsafe.StringData("foo") } // self-testing only func assert1() { var x int assert() /* ERROR "not enough arguments" */ assert(1, 2) /* ERROR "too many arguments" */ assert("foo" /* ERROR "boolean constant" */ ) assert(x /* ERROR "boolean constant" */) assert(true) assert /* ERROR "failed" */ (false) _ = assert(true) var s []byte assert(s... /* ERROR "invalid use of ..." */ ) } func assert2() { f1 := func() (x bool) { return } f2 := func() (x bool) { return } assert(f0 /* ERROR "used as value" */ ()) assert(f1 /* ERROR "boolean constant" */ ()) assert(f2 /* ERROR "boolean constant" */ ()) } // self-testing only func trace1() { // Uncomment the code below to test trace - will produce console output // _ = trace /* ERROR "no value" */ () // _ = trace(1) // _ = trace(true, 1.2, '\'', "foo", 42i, "foo" <= "bar") var s []byte trace(s... /* ERROR "invalid use of ..." */ ) } func trace2() { f1 := func() (x int) { return } f2 := func() (x int, y string) { return } f3 := func() (x int, y string, z []int) { return } _ = f1 _ = f2 _ = f3 // Uncomment the code below to test trace - will produce console output // trace(f0()) // trace(f1()) // trace(f2()) // trace(f3()) // trace(f0(), 1) // trace(f1(), 1, 2) // trace(f2(), 1, 2, 3) // trace(f3(), 1, 2, 3, 4) }
go/src/internal/types/testdata/check/builtins0.go/0
{ "file_path": "go/src/internal/types/testdata/check/builtins0.go", "repo_id": "go", "token_count": 12524 }
305
// -lang=go1.17 // Copyright 2011 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. // type declarations package p // don't permit non-interface elements in interfaces import "unsafe" const pi = 3.1415 type ( N undefined /* ERROR "undefined" */ B bool I int32 A [10]P T struct { x, y P } P *T R (*R) F func(A) I Y interface { f(A) I } S [](((P))) M map[I]F C chan<- I // blank types must be typechecked _ pi /* ERROR "not a type" */ _ struct{} _ struct{ pi /* ERROR "not a type" */ } ) // declarations of init const _, init /* ERROR "cannot declare init" */ , _ = 0, 1, 2 type init /* ERROR "cannot declare init" */ struct{} var _, init /* ERROR "cannot declare init" */ int func init() {} func init /* ERROR "missing function body" */ () func _() { const init = 0 } func _() { type init int } func _() { var init int; _ = init } // invalid array types type ( iA0 [... /* ERROR "invalid use of [...] array" */ ]byte // The error message below could be better. At the moment // we believe an integer that is too large is not an integer. // But at least we get an error. iA1 [1 /* ERROR "invalid array length" */ <<100]int iA2 [- /* ERROR "invalid array length" */ 1]complex128 iA3 ["foo" /* ERROR "must be integer" */ ]string iA4 [float64 /* ERROR "must be integer" */ (0)]int ) type ( p1 pi.foo /* ERROR "pi.foo is not a type" */ p2 unsafe.Pointer ) type ( Pi pi /* ERROR "not a type" */ a /* ERROR "invalid recursive type" */ a a /* ERROR "redeclared" */ int b /* ERROR "invalid recursive type" */ c c d d e e b t *t U V V *W W U P1 *S2 P2 P1 S0 struct { } S1 struct { a, b, c int u, v, a /* ERROR "redeclared" */ float32 } S2 struct { S0 // embedded field S0 /* ERROR "redeclared" */ int } S3 struct { x S2 } S4/* ERROR "invalid recursive type" */ struct { S4 } S5 /* ERROR "invalid recursive type" */ struct { S6 } S6 struct { field S7 } S7 struct { S5 } L1 []L1 L2 []int A1 [10.0]int A2 /* ERROR "invalid recursive type" */ [10]A2 A3 /* ERROR "invalid recursive type" */ [10]struct { x A4 } A4 [10]A3 F1 func() F2 func(x, y, z float32) F3 func(x, y, x /* ERROR "redeclared" */ float32) F4 func() (x, y, x /* ERROR "redeclared" */ float32) F5 func(x int) (x /* ERROR "redeclared" */ float32) F6 func(x ...int) I1 interface{} I2 interface { m1() } I3 interface { m1() m1 /* ERROR "duplicate method m1" */ () } I4 interface { m1(x, y, x /* ERROR "redeclared" */ float32) m2() (x, y, x /* ERROR "redeclared" */ float32) m3(x int) (x /* ERROR "redeclared" */ float32) } I5 interface { m1(I5) } I6 interface { S0 /* ERROR "non-interface type S0" */ } I7 interface { I1 I1 } I8 /* ERROR "invalid recursive type" */ interface { I8 } I9 /* ERROR "invalid recursive type" */ interface { I10 } I10 interface { I11 } I11 interface { I9 } C1 chan int C2 <-chan int C3 chan<- C3 C4 chan C5 C5 chan C6 C6 chan C4 M1 map[Last]string M2 map[string]M2 Last int ) // cycles in function/method declarations // (test cases for issues #5217, #25790 and variants) func f1(x f1 /* ERROR "not a type" */ ) {} func f2(x *f2 /* ERROR "not a type" */ ) {} func f3() (x f3 /* ERROR "not a type" */ ) { return } func f4() (x *f4 /* ERROR "not a type" */ ) { return } // TODO(#43215) this should be detected as a cycle error func f5([unsafe.Sizeof(f5)]int) {} func (S0) m1 (x S0.m1 /* ERROR "S0.m1 is not a type" */ ) {} func (S0) m2 (x *S0.m2 /* ERROR "S0.m2 is not a type" */ ) {} func (S0) m3 () (x S0.m3 /* ERROR "S0.m3 is not a type" */ ) { return } func (S0) m4 () (x *S0.m4 /* ERROR "S0.m4 is not a type" */ ) { return } // interfaces may not have any blank methods type BlankI interface { _ /* ERROR "methods must have a unique non-blank name" */ () _ /* ERROR "methods must have a unique non-blank name" */ (float32) int m() } // non-interface types may have multiple blank methods type BlankT struct{} func (BlankT) _() {} func (BlankT) _(int) {} func (BlankT) _() int { return 0 } func (BlankT) _(int) int { return 0}
go/src/internal/types/testdata/check/decls0.go/0
{ "file_path": "go/src/internal/types/testdata/check/decls0.go", "repo_id": "go", "token_count": 1719 }
306
// Copyright 2013 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. // terminating statements package stmt1 func _() {} func _() int {} /* ERROR "missing return" */ func _() int { panic(0) } func _() int { (panic(0)) } // block statements func _(x, y int) (z int) { { return } } func _(x, y int) (z int) { { return; ; ; // trailing empty statements are ok } ; ; ; } func _(x, y int) (z int) { { } } /* ERROR "missing return" */ func _(x, y int) (z int) { { ; ; ; } ; ; ; } /* ERROR "missing return" */ // if statements func _(x, y int) (z int) { if x < y { return } return 1 } func _(x, y int) (z int) { if x < y { return; ; ; ; } return 1 } func _(x, y int) (z int) { if x < y { return } return 1; ; } func _(x, y int) (z int) { if x < y { return } } /* ERROR "missing return" */ func _(x, y int) (z int) { if x < y { } else { return 1 } } /* ERROR "missing return" */ func _(x, y int) (z int) { if x < y { return } else { return } } // for statements func _(x, y int) (z int) { for x < y { return } } /* ERROR "missing return" */ func _(x, y int) (z int) { for { return } } func _(x, y int) (z int) { for { return; ; ; ; } } func _(x, y int) (z int) { for { return break } ; ; ; } /* ERROR "missing return" */ func _(x, y int) (z int) { for { for { break } return } } func _(x, y int) (z int) { for { for { break } return ; ; } ; } func _(x, y int) (z int) { L: for { for { break L } return } } /* ERROR "missing return" */ // switch statements func _(x, y int) (z int) { switch x { case 0: return default: return } } func _(x, y int) (z int) { switch x { case 0: return; default: return; ; ; } } func _(x, y int) (z int) { switch x { case 0: return } } /* ERROR "missing return" */ func _(x, y int) (z int) { switch x { case 0: return case 1: break } } /* ERROR "missing return" */ func _(x, y int) (z int) { switch x { case 0: return default: switch y { case 0: break } panic(0) } } func _(x, y int) (z int) { switch x { case 0: return default: switch y { case 0: break } panic(0); ; ; } ; } func _(x, y int) (z int) { L: switch x { case 0: return default: switch y { case 0: break L } panic(0) } } /* ERROR "missing return" */ // select statements func _(ch chan int) (z int) { select {} } // nice! func _(ch chan int) (z int) { select {} ; ; } func _(ch chan int) (z int) { select { default: break } } /* ERROR "missing return" */ func _(ch chan int) (z int) { select { case <-ch: return default: break } } /* ERROR "missing return" */ func _(ch chan int) (z int) { select { case <-ch: return default: for i := 0; i < 10; i++ { break } return } } func _(ch chan int) (z int) { select { case <-ch: return; ; ; default: for i := 0; i < 10; i++ { break } return; ; ; } ; ; ; } func _(ch chan int) (z int) { L: select { case <-ch: return default: for i := 0; i < 10; i++ { break L } return } ; ; ; } /* ERROR "missing return" */ func parenPanic() int { ((((((panic)))(0)))) } func issue23218a() int { { panic := func(interface{}){} panic(0) } } /* ERROR "missing return" */ func issue23218b() int { { panic := func(interface{}){} ((((panic))))(0) } } /* ERROR "missing return" */
go/src/internal/types/testdata/check/stmt1.go/0
{ "file_path": "go/src/internal/types/testdata/check/stmt1.go", "repo_id": "go", "token_count": 1526 }
307
// Copyright 2020 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. package issue20583 const ( _ = 6e886451608 /* ERROR "malformed constant" */ /2 _ = 6e886451608i /* ERROR "malformed constant" */ /2 _ = 0 * 1e+1000000000 // ERROR "malformed constant" x = 1e100000000 _ = x*x*x*x*x*x* /* ERROR "not representable" */ x )
go/src/internal/types/testdata/fixedbugs/issue20583.go/0
{ "file_path": "go/src/internal/types/testdata/fixedbugs/issue20583.go", "repo_id": "go", "token_count": 145 }
308
// Copyright 2020 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. package p func _[T any](x interface{}){ switch x.(type) { case T: // ok to use a type parameter case int: } switch x.(type) { case T: case T /* ERROR "duplicate case" */ : } } type constraint interface { ~int } func _[T constraint](x interface{}){ switch x.(type) { case T: // ok to use a type parameter even if type set contains int case int: } } func _(x constraint /* ERROR "contains type constraints" */ ) { switch x.(type) { // no need to report another error } }
go/src/internal/types/testdata/fixedbugs/issue42758.go/0
{ "file_path": "go/src/internal/types/testdata/fixedbugs/issue42758.go", "repo_id": "go", "token_count": 216 }
309
// Copyright 2021 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. package p type Builder /* ERROR "invalid recursive type" */ [T interface{ struct{ Builder[T] } }] struct{} type myBuilder struct { Builder[myBuilder] }
go/src/internal/types/testdata/fixedbugs/issue45550.go/0
{ "file_path": "go/src/internal/types/testdata/fixedbugs/issue45550.go", "repo_id": "go", "token_count": 88 }
310
// Copyright 2021 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. package p // For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639). // type T1[P any] P // // func (T1[_]) m() {} // // func _[P any](x *T1[P]) { // // x.m exists because x is of type *T1 where T1 is a defined type // // (even though under(T1) is a type parameter) // x.m() // } func _[P interface{ m() }](x P) { x.m() // (&x).m doesn't exist because &x is of type *P // and pointers to type parameters don't have methods (&x).m /* ERROR "type *P is pointer to type parameter, not type parameter" */ () } type T2 interface{ m() } func _(x *T2) { // x.m doesn't exists because x is of type *T2 // and pointers to interfaces don't have methods x.m /* ERROR "type *T2 is pointer to interface, not interface" */() } // Test case 1 from issue type Fooer1[t any] interface { Foo(Barer[t]) } type Barer[t any] interface { Bar(t) } // For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639). // type Foo1[t any] t // type Bar[t any] t // // func (l Foo1[t]) Foo(v Barer[t]) { v.Bar(t(l)) } // func (b *Bar[t]) Bar(l t) { *b = Bar[t](l) } // // func _[t any](f Fooer1[t]) t { // var b Bar[t] // f.Foo(&b) // return t(b) // } // Test case 2 from issue // For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639). // type Fooer2[t any] interface { // Foo() // } // // type Foo2[t any] t // // func (f *Foo2[t]) Foo() {} // // func _[t any](v t) { // var f = Foo2[t](v) // _ = Fooer2[t](&f) // }
go/src/internal/types/testdata/fixedbugs/issue47747.go/0
{ "file_path": "go/src/internal/types/testdata/fixedbugs/issue47747.go", "repo_id": "go", "token_count": 723 }
311
// Copyright 2021 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. package p func f[P any](a, _ P) { var x int // TODO(gri) these error messages, while correct, could be better f(a, x /* ERROR "type int of x does not match inferred type P for P" */) f(x, a /* ERROR "type P of a does not match inferred type int for P" */) } func g[P any](a, b P) { g(a, b) g(&a, &b) g([]P{}, []P{}) // work-around: provide type argument explicitly g[*P](&a, &b) g[[]P]([]P{}, []P{}) }
go/src/internal/types/testdata/fixedbugs/issue48619.go/0
{ "file_path": "go/src/internal/types/testdata/fixedbugs/issue48619.go", "repo_id": "go", "token_count": 218 }
312
// Copyright 2021 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. package p type integer interface { ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr } func Add1024[T integer](s []T) { for i, v := range s { s[i] = v + 1024 // ERROR "cannot convert 1024 (untyped int constant) to type T" } } func f[T interface{ int8 }]() { println(T(1024 /* ERROR "cannot convert 1024 (untyped int value) to type T" */)) }
go/src/internal/types/testdata/fixedbugs/issue49247.go/0
{ "file_path": "go/src/internal/types/testdata/fixedbugs/issue49247.go", "repo_id": "go", "token_count": 199 }
313
// Copyright 2022 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. package p func _[S string | []byte](s S) { var buf []byte _ = append(buf, s...) } func _[S ~string | ~[]byte](s S) { var buf []byte _ = append(buf, s...) } // test case from issue type byteseq interface { string | []byte } // This should allow to eliminate the two functions above. func AppendByteString[source byteseq](buf []byte, s source) []byte { return append(buf, s[1:6]...) }
go/src/internal/types/testdata/fixedbugs/issue50281.go/0
{ "file_path": "go/src/internal/types/testdata/fixedbugs/issue50281.go", "repo_id": "go", "token_count": 188 }
314
// -lang=go1.12 // Copyright 2022 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. package p type resultFlags uint // Example from #52031. // // The following shifts should not produce errors on Go < 1.13, as their // untyped constant operands are representable by type uint. const ( _ resultFlags = (1 << iota) / 2 reportEqual reportUnequal reportByIgnore reportByMethod reportByFunc reportByCycle ) // Invalid cases. var x int = 1 var _ = (8 << x /* ERRORx `signed shift count .* requires go1.13 or later` */) const _ = (1 << 1.2 /* ERROR "truncated to uint" */) var y float64 var _ = (1 << y /* ERROR "must be integer" */)
go/src/internal/types/testdata/fixedbugs/issue52031.go/0
{ "file_path": "go/src/internal/types/testdata/fixedbugs/issue52031.go", "repo_id": "go", "token_count": 241 }
315
// Copyright 2023 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. package p func f[P any](P) P { panic(0) } var v func(string) int = f // ERROR "inferred type func(string) string for func(P) P does not match type func(string) int of v" func _() func(string) int { return f // ERROR "inferred type func(string) string for func(P) P does not match type func(string) int of result variable" }
go/src/internal/types/testdata/fixedbugs/issue60747.go/0
{ "file_path": "go/src/internal/types/testdata/fixedbugs/issue60747.go", "repo_id": "go", "token_count": 149 }
316
// -lang=go1.16 // 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. //go:build go1.21 package main import "slices" func main() { _ = slices.Clone([]string{}) // no error should be reported here }
go/src/internal/types/testdata/fixedbugs/issue66064.go/0
{ "file_path": "go/src/internal/types/testdata/fixedbugs/issue66064.go", "repo_id": "go", "token_count": 100 }
317
// Copyright 2023 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. package p type MyInt int32 type MyBool bool type MyString string type MyFunc1 func(func(int) bool) type MyFunc2 func(int) bool type MyFunc3 func(MyFunc2) type T struct{} func (*T) PM() {} func (T) M() {} func f1() {} func f2(func()) {} func f4(func(int) bool) {} func f5(func(int, string) bool) {} func f7(func(int) MyBool) {} func f8(func(MyInt, MyString) MyBool) {} func test() { // TODO: Would be nice to test 'for range T.M' and 'for range (*T).PM' directly, // but there is no gofmt-friendly way to write the error pattern in the right place. m1 := T.M for range m1 /* ERROR "cannot range over m1 (variable of type func(T)): func must be func(yield func(...) bool): argument is not func" */ { } m2 := (*T).PM for range m2 /* ERROR "cannot range over m2 (variable of type func(*T)): func must be func(yield func(...) bool): argument is not func" */ { } for range f1 /* ERROR "cannot range over f1 (value of type func()): func must be func(yield func(...) bool): wrong argument count" */ { } for range f2 /* ERROR "cannot range over f2 (value of type func(func())): func must be func(yield func(...) bool): yield func does not return bool" */ { } for range f4 { } for _ = range f4 { } for _, _ = range f5 { } for _ = range f7 { } for _, _ = range f8 { } for range 1 { } for range uint8(1) { } for range int64(1) { } for range MyInt(1) { } for range 'x' { } for range 1.0 /* ERROR "cannot range over 1.0 (untyped float constant 1)" */ { } for _ = range MyFunc1(nil) { } for _ = range MyFunc3(nil) { } for _ = range (func(MyFunc2))(nil) { } var i int var s string var mi MyInt var ms MyString for i := range f4 { _ = i } for i = range f4 { _ = i } for i, s := range f5 { _, _ = i, s } for i, s = range f5 { _, _ = i, s } for i, _ := range f5 { _ = i } for i, _ = range f5 { _ = i } for i := range f7 { _ = i } for i = range f7 { _ = i } for mi, _ := range f8 { _ = mi } for mi, _ = range f8 { _ = mi } for mi, ms := range f8 { _, _ = mi, ms } for i /* ERROR "cannot use i (value of type MyInt) as int value in assignment" */, s /* ERROR "cannot use s (value of type MyString) as string value in assignment" */ = range f8 { _, _ = mi, ms } for mi, ms := range f8 { i, s = mi /* ERROR "cannot use mi (variable of type MyInt) as int value in assignment" */, ms /* ERROR "cannot use ms (variable of type MyString) as string value in assignment" */ } for mi, ms = range f8 { _, _ = mi, ms } for i := range 10 { _ = i } for i = range 10 { _ = i } for i, j /* ERROR "range over 10 (untyped int constant) permits only one iteration variable" */ := range 10 { _, _ = i, j } for mi := range MyInt(10) { _ = mi } for mi = range MyInt(10) { _ = mi } } func _[T int | string](x T) { for range x /* ERROR "cannot range over x (variable of type T constrained by int | string): no core type" */ { } } func _[T int | int64](x T) { for range x /* ERROR "cannot range over x (variable of type T constrained by int | int64): no core type" */ { } } func _[T ~int](x T) { for range x { // ok } } func _[T any](x func(func(T) bool)) { for _ = range x { // ok } } func _[T ~func(func(int) bool)](x T) { for _ = range x { // ok } } // go.dev/issue/65236 func seq0(func() bool) {} func seq1(func(int) bool) {} func seq2(func(int, int) bool) {} func _() { for range seq0 { } for _ /* ERROR "range over seq0 (value of type func(func() bool)) permits no iteration variables" */ = range seq0 { } for range seq1 { } for _ = range seq1 { } for _, _ /* ERROR "range over seq1 (value of type func(func(int) bool)) permits only one iteration variable" */ = range seq1 { } for range seq2 { } for _ = range seq2 { } for _, _ = range seq2 { } // Note: go/types reports a parser error in this case, hence the different error messages. for _, _, _ /* ERRORx "(range clause permits at most two iteration variables|expected at most 2 expressions)" */ = range seq2 { } }
go/src/internal/types/testdata/spec/range.go/0
{ "file_path": "go/src/internal/types/testdata/spec/range.go", "repo_id": "go", "token_count": 1720 }
318
// Copyright 2020 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. package fs import ( "errors" "internal/bytealg" "slices" ) // ReadDirFS is the interface implemented by a file system // that provides an optimized implementation of [ReadDir]. type ReadDirFS interface { FS // ReadDir reads the named directory // and returns a list of directory entries sorted by filename. ReadDir(name string) ([]DirEntry, error) } // ReadDir reads the named directory // and returns a list of directory entries sorted by filename. // // If fs implements [ReadDirFS], ReadDir calls fs.ReadDir. // Otherwise ReadDir calls fs.Open and uses ReadDir and Close // on the returned file. func ReadDir(fsys FS, name string) ([]DirEntry, error) { if fsys, ok := fsys.(ReadDirFS); ok { return fsys.ReadDir(name) } file, err := fsys.Open(name) if err != nil { return nil, err } defer file.Close() dir, ok := file.(ReadDirFile) if !ok { return nil, &PathError{Op: "readdir", Path: name, Err: errors.New("not implemented")} } list, err := dir.ReadDir(-1) slices.SortFunc(list, func(a, b DirEntry) int { return bytealg.CompareString(a.Name(), b.Name()) }) return list, err } // dirInfo is a DirEntry based on a FileInfo. type dirInfo struct { fileInfo FileInfo } func (di dirInfo) IsDir() bool { return di.fileInfo.IsDir() } func (di dirInfo) Type() FileMode { return di.fileInfo.Mode().Type() } func (di dirInfo) Info() (FileInfo, error) { return di.fileInfo, nil } func (di dirInfo) Name() string { return di.fileInfo.Name() } func (di dirInfo) String() string { return FormatDirEntry(di) } // FileInfoToDirEntry returns a [DirEntry] that returns information from info. // If info is nil, FileInfoToDirEntry returns nil. func FileInfoToDirEntry(info FileInfo) DirEntry { if info == nil { return nil } return dirInfo{fileInfo: info} }
go/src/io/fs/readdir.go/0
{ "file_path": "go/src/io/fs/readdir.go", "repo_id": "go", "token_count": 650 }
319
// Copyright 2010 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. package ioutil_test import ( "io/fs" . "io/ioutil" "os" "path/filepath" "regexp" "strings" "testing" ) func TestTempFile(t *testing.T) { dir, err := TempDir("", "TestTempFile_BadDir") if err != nil { t.Fatal(err) } defer os.RemoveAll(dir) nonexistentDir := filepath.Join(dir, "_not_exists_") f, err := TempFile(nonexistentDir, "foo") if f != nil || err == nil { t.Errorf("TempFile(%q, `foo`) = %v, %v", nonexistentDir, f, err) } } func TestTempFile_pattern(t *testing.T) { tests := []struct{ pattern, prefix, suffix string }{ {"ioutil_test", "ioutil_test", ""}, {"ioutil_test*", "ioutil_test", ""}, {"ioutil_test*xyz", "ioutil_test", "xyz"}, } for _, test := range tests { f, err := TempFile("", test.pattern) if err != nil { t.Errorf("TempFile(..., %q) error: %v", test.pattern, err) continue } defer os.Remove(f.Name()) base := filepath.Base(f.Name()) f.Close() if !(strings.HasPrefix(base, test.prefix) && strings.HasSuffix(base, test.suffix)) { t.Errorf("TempFile pattern %q created bad name %q; want prefix %q & suffix %q", test.pattern, base, test.prefix, test.suffix) } } } // This string is from os.errPatternHasSeparator. const patternHasSeparator = "pattern contains path separator" func TestTempFile_BadPattern(t *testing.T) { tmpDir, err := TempDir("", t.Name()) if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpDir) const sep = string(os.PathSeparator) tests := []struct { pattern string wantErr bool }{ {"ioutil*test", false}, {"ioutil_test*foo", false}, {"ioutil_test" + sep + "foo", true}, {"ioutil_test*" + sep + "foo", true}, {"ioutil_test" + sep + "*foo", true}, {sep + "ioutil_test" + sep + "*foo", true}, {"ioutil_test*foo" + sep, true}, } for _, tt := range tests { t.Run(tt.pattern, func(t *testing.T) { tmpfile, err := TempFile(tmpDir, tt.pattern) defer func() { if tmpfile != nil { tmpfile.Close() } }() if tt.wantErr { if err == nil { t.Errorf("Expected an error for pattern %q", tt.pattern) } else if !strings.Contains(err.Error(), patternHasSeparator) { t.Errorf("Error mismatch: got %#v, want %q for pattern %q", err, patternHasSeparator, tt.pattern) } } else if err != nil { t.Errorf("Unexpected error %v for pattern %q", err, tt.pattern) } }) } } func TestTempDir(t *testing.T) { name, err := TempDir("/_not_exists_", "foo") if name != "" || err == nil { t.Errorf("TempDir(`/_not_exists_`, `foo`) = %v, %v", name, err) } tests := []struct { pattern string wantPrefix, wantSuffix string }{ {"ioutil_test", "ioutil_test", ""}, {"ioutil_test*", "ioutil_test", ""}, {"ioutil_test*xyz", "ioutil_test", "xyz"}, } dir := os.TempDir() runTestTempDir := func(t *testing.T, pattern, wantRePat string) { name, err := TempDir(dir, pattern) if name == "" || err != nil { t.Fatalf("TempDir(dir, `ioutil_test`) = %v, %v", name, err) } defer os.Remove(name) re := regexp.MustCompile(wantRePat) if !re.MatchString(name) { t.Errorf("TempDir(%q, %q) created bad name\n\t%q\ndid not match pattern\n\t%q", dir, pattern, name, wantRePat) } } for _, tt := range tests { t.Run(tt.pattern, func(t *testing.T) { wantRePat := "^" + regexp.QuoteMeta(filepath.Join(dir, tt.wantPrefix)) + "[0-9]+" + regexp.QuoteMeta(tt.wantSuffix) + "$" runTestTempDir(t, tt.pattern, wantRePat) }) } // Separately testing "*xyz" (which has no prefix). That is when constructing the // pattern to assert on, as in the previous loop, using filepath.Join for an empty // prefix filepath.Join(dir, ""), produces the pattern: // ^<DIR>[0-9]+xyz$ // yet we just want to match // "^<DIR>/[0-9]+xyz" t.Run("*xyz", func(t *testing.T) { wantRePat := "^" + regexp.QuoteMeta(filepath.Join(dir)) + regexp.QuoteMeta(string(filepath.Separator)) + "[0-9]+xyz$" runTestTempDir(t, "*xyz", wantRePat) }) } // test that we return a nice error message if the dir argument to TempDir doesn't // exist (or that it's empty and os.TempDir doesn't exist) func TestTempDir_BadDir(t *testing.T) { dir, err := TempDir("", "TestTempDir_BadDir") if err != nil { t.Fatal(err) } defer os.RemoveAll(dir) badDir := filepath.Join(dir, "not-exist") _, err = TempDir(badDir, "foo") if pe, ok := err.(*fs.PathError); !ok || !os.IsNotExist(err) || pe.Path != badDir { t.Errorf("TempDir error = %#v; want PathError for path %q satisfying os.IsNotExist", err, badDir) } } func TestTempDir_BadPattern(t *testing.T) { tmpDir, err := TempDir("", t.Name()) if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpDir) const sep = string(os.PathSeparator) tests := []struct { pattern string wantErr bool }{ {"ioutil*test", false}, {"ioutil_test*foo", false}, {"ioutil_test" + sep + "foo", true}, {"ioutil_test*" + sep + "foo", true}, {"ioutil_test" + sep + "*foo", true}, {sep + "ioutil_test" + sep + "*foo", true}, {"ioutil_test*foo" + sep, true}, } for _, tt := range tests { t.Run(tt.pattern, func(t *testing.T) { _, err := TempDir(tmpDir, tt.pattern) if tt.wantErr { if err == nil { t.Errorf("Expected an error for pattern %q", tt.pattern) } else if !strings.Contains(err.Error(), patternHasSeparator) { t.Errorf("Error mismatch: got %#v, want %q for pattern %q", err, patternHasSeparator, tt.pattern) } } else if err != nil { t.Errorf("Unexpected error %v for pattern %q", err, tt.pattern) } }) } }
go/src/io/ioutil/tempfile_test.go/0
{ "file_path": "go/src/io/ioutil/tempfile_test.go", "repo_id": "go", "token_count": 2418 }
320
// Copyright 2022 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. package slog_test import ( "context" "log/slog" "log/slog/internal/slogtest" "os" ) // A LevelHandler wraps a Handler with an Enabled method // that returns false for levels below a minimum. type LevelHandler struct { level slog.Leveler handler slog.Handler } // NewLevelHandler returns a LevelHandler with the given level. // All methods except Enabled delegate to h. func NewLevelHandler(level slog.Leveler, h slog.Handler) *LevelHandler { // Optimization: avoid chains of LevelHandlers. if lh, ok := h.(*LevelHandler); ok { h = lh.Handler() } return &LevelHandler{level, h} } // Enabled implements Handler.Enabled by reporting whether // level is at least as large as h's level. func (h *LevelHandler) Enabled(_ context.Context, level slog.Level) bool { return level >= h.level.Level() } // Handle implements Handler.Handle. func (h *LevelHandler) Handle(ctx context.Context, r slog.Record) error { return h.handler.Handle(ctx, r) } // WithAttrs implements Handler.WithAttrs. func (h *LevelHandler) WithAttrs(attrs []slog.Attr) slog.Handler { return NewLevelHandler(h.level, h.handler.WithAttrs(attrs)) } // WithGroup implements Handler.WithGroup. func (h *LevelHandler) WithGroup(name string) slog.Handler { return NewLevelHandler(h.level, h.handler.WithGroup(name)) } // Handler returns the Handler wrapped by h. func (h *LevelHandler) Handler() slog.Handler { return h.handler } // This example shows how to Use a LevelHandler to change the level of an // existing Handler while preserving its other behavior. // // This example demonstrates increasing the log level to reduce a logger's // output. // // Another typical use would be to decrease the log level (to LevelDebug, say) // during a part of the program that was suspected of containing a bug. func ExampleHandler_levelHandler() { th := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime}) logger := slog.New(NewLevelHandler(slog.LevelWarn, th)) logger.Info("not printed") logger.Warn("printed") // Output: // level=WARN msg=printed }
go/src/log/slog/example_level_handler_test.go/0
{ "file_path": "go/src/log/slog/example_level_handler_test.go", "repo_id": "go", "token_count": 668 }
321
// Copyright 2022 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. package slog import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "log/slog/internal/buffer" "strconv" "sync" "time" "unicode/utf8" ) // JSONHandler is a [Handler] that writes Records to an [io.Writer] as // line-delimited JSON objects. type JSONHandler struct { *commonHandler } // NewJSONHandler creates a [JSONHandler] that writes to w, // using the given options. // If opts is nil, the default options are used. func NewJSONHandler(w io.Writer, opts *HandlerOptions) *JSONHandler { if opts == nil { opts = &HandlerOptions{} } return &JSONHandler{ &commonHandler{ json: true, w: w, opts: *opts, mu: &sync.Mutex{}, }, } } // Enabled reports whether the handler handles records at the given level. // The handler ignores records whose level is lower. func (h *JSONHandler) Enabled(_ context.Context, level Level) bool { return h.commonHandler.enabled(level) } // WithAttrs returns a new [JSONHandler] whose attributes consists // of h's attributes followed by attrs. func (h *JSONHandler) WithAttrs(attrs []Attr) Handler { return &JSONHandler{commonHandler: h.commonHandler.withAttrs(attrs)} } func (h *JSONHandler) WithGroup(name string) Handler { return &JSONHandler{commonHandler: h.commonHandler.withGroup(name)} } // Handle formats its argument [Record] as a JSON object on a single line. // // If the Record's time is zero, the time is omitted. // Otherwise, the key is "time" // and the value is output as with json.Marshal. // // If the Record's level is zero, the level is omitted. // Otherwise, the key is "level" // and the value of [Level.String] is output. // // If the AddSource option is set and source information is available, // the key is "source", and the value is a record of type [Source]. // // The message's key is "msg". // // To modify these or other attributes, or remove them from the output, use // [HandlerOptions.ReplaceAttr]. // // Values are formatted as with an [encoding/json.Encoder] with SetEscapeHTML(false), // with two exceptions. // // First, an Attr whose Value is of type error is formatted as a string, by // calling its Error method. Only errors in Attrs receive this special treatment, // not errors embedded in structs, slices, maps or other data structures that // are processed by the [encoding/json] package. // // Second, an encoding failure does not cause Handle to return an error. // Instead, the error message is formatted as a string. // // Each call to Handle results in a single serialized call to io.Writer.Write. func (h *JSONHandler) Handle(_ context.Context, r Record) error { return h.commonHandler.handle(r) } // Adapted from time.Time.MarshalJSON to avoid allocation. func appendJSONTime(s *handleState, t time.Time) { if y := t.Year(); y < 0 || y >= 10000 { // RFC 3339 is clear that years are 4 digits exactly. // See golang.org/issue/4556#c15 for more discussion. s.appendError(errors.New("time.Time year outside of range [0,9999]")) } s.buf.WriteByte('"') *s.buf = t.AppendFormat(*s.buf, time.RFC3339Nano) s.buf.WriteByte('"') } func appendJSONValue(s *handleState, v Value) error { switch v.Kind() { case KindString: s.appendString(v.str()) case KindInt64: *s.buf = strconv.AppendInt(*s.buf, v.Int64(), 10) case KindUint64: *s.buf = strconv.AppendUint(*s.buf, v.Uint64(), 10) case KindFloat64: // json.Marshal is funny about floats; it doesn't // always match strconv.AppendFloat. So just call it. // That's expensive, but floats are rare. if err := appendJSONMarshal(s.buf, v.Float64()); err != nil { return err } case KindBool: *s.buf = strconv.AppendBool(*s.buf, v.Bool()) case KindDuration: // Do what json.Marshal does. *s.buf = strconv.AppendInt(*s.buf, int64(v.Duration()), 10) case KindTime: s.appendTime(v.Time()) case KindAny: a := v.Any() _, jm := a.(json.Marshaler) if err, ok := a.(error); ok && !jm { s.appendString(err.Error()) } else { return appendJSONMarshal(s.buf, a) } default: panic(fmt.Sprintf("bad kind: %s", v.Kind())) } return nil } func appendJSONMarshal(buf *buffer.Buffer, v any) error { // Use a json.Encoder to avoid escaping HTML. var bb bytes.Buffer enc := json.NewEncoder(&bb) enc.SetEscapeHTML(false) if err := enc.Encode(v); err != nil { return err } bs := bb.Bytes() buf.Write(bs[:len(bs)-1]) // remove final newline return nil } // appendEscapedJSONString escapes s for JSON and appends it to buf. // It does not surround the string in quotation marks. // // Modified from encoding/json/encode.go:encodeState.string, // with escapeHTML set to false. func appendEscapedJSONString(buf []byte, s string) []byte { char := func(b byte) { buf = append(buf, b) } str := func(s string) { buf = append(buf, s...) } start := 0 for i := 0; i < len(s); { if b := s[i]; b < utf8.RuneSelf { if safeSet[b] { i++ continue } if start < i { str(s[start:i]) } char('\\') switch b { case '\\', '"': char(b) case '\n': char('n') case '\r': char('r') case '\t': char('t') default: // This encodes bytes < 0x20 except for \t, \n and \r. str(`u00`) char(hex[b>>4]) char(hex[b&0xF]) } i++ start = i continue } c, size := utf8.DecodeRuneInString(s[i:]) if c == utf8.RuneError && size == 1 { if start < i { str(s[start:i]) } str(`\ufffd`) i += size start = i continue } // U+2028 is LINE SEPARATOR. // U+2029 is PARAGRAPH SEPARATOR. // They are both technically valid characters in JSON strings, // but don't work in JSONP, which has to be evaluated as JavaScript, // and can lead to security holes there. It is valid JSON to // escape them, so we do so unconditionally. // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion. if c == '\u2028' || c == '\u2029' { if start < i { str(s[start:i]) } str(`\u202`) char(hex[c&0xF]) i += size start = i continue } i += size } if start < len(s) { str(s[start:]) } return buf } const hex = "0123456789abcdef" // Copied from encoding/json/tables.go. // // safeSet holds the value true if the ASCII character with the given array // position can be represented inside a JSON string without any further // escaping. // // All values are true except for the ASCII control characters (0-31), the // double quote ("), and the backslash character ("\"). var safeSet = [utf8.RuneSelf]bool{ ' ': true, '!': true, '"': false, '#': true, '$': true, '%': true, '&': true, '\'': true, '(': true, ')': true, '*': true, '+': true, ',': true, '-': true, '.': true, '/': true, '0': true, '1': true, '2': true, '3': true, '4': true, '5': true, '6': true, '7': true, '8': true, '9': true, ':': true, ';': true, '<': true, '=': true, '>': true, '?': true, '@': true, 'A': true, 'B': true, 'C': true, 'D': true, 'E': true, 'F': true, 'G': true, 'H': true, 'I': true, 'J': true, 'K': true, 'L': true, 'M': true, 'N': true, 'O': true, 'P': true, 'Q': true, 'R': true, 'S': true, 'T': true, 'U': true, 'V': true, 'W': true, 'X': true, 'Y': true, 'Z': true, '[': true, '\\': false, ']': true, '^': true, '_': true, '`': true, 'a': true, 'b': true, 'c': true, 'd': true, 'e': true, 'f': true, 'g': true, 'h': true, 'i': true, 'j': true, 'k': true, 'l': true, 'm': true, 'n': true, 'o': true, 'p': true, 'q': true, 'r': true, 's': true, 't': true, 'u': true, 'v': true, 'w': true, 'x': true, 'y': true, 'z': true, '{': true, '|': true, '}': true, '~': true, '\u007f': true, }
go/src/log/slog/json_handler.go/0
{ "file_path": "go/src/log/slog/json_handler.go", "repo_id": "go", "token_count": 3572 }
322
// Copyright 2009 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. //go:build !windows && !plan9 package syslog import ( "errors" "fmt" "log" "net" "os" "strings" "sync" "time" ) // The Priority is a combination of the syslog facility and // severity. For example, [LOG_ALERT] | [LOG_FTP] sends an alert severity // message from the FTP facility. The default severity is [LOG_EMERG]; // the default facility is [LOG_KERN]. type Priority int const severityMask = 0x07 const facilityMask = 0xf8 const ( // Severity. // From /usr/include/sys/syslog.h. // These are the same on Linux, BSD, and OS X. LOG_EMERG Priority = iota LOG_ALERT LOG_CRIT LOG_ERR LOG_WARNING LOG_NOTICE LOG_INFO LOG_DEBUG ) const ( // Facility. // From /usr/include/sys/syslog.h. // These are the same up to LOG_FTP on Linux, BSD, and OS X. LOG_KERN Priority = iota << 3 LOG_USER LOG_MAIL LOG_DAEMON LOG_AUTH LOG_SYSLOG LOG_LPR LOG_NEWS LOG_UUCP LOG_CRON LOG_AUTHPRIV LOG_FTP _ // unused _ // unused _ // unused _ // unused LOG_LOCAL0 LOG_LOCAL1 LOG_LOCAL2 LOG_LOCAL3 LOG_LOCAL4 LOG_LOCAL5 LOG_LOCAL6 LOG_LOCAL7 ) // A Writer is a connection to a syslog server. type Writer struct { priority Priority tag string hostname string network string raddr string mu sync.Mutex // guards conn conn serverConn } // This interface and the separate syslog_unix.go file exist for // Solaris support as implemented by gccgo. On Solaris you cannot // simply open a TCP connection to the syslog daemon. The gccgo // sources have a syslog_solaris.go file that implements unixSyslog to // return a type that satisfies this interface and simply calls the C // library syslog function. type serverConn interface { writeString(p Priority, hostname, tag, s, nl string) error close() error } type netConn struct { local bool conn net.Conn } // New establishes a new connection to the system log daemon. Each // write to the returned writer sends a log message with the given // priority (a combination of the syslog facility and severity) and // prefix tag. If tag is empty, the [os.Args][0] is used. func New(priority Priority, tag string) (*Writer, error) { return Dial("", "", priority, tag) } // Dial establishes a connection to a log daemon by connecting to // address raddr on the specified network. Each write to the returned // writer sends a log message with the facility and severity // (from priority) and tag. If tag is empty, the [os.Args][0] is used. // If network is empty, Dial will connect to the local syslog server. // Otherwise, see the documentation for net.Dial for valid values // of network and raddr. func Dial(network, raddr string, priority Priority, tag string) (*Writer, error) { if priority < 0 || priority > LOG_LOCAL7|LOG_DEBUG { return nil, errors.New("log/syslog: invalid priority") } if tag == "" { tag = os.Args[0] } hostname, _ := os.Hostname() w := &Writer{ priority: priority, tag: tag, hostname: hostname, network: network, raddr: raddr, } w.mu.Lock() defer w.mu.Unlock() err := w.connect() if err != nil { return nil, err } return w, err } // connect makes a connection to the syslog server. // It must be called with w.mu held. func (w *Writer) connect() (err error) { if w.conn != nil { // ignore err from close, it makes sense to continue anyway w.conn.close() w.conn = nil } if w.network == "" { w.conn, err = unixSyslog() if w.hostname == "" { w.hostname = "localhost" } } else { var c net.Conn c, err = net.Dial(w.network, w.raddr) if err == nil { w.conn = &netConn{ conn: c, local: w.network == "unixgram" || w.network == "unix", } if w.hostname == "" { w.hostname = c.LocalAddr().String() } } } return } // Write sends a log message to the syslog daemon. func (w *Writer) Write(b []byte) (int, error) { return w.writeAndRetry(w.priority, string(b)) } // Close closes a connection to the syslog daemon. func (w *Writer) Close() error { w.mu.Lock() defer w.mu.Unlock() if w.conn != nil { err := w.conn.close() w.conn = nil return err } return nil } // Emerg logs a message with severity [LOG_EMERG], ignoring the severity // passed to New. func (w *Writer) Emerg(m string) error { _, err := w.writeAndRetry(LOG_EMERG, m) return err } // Alert logs a message with severity [LOG_ALERT], ignoring the severity // passed to New. func (w *Writer) Alert(m string) error { _, err := w.writeAndRetry(LOG_ALERT, m) return err } // Crit logs a message with severity [LOG_CRIT], ignoring the severity // passed to New. func (w *Writer) Crit(m string) error { _, err := w.writeAndRetry(LOG_CRIT, m) return err } // Err logs a message with severity [LOG_ERR], ignoring the severity // passed to New. func (w *Writer) Err(m string) error { _, err := w.writeAndRetry(LOG_ERR, m) return err } // Warning logs a message with severity [LOG_WARNING], ignoring the // severity passed to New. func (w *Writer) Warning(m string) error { _, err := w.writeAndRetry(LOG_WARNING, m) return err } // Notice logs a message with severity [LOG_NOTICE], ignoring the // severity passed to New. func (w *Writer) Notice(m string) error { _, err := w.writeAndRetry(LOG_NOTICE, m) return err } // Info logs a message with severity [LOG_INFO], ignoring the severity // passed to New. func (w *Writer) Info(m string) error { _, err := w.writeAndRetry(LOG_INFO, m) return err } // Debug logs a message with severity [LOG_DEBUG], ignoring the severity // passed to New. func (w *Writer) Debug(m string) error { _, err := w.writeAndRetry(LOG_DEBUG, m) return err } func (w *Writer) writeAndRetry(p Priority, s string) (int, error) { pr := (w.priority & facilityMask) | (p & severityMask) w.mu.Lock() defer w.mu.Unlock() if w.conn != nil { if n, err := w.write(pr, s); err == nil { return n, nil } } if err := w.connect(); err != nil { return 0, err } return w.write(pr, s) } // write generates and writes a syslog formatted string. The // format is as follows: <PRI>TIMESTAMP HOSTNAME TAG[PID]: MSG func (w *Writer) write(p Priority, msg string) (int, error) { // ensure it ends in a \n nl := "" if !strings.HasSuffix(msg, "\n") { nl = "\n" } err := w.conn.writeString(p, w.hostname, w.tag, msg, nl) if err != nil { return 0, err } // Note: return the length of the input, not the number of // bytes printed by Fprintf, because this must behave like // an io.Writer. return len(msg), nil } func (n *netConn) writeString(p Priority, hostname, tag, msg, nl string) error { if n.local { // Compared to the network form below, the changes are: // 1. Use time.Stamp instead of time.RFC3339. // 2. Drop the hostname field from the Fprintf. timestamp := time.Now().Format(time.Stamp) _, err := fmt.Fprintf(n.conn, "<%d>%s %s[%d]: %s%s", p, timestamp, tag, os.Getpid(), msg, nl) return err } timestamp := time.Now().Format(time.RFC3339) _, err := fmt.Fprintf(n.conn, "<%d>%s %s %s[%d]: %s%s", p, timestamp, hostname, tag, os.Getpid(), msg, nl) return err } func (n *netConn) close() error { return n.conn.Close() } // NewLogger creates a [log.Logger] whose output is written to the // system log service with the specified priority, a combination of // the syslog facility and severity. The logFlag argument is the flag // set passed through to [log.New] to create the Logger. func NewLogger(p Priority, logFlag int) (*log.Logger, error) { s, err := New(p, "") if err != nil { return nil, err } return log.New(s, "", logFlag), nil }
go/src/log/syslog/syslog.go/0
{ "file_path": "go/src/log/syslog/syslog.go", "repo_id": "go", "token_count": 2777 }
323
// Copyright 2016 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. package math import "internal/cpu" func expTrampolineSetup(x float64) float64 func expAsm(x float64) float64 func logTrampolineSetup(x float64) float64 func logAsm(x float64) float64 // Below here all functions are grouped in stubs.go for other // architectures. const haveArchLog10 = true func archLog10(x float64) float64 func log10TrampolineSetup(x float64) float64 func log10Asm(x float64) float64 const haveArchCos = true func archCos(x float64) float64 func cosTrampolineSetup(x float64) float64 func cosAsm(x float64) float64 const haveArchCosh = true func archCosh(x float64) float64 func coshTrampolineSetup(x float64) float64 func coshAsm(x float64) float64 const haveArchSin = true func archSin(x float64) float64 func sinTrampolineSetup(x float64) float64 func sinAsm(x float64) float64 const haveArchSinh = true func archSinh(x float64) float64 func sinhTrampolineSetup(x float64) float64 func sinhAsm(x float64) float64 const haveArchTanh = true func archTanh(x float64) float64 func tanhTrampolineSetup(x float64) float64 func tanhAsm(x float64) float64 const haveArchLog1p = true func archLog1p(x float64) float64 func log1pTrampolineSetup(x float64) float64 func log1pAsm(x float64) float64 const haveArchAtanh = true func archAtanh(x float64) float64 func atanhTrampolineSetup(x float64) float64 func atanhAsm(x float64) float64 const haveArchAcos = true func archAcos(x float64) float64 func acosTrampolineSetup(x float64) float64 func acosAsm(x float64) float64 const haveArchAcosh = true func archAcosh(x float64) float64 func acoshTrampolineSetup(x float64) float64 func acoshAsm(x float64) float64 const haveArchAsin = true func archAsin(x float64) float64 func asinTrampolineSetup(x float64) float64 func asinAsm(x float64) float64 const haveArchAsinh = true func archAsinh(x float64) float64 func asinhTrampolineSetup(x float64) float64 func asinhAsm(x float64) float64 const haveArchErf = true func archErf(x float64) float64 func erfTrampolineSetup(x float64) float64 func erfAsm(x float64) float64 const haveArchErfc = true func archErfc(x float64) float64 func erfcTrampolineSetup(x float64) float64 func erfcAsm(x float64) float64 const haveArchAtan = true func archAtan(x float64) float64 func atanTrampolineSetup(x float64) float64 func atanAsm(x float64) float64 const haveArchAtan2 = true func archAtan2(y, x float64) float64 func atan2TrampolineSetup(x, y float64) float64 func atan2Asm(x, y float64) float64 const haveArchCbrt = true func archCbrt(x float64) float64 func cbrtTrampolineSetup(x float64) float64 func cbrtAsm(x float64) float64 const haveArchTan = true func archTan(x float64) float64 func tanTrampolineSetup(x float64) float64 func tanAsm(x float64) float64 const haveArchExpm1 = true func archExpm1(x float64) float64 func expm1TrampolineSetup(x float64) float64 func expm1Asm(x float64) float64 const haveArchPow = true func archPow(x, y float64) float64 func powTrampolineSetup(x, y float64) float64 func powAsm(x, y float64) float64 const haveArchFrexp = false func archFrexp(x float64) (float64, int) { panic("not implemented") } const haveArchLdexp = false func archLdexp(frac float64, exp int) float64 { panic("not implemented") } const haveArchLog2 = false func archLog2(x float64) float64 { panic("not implemented") } const haveArchMod = false func archMod(x, y float64) float64 { panic("not implemented") } const haveArchRemainder = false func archRemainder(x, y float64) float64 { panic("not implemented") } // hasVX reports whether the machine has the z/Architecture // vector facility installed and enabled. var hasVX = cpu.S390X.HasVX
go/src/math/arith_s390x.go/0
{ "file_path": "go/src/math/arith_s390x.go", "repo_id": "go", "token_count": 1361 }
324
// Copyright 2015 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 the Bits type used for testing Float operations // via an independent (albeit slower) representations for floating-point // numbers. package big import ( "fmt" "slices" "testing" ) // A Bits value b represents a finite floating-point number x of the form // // x = 2**b[0] + 2**b[1] + ... 2**b[len(b)-1] // // The order of slice elements is not significant. Negative elements may be // used to form fractions. A Bits value is normalized if each b[i] occurs at // most once. For instance Bits{0, 0, 1} is not normalized but represents the // same floating-point number as Bits{2}, which is normalized. The zero (nil) // value of Bits is a ready to use Bits value and represents the value 0. type Bits []int func (x Bits) add(y Bits) Bits { return append(x, y...) } func (x Bits) mul(y Bits) Bits { var p Bits for _, x := range x { for _, y := range y { p = append(p, x+y) } } return p } func TestMulBits(t *testing.T) { for _, test := range []struct { x, y, want Bits }{ {nil, nil, nil}, {Bits{}, Bits{}, nil}, {Bits{0}, Bits{0}, Bits{0}}, {Bits{0}, Bits{1}, Bits{1}}, {Bits{1}, Bits{1, 2, 3}, Bits{2, 3, 4}}, {Bits{-1}, Bits{1}, Bits{0}}, {Bits{-10, -1, 0, 1, 10}, Bits{1, 2, 3}, Bits{-9, -8, -7, 0, 1, 2, 1, 2, 3, 2, 3, 4, 11, 12, 13}}, } { got := fmt.Sprintf("%v", test.x.mul(test.y)) want := fmt.Sprintf("%v", test.want) if got != want { t.Errorf("%v * %v = %s; want %s", test.x, test.y, got, want) } } } // norm returns the normalized bits for x: It removes multiple equal entries // by treating them as an addition (e.g., Bits{5, 5} => Bits{6}), and it sorts // the result list for reproducible results. func (x Bits) norm() Bits { m := make(map[int]bool) for _, b := range x { for m[b] { m[b] = false b++ } m[b] = true } var z Bits for b, set := range m { if set { z = append(z, b) } } slices.Sort([]int(z)) return z } func TestNormBits(t *testing.T) { for _, test := range []struct { x, want Bits }{ {nil, nil}, {Bits{}, Bits{}}, {Bits{0}, Bits{0}}, {Bits{0, 0}, Bits{1}}, {Bits{3, 1, 1}, Bits{2, 3}}, {Bits{10, 9, 8, 7, 6, 6}, Bits{11}}, } { got := fmt.Sprintf("%v", test.x.norm()) want := fmt.Sprintf("%v", test.want) if got != want { t.Errorf("normBits(%v) = %s; want %s", test.x, got, want) } } } // round returns the Float value corresponding to x after rounding x // to prec bits according to mode. func (x Bits) round(prec uint, mode RoundingMode) *Float { x = x.norm() // determine range var min, max int for i, b := range x { if i == 0 || b < min { min = b } if i == 0 || b > max { max = b } } prec0 := uint(max + 1 - min) if prec >= prec0 { return x.Float() } // prec < prec0 // determine bit 0, rounding, and sticky bit, and result bits z var bit0, rbit, sbit uint var z Bits r := max - int(prec) for _, b := range x { switch { case b == r: rbit = 1 case b < r: sbit = 1 default: // b > r if b == r+1 { bit0 = 1 } z = append(z, b) } } // round f := z.Float() // rounded to zero if mode == ToNearestAway { panic("not yet implemented") } if mode == ToNearestEven && rbit == 1 && (sbit == 1 || sbit == 0 && bit0 != 0) || mode == AwayFromZero { // round away from zero f.SetMode(ToZero).SetPrec(prec) f.Add(f, Bits{int(r) + 1}.Float()) } return f } // Float returns the *Float z of the smallest possible precision such that // z = sum(2**bits[i]), with i = range bits. If multiple bits[i] are equal, // they are added: Bits{0, 1, 0}.Float() == 2**0 + 2**1 + 2**0 = 4. func (bits Bits) Float() *Float { // handle 0 if len(bits) == 0 { return new(Float) } // len(bits) > 0 // determine lsb exponent var min int for i, b := range bits { if i == 0 || b < min { min = b } } // create bit pattern x := NewInt(0) for _, b := range bits { badj := b - min // propagate carry if necessary for x.Bit(badj) != 0 { x.SetBit(x, badj, 0) badj++ } x.SetBit(x, badj, 1) } // create corresponding float z := new(Float).SetInt(x) // normalized if e := int64(z.exp) + int64(min); MinExp <= e && e <= MaxExp { z.exp = int32(e) } else { // this should never happen for our test cases panic("exponent out of range") } return z } func TestFromBits(t *testing.T) { for _, test := range []struct { bits Bits want string }{ // all different bit numbers {nil, "0"}, {Bits{0}, "0x.8p+1"}, {Bits{1}, "0x.8p+2"}, {Bits{-1}, "0x.8p+0"}, {Bits{63}, "0x.8p+64"}, {Bits{33, -30}, "0x.8000000000000001p+34"}, {Bits{255, 0}, "0x.8000000000000000000000000000000000000000000000000000000000000001p+256"}, // multiple equal bit numbers {Bits{0, 0}, "0x.8p+2"}, {Bits{0, 0, 0, 0}, "0x.8p+3"}, {Bits{0, 1, 0}, "0x.8p+3"}, {append(Bits{2, 1, 0} /* 7 */, Bits{3, 1} /* 10 */ ...), "0x.88p+5" /* 17 */}, } { f := test.bits.Float() if got := f.Text('p', 0); got != test.want { t.Errorf("setBits(%v) = %s; want %s", test.bits, got, test.want) } } }
go/src/math/big/bits_test.go/0
{ "file_path": "go/src/math/big/bits_test.go", "repo_id": "go", "token_count": 2235 }
325
// Copyright 2009 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. // A little test program and benchmark for rational arithmetics. // Computes a Hilbert matrix, its inverse, multiplies them // and verifies that the product is the identity matrix. package big import ( "fmt" "testing" ) type matrix struct { n, m int a []*Rat } func (a *matrix) at(i, j int) *Rat { if !(0 <= i && i < a.n && 0 <= j && j < a.m) { panic("index out of range") } return a.a[i*a.m+j] } func (a *matrix) set(i, j int, x *Rat) { if !(0 <= i && i < a.n && 0 <= j && j < a.m) { panic("index out of range") } a.a[i*a.m+j] = x } func newMatrix(n, m int) *matrix { if !(0 <= n && 0 <= m) { panic("illegal matrix") } a := new(matrix) a.n = n a.m = m a.a = make([]*Rat, n*m) return a } func newUnit(n int) *matrix { a := newMatrix(n, n) for i := 0; i < n; i++ { for j := 0; j < n; j++ { x := NewRat(0, 1) if i == j { x.SetInt64(1) } a.set(i, j, x) } } return a } func newHilbert(n int) *matrix { a := newMatrix(n, n) for i := 0; i < n; i++ { for j := 0; j < n; j++ { a.set(i, j, NewRat(1, int64(i+j+1))) } } return a } func newInverseHilbert(n int) *matrix { a := newMatrix(n, n) for i := 0; i < n; i++ { for j := 0; j < n; j++ { x1 := new(Rat).SetInt64(int64(i + j + 1)) x2 := new(Rat).SetInt(new(Int).Binomial(int64(n+i), int64(n-j-1))) x3 := new(Rat).SetInt(new(Int).Binomial(int64(n+j), int64(n-i-1))) x4 := new(Rat).SetInt(new(Int).Binomial(int64(i+j), int64(i))) x1.Mul(x1, x2) x1.Mul(x1, x3) x1.Mul(x1, x4) x1.Mul(x1, x4) if (i+j)&1 != 0 { x1.Neg(x1) } a.set(i, j, x1) } } return a } func (a *matrix) mul(b *matrix) *matrix { if a.m != b.n { panic("illegal matrix multiply") } c := newMatrix(a.n, b.m) for i := 0; i < c.n; i++ { for j := 0; j < c.m; j++ { x := NewRat(0, 1) for k := 0; k < a.m; k++ { x.Add(x, new(Rat).Mul(a.at(i, k), b.at(k, j))) } c.set(i, j, x) } } return c } func (a *matrix) eql(b *matrix) bool { if a.n != b.n || a.m != b.m { return false } for i := 0; i < a.n; i++ { for j := 0; j < a.m; j++ { if a.at(i, j).Cmp(b.at(i, j)) != 0 { return false } } } return true } func (a *matrix) String() string { s := "" for i := 0; i < a.n; i++ { for j := 0; j < a.m; j++ { s += fmt.Sprintf("\t%s", a.at(i, j)) } s += "\n" } return s } func doHilbert(t *testing.T, n int) { a := newHilbert(n) b := newInverseHilbert(n) I := newUnit(n) ab := a.mul(b) if !ab.eql(I) { if t == nil { panic("Hilbert failed") } t.Errorf("a = %s\n", a) t.Errorf("b = %s\n", b) t.Errorf("a*b = %s\n", ab) t.Errorf("I = %s\n", I) } } func TestHilbert(t *testing.T) { doHilbert(t, 10) } func BenchmarkHilbert(b *testing.B) { for i := 0; i < b.N; i++ { doHilbert(nil, 10) } }
go/src/math/big/hilbert_test.go/0
{ "file_path": "go/src/math/big/hilbert_test.go", "repo_id": "go", "token_count": 1564 }
326
// Copyright 2010 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. package big import ( "math" "testing" ) func TestZeroRat(t *testing.T) { var x, y, z Rat y.SetFrac64(0, 42) if x.Cmp(&y) != 0 { t.Errorf("x and y should be both equal and zero") } if s := x.String(); s != "0/1" { t.Errorf("got x = %s, want 0/1", s) } if s := x.RatString(); s != "0" { t.Errorf("got x = %s, want 0", s) } z.Add(&x, &y) if s := z.RatString(); s != "0" { t.Errorf("got x+y = %s, want 0", s) } z.Sub(&x, &y) if s := z.RatString(); s != "0" { t.Errorf("got x-y = %s, want 0", s) } z.Mul(&x, &y) if s := z.RatString(); s != "0" { t.Errorf("got x*y = %s, want 0", s) } // check for division by zero defer func() { if s := recover(); s == nil || s.(string) != "division by zero" { panic(s) } }() z.Quo(&x, &y) } func TestRatSign(t *testing.T) { zero := NewRat(0, 1) for _, a := range setStringTests { x, ok := new(Rat).SetString(a.in) if !ok { continue } s := x.Sign() e := x.Cmp(zero) if s != e { t.Errorf("got %d; want %d for z = %v", s, e, &x) } } } var ratCmpTests = []struct { rat1, rat2 string out int }{ {"0", "0/1", 0}, {"1/1", "1", 0}, {"-1", "-2/2", 0}, {"1", "0", 1}, {"0/1", "1/1", -1}, {"-5/1434770811533343057144", "-5/1434770811533343057145", -1}, {"49832350382626108453/8964749413", "49832350382626108454/8964749413", -1}, {"-37414950961700930/7204075375675961", "37414950961700930/7204075375675961", -1}, {"37414950961700930/7204075375675961", "74829901923401860/14408150751351922", 0}, } func TestRatCmp(t *testing.T) { for i, test := range ratCmpTests { x, _ := new(Rat).SetString(test.rat1) y, _ := new(Rat).SetString(test.rat2) out := x.Cmp(y) if out != test.out { t.Errorf("#%d got out = %v; want %v", i, out, test.out) } } } func TestIsInt(t *testing.T) { one := NewInt(1) for _, a := range setStringTests { x, ok := new(Rat).SetString(a.in) if !ok { continue } i := x.IsInt() e := x.Denom().Cmp(one) == 0 if i != e { t.Errorf("got IsInt(%v) == %v; want %v", x, i, e) } } } func TestRatAbs(t *testing.T) { zero := new(Rat) for _, a := range setStringTests { x, ok := new(Rat).SetString(a.in) if !ok { continue } e := new(Rat).Set(x) if e.Cmp(zero) < 0 { e.Sub(zero, e) } z := new(Rat).Abs(x) if z.Cmp(e) != 0 { t.Errorf("got Abs(%v) = %v; want %v", x, z, e) } } } func TestRatNeg(t *testing.T) { zero := new(Rat) for _, a := range setStringTests { x, ok := new(Rat).SetString(a.in) if !ok { continue } e := new(Rat).Sub(zero, x) z := new(Rat).Neg(x) if z.Cmp(e) != 0 { t.Errorf("got Neg(%v) = %v; want %v", x, z, e) } } } func TestRatInv(t *testing.T) { zero := new(Rat) for _, a := range setStringTests { x, ok := new(Rat).SetString(a.in) if !ok { continue } if x.Cmp(zero) == 0 { continue // avoid division by zero } e := new(Rat).SetFrac(x.Denom(), x.Num()) z := new(Rat).Inv(x) if z.Cmp(e) != 0 { t.Errorf("got Inv(%v) = %v; want %v", x, z, e) } } } type ratBinFun func(z, x, y *Rat) *Rat type ratBinArg struct { x, y, z string } func testRatBin(t *testing.T, i int, name string, f ratBinFun, a ratBinArg) { x, _ := new(Rat).SetString(a.x) y, _ := new(Rat).SetString(a.y) z, _ := new(Rat).SetString(a.z) out := f(new(Rat), x, y) if out.Cmp(z) != 0 { t.Errorf("%s #%d got %s want %s", name, i, out, z) } } var ratBinTests = []struct { x, y string sum, prod string }{ {"0", "0", "0", "0"}, {"0", "1", "1", "0"}, {"-1", "0", "-1", "0"}, {"-1", "1", "0", "-1"}, {"1", "1", "2", "1"}, {"1/2", "1/2", "1", "1/4"}, {"1/4", "1/3", "7/12", "1/12"}, {"2/5", "-14/3", "-64/15", "-28/15"}, {"4707/49292519774798173060", "-3367/70976135186689855734", "84058377121001851123459/1749296273614329067191168098769082663020", "-1760941/388732505247628681598037355282018369560"}, {"-61204110018146728334/3", "-31052192278051565633/2", "-215564796870448153567/6", "950260896245257153059642991192710872711/3"}, {"-854857841473707320655/4237645934602118692642972629634714039", "-18/31750379913563777419", "-27/133467566250814981", "15387441146526731771790/134546868362786310073779084329032722548987800600710485341"}, {"618575745270541348005638912139/19198433543745179392300736", "-19948846211000086/637313996471", "27674141753240653/30123979153216", "-6169936206128396568797607742807090270137721977/6117715203873571641674006593837351328"}, {"-3/26206484091896184128", "5/2848423294177090248", "15310893822118706237/9330894968229805033368778458685147968", "-5/24882386581946146755650075889827061248"}, {"26946729/330400702820", "41563965/225583428284", "1238218672302860271/4658307703098666660055", "224002580204097/14906584649915733312176"}, {"-8259900599013409474/7", "-84829337473700364773/56707961321161574960", "-468402123685491748914621885145127724451/396955729248131024720", "350340947706464153265156004876107029701/198477864624065512360"}, {"575775209696864/1320203974639986246357", "29/712593081308", "410331716733912717985762465/940768218243776489278275419794956", "808/45524274987585732633"}, {"1786597389946320496771/2066653520653241", "6269770/1992362624741777", "3559549865190272133656109052308126637/4117523232840525481453983149257", "8967230/3296219033"}, {"-36459180403360509753/32150500941194292113930", "9381566963714/9633539", "301622077145533298008420642898530153/309723104686531919656937098270", "-3784609207827/3426986245"}, } func TestRatBin(t *testing.T) { for i, test := range ratBinTests { arg := ratBinArg{test.x, test.y, test.sum} testRatBin(t, i, "Add", (*Rat).Add, arg) arg = ratBinArg{test.y, test.x, test.sum} testRatBin(t, i, "Add symmetric", (*Rat).Add, arg) arg = ratBinArg{test.sum, test.x, test.y} testRatBin(t, i, "Sub", (*Rat).Sub, arg) arg = ratBinArg{test.sum, test.y, test.x} testRatBin(t, i, "Sub symmetric", (*Rat).Sub, arg) arg = ratBinArg{test.x, test.y, test.prod} testRatBin(t, i, "Mul", (*Rat).Mul, arg) arg = ratBinArg{test.y, test.x, test.prod} testRatBin(t, i, "Mul symmetric", (*Rat).Mul, arg) if test.x != "0" { arg = ratBinArg{test.prod, test.x, test.y} testRatBin(t, i, "Quo", (*Rat).Quo, arg) } if test.y != "0" { arg = ratBinArg{test.prod, test.y, test.x} testRatBin(t, i, "Quo symmetric", (*Rat).Quo, arg) } } } func TestIssue820(t *testing.T) { x := NewRat(3, 1) y := NewRat(2, 1) z := y.Quo(x, y) q := NewRat(3, 2) if z.Cmp(q) != 0 { t.Errorf("got %s want %s", z, q) } y = NewRat(3, 1) x = NewRat(2, 1) z = y.Quo(x, y) q = NewRat(2, 3) if z.Cmp(q) != 0 { t.Errorf("got %s want %s", z, q) } x = NewRat(3, 1) z = x.Quo(x, x) q = NewRat(3, 3) if z.Cmp(q) != 0 { t.Errorf("got %s want %s", z, q) } } var setFrac64Tests = []struct { a, b int64 out string }{ {0, 1, "0"}, {0, -1, "0"}, {1, 1, "1"}, {-1, 1, "-1"}, {1, -1, "-1"}, {-1, -1, "1"}, {-9223372036854775808, -9223372036854775808, "1"}, } func TestRatSetFrac64Rat(t *testing.T) { for i, test := range setFrac64Tests { x := new(Rat).SetFrac64(test.a, test.b) if x.RatString() != test.out { t.Errorf("#%d got %s want %s", i, x.RatString(), test.out) } } } func TestIssue2379(t *testing.T) { // 1) no aliasing q := NewRat(3, 2) x := new(Rat) x.SetFrac(NewInt(3), NewInt(2)) if x.Cmp(q) != 0 { t.Errorf("1) got %s want %s", x, q) } // 2) aliasing of numerator x = NewRat(2, 3) x.SetFrac(NewInt(3), x.Num()) if x.Cmp(q) != 0 { t.Errorf("2) got %s want %s", x, q) } // 3) aliasing of denominator x = NewRat(2, 3) x.SetFrac(x.Denom(), NewInt(2)) if x.Cmp(q) != 0 { t.Errorf("3) got %s want %s", x, q) } // 4) aliasing of numerator and denominator x = NewRat(2, 3) x.SetFrac(x.Denom(), x.Num()) if x.Cmp(q) != 0 { t.Errorf("4) got %s want %s", x, q) } // 5) numerator and denominator are the same q = NewRat(1, 1) x = new(Rat) n := NewInt(7) x.SetFrac(n, n) if x.Cmp(q) != 0 { t.Errorf("5) got %s want %s", x, q) } } func TestIssue3521(t *testing.T) { a := new(Int) b := new(Int) a.SetString("64375784358435883458348587", 0) b.SetString("4789759874531", 0) // 0) a raw zero value has 1 as denominator zero := new(Rat) one := NewInt(1) if zero.Denom().Cmp(one) != 0 { t.Errorf("0) got %s want %s", zero.Denom(), one) } // 1a) the denominator of an (uninitialized) zero value is not shared with the value s := &zero.b d := zero.Denom() if d == s { t.Errorf("1a) got %s (%p) == %s (%p) want different *Int values", d, d, s, s) } // 1b) the denominator of an (uninitialized) value is a new 1 each time d1 := zero.Denom() d2 := zero.Denom() if d1 == d2 { t.Errorf("1b) got %s (%p) == %s (%p) want different *Int values", d1, d1, d2, d2) } // 1c) the denominator of an initialized zero value is shared with the value x := new(Rat) x.Set(x) // initialize x (any operation that sets x explicitly will do) s = &x.b d = x.Denom() if d != s { t.Errorf("1c) got %s (%p) != %s (%p) want identical *Int values", d, d, s, s) } // 1d) a zero value remains zero independent of denominator x.Denom().Set(new(Int).Neg(b)) if x.Cmp(zero) != 0 { t.Errorf("1d) got %s want %s", x, zero) } // 1e) a zero value may have a denominator != 0 and != 1 x.Num().Set(a) qab := new(Rat).SetFrac(a, b) if x.Cmp(qab) != 0 { t.Errorf("1e) got %s want %s", x, qab) } // 2a) an integral value becomes a fraction depending on denominator x.SetFrac64(10, 2) x.Denom().SetInt64(3) q53 := NewRat(5, 3) if x.Cmp(q53) != 0 { t.Errorf("2a) got %s want %s", x, q53) } // 2b) an integral value becomes a fraction depending on denominator x = NewRat(10, 2) x.Denom().SetInt64(3) if x.Cmp(q53) != 0 { t.Errorf("2b) got %s want %s", x, q53) } // 3) changing the numerator/denominator of a Rat changes the Rat x.SetFrac(a, b) a = x.Num() b = x.Denom() a.SetInt64(5) b.SetInt64(3) if x.Cmp(q53) != 0 { t.Errorf("3) got %s want %s", x, q53) } } func TestFloat32Distribution(t *testing.T) { // Generate a distribution of (sign, mantissa, exp) values // broader than the float32 range, and check Rat.Float32() // always picks the closest float32 approximation. var add = []int64{ 0, 1, 3, 5, 7, 9, 11, } var winc, einc = uint64(5), 15 // quick test (~60ms on x86-64) if *long { winc, einc = uint64(1), 1 // soak test (~1.5s on x86-64) } for _, sign := range "+-" { for _, a := range add { for wid := uint64(0); wid < 30; wid += winc { b := 1<<wid + a if sign == '-' { b = -b } for exp := -150; exp < 150; exp += einc { num, den := NewInt(b), NewInt(1) if exp > 0 { num.Lsh(num, uint(exp)) } else { den.Lsh(den, uint(-exp)) } r := new(Rat).SetFrac(num, den) f, _ := r.Float32() if !checkIsBestApprox32(t, f, r) { // Append context information. t.Errorf("(input was mantissa %#x, exp %d; f = %g (%b); f ~ %g; r = %v)", b, exp, f, f, math.Ldexp(float64(b), exp), r) } checkNonLossyRoundtrip32(t, f) } } } } } func TestFloat64Distribution(t *testing.T) { // Generate a distribution of (sign, mantissa, exp) values // broader than the float64 range, and check Rat.Float64() // always picks the closest float64 approximation. var add = []int64{ 0, 1, 3, 5, 7, 9, 11, } var winc, einc = uint64(10), 500 // quick test (~12ms on x86-64) if *long { winc, einc = uint64(1), 1 // soak test (~75s on x86-64) } for _, sign := range "+-" { for _, a := range add { for wid := uint64(0); wid < 60; wid += winc { b := 1<<wid + a if sign == '-' { b = -b } for exp := -1100; exp < 1100; exp += einc { num, den := NewInt(b), NewInt(1) if exp > 0 { num.Lsh(num, uint(exp)) } else { den.Lsh(den, uint(-exp)) } r := new(Rat).SetFrac(num, den) f, _ := r.Float64() if !checkIsBestApprox64(t, f, r) { // Append context information. t.Errorf("(input was mantissa %#x, exp %d; f = %g (%b); f ~ %g; r = %v)", b, exp, f, f, math.Ldexp(float64(b), exp), r) } checkNonLossyRoundtrip64(t, f) } } } } } // TestSetFloat64NonFinite checks that SetFloat64 of a non-finite value // returns nil. func TestSetFloat64NonFinite(t *testing.T) { for _, f := range []float64{math.NaN(), math.Inf(+1), math.Inf(-1)} { var r Rat if r2 := r.SetFloat64(f); r2 != nil { t.Errorf("SetFloat64(%g) was %v, want nil", f, r2) } } } // checkNonLossyRoundtrip32 checks that a float->Rat->float roundtrip is // non-lossy for finite f. func checkNonLossyRoundtrip32(t *testing.T, f float32) { if !isFinite(float64(f)) { return } r := new(Rat).SetFloat64(float64(f)) if r == nil { t.Errorf("Rat.SetFloat64(float64(%g) (%b)) == nil", f, f) return } f2, exact := r.Float32() if f != f2 || !exact { t.Errorf("Rat.SetFloat64(float64(%g)).Float32() = %g (%b), %v, want %g (%b), %v; delta = %b", f, f2, f2, exact, f, f, true, f2-f) } } // checkNonLossyRoundtrip64 checks that a float->Rat->float roundtrip is // non-lossy for finite f. func checkNonLossyRoundtrip64(t *testing.T, f float64) { if !isFinite(f) { return } r := new(Rat).SetFloat64(f) if r == nil { t.Errorf("Rat.SetFloat64(%g (%b)) == nil", f, f) return } f2, exact := r.Float64() if f != f2 || !exact { t.Errorf("Rat.SetFloat64(%g).Float64() = %g (%b), %v, want %g (%b), %v; delta = %b", f, f2, f2, exact, f, f, true, f2-f) } } // delta returns the absolute difference between r and f. func delta(r *Rat, f float64) *Rat { d := new(Rat).Sub(r, new(Rat).SetFloat64(f)) return d.Abs(d) } // checkIsBestApprox32 checks that f is the best possible float32 // approximation of r. // Returns true on success. func checkIsBestApprox32(t *testing.T, f float32, r *Rat) bool { if math.Abs(float64(f)) >= math.MaxFloat32 { // Cannot check +Inf, -Inf, nor the float next to them (MaxFloat32). // But we have tests for these special cases. return true } // r must be strictly between f0 and f1, the floats bracketing f. f0 := math.Nextafter32(f, float32(math.Inf(-1))) f1 := math.Nextafter32(f, float32(math.Inf(+1))) // For f to be correct, r must be closer to f than to f0 or f1. df := delta(r, float64(f)) df0 := delta(r, float64(f0)) df1 := delta(r, float64(f1)) if df.Cmp(df0) > 0 { t.Errorf("Rat(%v).Float32() = %g (%b), but previous float32 %g (%b) is closer", r, f, f, f0, f0) return false } if df.Cmp(df1) > 0 { t.Errorf("Rat(%v).Float32() = %g (%b), but next float32 %g (%b) is closer", r, f, f, f1, f1) return false } if df.Cmp(df0) == 0 && !isEven32(f) { t.Errorf("Rat(%v).Float32() = %g (%b); halfway should have rounded to %g (%b) instead", r, f, f, f0, f0) return false } if df.Cmp(df1) == 0 && !isEven32(f) { t.Errorf("Rat(%v).Float32() = %g (%b); halfway should have rounded to %g (%b) instead", r, f, f, f1, f1) return false } return true } // checkIsBestApprox64 checks that f is the best possible float64 // approximation of r. // Returns true on success. func checkIsBestApprox64(t *testing.T, f float64, r *Rat) bool { if math.Abs(f) >= math.MaxFloat64 { // Cannot check +Inf, -Inf, nor the float next to them (MaxFloat64). // But we have tests for these special cases. return true } // r must be strictly between f0 and f1, the floats bracketing f. f0 := math.Nextafter(f, math.Inf(-1)) f1 := math.Nextafter(f, math.Inf(+1)) // For f to be correct, r must be closer to f than to f0 or f1. df := delta(r, f) df0 := delta(r, f0) df1 := delta(r, f1) if df.Cmp(df0) > 0 { t.Errorf("Rat(%v).Float64() = %g (%b), but previous float64 %g (%b) is closer", r, f, f, f0, f0) return false } if df.Cmp(df1) > 0 { t.Errorf("Rat(%v).Float64() = %g (%b), but next float64 %g (%b) is closer", r, f, f, f1, f1) return false } if df.Cmp(df0) == 0 && !isEven64(f) { t.Errorf("Rat(%v).Float64() = %g (%b); halfway should have rounded to %g (%b) instead", r, f, f, f0, f0) return false } if df.Cmp(df1) == 0 && !isEven64(f) { t.Errorf("Rat(%v).Float64() = %g (%b); halfway should have rounded to %g (%b) instead", r, f, f, f1, f1) return false } return true } func isEven32(f float32) bool { return math.Float32bits(f)&1 == 0 } func isEven64(f float64) bool { return math.Float64bits(f)&1 == 0 } func TestIsFinite(t *testing.T) { finites := []float64{ 1.0 / 3, 4891559871276714924261e+222, math.MaxFloat64, math.SmallestNonzeroFloat64, -math.MaxFloat64, -math.SmallestNonzeroFloat64, } for _, f := range finites { if !isFinite(f) { t.Errorf("!IsFinite(%g (%b))", f, f) } } nonfinites := []float64{ math.NaN(), math.Inf(-1), math.Inf(+1), } for _, f := range nonfinites { if isFinite(f) { t.Errorf("IsFinite(%g, (%b))", f, f) } } } func TestRatSetInt64(t *testing.T) { var testCases = []int64{ 0, 1, -1, 12345, -98765, math.MaxInt64, math.MinInt64, } var r = new(Rat) for i, want := range testCases { r.SetInt64(want) if !r.IsInt() { t.Errorf("#%d: Rat.SetInt64(%d) is not an integer", i, want) } num := r.Num() if !num.IsInt64() { t.Errorf("#%d: Rat.SetInt64(%d) numerator is not an int64", i, want) } got := num.Int64() if got != want { t.Errorf("#%d: Rat.SetInt64(%d) = %d, but expected %d", i, want, got, want) } } } func TestRatSetUint64(t *testing.T) { var testCases = []uint64{ 0, 1, 12345, ^uint64(0), } var r = new(Rat) for i, want := range testCases { r.SetUint64(want) if !r.IsInt() { t.Errorf("#%d: Rat.SetUint64(%d) is not an integer", i, want) } num := r.Num() if !num.IsUint64() { t.Errorf("#%d: Rat.SetUint64(%d) numerator is not a uint64", i, want) } got := num.Uint64() if got != want { t.Errorf("#%d: Rat.SetUint64(%d) = %d, but expected %d", i, want, got, want) } } } func BenchmarkRatCmp(b *testing.B) { x, y := NewRat(4, 1), NewRat(7, 2) for i := 0; i < b.N; i++ { x.Cmp(y) } } // TestIssue34919 verifies that a Rat's denominator is not modified // when simply accessing the Rat value. func TestIssue34919(t *testing.T) { for _, acc := range []struct { name string f func(*Rat) }{ {"Float32", func(x *Rat) { x.Float32() }}, {"Float64", func(x *Rat) { x.Float64() }}, {"Inv", func(x *Rat) { new(Rat).Inv(x) }}, {"Sign", func(x *Rat) { x.Sign() }}, {"IsInt", func(x *Rat) { x.IsInt() }}, {"Num", func(x *Rat) { x.Num() }}, // {"Denom", func(x *Rat) { x.Denom() }}, TODO(gri) should we change the API? See issue #33792. } { // A denominator of length 0 is interpreted as 1. Make sure that // "materialization" of the denominator doesn't lead to setting // the underlying array element 0 to 1. r := &Rat{Int{abs: nat{991}}, Int{abs: make(nat, 0, 1)}} acc.f(r) if d := r.b.abs[:1][0]; d != 0 { t.Errorf("%s modified denominator: got %d, want 0", acc.name, d) } } } func TestDenomRace(t *testing.T) { x := NewRat(1, 2) const N = 3 c := make(chan bool, N) for i := 0; i < N; i++ { go func() { // Denom (also used by Float.SetRat) used to mutate x unnecessarily, // provoking race reports when run in the race detector. x.Denom() new(Float).SetRat(x) c <- true }() } for i := 0; i < N; i++ { <-c } }
go/src/math/big/rat_test.go/0
{ "file_path": "go/src/math/big/rat_test.go", "repo_id": "go", "token_count": 9238 }
327
// Copyright 2010 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. package cmplx // Polar returns the absolute value r and phase θ of x, // such that x = r * e**θi. // The phase is in the range [-Pi, Pi]. func Polar(x complex128) (r, θ float64) { return Abs(x), Phase(x) }
go/src/math/cmplx/polar.go/0
{ "file_path": "go/src/math/cmplx/polar.go", "repo_id": "go", "token_count": 119 }
328
// Copyright 2016 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. // Based on dim_amd64.s #include "textflag.h" #define PosInf 0x7FF0000000000000 #define NaN 0x7FF8000000000001 #define NegInf 0xFFF0000000000000 // func ·Max(x, y float64) float64 TEXT ·archMax(SB),NOSPLIT,$0 // +Inf special cases MOVD $PosInf, R4 MOVD x+0(FP), R8 CMPUBEQ R4, R8, isPosInf MOVD y+8(FP), R9 CMPUBEQ R4, R9, isPosInf // NaN special cases MOVD $~(1<<63), R5 // bit mask MOVD $PosInf, R4 MOVD R8, R2 AND R5, R2 // x = |x| CMPUBLT R4, R2, isMaxNaN MOVD R9, R3 AND R5, R3 // y = |y| CMPUBLT R4, R3, isMaxNaN // ±0 special cases OR R3, R2 BEQ isMaxZero FMOVD x+0(FP), F1 FMOVD y+8(FP), F2 FCMPU F2, F1 BGT +3(PC) FMOVD F1, ret+16(FP) RET FMOVD F2, ret+16(FP) RET isMaxNaN: // return NaN MOVD $NaN, R4 isPosInf: // return +Inf MOVD R4, ret+16(FP) RET isMaxZero: MOVD $(1<<63), R4 // -0.0 CMPUBEQ R4, R8, +3(PC) MOVD R8, ret+16(FP) // return 0 RET MOVD R9, ret+16(FP) // return other 0 RET // func archMin(x, y float64) float64 TEXT ·archMin(SB),NOSPLIT,$0 // -Inf special cases MOVD $NegInf, R4 MOVD x+0(FP), R8 CMPUBEQ R4, R8, isNegInf MOVD y+8(FP), R9 CMPUBEQ R4, R9, isNegInf // NaN special cases MOVD $~(1<<63), R5 MOVD $PosInf, R4 MOVD R8, R2 AND R5, R2 // x = |x| CMPUBLT R4, R2, isMinNaN MOVD R9, R3 AND R5, R3 // y = |y| CMPUBLT R4, R3, isMinNaN // ±0 special cases OR R3, R2 BEQ isMinZero FMOVD x+0(FP), F1 FMOVD y+8(FP), F2 FCMPU F2, F1 BLT +3(PC) FMOVD F1, ret+16(FP) RET FMOVD F2, ret+16(FP) RET isMinNaN: // return NaN MOVD $NaN, R4 isNegInf: // return -Inf MOVD R4, ret+16(FP) RET isMinZero: MOVD $(1<<63), R4 // -0.0 CMPUBEQ R4, R8, +3(PC) MOVD R9, ret+16(FP) // return other 0 RET MOVD R8, ret+16(FP) // return -0 RET
go/src/math/dim_s390x.s/0
{ "file_path": "go/src/math/dim_s390x.s", "repo_id": "go", "token_count": 1121 }
329
// Copyright 2017 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. #include "textflag.h" // Minimax polynomial approximation and other constants DATA ·expm1rodataL22<> + 0(SB)/8, $-1.0 DATA ·expm1rodataL22<> + 8(SB)/8, $800.0E+00 DATA ·expm1rodataL22<> + 16(SB)/8, $1.0 DATA ·expm1rodataL22<> + 24(SB)/8, $-.231904681384629956E-16 DATA ·expm1rodataL22<> + 32(SB)/8, $0.50000000000000029671E+00 DATA ·expm1rodataL22<> + 40(SB)/8, $0.16666666666666676570E+00 DATA ·expm1rodataL22<> + 48(SB)/8, $0.83333333323590973444E-02 DATA ·expm1rodataL22<> + 56(SB)/8, $0.13889096526400683566E-02 DATA ·expm1rodataL22<> + 64(SB)/8, $0.41666666661701152924E-01 DATA ·expm1rodataL22<> + 72(SB)/8, $0.19841562053987360264E-03 DATA ·expm1rodataL22<> + 80(SB)/8, $-.693147180559945286E+00 DATA ·expm1rodataL22<> + 88(SB)/8, $0.144269504088896339E+01 DATA ·expm1rodataL22<> + 96(SB)/8, $704.0E+00 GLOBL ·expm1rodataL22<> + 0(SB), RODATA, $104 DATA ·expm1xmone<> + 0(SB)/8, $0xbff0000000000000 GLOBL ·expm1xmone<> + 0(SB), RODATA, $8 DATA ·expm1xinf<> + 0(SB)/8, $0x7ff0000000000000 GLOBL ·expm1xinf<> + 0(SB), RODATA, $8 DATA ·expm1x4ff<> + 0(SB)/8, $0x4ff0000000000000 GLOBL ·expm1x4ff<> + 0(SB), RODATA, $8 DATA ·expm1x2ff<> + 0(SB)/8, $0x2ff0000000000000 GLOBL ·expm1x2ff<> + 0(SB), RODATA, $8 DATA ·expm1xaddexp<> + 0(SB)/8, $0xc2f0000100003ff0 GLOBL ·expm1xaddexp<> + 0(SB), RODATA, $8 // Log multipliers table DATA ·expm1tab<> + 0(SB)/8, $0.0 DATA ·expm1tab<> + 8(SB)/8, $-.171540871271399150E-01 DATA ·expm1tab<> + 16(SB)/8, $-.306597931864376363E-01 DATA ·expm1tab<> + 24(SB)/8, $-.410200970469965021E-01 DATA ·expm1tab<> + 32(SB)/8, $-.486343079978231466E-01 DATA ·expm1tab<> + 40(SB)/8, $-.538226193725835820E-01 DATA ·expm1tab<> + 48(SB)/8, $-.568439602538111520E-01 DATA ·expm1tab<> + 56(SB)/8, $-.579091847395528847E-01 DATA ·expm1tab<> + 64(SB)/8, $-.571909584179366341E-01 DATA ·expm1tab<> + 72(SB)/8, $-.548312665987204407E-01 DATA ·expm1tab<> + 80(SB)/8, $-.509471843643441085E-01 DATA ·expm1tab<> + 88(SB)/8, $-.456353588448863359E-01 DATA ·expm1tab<> + 96(SB)/8, $-.389755254243262365E-01 DATA ·expm1tab<> + 104(SB)/8, $-.310332908285244231E-01 DATA ·expm1tab<> + 112(SB)/8, $-.218623539150173528E-01 DATA ·expm1tab<> + 120(SB)/8, $-.115062908917949451E-01 GLOBL ·expm1tab<> + 0(SB), RODATA, $128 // Expm1 returns e**x - 1, the base-e exponential of x minus 1. // It is more accurate than Exp(x) - 1 when x is near zero. // // Special cases are: // Expm1(+Inf) = +Inf // Expm1(-Inf) = -1 // Expm1(NaN) = NaN // Very large values overflow to -1 or +Inf. // The algorithm used is minimax polynomial approximation using a table of // polynomial coefficients determined with a Remez exchange algorithm. TEXT ·expm1Asm(SB), NOSPLIT, $0-16 FMOVD x+0(FP), F0 MOVD $·expm1rodataL22<>+0(SB), R5 LTDBR F0, F0 BLTU L20 FMOVD F0, F2 L2: WORD $0xED205060 //cdb %f2,.L23-.L22(%r5) BYTE $0x00 BYTE $0x19 BGE L16 BVS L16 WFCEDBS V2, V2, V2 BVS LEXITTAGexpm1 MOVD $·expm1xaddexp<>+0(SB), R1 FMOVD 88(R5), F1 FMOVD 0(R1), F2 WFMSDB V0, V1, V2, V1 FMOVD 80(R5), F6 WFADB V1, V2, V4 FMOVD 72(R5), F2 FMADD F6, F4, F0 FMOVD 64(R5), F3 FMOVD 56(R5), F6 FMOVD 48(R5), F5 FMADD F2, F0, F6 WFMADB V0, V5, V3, V5 WFMDB V0, V0, V2 LGDR F1, R1 WFMADB V6, V2, V5, V6 FMOVD 40(R5), F3 FMOVD 32(R5), F5 WFMADB V0, V3, V5, V3 FMOVD 24(R5), F5 WFMADB V2, V6, V3, V2 FMADD F5, F4, F0 FMOVD 16(R5), F6 WFMADB V0, V2, V6, V2 RISBGZ $57, $60, $3, R1, R3 WORD $0xB3130022 //lcdbr %f2,%f2 MOVD $·expm1tab<>+0(SB), R2 WORD $0x68432000 //ld %f4,0(%r3,%r2) FMADD F4, F0, F0 SLD $48, R1, R2 WFMSDB V2, V0, V4, V0 LDGR R2, F4 WORD $0xB3130000 //lcdbr %f0,%f0 FSUB F4, F6 WFMSDB V0, V4, V6, V0 FMOVD F0, ret+8(FP) RET L16: WFCEDBS V2, V2, V4 BVS LEXITTAGexpm1 WORD $0xED205008 //cdb %f2,.L34-.L22(%r5) BYTE $0x00 BYTE $0x19 BLT L6 WFCEDBS V2, V0, V0 BVS L7 MOVD $·expm1xinf<>+0(SB), R1 FMOVD 0(R1), F0 FMOVD F0, ret+8(FP) RET L20: WORD $0xB3130020 //lcdbr %f2,%f0 BR L2 L6: MOVD $·expm1xaddexp<>+0(SB), R1 FMOVD 88(R5), F5 FMOVD 0(R1), F4 WFMSDB V0, V5, V4, V5 FMOVD 80(R5), F3 WFADB V5, V4, V1 VLEG $0, 48(R5), V16 WFMADB V1, V3, V0, V3 FMOVD 56(R5), F4 FMOVD 64(R5), F7 FMOVD 72(R5), F6 WFMADB V3, V16, V7, V16 WFMADB V3, V6, V4, V6 WFMDB V3, V3, V4 MOVD $·expm1tab<>+0(SB), R2 WFMADB V6, V4, V16, V6 VLEG $0, 32(R5), V16 FMOVD 40(R5), F7 WFMADB V3, V7, V16, V7 VLEG $0, 24(R5), V16 WFMADB V4, V6, V7, V4 WFMADB V1, V16, V3, V1 FMOVD 16(R5), F6 FMADD F4, F1, F6 LGDR F5, R1 WORD $0xB3130066 //lcdbr %f6,%f6 RISBGZ $57, $60, $3, R1, R3 WORD $0x68432000 //ld %f4,0(%r3,%r2) FMADD F4, F1, F1 MOVD $0x4086000000000000, R2 FMSUB F1, F6, F4 WORD $0xB3130044 //lcdbr %f4,%f4 WFCHDBS V2, V0, V0 BEQ L21 ADDW $0xF000, R1 RISBGN $0, $15, $48, R1, R2 LDGR R2, F0 FMADD F0, F4, F0 MOVD $·expm1x4ff<>+0(SB), R3 FMOVD 0(R5), F4 FMOVD 0(R3), F2 WFMADB V2, V0, V4, V0 FMOVD F0, ret+8(FP) RET L7: MOVD $·expm1xmone<>+0(SB), R1 FMOVD 0(R1), F0 FMOVD F0, ret+8(FP) RET L21: ADDW $0x1000, R1 RISBGN $0, $15, $48, R1, R2 LDGR R2, F0 FMADD F0, F4, F0 MOVD $·expm1x2ff<>+0(SB), R3 FMOVD 0(R5), F4 FMOVD 0(R3), F2 WFMADB V2, V0, V4, V0 FMOVD F0, ret+8(FP) RET LEXITTAGexpm1: FMOVD F0, ret+8(FP) RET
go/src/math/expm1_s390x.s/0
{ "file_path": "go/src/math/expm1_s390x.s", "repo_id": "go", "token_count": 3218 }
330
// Copyright 2010 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. package math /* Hypot -- sqrt(p*p + q*q), but overflows only if the result does. */ // Hypot returns [Sqrt](p*p + q*q), taking care to avoid // unnecessary overflow and underflow. // // Special cases are: // // Hypot(±Inf, q) = +Inf // Hypot(p, ±Inf) = +Inf // Hypot(NaN, q) = NaN // Hypot(p, NaN) = NaN func Hypot(p, q float64) float64 { if haveArchHypot { return archHypot(p, q) } return hypot(p, q) } func hypot(p, q float64) float64 { p, q = Abs(p), Abs(q) // special cases switch { case IsInf(p, 1) || IsInf(q, 1): return Inf(1) case IsNaN(p) || IsNaN(q): return NaN() } if p < q { p, q = q, p } if p == 0 { return 0 } q = q / p return p * Sqrt(1+q*q) }
go/src/math/hypot.go/0
{ "file_path": "go/src/math/hypot.go", "repo_id": "go", "token_count": 367 }
331
// Copyright 2009 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. package rand import ( "math" ) /* * Normal distribution * * See "The Ziggurat Method for Generating Random Variables" * (Marsaglia & Tsang, 2000) * http://www.jstatsoft.org/v05/i08/paper [pdf] */ const ( rn = 3.442619855899 ) func absInt32(i int32) uint32 { if i < 0 { return uint32(-i) } return uint32(i) } // NormFloat64 returns a normally distributed float64 in // the range -math.MaxFloat64 through +math.MaxFloat64 inclusive, // with standard normal distribution (mean = 0, stddev = 1). // To produce a different normal distribution, callers can // adjust the output using: // // sample = NormFloat64() * desiredStdDev + desiredMean func (r *Rand) NormFloat64() float64 { for { u := r.Uint64() j := int32(u) // Possibly negative i := u >> 32 & 0x7F x := float64(j) * float64(wn[i]) if absInt32(j) < kn[i] { // This case should be hit better than 99% of the time. return x } if i == 0 { // This extra work is only required for the base strip. for { x = -math.Log(r.Float64()) * (1.0 / rn) y := -math.Log(r.Float64()) if y+y >= x*x { break } } if j > 0 { return rn + x } return -rn - x } if fn[i]+float32(r.Float64())*(fn[i-1]-fn[i]) < float32(math.Exp(-.5*x*x)) { return x } } } var kn = [128]uint32{ 0x76ad2212, 0x0, 0x600f1b53, 0x6ce447a6, 0x725b46a2, 0x7560051d, 0x774921eb, 0x789a25bd, 0x799045c3, 0x7a4bce5d, 0x7adf629f, 0x7b5682a6, 0x7bb8a8c6, 0x7c0ae722, 0x7c50cce7, 0x7c8cec5b, 0x7cc12cd6, 0x7ceefed2, 0x7d177e0b, 0x7d3b8883, 0x7d5bce6c, 0x7d78dd64, 0x7d932886, 0x7dab0e57, 0x7dc0dd30, 0x7dd4d688, 0x7de73185, 0x7df81cea, 0x7e07c0a3, 0x7e163efa, 0x7e23b587, 0x7e303dfd, 0x7e3beec2, 0x7e46db77, 0x7e51155d, 0x7e5aabb3, 0x7e63abf7, 0x7e6c222c, 0x7e741906, 0x7e7b9a18, 0x7e82adfa, 0x7e895c63, 0x7e8fac4b, 0x7e95a3fb, 0x7e9b4924, 0x7ea0a0ef, 0x7ea5b00d, 0x7eaa7ac3, 0x7eaf04f3, 0x7eb3522a, 0x7eb765a5, 0x7ebb4259, 0x7ebeeafd, 0x7ec2620a, 0x7ec5a9c4, 0x7ec8c441, 0x7ecbb365, 0x7ece78ed, 0x7ed11671, 0x7ed38d62, 0x7ed5df12, 0x7ed80cb4, 0x7eda175c, 0x7edc0005, 0x7eddc78e, 0x7edf6ebf, 0x7ee0f647, 0x7ee25ebe, 0x7ee3a8a9, 0x7ee4d473, 0x7ee5e276, 0x7ee6d2f5, 0x7ee7a620, 0x7ee85c10, 0x7ee8f4cd, 0x7ee97047, 0x7ee9ce59, 0x7eea0eca, 0x7eea3147, 0x7eea3568, 0x7eea1aab, 0x7ee9e071, 0x7ee98602, 0x7ee90a88, 0x7ee86d08, 0x7ee7ac6a, 0x7ee6c769, 0x7ee5bc9c, 0x7ee48a67, 0x7ee32efc, 0x7ee1a857, 0x7edff42f, 0x7ede0ffa, 0x7edbf8d9, 0x7ed9ab94, 0x7ed7248d, 0x7ed45fae, 0x7ed1585c, 0x7ece095f, 0x7eca6ccb, 0x7ec67be2, 0x7ec22eee, 0x7ebd7d1a, 0x7eb85c35, 0x7eb2c075, 0x7eac9c20, 0x7ea5df27, 0x7e9e769f, 0x7e964c16, 0x7e8d44ba, 0x7e834033, 0x7e781728, 0x7e6b9933, 0x7e5d8a1a, 0x7e4d9ded, 0x7e3b737a, 0x7e268c2f, 0x7e0e3ff5, 0x7df1aa5d, 0x7dcf8c72, 0x7da61a1e, 0x7d72a0fb, 0x7d30e097, 0x7cd9b4ab, 0x7c600f1a, 0x7ba90bdc, 0x7a722176, 0x77d664e5, } var wn = [128]float32{ 1.7290405e-09, 1.2680929e-10, 1.6897518e-10, 1.9862688e-10, 2.2232431e-10, 2.4244937e-10, 2.601613e-10, 2.7611988e-10, 2.9073963e-10, 3.042997e-10, 3.1699796e-10, 3.289802e-10, 3.4035738e-10, 3.5121603e-10, 3.616251e-10, 3.7164058e-10, 3.8130857e-10, 3.9066758e-10, 3.9975012e-10, 4.08584e-10, 4.1719309e-10, 4.2559822e-10, 4.338176e-10, 4.418672e-10, 4.497613e-10, 4.5751258e-10, 4.651324e-10, 4.7263105e-10, 4.8001775e-10, 4.87301e-10, 4.944885e-10, 5.015873e-10, 5.0860405e-10, 5.155446e-10, 5.2241467e-10, 5.2921934e-10, 5.359635e-10, 5.426517e-10, 5.4928817e-10, 5.5587696e-10, 5.624219e-10, 5.6892646e-10, 5.753941e-10, 5.818282e-10, 5.882317e-10, 5.946077e-10, 6.00959e-10, 6.072884e-10, 6.135985e-10, 6.19892e-10, 6.2617134e-10, 6.3243905e-10, 6.386974e-10, 6.449488e-10, 6.511956e-10, 6.5744005e-10, 6.6368433e-10, 6.699307e-10, 6.7618144e-10, 6.824387e-10, 6.8870465e-10, 6.949815e-10, 7.012715e-10, 7.075768e-10, 7.1389966e-10, 7.202424e-10, 7.266073e-10, 7.329966e-10, 7.394128e-10, 7.4585826e-10, 7.5233547e-10, 7.58847e-10, 7.653954e-10, 7.719835e-10, 7.7861395e-10, 7.852897e-10, 7.920138e-10, 7.987892e-10, 8.0561924e-10, 8.125073e-10, 8.194569e-10, 8.2647167e-10, 8.3355556e-10, 8.407127e-10, 8.479473e-10, 8.55264e-10, 8.6266755e-10, 8.7016316e-10, 8.777562e-10, 8.8545243e-10, 8.932582e-10, 9.0117996e-10, 9.09225e-10, 9.174008e-10, 9.2571584e-10, 9.341788e-10, 9.427997e-10, 9.515889e-10, 9.605579e-10, 9.697193e-10, 9.790869e-10, 9.88676e-10, 9.985036e-10, 1.0085882e-09, 1.0189509e-09, 1.0296151e-09, 1.0406069e-09, 1.0519566e-09, 1.063698e-09, 1.0758702e-09, 1.0885183e-09, 1.1016947e-09, 1.1154611e-09, 1.1298902e-09, 1.1450696e-09, 1.1611052e-09, 1.1781276e-09, 1.1962995e-09, 1.2158287e-09, 1.2369856e-09, 1.2601323e-09, 1.2857697e-09, 1.3146202e-09, 1.347784e-09, 1.3870636e-09, 1.4357403e-09, 1.5008659e-09, 1.6030948e-09, } var fn = [128]float32{ 1, 0.9635997, 0.9362827, 0.9130436, 0.89228165, 0.87324303, 0.8555006, 0.8387836, 0.8229072, 0.8077383, 0.793177, 0.7791461, 0.7655842, 0.7524416, 0.73967725, 0.7272569, 0.7151515, 0.7033361, 0.69178915, 0.68049186, 0.6694277, 0.658582, 0.6479418, 0.63749546, 0.6272325, 0.6171434, 0.6072195, 0.5974532, 0.58783704, 0.5783647, 0.56903, 0.5598274, 0.5507518, 0.54179835, 0.5329627, 0.52424055, 0.5156282, 0.50712204, 0.49871865, 0.49041483, 0.48220766, 0.4740943, 0.46607214, 0.4581387, 0.45029163, 0.44252872, 0.43484783, 0.427247, 0.41972435, 0.41227803, 0.40490642, 0.39760786, 0.3903808, 0.3832238, 0.37613547, 0.36911446, 0.3621595, 0.35526937, 0.34844297, 0.34167916, 0.33497685, 0.3283351, 0.3217529, 0.3152294, 0.30876362, 0.30235484, 0.29600215, 0.28970486, 0.2834622, 0.2772735, 0.27113807, 0.2650553, 0.25902456, 0.2530453, 0.24711695, 0.241239, 0.23541094, 0.22963232, 0.2239027, 0.21822165, 0.21258877, 0.20700371, 0.20146611, 0.19597565, 0.19053204, 0.18513499, 0.17978427, 0.17447963, 0.1692209, 0.16400786, 0.15884037, 0.15371831, 0.14864157, 0.14361008, 0.13862377, 0.13368265, 0.12878671, 0.12393598, 0.119130544, 0.11437051, 0.10965602, 0.104987256, 0.10036444, 0.095787846, 0.0912578, 0.08677467, 0.0823389, 0.077950984, 0.073611505, 0.06932112, 0.06508058, 0.06089077, 0.056752663, 0.0526674, 0.048636295, 0.044660863, 0.040742867, 0.03688439, 0.033087887, 0.029356318, 0.025693292, 0.022103304, 0.018592102, 0.015167298, 0.011839478, 0.008624485, 0.005548995, 0.0026696292, }
go/src/math/rand/v2/normal.go/0
{ "file_path": "go/src/math/rand/v2/normal.go", "repo_id": "go", "token_count": 3813 }
332
// Copyright 2009 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. package math // The original C code and the long comment below are // from FreeBSD's /usr/src/lib/msun/src/e_sqrt.c and // came with this notice. The go code is a simplified // version of the original C. // // ==================================================== // Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. // // Developed at SunPro, a Sun Microsystems, Inc. business. // Permission to use, copy, modify, and distribute this // software is freely granted, provided that this notice // is preserved. // ==================================================== // // __ieee754_sqrt(x) // Return correctly rounded sqrt. // ----------------------------------------- // | Use the hardware sqrt if you have one | // ----------------------------------------- // Method: // Bit by bit method using integer arithmetic. (Slow, but portable) // 1. Normalization // Scale x to y in [1,4) with even powers of 2: // find an integer k such that 1 <= (y=x*2**(2k)) < 4, then // sqrt(x) = 2**k * sqrt(y) // 2. Bit by bit computation // Let q = sqrt(y) truncated to i bit after binary point (q = 1), // i 0 // i+1 2 // s = 2*q , and y = 2 * ( y - q ). (1) // i i i i // // To compute q from q , one checks whether // i+1 i // // -(i+1) 2 // (q + 2 ) <= y. (2) // i // -(i+1) // If (2) is false, then q = q ; otherwise q = q + 2 . // i+1 i i+1 i // // With some algebraic manipulation, it is not difficult to see // that (2) is equivalent to // -(i+1) // s + 2 <= y (3) // i i // // The advantage of (3) is that s and y can be computed by // i i // the following recurrence formula: // if (3) is false // // s = s , y = y ; (4) // i+1 i i+1 i // // otherwise, // -i -(i+1) // s = s + 2 , y = y - s - 2 (5) // i+1 i i+1 i i // // One may easily use induction to prove (4) and (5). // Note. Since the left hand side of (3) contain only i+2 bits, // it is not necessary to do a full (53-bit) comparison // in (3). // 3. Final rounding // After generating the 53 bits result, we compute one more bit. // Together with the remainder, we can decide whether the // result is exact, bigger than 1/2ulp, or less than 1/2ulp // (it will never equal to 1/2ulp). // The rounding mode can be detected by checking whether // huge + tiny is equal to huge, and whether huge - tiny is // equal to huge for some floating point number "huge" and "tiny". // // // Notes: Rounding mode detection omitted. The constants "mask", "shift", // and "bias" are found in src/math/bits.go // Sqrt returns the square root of x. // // Special cases are: // // Sqrt(+Inf) = +Inf // Sqrt(±0) = ±0 // Sqrt(x < 0) = NaN // Sqrt(NaN) = NaN func Sqrt(x float64) float64 { return sqrt(x) } // Note: On systems where Sqrt is a single instruction, the compiler // may turn a direct call into a direct use of that instruction instead. func sqrt(x float64) float64 { // special cases switch { case x == 0 || IsNaN(x) || IsInf(x, 1): return x case x < 0: return NaN() } ix := Float64bits(x) // normalize x exp := int((ix >> shift) & mask) if exp == 0 { // subnormal x for ix&(1<<shift) == 0 { ix <<= 1 exp-- } exp++ } exp -= bias // unbias exponent ix &^= mask << shift ix |= 1 << shift if exp&1 == 1 { // odd exp, double x to make it even ix <<= 1 } exp >>= 1 // exp = exp/2, exponent of square root // generate sqrt(x) bit by bit ix <<= 1 var q, s uint64 // q = sqrt(x) r := uint64(1 << (shift + 1)) // r = moving bit from MSB to LSB for r != 0 { t := s + r if t <= ix { s = t + r ix -= t q += r } ix <<= 1 r >>= 1 } // final rounding if ix != 0 { // remainder, result not exact q += q & 1 // round according to extra bit } ix = q>>1 + uint64(exp-1+bias)<<shift // significand + biased exponent return Float64frombits(ix) }
go/src/math/sqrt.go/0
{ "file_path": "go/src/math/sqrt.go", "repo_id": "go", "token_count": 2330 }
333
// Copyright 2011 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. package multipart import ( "bytes" "errors" "internal/godebug" "io" "math" "net/textproto" "os" "strconv" ) // ErrMessageTooLarge is returned by ReadForm if the message form // data is too large to be processed. var ErrMessageTooLarge = errors.New("multipart: message too large") // TODO(adg,bradfitz): find a way to unify the DoS-prevention strategy here // with that of the http package's ParseForm. // ReadForm parses an entire multipart message whose parts have // a Content-Disposition of "form-data". // It stores up to maxMemory bytes + 10MB (reserved for non-file parts) // in memory. File parts which can't be stored in memory will be stored on // disk in temporary files. // It returns [ErrMessageTooLarge] if all non-file parts can't be stored in // memory. func (r *Reader) ReadForm(maxMemory int64) (*Form, error) { return r.readForm(maxMemory) } var ( multipartfiles = godebug.New("#multipartfiles") // TODO: document and remove # multipartmaxparts = godebug.New("multipartmaxparts") ) func (r *Reader) readForm(maxMemory int64) (_ *Form, err error) { form := &Form{make(map[string][]string), make(map[string][]*FileHeader)} var ( file *os.File fileOff int64 ) numDiskFiles := 0 combineFiles := true if multipartfiles.Value() == "distinct" { combineFiles = false // multipartfiles.IncNonDefault() // TODO: uncomment after documenting } maxParts := 1000 if s := multipartmaxparts.Value(); s != "" { if v, err := strconv.Atoi(s); err == nil && v >= 0 { maxParts = v multipartmaxparts.IncNonDefault() } } maxHeaders := maxMIMEHeaders() defer func() { if file != nil { if cerr := file.Close(); err == nil { err = cerr } } if combineFiles && numDiskFiles > 1 { for _, fhs := range form.File { for _, fh := range fhs { fh.tmpshared = true } } } if err != nil { form.RemoveAll() if file != nil { os.Remove(file.Name()) } } }() // maxFileMemoryBytes is the maximum bytes of file data we will store in memory. // Data past this limit is written to disk. // This limit strictly applies to content, not metadata (filenames, MIME headers, etc.), // since metadata is always stored in memory, not disk. // // maxMemoryBytes is the maximum bytes we will store in memory, including file content, // non-file part values, metadata, and map entry overhead. // // We reserve an additional 10 MB in maxMemoryBytes for non-file data. // // The relationship between these parameters, as well as the overly-large and // unconfigurable 10 MB added on to maxMemory, is unfortunate but difficult to change // within the constraints of the API as documented. maxFileMemoryBytes := maxMemory if maxFileMemoryBytes == math.MaxInt64 { maxFileMemoryBytes-- } maxMemoryBytes := maxMemory + int64(10<<20) if maxMemoryBytes <= 0 { if maxMemory < 0 { maxMemoryBytes = 0 } else { maxMemoryBytes = math.MaxInt64 } } var copyBuf []byte for { p, err := r.nextPart(false, maxMemoryBytes, maxHeaders) if err == io.EOF { break } if err != nil { return nil, err } if maxParts <= 0 { return nil, ErrMessageTooLarge } maxParts-- name := p.FormName() if name == "" { continue } filename := p.FileName() // Multiple values for the same key (one map entry, longer slice) are cheaper // than the same number of values for different keys (many map entries), but // using a consistent per-value cost for overhead is simpler. const mapEntryOverhead = 200 maxMemoryBytes -= int64(len(name)) maxMemoryBytes -= mapEntryOverhead if maxMemoryBytes < 0 { // We can't actually take this path, since nextPart would already have // rejected the MIME headers for being too large. Check anyway. return nil, ErrMessageTooLarge } var b bytes.Buffer if filename == "" { // value, store as string in memory n, err := io.CopyN(&b, p, maxMemoryBytes+1) if err != nil && err != io.EOF { return nil, err } maxMemoryBytes -= n if maxMemoryBytes < 0 { return nil, ErrMessageTooLarge } form.Value[name] = append(form.Value[name], b.String()) continue } // file, store in memory or on disk const fileHeaderSize = 100 maxMemoryBytes -= mimeHeaderSize(p.Header) maxMemoryBytes -= mapEntryOverhead maxMemoryBytes -= fileHeaderSize if maxMemoryBytes < 0 { return nil, ErrMessageTooLarge } for _, v := range p.Header { maxHeaders -= int64(len(v)) } fh := &FileHeader{ Filename: filename, Header: p.Header, } n, err := io.CopyN(&b, p, maxFileMemoryBytes+1) if err != nil && err != io.EOF { return nil, err } if n > maxFileMemoryBytes { if file == nil { file, err = os.CreateTemp(r.tempDir, "multipart-") if err != nil { return nil, err } } numDiskFiles++ if _, err := file.Write(b.Bytes()); err != nil { return nil, err } if copyBuf == nil { copyBuf = make([]byte, 32*1024) // same buffer size as io.Copy uses } // os.File.ReadFrom will allocate its own copy buffer if we let io.Copy use it. type writerOnly struct{ io.Writer } remainingSize, err := io.CopyBuffer(writerOnly{file}, p, copyBuf) if err != nil { return nil, err } fh.tmpfile = file.Name() fh.Size = int64(b.Len()) + remainingSize fh.tmpoff = fileOff fileOff += fh.Size if !combineFiles { if err := file.Close(); err != nil { return nil, err } file = nil } } else { fh.content = b.Bytes() fh.Size = int64(len(fh.content)) maxFileMemoryBytes -= n maxMemoryBytes -= n } form.File[name] = append(form.File[name], fh) } return form, nil } func mimeHeaderSize(h textproto.MIMEHeader) (size int64) { size = 400 for k, vs := range h { size += int64(len(k)) size += 200 // map entry overhead for _, v := range vs { size += int64(len(v)) } } return size } // Form is a parsed multipart form. // Its File parts are stored either in memory or on disk, // and are accessible via the [*FileHeader]'s Open method. // Its Value parts are stored as strings. // Both are keyed by field name. type Form struct { Value map[string][]string File map[string][]*FileHeader } // RemoveAll removes any temporary files associated with a [Form]. func (f *Form) RemoveAll() error { var err error for _, fhs := range f.File { for _, fh := range fhs { if fh.tmpfile != "" { e := os.Remove(fh.tmpfile) if e != nil && !errors.Is(e, os.ErrNotExist) && err == nil { err = e } } } } return err } // A FileHeader describes a file part of a multipart request. type FileHeader struct { Filename string Header textproto.MIMEHeader Size int64 content []byte tmpfile string tmpoff int64 tmpshared bool } // Open opens and returns the [FileHeader]'s associated File. func (fh *FileHeader) Open() (File, error) { if b := fh.content; b != nil { r := io.NewSectionReader(bytes.NewReader(b), 0, int64(len(b))) return sectionReadCloser{r, nil}, nil } if fh.tmpshared { f, err := os.Open(fh.tmpfile) if err != nil { return nil, err } r := io.NewSectionReader(f, fh.tmpoff, fh.Size) return sectionReadCloser{r, f}, nil } return os.Open(fh.tmpfile) } // File is an interface to access the file part of a multipart message. // Its contents may be either stored in memory or on disk. // If stored on disk, the File's underlying concrete type will be an *os.File. type File interface { io.Reader io.ReaderAt io.Seeker io.Closer } // helper types to turn a []byte into a File type sectionReadCloser struct { *io.SectionReader io.Closer } func (rc sectionReadCloser) Close() error { if rc.Closer != nil { return rc.Closer.Close() } return nil }
go/src/mime/multipart/formdata.go/0
{ "file_path": "go/src/mime/multipart/formdata.go", "repo_id": "go", "token_count": 2929 }
334
// Copyright 2010 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. // Package mime implements parts of the MIME spec. package mime import ( "fmt" "slices" "strings" "sync" ) var ( mimeTypes sync.Map // map[string]string; ".Z" => "application/x-compress" mimeTypesLower sync.Map // map[string]string; ".z" => "application/x-compress" // extensions maps from MIME type to list of lowercase file // extensions: "image/jpeg" => [".jpg", ".jpeg"] extensionsMu sync.Mutex // Guards stores (but not loads) on extensions. extensions sync.Map // map[string][]string; slice values are append-only. ) // setMimeTypes is used by initMime's non-test path, and by tests. func setMimeTypes(lowerExt, mixExt map[string]string) { mimeTypes.Clear() mimeTypesLower.Clear() extensions.Clear() for k, v := range lowerExt { mimeTypesLower.Store(k, v) } for k, v := range mixExt { mimeTypes.Store(k, v) } extensionsMu.Lock() defer extensionsMu.Unlock() for k, v := range lowerExt { justType, _, err := ParseMediaType(v) if err != nil { panic(err) } var exts []string if ei, ok := extensions.Load(justType); ok { exts = ei.([]string) } extensions.Store(justType, append(exts, k)) } } var builtinTypesLower = map[string]string{ ".avif": "image/avif", ".css": "text/css; charset=utf-8", ".gif": "image/gif", ".htm": "text/html; charset=utf-8", ".html": "text/html; charset=utf-8", ".jpeg": "image/jpeg", ".jpg": "image/jpeg", ".js": "text/javascript; charset=utf-8", ".json": "application/json", ".mjs": "text/javascript; charset=utf-8", ".pdf": "application/pdf", ".png": "image/png", ".svg": "image/svg+xml", ".wasm": "application/wasm", ".webp": "image/webp", ".xml": "text/xml; charset=utf-8", } var once sync.Once // guards initMime var testInitMime, osInitMime func() func initMime() { if fn := testInitMime; fn != nil { fn() } else { setMimeTypes(builtinTypesLower, builtinTypesLower) osInitMime() } } // TypeByExtension returns the MIME type associated with the file extension ext. // The extension ext should begin with a leading dot, as in ".html". // When ext has no associated type, TypeByExtension returns "". // // Extensions are looked up first case-sensitively, then case-insensitively. // // The built-in table is small but on unix it is augmented by the local // system's MIME-info database or mime.types file(s) if available under one or // more of these names: // // /usr/local/share/mime/globs2 // /usr/share/mime/globs2 // /etc/mime.types // /etc/apache2/mime.types // /etc/apache/mime.types // // On Windows, MIME types are extracted from the registry. // // Text types have the charset parameter set to "utf-8" by default. func TypeByExtension(ext string) string { once.Do(initMime) // Case-sensitive lookup. if v, ok := mimeTypes.Load(ext); ok { return v.(string) } // Case-insensitive lookup. // Optimistically assume a short ASCII extension and be // allocation-free in that case. var buf [10]byte lower := buf[:0] const utf8RuneSelf = 0x80 // from utf8 package, but not importing it. for i := 0; i < len(ext); i++ { c := ext[i] if c >= utf8RuneSelf { // Slow path. si, _ := mimeTypesLower.Load(strings.ToLower(ext)) s, _ := si.(string) return s } if 'A' <= c && c <= 'Z' { lower = append(lower, c+('a'-'A')) } else { lower = append(lower, c) } } si, _ := mimeTypesLower.Load(string(lower)) s, _ := si.(string) return s } // ExtensionsByType returns the extensions known to be associated with the MIME // type typ. The returned extensions will each begin with a leading dot, as in // ".html". When typ has no associated extensions, ExtensionsByType returns an // nil slice. func ExtensionsByType(typ string) ([]string, error) { justType, _, err := ParseMediaType(typ) if err != nil { return nil, err } once.Do(initMime) s, ok := extensions.Load(justType) if !ok { return nil, nil } ret := append([]string(nil), s.([]string)...) slices.Sort(ret) return ret, nil } // AddExtensionType sets the MIME type associated with // the extension ext to typ. The extension should begin with // a leading dot, as in ".html". func AddExtensionType(ext, typ string) error { if !strings.HasPrefix(ext, ".") { return fmt.Errorf("mime: extension %q missing leading dot", ext) } once.Do(initMime) return setExtensionType(ext, typ) } func setExtensionType(extension, mimeType string) error { justType, param, err := ParseMediaType(mimeType) if err != nil { return err } if strings.HasPrefix(mimeType, "text/") && param["charset"] == "" { param["charset"] = "utf-8" mimeType = FormatMediaType(mimeType, param) } extLower := strings.ToLower(extension) mimeTypes.Store(extension, mimeType) mimeTypesLower.Store(extLower, mimeType) extensionsMu.Lock() defer extensionsMu.Unlock() var exts []string if ei, ok := extensions.Load(justType); ok { exts = ei.([]string) } for _, v := range exts { if v == extLower { return nil } } extensions.Store(justType, append(exts, extLower)) return nil }
go/src/mime/type.go/0
{ "file_path": "go/src/mime/type.go", "repo_id": "go", "token_count": 1927 }
335
// Copyright 2012 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 API tests across platforms and should never have a build // constraint. package net import ( "testing" "time" ) // someTimeout is used just to test that net.Conn implementations // don't explode when their SetFooDeadline methods are called. // It isn't actually used for testing timeouts. const someTimeout = 1 * time.Hour func TestConnAndListener(t *testing.T) { for i, network := range []string{"tcp", "unix", "unixpacket"} { i, network := i, network t.Run(network, func(t *testing.T) { if !testableNetwork(network) { t.Skipf("skipping %s test", network) } ls := newLocalServer(t, network) defer ls.teardown() ch := make(chan error, 1) handler := func(ls *localServer, ln Listener) { ls.transponder(ln, ch) } if err := ls.buildup(handler); err != nil { t.Fatal(err) } if ls.Listener.Addr().Network() != network { t.Fatalf("got %s; want %s", ls.Listener.Addr().Network(), network) } c, err := Dial(ls.Listener.Addr().Network(), ls.Listener.Addr().String()) if err != nil { t.Fatal(err) } defer c.Close() if c.LocalAddr().Network() != network || c.RemoteAddr().Network() != network { t.Fatalf("got %s->%s; want %s->%s", c.LocalAddr().Network(), c.RemoteAddr().Network(), network, network) } c.SetDeadline(time.Now().Add(someTimeout)) c.SetReadDeadline(time.Now().Add(someTimeout)) c.SetWriteDeadline(time.Now().Add(someTimeout)) if _, err := c.Write([]byte("CONN AND LISTENER TEST")); err != nil { t.Fatal(err) } rb := make([]byte, 128) if _, err := c.Read(rb); err != nil { t.Fatal(err) } for err := range ch { t.Errorf("#%d: %v", i, err) } }) } }
go/src/net/conn_test.go/0
{ "file_path": "go/src/net/conn_test.go", "repo_id": "go", "token_count": 731 }
336
// Copyright 2015 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. //go:build !plan9 package net import ( "os" "syscall" "testing" ) func TestSpuriousENOTAVAIL(t *testing.T) { for _, tt := range []struct { error ok bool }{ {syscall.EADDRNOTAVAIL, true}, {&os.SyscallError{Syscall: "syscall", Err: syscall.EADDRNOTAVAIL}, true}, {&OpError{Op: "op", Err: syscall.EADDRNOTAVAIL}, true}, {&OpError{Op: "op", Err: &os.SyscallError{Syscall: "syscall", Err: syscall.EADDRNOTAVAIL}}, true}, {syscall.EINVAL, false}, {&os.SyscallError{Syscall: "syscall", Err: syscall.EINVAL}, false}, {&OpError{Op: "op", Err: syscall.EINVAL}, false}, {&OpError{Op: "op", Err: &os.SyscallError{Syscall: "syscall", Err: syscall.EINVAL}}, false}, } { if ok := spuriousENOTAVAIL(tt.error); ok != tt.ok { t.Errorf("spuriousENOTAVAIL(%v) = %v; want %v", tt.error, ok, tt.ok) } } }
go/src/net/error_posix_test.go/0
{ "file_path": "go/src/net/error_posix_test.go", "repo_id": "go", "token_count": 431 }
337
// Copyright 2011 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. package net import ( "errors" "io" "os" "syscall" ) func (fd *netFD) status(ln int) (string, error) { if !fd.ok() { return "", syscall.EINVAL } status, err := os.Open(fd.dir + "/status") if err != nil { return "", err } defer status.Close() buf := make([]byte, ln) n, err := io.ReadFull(status, buf[:]) if err != nil { return "", err } return string(buf[:n]), nil } func newFileFD(f *os.File) (net *netFD, err error) { var ctl *os.File close := func(fd int) { if err != nil { syscall.Close(fd) } } path, err := syscall.Fd2path(int(f.Fd())) if err != nil { return nil, os.NewSyscallError("fd2path", err) } comp := splitAtBytes(path, "/") n := len(comp) if n < 3 || comp[0][0:3] != "net" { return nil, syscall.EPLAN9 } name := comp[2] switch file := comp[n-1]; file { case "ctl", "clone": fd, err := syscall.Dup(int(f.Fd()), -1) if err != nil { return nil, os.NewSyscallError("dup", err) } defer close(fd) dir := netdir + "/" + comp[n-2] ctl = os.NewFile(uintptr(fd), dir+"/"+file) ctl.Seek(0, io.SeekStart) var buf [16]byte n, err := ctl.Read(buf[:]) if err != nil { return nil, err } name = string(buf[:n]) default: if len(comp) < 4 { return nil, errors.New("could not find control file for connection") } dir := netdir + "/" + comp[1] + "/" + name ctl, err = os.OpenFile(dir+"/ctl", os.O_RDWR, 0) if err != nil { return nil, err } defer close(int(ctl.Fd())) } dir := netdir + "/" + comp[1] + "/" + name laddr, err := readPlan9Addr(comp[1], dir+"/local") if err != nil { return nil, err } return newFD(comp[1], name, nil, ctl, nil, laddr, nil) } func fileConn(f *os.File) (Conn, error) { fd, err := newFileFD(f) if err != nil { return nil, err } if !fd.ok() { return nil, syscall.EINVAL } fd.data, err = os.OpenFile(fd.dir+"/data", os.O_RDWR, 0) if err != nil { return nil, err } switch fd.laddr.(type) { case *TCPAddr: return newTCPConn(fd, defaultTCPKeepAliveIdle, KeepAliveConfig{}, testPreHookSetKeepAlive, testHookSetKeepAlive), nil case *UDPAddr: return newUDPConn(fd), nil } return nil, syscall.EPLAN9 } func fileListener(f *os.File) (Listener, error) { fd, err := newFileFD(f) if err != nil { return nil, err } switch fd.laddr.(type) { case *TCPAddr: default: return nil, syscall.EPLAN9 } // check that file corresponds to a listener s, err := fd.status(len("Listen")) if err != nil { return nil, err } if s != "Listen" { return nil, errors.New("file does not represent a listener") } return &TCPListener{fd: fd}, nil } func filePacketConn(f *os.File) (PacketConn, error) { return nil, syscall.EPLAN9 }
go/src/net/file_plan9.go/0
{ "file_path": "go/src/net/file_plan9.go", "repo_id": "go", "token_count": 1246 }
338
// Copyright 2011 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 CGI from the perspective of a child // process. package cgi import ( "bufio" "crypto/tls" "errors" "fmt" "io" "net" "net/http" "net/url" "os" "strconv" "strings" ) // Request returns the HTTP request as represented in the current // environment. This assumes the current program is being run // by a web server in a CGI environment. // The returned Request's Body is populated, if applicable. func Request() (*http.Request, error) { r, err := RequestFromMap(envMap(os.Environ())) if err != nil { return nil, err } if r.ContentLength > 0 { r.Body = io.NopCloser(io.LimitReader(os.Stdin, r.ContentLength)) } return r, nil } func envMap(env []string) map[string]string { m := make(map[string]string) for _, kv := range env { if k, v, ok := strings.Cut(kv, "="); ok { m[k] = v } } return m } // RequestFromMap creates an [http.Request] from CGI variables. // The returned Request's Body field is not populated. func RequestFromMap(params map[string]string) (*http.Request, error) { r := new(http.Request) r.Method = params["REQUEST_METHOD"] if r.Method == "" { return nil, errors.New("cgi: no REQUEST_METHOD in environment") } r.Proto = params["SERVER_PROTOCOL"] var ok bool r.ProtoMajor, r.ProtoMinor, ok = http.ParseHTTPVersion(r.Proto) if !ok { return nil, errors.New("cgi: invalid SERVER_PROTOCOL version") } r.Close = true r.Trailer = http.Header{} r.Header = http.Header{} r.Host = params["HTTP_HOST"] if lenstr := params["CONTENT_LENGTH"]; lenstr != "" { clen, err := strconv.ParseInt(lenstr, 10, 64) if err != nil { return nil, errors.New("cgi: bad CONTENT_LENGTH in environment: " + lenstr) } r.ContentLength = clen } if ct := params["CONTENT_TYPE"]; ct != "" { r.Header.Set("Content-Type", ct) } // Copy "HTTP_FOO_BAR" variables to "Foo-Bar" Headers for k, v := range params { if k == "HTTP_HOST" { continue } if after, found := strings.CutPrefix(k, "HTTP_"); found { r.Header.Add(strings.ReplaceAll(after, "_", "-"), v) } } uriStr := params["REQUEST_URI"] if uriStr == "" { // Fallback to SCRIPT_NAME, PATH_INFO and QUERY_STRING. uriStr = params["SCRIPT_NAME"] + params["PATH_INFO"] s := params["QUERY_STRING"] if s != "" { uriStr += "?" + s } } // There's apparently a de-facto standard for this. // https://web.archive.org/web/20170105004655/http://docstore.mik.ua/orelly/linux/cgi/ch03_02.htm#ch03-35636 if s := params["HTTPS"]; s == "on" || s == "ON" || s == "1" { r.TLS = &tls.ConnectionState{HandshakeComplete: true} } if r.Host != "" { // Hostname is provided, so we can reasonably construct a URL. rawurl := r.Host + uriStr if r.TLS == nil { rawurl = "http://" + rawurl } else { rawurl = "https://" + rawurl } url, err := url.Parse(rawurl) if err != nil { return nil, errors.New("cgi: failed to parse host and REQUEST_URI into a URL: " + rawurl) } r.URL = url } // Fallback logic if we don't have a Host header or the URL // failed to parse if r.URL == nil { url, err := url.Parse(uriStr) if err != nil { return nil, errors.New("cgi: failed to parse REQUEST_URI into a URL: " + uriStr) } r.URL = url } // Request.RemoteAddr has its port set by Go's standard http // server, so we do here too. remotePort, _ := strconv.Atoi(params["REMOTE_PORT"]) // zero if unset or invalid r.RemoteAddr = net.JoinHostPort(params["REMOTE_ADDR"], strconv.Itoa(remotePort)) return r, nil } // Serve executes the provided [Handler] on the currently active CGI // request, if any. If there's no current CGI environment // an error is returned. The provided handler may be nil to use // [http.DefaultServeMux]. func Serve(handler http.Handler) error { req, err := Request() if err != nil { return err } if req.Body == nil { req.Body = http.NoBody } if handler == nil { handler = http.DefaultServeMux } rw := &response{ req: req, header: make(http.Header), bufw: bufio.NewWriter(os.Stdout), } handler.ServeHTTP(rw, req) rw.Write(nil) // make sure a response is sent if err = rw.bufw.Flush(); err != nil { return err } return nil } type response struct { req *http.Request header http.Header code int wroteHeader bool wroteCGIHeader bool bufw *bufio.Writer } func (r *response) Flush() { r.bufw.Flush() } func (r *response) Header() http.Header { return r.header } func (r *response) Write(p []byte) (n int, err error) { if !r.wroteHeader { r.WriteHeader(http.StatusOK) } if !r.wroteCGIHeader { r.writeCGIHeader(p) } return r.bufw.Write(p) } func (r *response) WriteHeader(code int) { if r.wroteHeader { // Note: explicitly using Stderr, as Stdout is our HTTP output. fmt.Fprintf(os.Stderr, "CGI attempted to write header twice on request for %s", r.req.URL) return } r.wroteHeader = true r.code = code } // writeCGIHeader finalizes the header sent to the client and writes it to the output. // p is not written by writeHeader, but is the first chunk of the body // that will be written. It is sniffed for a Content-Type if none is // set explicitly. func (r *response) writeCGIHeader(p []byte) { if r.wroteCGIHeader { return } r.wroteCGIHeader = true fmt.Fprintf(r.bufw, "Status: %d %s\r\n", r.code, http.StatusText(r.code)) if _, hasType := r.header["Content-Type"]; !hasType { r.header.Set("Content-Type", http.DetectContentType(p)) } r.header.Write(r.bufw) r.bufw.WriteString("\r\n") r.bufw.Flush() }
go/src/net/http/cgi/child.go/0
{ "file_path": "go/src/net/http/cgi/child.go", "repo_id": "go", "token_count": 2204 }
339
// Copyright 2012 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. package cookiejar import ( "testing" ) var punycodeTestCases = [...]struct { s, encoded string }{ {"", ""}, {"-", "--"}, {"-a", "-a-"}, {"-a-", "-a--"}, {"a", "a-"}, {"a-", "a--"}, {"a-b", "a-b-"}, {"books", "books-"}, {"bücher", "bcher-kva"}, {"Hello世界", "Hello-ck1hg65u"}, {"ü", "tda"}, {"üý", "tdac"}, // The test cases below come from RFC 3492 section 7.1 with Errata 3026. { // (A) Arabic (Egyptian). "\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644" + "\u0645\u0648\u0634\u0639\u0631\u0628\u064A\u061F", "egbpdaj6bu4bxfgehfvwxn", }, { // (B) Chinese (simplified). "\u4ED6\u4EEC\u4E3A\u4EC0\u4E48\u4E0D\u8BF4\u4E2D\u6587", "ihqwcrb4cv8a8dqg056pqjye", }, { // (C) Chinese (traditional). "\u4ED6\u5011\u7232\u4EC0\u9EBD\u4E0D\u8AAA\u4E2D\u6587", "ihqwctvzc91f659drss3x8bo0yb", }, { // (D) Czech. "\u0050\u0072\u006F\u010D\u0070\u0072\u006F\u0073\u0074" + "\u011B\u006E\u0065\u006D\u006C\u0075\u0076\u00ED\u010D" + "\u0065\u0073\u006B\u0079", "Proprostnemluvesky-uyb24dma41a", }, { // (E) Hebrew. "\u05DC\u05DE\u05D4\u05D4\u05DD\u05E4\u05E9\u05D5\u05D8" + "\u05DC\u05D0\u05DE\u05D3\u05D1\u05E8\u05D9\u05DD\u05E2" + "\u05D1\u05E8\u05D9\u05EA", "4dbcagdahymbxekheh6e0a7fei0b", }, { // (F) Hindi (Devanagari). "\u092F\u0939\u0932\u094B\u0917\u0939\u093F\u0928\u094D" + "\u0926\u0940\u0915\u094D\u092F\u094B\u0902\u0928\u0939" + "\u0940\u0902\u092C\u094B\u0932\u0938\u0915\u0924\u0947" + "\u0939\u0948\u0902", "i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd", }, { // (G) Japanese (kanji and hiragana). "\u306A\u305C\u307F\u3093\u306A\u65E5\u672C\u8A9E\u3092" + "\u8A71\u3057\u3066\u304F\u308C\u306A\u3044\u306E\u304B", "n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa", }, { // (H) Korean (Hangul syllables). "\uC138\uACC4\uC758\uBAA8\uB4E0\uC0AC\uB78C\uB4E4\uC774" + "\uD55C\uAD6D\uC5B4\uB97C\uC774\uD574\uD55C\uB2E4\uBA74" + "\uC5BC\uB9C8\uB098\uC88B\uC744\uAE4C", "989aomsvi5e83db1d2a355cv1e0vak1dwrv93d5xbh15a0dt30a5j" + "psd879ccm6fea98c", }, { // (I) Russian (Cyrillic). "\u043F\u043E\u0447\u0435\u043C\u0443\u0436\u0435\u043E" + "\u043D\u0438\u043D\u0435\u0433\u043E\u0432\u043E\u0440" + "\u044F\u0442\u043F\u043E\u0440\u0443\u0441\u0441\u043A" + "\u0438", "b1abfaaepdrnnbgefbadotcwatmq2g4l", }, { // (J) Spanish. "\u0050\u006F\u0072\u0071\u0075\u00E9\u006E\u006F\u0070" + "\u0075\u0065\u0064\u0065\u006E\u0073\u0069\u006D\u0070" + "\u006C\u0065\u006D\u0065\u006E\u0074\u0065\u0068\u0061" + "\u0062\u006C\u0061\u0072\u0065\u006E\u0045\u0073\u0070" + "\u0061\u00F1\u006F\u006C", "PorqunopuedensimplementehablarenEspaol-fmd56a", }, { // (K) Vietnamese. "\u0054\u1EA1\u0069\u0073\u0061\u006F\u0068\u1ECD\u006B" + "\u0068\u00F4\u006E\u0067\u0074\u0068\u1EC3\u0063\u0068" + "\u1EC9\u006E\u00F3\u0069\u0074\u0069\u1EBF\u006E\u0067" + "\u0056\u0069\u1EC7\u0074", "TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g", }, { // (L) 3<nen>B<gumi><kinpachi><sensei>. "\u0033\u5E74\u0042\u7D44\u91D1\u516B\u5148\u751F", "3B-ww4c5e180e575a65lsy2b", }, { // (M) <amuro><namie>-with-SUPER-MONKEYS. "\u5B89\u5BA4\u5948\u7F8E\u6075\u002D\u0077\u0069\u0074" + "\u0068\u002D\u0053\u0055\u0050\u0045\u0052\u002D\u004D" + "\u004F\u004E\u004B\u0045\u0059\u0053", "-with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n", }, { // (N) Hello-Another-Way-<sorezore><no><basho>. "\u0048\u0065\u006C\u006C\u006F\u002D\u0041\u006E\u006F" + "\u0074\u0068\u0065\u0072\u002D\u0057\u0061\u0079\u002D" + "\u305D\u308C\u305E\u308C\u306E\u5834\u6240", "Hello-Another-Way--fc4qua05auwb3674vfr0b", }, { // (O) <hitotsu><yane><no><shita>2. "\u3072\u3068\u3064\u5C4B\u6839\u306E\u4E0B\u0032", "2-u9tlzr9756bt3uc0v", }, { // (P) Maji<de>Koi<suru>5<byou><mae> "\u004D\u0061\u006A\u0069\u3067\u004B\u006F\u0069\u3059" + "\u308B\u0035\u79D2\u524D", "MajiKoi5-783gue6qz075azm5e", }, { // (Q) <pafii>de<runba> "\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", "de-jg4avhby1noc0d", }, { // (R) <sono><supiido><de> "\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067", "d9juau41awczczp", }, { // (S) -> $1.00 <- "\u002D\u003E\u0020\u0024\u0031\u002E\u0030\u0030\u0020" + "\u003C\u002D", "-> $1.00 <--", }, } func TestPunycode(t *testing.T) { for _, tc := range punycodeTestCases { if got, err := encode("", tc.s); err != nil { t.Errorf(`encode("", %q): %v`, tc.s, err) } else if got != tc.encoded { t.Errorf(`encode("", %q): got %q, want %q`, tc.s, got, tc.encoded) } } }
go/src/net/http/cookiejar/punycode_test.go/0
{ "file_path": "go/src/net/http/cookiejar/punycode_test.go", "repo_id": "go", "token_count": 3060 }
340
// Copyright 2010 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. package http import ( "io" "net/http/httptrace" "net/http/internal/ascii" "net/textproto" "slices" "strings" "sync" "time" "golang.org/x/net/http/httpguts" ) // A Header represents the key-value pairs in an HTTP header. // // The keys should be in canonical form, as returned by // [CanonicalHeaderKey]. type Header map[string][]string // Add adds the key, value pair to the header. // It appends to any existing values associated with key. // The key is case insensitive; it is canonicalized by // [CanonicalHeaderKey]. func (h Header) Add(key, value string) { textproto.MIMEHeader(h).Add(key, value) } // Set sets the header entries associated with key to the // single element value. It replaces any existing values // associated with key. The key is case insensitive; it is // canonicalized by [textproto.CanonicalMIMEHeaderKey]. // To use non-canonical keys, assign to the map directly. func (h Header) Set(key, value string) { textproto.MIMEHeader(h).Set(key, value) } // Get gets the first value associated with the given key. If // there are no values associated with the key, Get returns "". // It is case insensitive; [textproto.CanonicalMIMEHeaderKey] is // used to canonicalize the provided key. Get assumes that all // keys are stored in canonical form. To use non-canonical keys, // access the map directly. func (h Header) Get(key string) string { return textproto.MIMEHeader(h).Get(key) } // Values returns all values associated with the given key. // It is case insensitive; [textproto.CanonicalMIMEHeaderKey] is // used to canonicalize the provided key. To use non-canonical // keys, access the map directly. // The returned slice is not a copy. func (h Header) Values(key string) []string { return textproto.MIMEHeader(h).Values(key) } // get is like Get, but key must already be in CanonicalHeaderKey form. func (h Header) get(key string) string { if v := h[key]; len(v) > 0 { return v[0] } return "" } // has reports whether h has the provided key defined, even if it's // set to 0-length slice. func (h Header) has(key string) bool { _, ok := h[key] return ok } // Del deletes the values associated with key. // The key is case insensitive; it is canonicalized by // [CanonicalHeaderKey]. func (h Header) Del(key string) { textproto.MIMEHeader(h).Del(key) } // Write writes a header in wire format. func (h Header) Write(w io.Writer) error { return h.write(w, nil) } func (h Header) write(w io.Writer, trace *httptrace.ClientTrace) error { return h.writeSubset(w, nil, trace) } // Clone returns a copy of h or nil if h is nil. func (h Header) Clone() Header { if h == nil { return nil } // Find total number of values. nv := 0 for _, vv := range h { nv += len(vv) } sv := make([]string, nv) // shared backing array for headers' values h2 := make(Header, len(h)) for k, vv := range h { if vv == nil { // Preserve nil values. ReverseProxy distinguishes // between nil and zero-length header values. h2[k] = nil continue } n := copy(sv, vv) h2[k] = sv[:n:n] sv = sv[n:] } return h2 } var timeFormats = []string{ TimeFormat, time.RFC850, time.ANSIC, } // ParseTime parses a time header (such as the Date: header), // trying each of the three formats allowed by HTTP/1.1: // [TimeFormat], [time.RFC850], and [time.ANSIC]. func ParseTime(text string) (t time.Time, err error) { for _, layout := range timeFormats { t, err = time.Parse(layout, text) if err == nil { return } } return } var headerNewlineToSpace = strings.NewReplacer("\n", " ", "\r", " ") // stringWriter implements WriteString on a Writer. type stringWriter struct { w io.Writer } func (w stringWriter) WriteString(s string) (n int, err error) { return w.w.Write([]byte(s)) } type keyValues struct { key string values []string } // headerSorter contains a slice of keyValues sorted by keyValues.key. type headerSorter struct { kvs []keyValues } var headerSorterPool = sync.Pool{ New: func() any { return new(headerSorter) }, } // sortedKeyValues returns h's keys sorted in the returned kvs // slice. The headerSorter used to sort is also returned, for possible // return to headerSorterCache. func (h Header) sortedKeyValues(exclude map[string]bool) (kvs []keyValues, hs *headerSorter) { hs = headerSorterPool.Get().(*headerSorter) if cap(hs.kvs) < len(h) { hs.kvs = make([]keyValues, 0, len(h)) } kvs = hs.kvs[:0] for k, vv := range h { if !exclude[k] { kvs = append(kvs, keyValues{k, vv}) } } hs.kvs = kvs slices.SortFunc(hs.kvs, func(a, b keyValues) int { return strings.Compare(a.key, b.key) }) return kvs, hs } // WriteSubset writes a header in wire format. // If exclude is not nil, keys where exclude[key] == true are not written. // Keys are not canonicalized before checking the exclude map. func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error { return h.writeSubset(w, exclude, nil) } func (h Header) writeSubset(w io.Writer, exclude map[string]bool, trace *httptrace.ClientTrace) error { ws, ok := w.(io.StringWriter) if !ok { ws = stringWriter{w} } kvs, sorter := h.sortedKeyValues(exclude) var formattedVals []string for _, kv := range kvs { if !httpguts.ValidHeaderFieldName(kv.key) { // This could be an error. In the common case of // writing response headers, however, we have no good // way to provide the error back to the server // handler, so just drop invalid headers instead. continue } for _, v := range kv.values { v = headerNewlineToSpace.Replace(v) v = textproto.TrimString(v) for _, s := range []string{kv.key, ": ", v, "\r\n"} { if _, err := ws.WriteString(s); err != nil { headerSorterPool.Put(sorter) return err } } if trace != nil && trace.WroteHeaderField != nil { formattedVals = append(formattedVals, v) } } if trace != nil && trace.WroteHeaderField != nil { trace.WroteHeaderField(kv.key, formattedVals) formattedVals = nil } } headerSorterPool.Put(sorter) return nil } // CanonicalHeaderKey returns the canonical format of the // header key s. The canonicalization converts the first // letter and any letter following a hyphen to upper case; // the rest are converted to lowercase. For example, the // canonical key for "accept-encoding" is "Accept-Encoding". // If s contains a space or invalid header field bytes, it is // returned without modifications. func CanonicalHeaderKey(s string) string { return textproto.CanonicalMIMEHeaderKey(s) } // hasToken reports whether token appears with v, ASCII // case-insensitive, with space or comma boundaries. // token must be all lowercase. // v may contain mixed cased. func hasToken(v, token string) bool { if len(token) > len(v) || token == "" { return false } if v == token { return true } for sp := 0; sp <= len(v)-len(token); sp++ { // Check that first character is good. // The token is ASCII, so checking only a single byte // is sufficient. We skip this potential starting // position if both the first byte and its potential // ASCII uppercase equivalent (b|0x20) don't match. // False positives ('^' => '~') are caught by EqualFold. if b := v[sp]; b != token[0] && b|0x20 != token[0] { continue } // Check that start pos is on a valid token boundary. if sp > 0 && !isTokenBoundary(v[sp-1]) { continue } // Check that end pos is on a valid token boundary. if endPos := sp + len(token); endPos != len(v) && !isTokenBoundary(v[endPos]) { continue } if ascii.EqualFold(v[sp:sp+len(token)], token) { return true } } return false } func isTokenBoundary(b byte) bool { return b == ' ' || b == ',' || b == '\t' }
go/src/net/http/header.go/0
{ "file_path": "go/src/net/http/header.go", "repo_id": "go", "token_count": 2743 }
341
// Copyright 2015 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. package httputil_test import ( "fmt" "io" "log" "net/http" "net/http/httptest" "net/http/httputil" "net/url" "strings" ) func ExampleDumpRequest() { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { dump, err := httputil.DumpRequest(r, true) if err != nil { http.Error(w, fmt.Sprint(err), http.StatusInternalServerError) return } fmt.Fprintf(w, "%q", dump) })) defer ts.Close() const body = "Go is a general-purpose language designed with systems programming in mind." req, err := http.NewRequest("POST", ts.URL, strings.NewReader(body)) if err != nil { log.Fatal(err) } req.Host = "www.example.org" resp, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() b, err := io.ReadAll(resp.Body) if err != nil { log.Fatal(err) } fmt.Printf("%s", b) // Output: // "POST / HTTP/1.1\r\nHost: www.example.org\r\nAccept-Encoding: gzip\r\nContent-Length: 75\r\nUser-Agent: Go-http-client/1.1\r\n\r\nGo is a general-purpose language designed with systems programming in mind." } func ExampleDumpRequestOut() { const body = "Go is a general-purpose language designed with systems programming in mind." req, err := http.NewRequest("PUT", "http://www.example.org", strings.NewReader(body)) if err != nil { log.Fatal(err) } dump, err := httputil.DumpRequestOut(req, true) if err != nil { log.Fatal(err) } fmt.Printf("%q", dump) // Output: // "PUT / HTTP/1.1\r\nHost: www.example.org\r\nUser-Agent: Go-http-client/1.1\r\nContent-Length: 75\r\nAccept-Encoding: gzip\r\n\r\nGo is a general-purpose language designed with systems programming in mind." } func ExampleDumpResponse() { const body = "Go is a general-purpose language designed with systems programming in mind." ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Date", "Wed, 19 Jul 1972 19:00:00 GMT") fmt.Fprintln(w, body) })) defer ts.Close() resp, err := http.Get(ts.URL) if err != nil { log.Fatal(err) } defer resp.Body.Close() dump, err := httputil.DumpResponse(resp, true) if err != nil { log.Fatal(err) } fmt.Printf("%q", dump) // Output: // "HTTP/1.1 200 OK\r\nContent-Length: 76\r\nContent-Type: text/plain; charset=utf-8\r\nDate: Wed, 19 Jul 1972 19:00:00 GMT\r\n\r\nGo is a general-purpose language designed with systems programming in mind.\n" } func ExampleReverseProxy() { backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "this call was relayed by the reverse proxy") })) defer backendServer.Close() rpURL, err := url.Parse(backendServer.URL) if err != nil { log.Fatal(err) } frontendProxy := httptest.NewServer(&httputil.ReverseProxy{ Rewrite: func(r *httputil.ProxyRequest) { r.SetXForwarded() r.SetURL(rpURL) }, }) defer frontendProxy.Close() resp, err := http.Get(frontendProxy.URL) if err != nil { log.Fatal(err) } b, err := io.ReadAll(resp.Body) if err != nil { log.Fatal(err) } fmt.Printf("%s", b) // Output: // this call was relayed by the reverse proxy }
go/src/net/http/httputil/example_test.go/0
{ "file_path": "go/src/net/http/httputil/example_test.go", "repo_id": "go", "token_count": 1309 }
342
// Copyright 2023 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. // Patterns for ServeMux routing. package http import ( "errors" "fmt" "net/url" "strings" "unicode" ) // A pattern is something that can be matched against an HTTP request. // It has an optional method, an optional host, and a path. type pattern struct { str string // original string method string host string // The representation of a path differs from the surface syntax, which // simplifies most algorithms. // // Paths ending in '/' are represented with an anonymous "..." wildcard. // For example, the path "a/" is represented as a literal segment "a" followed // by a segment with multi==true. // // Paths ending in "{$}" are represented with the literal segment "/". // For example, the path "a/{$}" is represented as a literal segment "a" followed // by a literal segment "/". segments []segment loc string // source location of registering call, for helpful messages } func (p *pattern) String() string { return p.str } func (p *pattern) lastSegment() segment { return p.segments[len(p.segments)-1] } // A segment is a pattern piece that matches one or more path segments, or // a trailing slash. // // If wild is false, it matches a literal segment, or, if s == "/", a trailing slash. // Examples: // // "a" => segment{s: "a"} // "/{$}" => segment{s: "/"} // // If wild is true and multi is false, it matches a single path segment. // Example: // // "{x}" => segment{s: "x", wild: true} // // If both wild and multi are true, it matches all remaining path segments. // Example: // // "{rest...}" => segment{s: "rest", wild: true, multi: true} type segment struct { s string // literal or wildcard name or "/" for "/{$}". wild bool multi bool // "..." wildcard } // parsePattern parses a string into a Pattern. // The string's syntax is // // [METHOD] [HOST]/[PATH] // // where: // - METHOD is an HTTP method // - HOST is a hostname // - PATH consists of slash-separated segments, where each segment is either // a literal or a wildcard of the form "{name}", "{name...}", or "{$}". // // METHOD, HOST and PATH are all optional; that is, the string can be "/". // If METHOD is present, it must be followed by at least one space or tab. // Wildcard names must be valid Go identifiers. // The "{$}" and "{name...}" wildcard must occur at the end of PATH. // PATH may end with a '/'. // Wildcard names in a path must be distinct. func parsePattern(s string) (_ *pattern, err error) { if len(s) == 0 { return nil, errors.New("empty pattern") } off := 0 // offset into string defer func() { if err != nil { err = fmt.Errorf("at offset %d: %w", off, err) } }() method, rest, found := s, "", false if i := strings.IndexAny(s, " \t"); i >= 0 { method, rest, found = s[:i], strings.TrimLeft(s[i+1:], " \t"), true } if !found { rest = method method = "" } if method != "" && !validMethod(method) { return nil, fmt.Errorf("invalid method %q", method) } p := &pattern{str: s, method: method} if found { off = len(method) + 1 } i := strings.IndexByte(rest, '/') if i < 0 { return nil, errors.New("host/path missing /") } p.host = rest[:i] rest = rest[i:] if j := strings.IndexByte(p.host, '{'); j >= 0 { off += j return nil, errors.New("host contains '{' (missing initial '/'?)") } // At this point, rest is the path. off += i // An unclean path with a method that is not CONNECT can never match, // because paths are cleaned before matching. if method != "" && method != "CONNECT" && rest != cleanPath(rest) { return nil, errors.New("non-CONNECT pattern with unclean path can never match") } seenNames := map[string]bool{} // remember wildcard names to catch dups for len(rest) > 0 { // Invariant: rest[0] == '/'. rest = rest[1:] off = len(s) - len(rest) if len(rest) == 0 { // Trailing slash. p.segments = append(p.segments, segment{wild: true, multi: true}) break } i := strings.IndexByte(rest, '/') if i < 0 { i = len(rest) } var seg string seg, rest = rest[:i], rest[i:] if i := strings.IndexByte(seg, '{'); i < 0 { // Literal. seg = pathUnescape(seg) p.segments = append(p.segments, segment{s: seg}) } else { // Wildcard. if i != 0 { return nil, errors.New("bad wildcard segment (must start with '{')") } if seg[len(seg)-1] != '}' { return nil, errors.New("bad wildcard segment (must end with '}')") } name := seg[1 : len(seg)-1] if name == "$" { if len(rest) != 0 { return nil, errors.New("{$} not at end") } p.segments = append(p.segments, segment{s: "/"}) break } name, multi := strings.CutSuffix(name, "...") if multi && len(rest) != 0 { return nil, errors.New("{...} wildcard not at end") } if name == "" { return nil, errors.New("empty wildcard") } if !isValidWildcardName(name) { return nil, fmt.Errorf("bad wildcard name %q", name) } if seenNames[name] { return nil, fmt.Errorf("duplicate wildcard name %q", name) } seenNames[name] = true p.segments = append(p.segments, segment{s: name, wild: true, multi: multi}) } } return p, nil } func isValidWildcardName(s string) bool { if s == "" { return false } // Valid Go identifier. for i, c := range s { if !unicode.IsLetter(c) && c != '_' && (i == 0 || !unicode.IsDigit(c)) { return false } } return true } func pathUnescape(path string) string { u, err := url.PathUnescape(path) if err != nil { // Invalidly escaped path; use the original return path } return u } // relationship is a relationship between two patterns, p1 and p2. type relationship string const ( equivalent relationship = "equivalent" // both match the same requests moreGeneral relationship = "moreGeneral" // p1 matches everything p2 does & more moreSpecific relationship = "moreSpecific" // p2 matches everything p1 does & more disjoint relationship = "disjoint" // there is no request that both match overlaps relationship = "overlaps" // there is a request that both match, but neither is more specific ) // conflictsWith reports whether p1 conflicts with p2, that is, whether // there is a request that both match but where neither is higher precedence // than the other. // // Precedence is defined by two rules: // 1. Patterns with a host win over patterns without a host. // 2. Patterns whose method and path is more specific win. One pattern is more // specific than another if the second matches all the (method, path) pairs // of the first and more. // // If rule 1 doesn't apply, then two patterns conflict if their relationship // is either equivalence (they match the same set of requests) or overlap // (they both match some requests, but neither is more specific than the other). func (p1 *pattern) conflictsWith(p2 *pattern) bool { if p1.host != p2.host { // Either one host is empty and the other isn't, in which case the // one with the host wins by rule 1, or neither host is empty // and they differ, so they won't match the same paths. return false } rel := p1.comparePathsAndMethods(p2) return rel == equivalent || rel == overlaps } func (p1 *pattern) comparePathsAndMethods(p2 *pattern) relationship { mrel := p1.compareMethods(p2) // Optimization: avoid a call to comparePaths. if mrel == disjoint { return disjoint } prel := p1.comparePaths(p2) return combineRelationships(mrel, prel) } // compareMethods determines the relationship between the method // part of patterns p1 and p2. // // A method can either be empty, "GET", or something else. // The empty string matches any method, so it is the most general. // "GET" matches both GET and HEAD. // Anything else matches only itself. func (p1 *pattern) compareMethods(p2 *pattern) relationship { if p1.method == p2.method { return equivalent } if p1.method == "" { // p1 matches any method, but p2 does not, so p1 is more general. return moreGeneral } if p2.method == "" { return moreSpecific } if p1.method == "GET" && p2.method == "HEAD" { // p1 matches GET and HEAD; p2 matches only HEAD. return moreGeneral } if p2.method == "GET" && p1.method == "HEAD" { return moreSpecific } return disjoint } // comparePaths determines the relationship between the path // part of two patterns. func (p1 *pattern) comparePaths(p2 *pattern) relationship { // Optimization: if a path pattern doesn't end in a multi ("...") wildcard, then it // can only match paths with the same number of segments. if len(p1.segments) != len(p2.segments) && !p1.lastSegment().multi && !p2.lastSegment().multi { return disjoint } // Consider corresponding segments in the two path patterns. var segs1, segs2 []segment rel := equivalent for segs1, segs2 = p1.segments, p2.segments; len(segs1) > 0 && len(segs2) > 0; segs1, segs2 = segs1[1:], segs2[1:] { rel = combineRelationships(rel, compareSegments(segs1[0], segs2[0])) if rel == disjoint { return rel } } // We've reached the end of the corresponding segments of the patterns. // If they have the same number of segments, then we've already determined // their relationship. if len(segs1) == 0 && len(segs2) == 0 { return rel } // Otherwise, the only way they could fail to be disjoint is if the shorter // pattern ends in a multi. In that case, that multi is more general // than the remainder of the longer pattern, so combine those two relationships. if len(segs1) < len(segs2) && p1.lastSegment().multi { return combineRelationships(rel, moreGeneral) } if len(segs2) < len(segs1) && p2.lastSegment().multi { return combineRelationships(rel, moreSpecific) } return disjoint } // compareSegments determines the relationship between two segments. func compareSegments(s1, s2 segment) relationship { if s1.multi && s2.multi { return equivalent } if s1.multi { return moreGeneral } if s2.multi { return moreSpecific } if s1.wild && s2.wild { return equivalent } if s1.wild { if s2.s == "/" { // A single wildcard doesn't match a trailing slash. return disjoint } return moreGeneral } if s2.wild { if s1.s == "/" { return disjoint } return moreSpecific } // Both literals. if s1.s == s2.s { return equivalent } return disjoint } // combineRelationships determines the overall relationship of two patterns // given the relationships of a partition of the patterns into two parts. // // For example, if p1 is more general than p2 in one way but equivalent // in the other, then it is more general overall. // // Or if p1 is more general in one way and more specific in the other, then // they overlap. func combineRelationships(r1, r2 relationship) relationship { switch r1 { case equivalent: return r2 case disjoint: return disjoint case overlaps: if r2 == disjoint { return disjoint } return overlaps case moreGeneral, moreSpecific: switch r2 { case equivalent: return r1 case inverseRelationship(r1): return overlaps default: return r2 } default: panic(fmt.Sprintf("unknown relationship %q", r1)) } } // If p1 has relationship `r` to p2, then // p2 has inverseRelationship(r) to p1. func inverseRelationship(r relationship) relationship { switch r { case moreSpecific: return moreGeneral case moreGeneral: return moreSpecific default: return r } } // isLitOrSingle reports whether the segment is a non-dollar literal or a single wildcard. func isLitOrSingle(seg segment) bool { if seg.wild { return !seg.multi } return seg.s != "/" } // describeConflict returns an explanation of why two patterns conflict. func describeConflict(p1, p2 *pattern) string { mrel := p1.compareMethods(p2) prel := p1.comparePaths(p2) rel := combineRelationships(mrel, prel) if rel == equivalent { return fmt.Sprintf("%s matches the same requests as %s", p1, p2) } if rel != overlaps { panic("describeConflict called with non-conflicting patterns") } if prel == overlaps { return fmt.Sprintf(`%[1]s and %[2]s both match some paths, like %[3]q. But neither is more specific than the other. %[1]s matches %[4]q, but %[2]s doesn't. %[2]s matches %[5]q, but %[1]s doesn't.`, p1, p2, commonPath(p1, p2), differencePath(p1, p2), differencePath(p2, p1)) } if mrel == moreGeneral && prel == moreSpecific { return fmt.Sprintf("%s matches more methods than %s, but has a more specific path pattern", p1, p2) } if mrel == moreSpecific && prel == moreGeneral { return fmt.Sprintf("%s matches fewer methods than %s, but has a more general path pattern", p1, p2) } return fmt.Sprintf("bug: unexpected way for two patterns %s and %s to conflict: methods %s, paths %s", p1, p2, mrel, prel) } // writeMatchingPath writes to b a path that matches the segments. func writeMatchingPath(b *strings.Builder, segs []segment) { for _, s := range segs { writeSegment(b, s) } } func writeSegment(b *strings.Builder, s segment) { b.WriteByte('/') if !s.multi && s.s != "/" { b.WriteString(s.s) } } // commonPath returns a path that both p1 and p2 match. // It assumes there is such a path. func commonPath(p1, p2 *pattern) string { var b strings.Builder var segs1, segs2 []segment for segs1, segs2 = p1.segments, p2.segments; len(segs1) > 0 && len(segs2) > 0; segs1, segs2 = segs1[1:], segs2[1:] { if s1 := segs1[0]; s1.wild { writeSegment(&b, segs2[0]) } else { writeSegment(&b, s1) } } if len(segs1) > 0 { writeMatchingPath(&b, segs1) } else if len(segs2) > 0 { writeMatchingPath(&b, segs2) } return b.String() } // differencePath returns a path that p1 matches and p2 doesn't. // It assumes there is such a path. func differencePath(p1, p2 *pattern) string { var b strings.Builder var segs1, segs2 []segment for segs1, segs2 = p1.segments, p2.segments; len(segs1) > 0 && len(segs2) > 0; segs1, segs2 = segs1[1:], segs2[1:] { s1 := segs1[0] s2 := segs2[0] if s1.multi && s2.multi { // From here the patterns match the same paths, so we must have found a difference earlier. b.WriteByte('/') return b.String() } if s1.multi && !s2.multi { // s1 ends in a "..." wildcard but s2 does not. // A trailing slash will distinguish them, unless s2 ends in "{$}", // in which case any segment will do; prefer the wildcard name if // it has one. b.WriteByte('/') if s2.s == "/" { if s1.s != "" { b.WriteString(s1.s) } else { b.WriteString("x") } } return b.String() } if !s1.multi && s2.multi { writeSegment(&b, s1) } else if s1.wild && s2.wild { // Both patterns will match whatever we put here; use // the first wildcard name. writeSegment(&b, s1) } else if s1.wild && !s2.wild { // s1 is a wildcard, s2 is a literal. // Any segment other than s2.s will work. // Prefer the wildcard name, but if it's the same as the literal, // tweak the literal. if s1.s != s2.s { writeSegment(&b, s1) } else { b.WriteByte('/') b.WriteString(s2.s + "x") } } else if !s1.wild && s2.wild { writeSegment(&b, s1) } else { // Both are literals. A precondition of this function is that the // patterns overlap, so they must be the same literal. Use it. if s1.s != s2.s { panic(fmt.Sprintf("literals differ: %q and %q", s1.s, s2.s)) } writeSegment(&b, s1) } } if len(segs1) > 0 { // p1 is longer than p2, and p2 does not end in a multi. // Anything that matches the rest of p1 will do. writeMatchingPath(&b, segs1) } else if len(segs2) > 0 { writeMatchingPath(&b, segs2) } return b.String() }
go/src/net/http/pattern.go/0
{ "file_path": "go/src/net/http/pattern.go", "repo_id": "go", "token_count": 5715 }
343
// Copyright 2018 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. //go:build !js package http import _ "unsafe" // for linkname // RoundTrip should be an internal detail, // but widely used packages access it using linkname. // Notable members of the hall of shame include: // - github.com/erda-project/erda-infra // // Do not remove or change the type signature. // See go.dev/issue/67401. // //go:linkname badRoundTrip net/http.(*Transport).RoundTrip func badRoundTrip(*Transport, *Request) (*Response, error) // RoundTrip implements the [RoundTripper] interface. // // For higher-level HTTP client support (such as handling of cookies // and redirects), see [Get], [Post], and the [Client] type. // // Like the RoundTripper interface, the error types returned // by RoundTrip are unspecified. func (t *Transport) RoundTrip(req *Request) (*Response, error) { return t.roundTrip(req) }
go/src/net/http/roundtrip.go/0
{ "file_path": "go/src/net/http/roundtrip.go", "repo_id": "go", "token_count": 296 }
344
body {}
go/src/net/http/testdata/style.css/0
{ "file_path": "go/src/net/http/testdata/style.css", "repo_id": "go", "token_count": 3 }
345
// Copyright 2015 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. //go:build unix || (js && wasm) || wasip1 package socktest // Sockets maps a socket descriptor to the status of socket. type Sockets map[int]Status func (sw *Switch) sockso(s int) *Status { sw.smu.RLock() defer sw.smu.RUnlock() so, ok := sw.sotab[s] if !ok { return nil } return &so } // addLocked returns a new Status without locking. // sw.smu must be held before call. func (sw *Switch) addLocked(s, family, sotype, proto int) *Status { sw.once.Do(sw.init) so := Status{Cookie: cookie(family, sotype, proto)} sw.sotab[s] = so return &so }
go/src/net/internal/socktest/switch_unix.go/0
{ "file_path": "go/src/net/internal/socktest/switch_unix.go", "repo_id": "go", "token_count": 261 }
346
// Copyright 2011 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. //go:build !plan9 package net import ( "fmt" "internal/testenv" "os" "runtime" "syscall" "testing" "time" ) func (ln *TCPListener) port() string { _, port, err := SplitHostPort(ln.Addr().String()) if err != nil { return "" } return port } func (c *UDPConn) port() string { _, port, err := SplitHostPort(c.LocalAddr().String()) if err != nil { return "" } return port } var tcpListenerTests = []struct { network string address string }{ {"tcp", ""}, {"tcp", "0.0.0.0"}, {"tcp", "::ffff:0.0.0.0"}, {"tcp", "::"}, {"tcp", "127.0.0.1"}, {"tcp", "::ffff:127.0.0.1"}, {"tcp", "::1"}, {"tcp4", ""}, {"tcp4", "0.0.0.0"}, {"tcp4", "::ffff:0.0.0.0"}, {"tcp4", "127.0.0.1"}, {"tcp4", "::ffff:127.0.0.1"}, {"tcp6", ""}, {"tcp6", "::"}, {"tcp6", "::1"}, } // TestTCPListener tests both single and double listen to a test // listener with same address family, same listening address and // same port. func TestTCPListener(t *testing.T) { switch runtime.GOOS { case "plan9": t.Skipf("not supported on %s", runtime.GOOS) } for _, tt := range tcpListenerTests { if !testableListenArgs(tt.network, JoinHostPort(tt.address, "0"), "") { t.Logf("skipping %s test", tt.network+" "+tt.address) continue } ln1, err := Listen(tt.network, JoinHostPort(tt.address, "0")) if err != nil { t.Fatal(err) } if err := checkFirstListener(tt.network, ln1); err != nil { ln1.Close() t.Fatal(err) } ln2, err := Listen(tt.network, JoinHostPort(tt.address, ln1.(*TCPListener).port())) if err == nil { ln2.Close() } if err := checkSecondListener(tt.network, tt.address, err); err != nil { ln1.Close() t.Fatal(err) } ln1.Close() } } var udpListenerTests = []struct { network string address string }{ {"udp", ""}, {"udp", "0.0.0.0"}, {"udp", "::ffff:0.0.0.0"}, {"udp", "::"}, {"udp", "127.0.0.1"}, {"udp", "::ffff:127.0.0.1"}, {"udp", "::1"}, {"udp4", ""}, {"udp4", "0.0.0.0"}, {"udp4", "::ffff:0.0.0.0"}, {"udp4", "127.0.0.1"}, {"udp4", "::ffff:127.0.0.1"}, {"udp6", ""}, {"udp6", "::"}, {"udp6", "::1"}, } // TestUDPListener tests both single and double listen to a test // listener with same address family, same listening address and // same port. func TestUDPListener(t *testing.T) { switch runtime.GOOS { case "plan9": t.Skipf("not supported on %s", runtime.GOOS) } for _, tt := range udpListenerTests { if !testableListenArgs(tt.network, JoinHostPort(tt.address, "0"), "") { t.Logf("skipping %s test", tt.network+" "+tt.address) continue } c1, err := ListenPacket(tt.network, JoinHostPort(tt.address, "0")) if err != nil { t.Fatal(err) } if err := checkFirstListener(tt.network, c1); err != nil { c1.Close() t.Fatal(err) } c2, err := ListenPacket(tt.network, JoinHostPort(tt.address, c1.(*UDPConn).port())) if err == nil { c2.Close() } if err := checkSecondListener(tt.network, tt.address, err); err != nil { c1.Close() t.Fatal(err) } c1.Close() } } var dualStackTCPListenerTests = []struct { network1, address1 string // first listener network2, address2 string // second listener xerr error // expected error value, nil or other }{ // Test cases and expected results for the attempting 2nd listen on the same port // 1st listen 2nd listen darwin freebsd linux openbsd // ------------------------------------------------------------------------------------ // "tcp" "" "tcp" "" - - - - // "tcp" "" "tcp" "0.0.0.0" - - - - // "tcp" "0.0.0.0" "tcp" "" - - - - // ------------------------------------------------------------------------------------ // "tcp" "" "tcp" "[::]" - - - ok // "tcp" "[::]" "tcp" "" - - - ok // "tcp" "0.0.0.0" "tcp" "[::]" - - - ok // "tcp" "[::]" "tcp" "0.0.0.0" - - - ok // "tcp" "[::ffff:0.0.0.0]" "tcp" "[::]" - - - ok // "tcp" "[::]" "tcp" "[::ffff:0.0.0.0]" - - - ok // ------------------------------------------------------------------------------------ // "tcp4" "" "tcp6" "" ok ok ok ok // "tcp6" "" "tcp4" "" ok ok ok ok // "tcp4" "0.0.0.0" "tcp6" "[::]" ok ok ok ok // "tcp6" "[::]" "tcp4" "0.0.0.0" ok ok ok ok // ------------------------------------------------------------------------------------ // "tcp" "127.0.0.1" "tcp" "[::1]" ok ok ok ok // "tcp" "[::1]" "tcp" "127.0.0.1" ok ok ok ok // "tcp4" "127.0.0.1" "tcp6" "[::1]" ok ok ok ok // "tcp6" "[::1]" "tcp4" "127.0.0.1" ok ok ok ok // // Platform default configurations: // darwin, kernel version 11.3.0 // net.inet6.ip6.v6only=0 (overridable by sysctl or IPV6_V6ONLY option) // freebsd, kernel version 8.2 // net.inet6.ip6.v6only=1 (overridable by sysctl or IPV6_V6ONLY option) // linux, kernel version 3.0.0 // net.ipv6.bindv6only=0 (overridable by sysctl or IPV6_V6ONLY option) // openbsd, kernel version 5.0 // net.inet6.ip6.v6only=1 (overriding is prohibited) {"tcp", "", "tcp", "", syscall.EADDRINUSE}, {"tcp", "", "tcp", "0.0.0.0", syscall.EADDRINUSE}, {"tcp", "0.0.0.0", "tcp", "", syscall.EADDRINUSE}, {"tcp", "", "tcp", "::", syscall.EADDRINUSE}, {"tcp", "::", "tcp", "", syscall.EADDRINUSE}, {"tcp", "0.0.0.0", "tcp", "::", syscall.EADDRINUSE}, {"tcp", "::", "tcp", "0.0.0.0", syscall.EADDRINUSE}, {"tcp", "::ffff:0.0.0.0", "tcp", "::", syscall.EADDRINUSE}, {"tcp", "::", "tcp", "::ffff:0.0.0.0", syscall.EADDRINUSE}, {"tcp4", "", "tcp6", "", nil}, {"tcp6", "", "tcp4", "", nil}, {"tcp4", "0.0.0.0", "tcp6", "::", nil}, {"tcp6", "::", "tcp4", "0.0.0.0", nil}, {"tcp", "127.0.0.1", "tcp", "::1", nil}, {"tcp", "::1", "tcp", "127.0.0.1", nil}, {"tcp4", "127.0.0.1", "tcp6", "::1", nil}, {"tcp6", "::1", "tcp4", "127.0.0.1", nil}, } // TestDualStackTCPListener tests both single and double listen // to a test listener with various address families, different // listening address and same port. // // On DragonFly BSD, we expect the kernel version of node under test // to be greater than or equal to 4.4. func TestDualStackTCPListener(t *testing.T) { switch runtime.GOOS { case "plan9": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv4() || !supportsIPv6() { t.Skip("both IPv4 and IPv6 are required") } for _, tt := range dualStackTCPListenerTests { if !testableListenArgs(tt.network1, JoinHostPort(tt.address1, "0"), "") { t.Logf("skipping %s test", tt.network1+" "+tt.address1) continue } if !supportsIPv4map() && differentWildcardAddr(tt.address1, tt.address2) { tt.xerr = nil } var firstErr, secondErr error for i := 0; i < 5; i++ { lns, err := newDualStackListener() if err != nil { t.Fatal(err) } port := lns[0].port() for _, ln := range lns { ln.Close() } var ln1 Listener ln1, firstErr = Listen(tt.network1, JoinHostPort(tt.address1, port)) if firstErr != nil { continue } if err := checkFirstListener(tt.network1, ln1); err != nil { ln1.Close() t.Fatal(err) } ln2, err := Listen(tt.network2, JoinHostPort(tt.address2, ln1.(*TCPListener).port())) if err == nil { ln2.Close() } if secondErr = checkDualStackSecondListener(tt.network2, tt.address2, err, tt.xerr); secondErr != nil { ln1.Close() continue } ln1.Close() break } if firstErr != nil { t.Error(firstErr) } if secondErr != nil { t.Error(secondErr) } } } var dualStackUDPListenerTests = []struct { network1, address1 string // first listener network2, address2 string // second listener xerr error // expected error value, nil or other }{ {"udp", "", "udp", "", syscall.EADDRINUSE}, {"udp", "", "udp", "0.0.0.0", syscall.EADDRINUSE}, {"udp", "0.0.0.0", "udp", "", syscall.EADDRINUSE}, {"udp", "", "udp", "::", syscall.EADDRINUSE}, {"udp", "::", "udp", "", syscall.EADDRINUSE}, {"udp", "0.0.0.0", "udp", "::", syscall.EADDRINUSE}, {"udp", "::", "udp", "0.0.0.0", syscall.EADDRINUSE}, {"udp", "::ffff:0.0.0.0", "udp", "::", syscall.EADDRINUSE}, {"udp", "::", "udp", "::ffff:0.0.0.0", syscall.EADDRINUSE}, {"udp4", "", "udp6", "", nil}, {"udp6", "", "udp4", "", nil}, {"udp4", "0.0.0.0", "udp6", "::", nil}, {"udp6", "::", "udp4", "0.0.0.0", nil}, {"udp", "127.0.0.1", "udp", "::1", nil}, {"udp", "::1", "udp", "127.0.0.1", nil}, {"udp4", "127.0.0.1", "udp6", "::1", nil}, {"udp6", "::1", "udp4", "127.0.0.1", nil}, } // TestDualStackUDPListener tests both single and double listen // to a test listener with various address families, different // listening address and same port. // // On DragonFly BSD, we expect the kernel version of node under test // to be greater than or equal to 4.4. func TestDualStackUDPListener(t *testing.T) { switch runtime.GOOS { case "plan9": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv4() || !supportsIPv6() { t.Skip("both IPv4 and IPv6 are required") } for _, tt := range dualStackUDPListenerTests { if !testableListenArgs(tt.network1, JoinHostPort(tt.address1, "0"), "") { t.Logf("skipping %s test", tt.network1+" "+tt.address1) continue } if !supportsIPv4map() && differentWildcardAddr(tt.address1, tt.address2) { tt.xerr = nil } var firstErr, secondErr error for i := 0; i < 5; i++ { cs, err := newDualStackPacketListener() if err != nil { t.Fatal(err) } port := cs[0].port() for _, c := range cs { c.Close() } var c1 PacketConn c1, firstErr = ListenPacket(tt.network1, JoinHostPort(tt.address1, port)) if firstErr != nil { continue } if err := checkFirstListener(tt.network1, c1); err != nil { c1.Close() t.Fatal(err) } c2, err := ListenPacket(tt.network2, JoinHostPort(tt.address2, c1.(*UDPConn).port())) if err == nil { c2.Close() } if secondErr = checkDualStackSecondListener(tt.network2, tt.address2, err, tt.xerr); secondErr != nil { c1.Close() continue } c1.Close() break } if firstErr != nil { t.Error(firstErr) } if secondErr != nil { t.Error(secondErr) } } } func differentWildcardAddr(i, j string) bool { if (i == "" || i == "0.0.0.0" || i == "::ffff:0.0.0.0") && (j == "" || j == "0.0.0.0" || j == "::ffff:0.0.0.0") { return false } if i == "[::]" && j == "[::]" { return false } return true } func checkFirstListener(network string, ln any) error { switch network { case "tcp": fd := ln.(*TCPListener).fd if err := checkDualStackAddrFamily(fd); err != nil { return err } case "tcp4": fd := ln.(*TCPListener).fd if fd.family != syscall.AF_INET { return fmt.Errorf("%v got %v; want %v", fd.laddr, fd.family, syscall.AF_INET) } case "tcp6": fd := ln.(*TCPListener).fd if fd.family != syscall.AF_INET6 { return fmt.Errorf("%v got %v; want %v", fd.laddr, fd.family, syscall.AF_INET6) } case "udp": fd := ln.(*UDPConn).fd if err := checkDualStackAddrFamily(fd); err != nil { return err } case "udp4": fd := ln.(*UDPConn).fd if fd.family != syscall.AF_INET { return fmt.Errorf("%v got %v; want %v", fd.laddr, fd.family, syscall.AF_INET) } case "udp6": fd := ln.(*UDPConn).fd if fd.family != syscall.AF_INET6 { return fmt.Errorf("%v got %v; want %v", fd.laddr, fd.family, syscall.AF_INET6) } default: return UnknownNetworkError(network) } return nil } func checkSecondListener(network, address string, err error) error { switch network { case "tcp", "tcp4", "tcp6": if err == nil { return fmt.Errorf("%s should fail", network+" "+address) } case "udp", "udp4", "udp6": if err == nil { return fmt.Errorf("%s should fail", network+" "+address) } default: return UnknownNetworkError(network) } return nil } func checkDualStackSecondListener(network, address string, err, xerr error) error { switch network { case "tcp", "tcp4", "tcp6": if xerr == nil && err != nil || xerr != nil && err == nil { return fmt.Errorf("%s got %v; want %v", network+" "+address, err, xerr) } case "udp", "udp4", "udp6": if xerr == nil && err != nil || xerr != nil && err == nil { return fmt.Errorf("%s got %v; want %v", network+" "+address, err, xerr) } default: return UnknownNetworkError(network) } return nil } func checkDualStackAddrFamily(fd *netFD) error { switch a := fd.laddr.(type) { case *TCPAddr: // If a node under test supports both IPv6 capability // and IPv6 IPv4-mapping capability, we can assume // that the node listens on a wildcard address with an // AF_INET6 socket. if supportsIPv4map() && fd.laddr.(*TCPAddr).isWildcard() { if fd.family != syscall.AF_INET6 { return fmt.Errorf("Listen(%s, %v) returns %v; want %v", fd.net, fd.laddr, fd.family, syscall.AF_INET6) } } else { if fd.family != a.family() { return fmt.Errorf("Listen(%s, %v) returns %v; want %v", fd.net, fd.laddr, fd.family, a.family()) } } case *UDPAddr: // If a node under test supports both IPv6 capability // and IPv6 IPv4-mapping capability, we can assume // that the node listens on a wildcard address with an // AF_INET6 socket. if supportsIPv4map() && fd.laddr.(*UDPAddr).isWildcard() { if fd.family != syscall.AF_INET6 { return fmt.Errorf("ListenPacket(%s, %v) returns %v; want %v", fd.net, fd.laddr, fd.family, syscall.AF_INET6) } } else { if fd.family != a.family() { return fmt.Errorf("ListenPacket(%s, %v) returns %v; want %v", fd.net, fd.laddr, fd.family, a.family()) } } default: return fmt.Errorf("unexpected protocol address type: %T", a) } return nil } func TestWildWildcardListener(t *testing.T) { testenv.MustHaveExternalNetwork(t) switch runtime.GOOS { case "plan9": t.Skipf("not supported on %s", runtime.GOOS) } defer func() { if p := recover(); p != nil { t.Fatalf("panicked: %v", p) } }() if ln, err := Listen("tcp", ""); err == nil { ln.Close() } if ln, err := ListenPacket("udp", ""); err == nil { ln.Close() } if ln, err := ListenTCP("tcp", nil); err == nil { ln.Close() } if ln, err := ListenUDP("udp", nil); err == nil { ln.Close() } if ln, err := ListenIP("ip:icmp", nil); err == nil { ln.Close() } } var ipv4MulticastListenerTests = []struct { net string gaddr *UDPAddr // see RFC 4727 }{ {"udp", &UDPAddr{IP: IPv4(224, 0, 0, 254), Port: 12345}}, {"udp4", &UDPAddr{IP: IPv4(224, 0, 0, 254), Port: 12345}}, } // TestIPv4MulticastListener tests both single and double listen to a // test listener with same address family, same group address and same // port. func TestIPv4MulticastListener(t *testing.T) { testenv.MustHaveExternalNetwork(t) switch runtime.GOOS { case "android", "plan9": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv4() { t.Skip("IPv4 is not supported") } closer := func(cs []*UDPConn) { for _, c := range cs { if c != nil { c.Close() } } } for _, ifi := range []*Interface{loopbackInterface(), nil} { // Note that multicast interface assignment by system // is not recommended because it usually relies on // routing stuff for finding out an appropriate // nexthop containing both network and link layer // adjacencies. if ifi == nil || !*testIPv4 { continue } for _, tt := range ipv4MulticastListenerTests { var err error cs := make([]*UDPConn, 2) if cs[0], err = ListenMulticastUDP(tt.net, ifi, tt.gaddr); err != nil { t.Fatal(err) } if err := checkMulticastListener(cs[0], tt.gaddr.IP); err != nil { closer(cs) t.Fatal(err) } if cs[1], err = ListenMulticastUDP(tt.net, ifi, tt.gaddr); err != nil { closer(cs) t.Fatal(err) } if err := checkMulticastListener(cs[1], tt.gaddr.IP); err != nil { closer(cs) t.Fatal(err) } closer(cs) } } } var ipv6MulticastListenerTests = []struct { net string gaddr *UDPAddr // see RFC 4727 }{ {"udp", &UDPAddr{IP: ParseIP("ff01::114"), Port: 12345}}, {"udp", &UDPAddr{IP: ParseIP("ff02::114"), Port: 12345}}, {"udp", &UDPAddr{IP: ParseIP("ff04::114"), Port: 12345}}, {"udp", &UDPAddr{IP: ParseIP("ff05::114"), Port: 12345}}, {"udp", &UDPAddr{IP: ParseIP("ff08::114"), Port: 12345}}, {"udp", &UDPAddr{IP: ParseIP("ff0e::114"), Port: 12345}}, {"udp6", &UDPAddr{IP: ParseIP("ff01::114"), Port: 12345}}, {"udp6", &UDPAddr{IP: ParseIP("ff02::114"), Port: 12345}}, {"udp6", &UDPAddr{IP: ParseIP("ff04::114"), Port: 12345}}, {"udp6", &UDPAddr{IP: ParseIP("ff05::114"), Port: 12345}}, {"udp6", &UDPAddr{IP: ParseIP("ff08::114"), Port: 12345}}, {"udp6", &UDPAddr{IP: ParseIP("ff0e::114"), Port: 12345}}, } // TestIPv6MulticastListener tests both single and double listen to a // test listener with same address family, same group address and same // port. func TestIPv6MulticastListener(t *testing.T) { testenv.MustHaveExternalNetwork(t) switch runtime.GOOS { case "plan9": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6() { t.Skip("IPv6 is not supported") } if os.Getuid() != 0 { t.Skip("must be root") } closer := func(cs []*UDPConn) { for _, c := range cs { if c != nil { c.Close() } } } for _, ifi := range []*Interface{loopbackInterface(), nil} { // Note that multicast interface assignment by system // is not recommended because it usually relies on // routing stuff for finding out an appropriate // nexthop containing both network and link layer // adjacencies. if ifi == nil && !*testIPv6 { continue } for _, tt := range ipv6MulticastListenerTests { var err error cs := make([]*UDPConn, 2) if cs[0], err = ListenMulticastUDP(tt.net, ifi, tt.gaddr); err != nil { t.Fatal(err) } if err := checkMulticastListener(cs[0], tt.gaddr.IP); err != nil { closer(cs) t.Fatal(err) } if cs[1], err = ListenMulticastUDP(tt.net, ifi, tt.gaddr); err != nil { closer(cs) t.Fatal(err) } if err := checkMulticastListener(cs[1], tt.gaddr.IP); err != nil { closer(cs) t.Fatal(err) } closer(cs) } } } func checkMulticastListener(c *UDPConn, ip IP) error { if ok, err := multicastRIBContains(ip); err != nil { return err } else if !ok { return fmt.Errorf("%s not found in multicast rib", ip.String()) } la := c.LocalAddr() if la, ok := la.(*UDPAddr); !ok || la.Port == 0 { return fmt.Errorf("got %v; want a proper address with non-zero port number", la) } return nil } func multicastRIBContains(ip IP) (bool, error) { switch runtime.GOOS { case "aix", "dragonfly", "netbsd", "openbsd", "plan9", "solaris", "illumos", "windows": return true, nil // not implemented yet case "linux": if runtime.GOARCH == "arm" || runtime.GOARCH == "alpha" { return true, nil // not implemented yet } } ift, err := Interfaces() if err != nil { return false, err } for _, ifi := range ift { ifmat, err := ifi.MulticastAddrs() if err != nil { return false, err } for _, ifma := range ifmat { if ifma.(*IPAddr).IP.Equal(ip) { return true, nil } } } return false, nil } // Issue 21856. func TestClosingListener(t *testing.T) { ln := newLocalListener(t, "tcp") addr := ln.Addr() go func() { for { c, err := ln.Accept() if err != nil { return } c.Close() } }() // Let the goroutine start. We don't sleep long: if the // goroutine doesn't start, the test will pass without really // testing anything, which is OK. time.Sleep(time.Millisecond) ln.Close() ln2, err := Listen("tcp", addr.String()) if err != nil { t.Fatal(err) } ln2.Close() } func TestListenConfigControl(t *testing.T) { switch runtime.GOOS { case "plan9": t.Skipf("not supported on %s", runtime.GOOS) } t.Run("StreamListen", func(t *testing.T) { for _, network := range []string{"tcp", "tcp4", "tcp6", "unix", "unixpacket"} { if !testableNetwork(network) { continue } ln := newLocalListener(t, network, &ListenConfig{Control: controlOnConnSetup}) ln.Close() } }) t.Run("PacketListen", func(t *testing.T) { for _, network := range []string{"udp", "udp4", "udp6", "unixgram"} { if !testableNetwork(network) { continue } c := newLocalPacketListener(t, network, &ListenConfig{Control: controlOnConnSetup}) c.Close() } }) }
go/src/net/listen_test.go/0
{ "file_path": "go/src/net/listen_test.go", "repo_id": "go", "token_count": 9715 }
347
// Copyright 2015 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. package net import ( "flag" "fmt" "net/internal/socktest" "os" "runtime" "slices" "strings" "sync" "testing" "time" ) var ( sw socktest.Switch // uninstallTestHooks runs just before a run of benchmarks. testHookUninstaller sync.Once ) var ( testTCPBig = flag.Bool("tcpbig", false, "whether to test massive size of data per read or write call on TCP connection") testDNSFlood = flag.Bool("dnsflood", false, "whether to test DNS query flooding") // If external IPv4 connectivity exists, we can try dialing // non-node/interface local scope IPv4 addresses. // On Windows, Lookup APIs may not return IPv4-related // resource records when a node has no external IPv4 // connectivity. testIPv4 = flag.Bool("ipv4", true, "assume external IPv4 connectivity exists") // If external IPv6 connectivity exists, we can try dialing // non-node/interface local scope IPv6 addresses. // On Windows, Lookup APIs may not return IPv6-related // resource records when a node has no external IPv6 // connectivity. testIPv6 = flag.Bool("ipv6", false, "assume external IPv6 connectivity exists") ) func TestMain(m *testing.M) { setupTestData() installTestHooks() st := m.Run() testHookUninstaller.Do(uninstallTestHooks) if testing.Verbose() { printRunningGoroutines() printInflightSockets() printSocketStats() } forceCloseSockets() os.Exit(st) } // mustSetDeadline calls the bound method m to set a deadline on a Conn. // If the call fails, mustSetDeadline skips t if the current GOOS is believed // not to support deadlines, or fails the test otherwise. func mustSetDeadline(t testing.TB, m func(time.Time) error, d time.Duration) { err := m(time.Now().Add(d)) if err != nil { t.Helper() if runtime.GOOS == "plan9" { t.Skipf("skipping: %s does not support deadlines", runtime.GOOS) } t.Fatal(err) } } type ipv6LinkLocalUnicastTest struct { network, address string nameLookup bool } var ( ipv6LinkLocalUnicastTCPTests []ipv6LinkLocalUnicastTest ipv6LinkLocalUnicastUDPTests []ipv6LinkLocalUnicastTest ) func setupTestData() { if supportsIPv4() { resolveTCPAddrTests = append(resolveTCPAddrTests, []resolveTCPAddrTest{ {"tcp", "localhost:1", &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 1}, nil}, {"tcp4", "localhost:2", &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 2}, nil}, }...) resolveUDPAddrTests = append(resolveUDPAddrTests, []resolveUDPAddrTest{ {"udp", "localhost:1", &UDPAddr{IP: IPv4(127, 0, 0, 1), Port: 1}, nil}, {"udp4", "localhost:2", &UDPAddr{IP: IPv4(127, 0, 0, 1), Port: 2}, nil}, }...) resolveIPAddrTests = append(resolveIPAddrTests, []resolveIPAddrTest{ {"ip", "localhost", &IPAddr{IP: IPv4(127, 0, 0, 1)}, nil}, {"ip4", "localhost", &IPAddr{IP: IPv4(127, 0, 0, 1)}, nil}, }...) } if supportsIPv6() { resolveTCPAddrTests = append(resolveTCPAddrTests, resolveTCPAddrTest{"tcp6", "localhost:3", &TCPAddr{IP: IPv6loopback, Port: 3}, nil}) resolveUDPAddrTests = append(resolveUDPAddrTests, resolveUDPAddrTest{"udp6", "localhost:3", &UDPAddr{IP: IPv6loopback, Port: 3}, nil}) resolveIPAddrTests = append(resolveIPAddrTests, resolveIPAddrTest{"ip6", "localhost", &IPAddr{IP: IPv6loopback}, nil}) // Issue 20911: don't return IPv4 addresses for // Resolve*Addr calls of the IPv6 unspecified address. resolveTCPAddrTests = append(resolveTCPAddrTests, resolveTCPAddrTest{"tcp", "[::]:4", &TCPAddr{IP: IPv6unspecified, Port: 4}, nil}) resolveUDPAddrTests = append(resolveUDPAddrTests, resolveUDPAddrTest{"udp", "[::]:4", &UDPAddr{IP: IPv6unspecified, Port: 4}, nil}) resolveIPAddrTests = append(resolveIPAddrTests, resolveIPAddrTest{"ip", "::", &IPAddr{IP: IPv6unspecified}, nil}) } ifi := loopbackInterface() if ifi != nil { index := fmt.Sprintf("%v", ifi.Index) resolveTCPAddrTests = append(resolveTCPAddrTests, []resolveTCPAddrTest{ {"tcp6", "[fe80::1%" + ifi.Name + "]:1", &TCPAddr{IP: ParseIP("fe80::1"), Port: 1, Zone: zoneCache.name(ifi.Index)}, nil}, {"tcp6", "[fe80::1%" + index + "]:2", &TCPAddr{IP: ParseIP("fe80::1"), Port: 2, Zone: index}, nil}, }...) resolveUDPAddrTests = append(resolveUDPAddrTests, []resolveUDPAddrTest{ {"udp6", "[fe80::1%" + ifi.Name + "]:1", &UDPAddr{IP: ParseIP("fe80::1"), Port: 1, Zone: zoneCache.name(ifi.Index)}, nil}, {"udp6", "[fe80::1%" + index + "]:2", &UDPAddr{IP: ParseIP("fe80::1"), Port: 2, Zone: index}, nil}, }...) resolveIPAddrTests = append(resolveIPAddrTests, []resolveIPAddrTest{ {"ip6", "fe80::1%" + ifi.Name, &IPAddr{IP: ParseIP("fe80::1"), Zone: zoneCache.name(ifi.Index)}, nil}, {"ip6", "fe80::1%" + index, &IPAddr{IP: ParseIP("fe80::1"), Zone: index}, nil}, }...) } addr := ipv6LinkLocalUnicastAddr(ifi) if addr != "" { if runtime.GOOS != "dragonfly" { ipv6LinkLocalUnicastTCPTests = append(ipv6LinkLocalUnicastTCPTests, []ipv6LinkLocalUnicastTest{ {"tcp", "[" + addr + "%" + ifi.Name + "]:0", false}, }...) ipv6LinkLocalUnicastUDPTests = append(ipv6LinkLocalUnicastUDPTests, []ipv6LinkLocalUnicastTest{ {"udp", "[" + addr + "%" + ifi.Name + "]:0", false}, }...) } ipv6LinkLocalUnicastTCPTests = append(ipv6LinkLocalUnicastTCPTests, []ipv6LinkLocalUnicastTest{ {"tcp6", "[" + addr + "%" + ifi.Name + "]:0", false}, }...) ipv6LinkLocalUnicastUDPTests = append(ipv6LinkLocalUnicastUDPTests, []ipv6LinkLocalUnicastTest{ {"udp6", "[" + addr + "%" + ifi.Name + "]:0", false}, }...) switch runtime.GOOS { case "darwin", "ios", "dragonfly", "freebsd", "openbsd", "netbsd": ipv6LinkLocalUnicastTCPTests = append(ipv6LinkLocalUnicastTCPTests, []ipv6LinkLocalUnicastTest{ {"tcp", "[localhost%" + ifi.Name + "]:0", true}, {"tcp6", "[localhost%" + ifi.Name + "]:0", true}, }...) ipv6LinkLocalUnicastUDPTests = append(ipv6LinkLocalUnicastUDPTests, []ipv6LinkLocalUnicastTest{ {"udp", "[localhost%" + ifi.Name + "]:0", true}, {"udp6", "[localhost%" + ifi.Name + "]:0", true}, }...) case "linux": ipv6LinkLocalUnicastTCPTests = append(ipv6LinkLocalUnicastTCPTests, []ipv6LinkLocalUnicastTest{ {"tcp", "[ip6-localhost%" + ifi.Name + "]:0", true}, {"tcp6", "[ip6-localhost%" + ifi.Name + "]:0", true}, }...) ipv6LinkLocalUnicastUDPTests = append(ipv6LinkLocalUnicastUDPTests, []ipv6LinkLocalUnicastTest{ {"udp", "[ip6-localhost%" + ifi.Name + "]:0", true}, {"udp6", "[ip6-localhost%" + ifi.Name + "]:0", true}, }...) } } } func printRunningGoroutines() { gss := runningGoroutines() if len(gss) == 0 { return } fmt.Fprintf(os.Stderr, "Running goroutines:\n") for _, gs := range gss { fmt.Fprintf(os.Stderr, "%v\n", gs) } fmt.Fprintf(os.Stderr, "\n") } // runningGoroutines returns a list of remaining goroutines. func runningGoroutines() []string { var gss []string b := make([]byte, 2<<20) b = b[:runtime.Stack(b, true)] for _, s := range strings.Split(string(b), "\n\n") { _, stack, _ := strings.Cut(s, "\n") stack = strings.TrimSpace(stack) if !strings.Contains(stack, "created by net") { continue } gss = append(gss, stack) } slices.Sort(gss) return gss } func printInflightSockets() { sos := sw.Sockets() if len(sos) == 0 { return } fmt.Fprintf(os.Stderr, "Inflight sockets:\n") for s, so := range sos { fmt.Fprintf(os.Stderr, "%v: %v\n", s, so) } fmt.Fprintf(os.Stderr, "\n") } func printSocketStats() { sts := sw.Stats() if len(sts) == 0 { return } fmt.Fprintf(os.Stderr, "Socket statistical information:\n") for _, st := range sts { fmt.Fprintf(os.Stderr, "%v\n", st) } fmt.Fprintf(os.Stderr, "\n") }
go/src/net/main_test.go/0
{ "file_path": "go/src/net/main_test.go", "repo_id": "go", "token_count": 3241 }
348
// Copyright 2010 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. package net import ( "io" "os" "sync" "time" ) // pipeDeadline is an abstraction for handling timeouts. type pipeDeadline struct { mu sync.Mutex // Guards timer and cancel timer *time.Timer cancel chan struct{} // Must be non-nil } func makePipeDeadline() pipeDeadline { return pipeDeadline{cancel: make(chan struct{})} } // set sets the point in time when the deadline will time out. // A timeout event is signaled by closing the channel returned by waiter. // Once a timeout has occurred, the deadline can be refreshed by specifying a // t value in the future. // // A zero value for t prevents timeout. func (d *pipeDeadline) set(t time.Time) { d.mu.Lock() defer d.mu.Unlock() if d.timer != nil && !d.timer.Stop() { <-d.cancel // Wait for the timer callback to finish and close cancel } d.timer = nil // Time is zero, then there is no deadline. closed := isClosedChan(d.cancel) if t.IsZero() { if closed { d.cancel = make(chan struct{}) } return } // Time in the future, setup a timer to cancel in the future. if dur := time.Until(t); dur > 0 { if closed { d.cancel = make(chan struct{}) } d.timer = time.AfterFunc(dur, func() { close(d.cancel) }) return } // Time in the past, so close immediately. if !closed { close(d.cancel) } } // wait returns a channel that is closed when the deadline is exceeded. func (d *pipeDeadline) wait() chan struct{} { d.mu.Lock() defer d.mu.Unlock() return d.cancel } func isClosedChan(c <-chan struct{}) bool { select { case <-c: return true default: return false } } type pipeAddr struct{} func (pipeAddr) Network() string { return "pipe" } func (pipeAddr) String() string { return "pipe" } type pipe struct { wrMu sync.Mutex // Serialize Write operations // Used by local Read to interact with remote Write. // Successful receive on rdRx is always followed by send on rdTx. rdRx <-chan []byte rdTx chan<- int // Used by local Write to interact with remote Read. // Successful send on wrTx is always followed by receive on wrRx. wrTx chan<- []byte wrRx <-chan int once sync.Once // Protects closing localDone localDone chan struct{} remoteDone <-chan struct{} readDeadline pipeDeadline writeDeadline pipeDeadline } // Pipe creates a synchronous, in-memory, full duplex // network connection; both ends implement the [Conn] interface. // Reads on one end are matched with writes on the other, // copying data directly between the two; there is no internal // buffering. func Pipe() (Conn, Conn) { cb1 := make(chan []byte) cb2 := make(chan []byte) cn1 := make(chan int) cn2 := make(chan int) done1 := make(chan struct{}) done2 := make(chan struct{}) p1 := &pipe{ rdRx: cb1, rdTx: cn1, wrTx: cb2, wrRx: cn2, localDone: done1, remoteDone: done2, readDeadline: makePipeDeadline(), writeDeadline: makePipeDeadline(), } p2 := &pipe{ rdRx: cb2, rdTx: cn2, wrTx: cb1, wrRx: cn1, localDone: done2, remoteDone: done1, readDeadline: makePipeDeadline(), writeDeadline: makePipeDeadline(), } return p1, p2 } func (*pipe) LocalAddr() Addr { return pipeAddr{} } func (*pipe) RemoteAddr() Addr { return pipeAddr{} } func (p *pipe) Read(b []byte) (int, error) { n, err := p.read(b) if err != nil && err != io.EOF && err != io.ErrClosedPipe { err = &OpError{Op: "read", Net: "pipe", Err: err} } return n, err } func (p *pipe) read(b []byte) (n int, err error) { switch { case isClosedChan(p.localDone): return 0, io.ErrClosedPipe case isClosedChan(p.remoteDone): return 0, io.EOF case isClosedChan(p.readDeadline.wait()): return 0, os.ErrDeadlineExceeded } select { case bw := <-p.rdRx: nr := copy(b, bw) p.rdTx <- nr return nr, nil case <-p.localDone: return 0, io.ErrClosedPipe case <-p.remoteDone: return 0, io.EOF case <-p.readDeadline.wait(): return 0, os.ErrDeadlineExceeded } } func (p *pipe) Write(b []byte) (int, error) { n, err := p.write(b) if err != nil && err != io.ErrClosedPipe { err = &OpError{Op: "write", Net: "pipe", Err: err} } return n, err } func (p *pipe) write(b []byte) (n int, err error) { switch { case isClosedChan(p.localDone): return 0, io.ErrClosedPipe case isClosedChan(p.remoteDone): return 0, io.ErrClosedPipe case isClosedChan(p.writeDeadline.wait()): return 0, os.ErrDeadlineExceeded } p.wrMu.Lock() // Ensure entirety of b is written together defer p.wrMu.Unlock() for once := true; once || len(b) > 0; once = false { select { case p.wrTx <- b: nw := <-p.wrRx b = b[nw:] n += nw case <-p.localDone: return n, io.ErrClosedPipe case <-p.remoteDone: return n, io.ErrClosedPipe case <-p.writeDeadline.wait(): return n, os.ErrDeadlineExceeded } } return n, nil } func (p *pipe) SetDeadline(t time.Time) error { if isClosedChan(p.localDone) || isClosedChan(p.remoteDone) { return io.ErrClosedPipe } p.readDeadline.set(t) p.writeDeadline.set(t) return nil } func (p *pipe) SetReadDeadline(t time.Time) error { if isClosedChan(p.localDone) || isClosedChan(p.remoteDone) { return io.ErrClosedPipe } p.readDeadline.set(t) return nil } func (p *pipe) SetWriteDeadline(t time.Time) error { if isClosedChan(p.localDone) || isClosedChan(p.remoteDone) { return io.ErrClosedPipe } p.writeDeadline.set(t) return nil } func (p *pipe) Close() error { p.once.Do(func() { close(p.localDone) }) return nil }
go/src/net/pipe.go/0
{ "file_path": "go/src/net/pipe.go", "repo_id": "go", "token_count": 2199 }
349
// Copyright 2014 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. package rpc import ( "errors" "fmt" "net" "strings" "testing" ) type shutdownCodec struct { responded chan int closed bool } func (c *shutdownCodec) WriteRequest(*Request, any) error { return nil } func (c *shutdownCodec) ReadResponseBody(any) error { return nil } func (c *shutdownCodec) ReadResponseHeader(*Response) error { c.responded <- 1 return errors.New("shutdownCodec ReadResponseHeader") } func (c *shutdownCodec) Close() error { c.closed = true return nil } func TestCloseCodec(t *testing.T) { codec := &shutdownCodec{responded: make(chan int)} client := NewClientWithCodec(codec) <-codec.responded client.Close() if !codec.closed { t.Error("client.Close did not close codec") } } // Test that errors in gob shut down the connection. Issue 7689. type R struct { msg []byte // Not exported, so R does not work with gob. } type S struct{} func (s *S) Recv(nul *struct{}, reply *R) error { *reply = R{[]byte("foo")} return nil } func TestGobError(t *testing.T) { defer func() { err := recover() if err == nil { t.Fatal("no error") } if !strings.Contains(err.(error).Error(), "reading body unexpected EOF") { t.Fatal("expected `reading body unexpected EOF', got", err) } }() Register(new(S)) listen, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { panic(err) } go Accept(listen) client, err := Dial("tcp", listen.Addr().String()) if err != nil { panic(err) } var reply Reply err = client.Call("S.Recv", &struct{}{}, &reply) if err != nil { panic(err) } fmt.Printf("%#v\n", reply) client.Close() listen.Close() }
go/src/net/rpc/client_test.go/0
{ "file_path": "go/src/net/rpc/client_test.go", "repo_id": "go", "token_count": 676 }
350
// Copyright 2010 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. package smtp import ( "bufio" "bytes" "crypto/tls" "crypto/x509" "fmt" "internal/testenv" "io" "net" "net/textproto" "runtime" "strings" "testing" "time" ) type authTest struct { auth Auth challenges []string name string responses []string } var authTests = []authTest{ {PlainAuth("", "user", "pass", "testserver"), []string{}, "PLAIN", []string{"\x00user\x00pass"}}, {PlainAuth("foo", "bar", "baz", "testserver"), []string{}, "PLAIN", []string{"foo\x00bar\x00baz"}}, {CRAMMD5Auth("user", "pass"), []string{"<123456.1322876914@testserver>"}, "CRAM-MD5", []string{"", "user 287eb355114cf5c471c26a875f1ca4ae"}}, } func TestAuth(t *testing.T) { testLoop: for i, test := range authTests { name, resp, err := test.auth.Start(&ServerInfo{"testserver", true, nil}) if name != test.name { t.Errorf("#%d got name %s, expected %s", i, name, test.name) } if !bytes.Equal(resp, []byte(test.responses[0])) { t.Errorf("#%d got response %s, expected %s", i, resp, test.responses[0]) } if err != nil { t.Errorf("#%d error: %s", i, err) } for j := range test.challenges { challenge := []byte(test.challenges[j]) expected := []byte(test.responses[j+1]) resp, err := test.auth.Next(challenge, true) if err != nil { t.Errorf("#%d error: %s", i, err) continue testLoop } if !bytes.Equal(resp, expected) { t.Errorf("#%d got %s, expected %s", i, resp, expected) continue testLoop } } } } func TestAuthPlain(t *testing.T) { tests := []struct { authName string server *ServerInfo err string }{ { authName: "servername", server: &ServerInfo{Name: "servername", TLS: true}, }, { // OK to use PlainAuth on localhost without TLS authName: "localhost", server: &ServerInfo{Name: "localhost", TLS: false}, }, { // NOT OK on non-localhost, even if server says PLAIN is OK. // (We don't know that the server is the real server.) authName: "servername", server: &ServerInfo{Name: "servername", Auth: []string{"PLAIN"}}, err: "unencrypted connection", }, { authName: "servername", server: &ServerInfo{Name: "servername", Auth: []string{"CRAM-MD5"}}, err: "unencrypted connection", }, { authName: "servername", server: &ServerInfo{Name: "attacker", TLS: true}, err: "wrong host name", }, } for i, tt := range tests { auth := PlainAuth("foo", "bar", "baz", tt.authName) _, _, err := auth.Start(tt.server) got := "" if err != nil { got = err.Error() } if got != tt.err { t.Errorf("%d. got error = %q; want %q", i, got, tt.err) } } } // Issue 17794: don't send a trailing space on AUTH command when there's no password. func TestClientAuthTrimSpace(t *testing.T) { server := "220 hello world\r\n" + "200 some more" var wrote strings.Builder var fake faker fake.ReadWriter = struct { io.Reader io.Writer }{ strings.NewReader(server), &wrote, } c, err := NewClient(fake, "fake.host") if err != nil { t.Fatalf("NewClient: %v", err) } c.tls = true c.didHello = true c.Auth(toServerEmptyAuth{}) c.Close() if got, want := wrote.String(), "AUTH FOOAUTH\r\n*\r\nQUIT\r\n"; got != want { t.Errorf("wrote %q; want %q", got, want) } } // toServerEmptyAuth is an implementation of Auth that only implements // the Start method, and returns "FOOAUTH", nil, nil. Notably, it returns // zero bytes for "toServer" so we can test that we don't send spaces at // the end of the line. See TestClientAuthTrimSpace. type toServerEmptyAuth struct{} func (toServerEmptyAuth) Start(server *ServerInfo) (proto string, toServer []byte, err error) { return "FOOAUTH", nil, nil } func (toServerEmptyAuth) Next(fromServer []byte, more bool) (toServer []byte, err error) { panic("unexpected call") } type faker struct { io.ReadWriter } func (f faker) Close() error { return nil } func (f faker) LocalAddr() net.Addr { return nil } func (f faker) RemoteAddr() net.Addr { return nil } func (f faker) SetDeadline(time.Time) error { return nil } func (f faker) SetReadDeadline(time.Time) error { return nil } func (f faker) SetWriteDeadline(time.Time) error { return nil } func TestBasic(t *testing.T) { server := strings.Join(strings.Split(basicServer, "\n"), "\r\n") client := strings.Join(strings.Split(basicClient, "\n"), "\r\n") var cmdbuf strings.Builder bcmdbuf := bufio.NewWriter(&cmdbuf) var fake faker fake.ReadWriter = bufio.NewReadWriter(bufio.NewReader(strings.NewReader(server)), bcmdbuf) c := &Client{Text: textproto.NewConn(fake), localName: "localhost"} if err := c.helo(); err != nil { t.Fatalf("HELO failed: %s", err) } if err := c.ehlo(); err == nil { t.Fatalf("Expected first EHLO to fail") } if err := c.ehlo(); err != nil { t.Fatalf("Second EHLO failed: %s", err) } c.didHello = true if ok, args := c.Extension("aUtH"); !ok || args != "LOGIN PLAIN" { t.Fatalf("Expected AUTH supported") } if ok, _ := c.Extension("DSN"); ok { t.Fatalf("Shouldn't support DSN") } if err := c.Mail("user@gmail.com"); err == nil { t.Fatalf("MAIL should require authentication") } if err := c.Verify("user1@gmail.com"); err == nil { t.Fatalf("First VRFY: expected no verification") } if err := c.Verify("user2@gmail.com>\r\nDATA\r\nAnother injected message body\r\n.\r\nQUIT\r\n"); err == nil { t.Fatalf("VRFY should have failed due to a message injection attempt") } if err := c.Verify("user2@gmail.com"); err != nil { t.Fatalf("Second VRFY: expected verification, got %s", err) } // fake TLS so authentication won't complain c.tls = true c.serverName = "smtp.google.com" if err := c.Auth(PlainAuth("", "user", "pass", "smtp.google.com")); err != nil { t.Fatalf("AUTH failed: %s", err) } if err := c.Rcpt("golang-nuts@googlegroups.com>\r\nDATA\r\nInjected message body\r\n.\r\nQUIT\r\n"); err == nil { t.Fatalf("RCPT should have failed due to a message injection attempt") } if err := c.Mail("user@gmail.com>\r\nDATA\r\nAnother injected message body\r\n.\r\nQUIT\r\n"); err == nil { t.Fatalf("MAIL should have failed due to a message injection attempt") } if err := c.Mail("user@gmail.com"); err != nil { t.Fatalf("MAIL failed: %s", err) } if err := c.Rcpt("golang-nuts@googlegroups.com"); err != nil { t.Fatalf("RCPT failed: %s", err) } msg := `From: user@gmail.com To: golang-nuts@googlegroups.com Subject: Hooray for Go Line 1 .Leading dot line . Goodbye.` w, err := c.Data() if err != nil { t.Fatalf("DATA failed: %s", err) } if _, err := w.Write([]byte(msg)); err != nil { t.Fatalf("Data write failed: %s", err) } if err := w.Close(); err != nil { t.Fatalf("Bad data response: %s", err) } if err := c.Quit(); err != nil { t.Fatalf("QUIT failed: %s", err) } bcmdbuf.Flush() actualcmds := cmdbuf.String() if client != actualcmds { t.Fatalf("Got:\n%s\nExpected:\n%s", actualcmds, client) } } var basicServer = `250 mx.google.com at your service 502 Unrecognized command. 250-mx.google.com at your service 250-SIZE 35651584 250-AUTH LOGIN PLAIN 250 8BITMIME 530 Authentication required 252 Send some mail, I'll try my best 250 User is valid 235 Accepted 250 Sender OK 250 Receiver OK 354 Go ahead 250 Data OK 221 OK ` var basicClient = `HELO localhost EHLO localhost EHLO localhost MAIL FROM:<user@gmail.com> BODY=8BITMIME VRFY user1@gmail.com VRFY user2@gmail.com AUTH PLAIN AHVzZXIAcGFzcw== MAIL FROM:<user@gmail.com> BODY=8BITMIME RCPT TO:<golang-nuts@googlegroups.com> DATA From: user@gmail.com To: golang-nuts@googlegroups.com Subject: Hooray for Go Line 1 ..Leading dot line . Goodbye. . QUIT ` func TestExtensions(t *testing.T) { fake := func(server string) (c *Client, bcmdbuf *bufio.Writer, cmdbuf *strings.Builder) { server = strings.Join(strings.Split(server, "\n"), "\r\n") cmdbuf = &strings.Builder{} bcmdbuf = bufio.NewWriter(cmdbuf) var fake faker fake.ReadWriter = bufio.NewReadWriter(bufio.NewReader(strings.NewReader(server)), bcmdbuf) c = &Client{Text: textproto.NewConn(fake), localName: "localhost"} return c, bcmdbuf, cmdbuf } t.Run("helo", func(t *testing.T) { const ( basicServer = `250 mx.google.com at your service 250 Sender OK 221 Goodbye ` basicClient = `HELO localhost MAIL FROM:<user@gmail.com> QUIT ` ) c, bcmdbuf, cmdbuf := fake(basicServer) if err := c.helo(); err != nil { t.Fatalf("HELO failed: %s", err) } c.didHello = true if err := c.Mail("user@gmail.com"); err != nil { t.Fatalf("MAIL FROM failed: %s", err) } if err := c.Quit(); err != nil { t.Fatalf("QUIT failed: %s", err) } bcmdbuf.Flush() actualcmds := cmdbuf.String() client := strings.Join(strings.Split(basicClient, "\n"), "\r\n") if client != actualcmds { t.Fatalf("Got:\n%s\nExpected:\n%s", actualcmds, client) } }) t.Run("ehlo", func(t *testing.T) { const ( basicServer = `250-mx.google.com at your service 250 SIZE 35651584 250 Sender OK 221 Goodbye ` basicClient = `EHLO localhost MAIL FROM:<user@gmail.com> QUIT ` ) c, bcmdbuf, cmdbuf := fake(basicServer) if err := c.Hello("localhost"); err != nil { t.Fatalf("EHLO failed: %s", err) } if ok, _ := c.Extension("8BITMIME"); ok { t.Fatalf("Shouldn't support 8BITMIME") } if ok, _ := c.Extension("SMTPUTF8"); ok { t.Fatalf("Shouldn't support SMTPUTF8") } if err := c.Mail("user@gmail.com"); err != nil { t.Fatalf("MAIL FROM failed: %s", err) } if err := c.Quit(); err != nil { t.Fatalf("QUIT failed: %s", err) } bcmdbuf.Flush() actualcmds := cmdbuf.String() client := strings.Join(strings.Split(basicClient, "\n"), "\r\n") if client != actualcmds { t.Fatalf("Got:\n%s\nExpected:\n%s", actualcmds, client) } }) t.Run("ehlo 8bitmime", func(t *testing.T) { const ( basicServer = `250-mx.google.com at your service 250-SIZE 35651584 250 8BITMIME 250 Sender OK 221 Goodbye ` basicClient = `EHLO localhost MAIL FROM:<user@gmail.com> BODY=8BITMIME QUIT ` ) c, bcmdbuf, cmdbuf := fake(basicServer) if err := c.Hello("localhost"); err != nil { t.Fatalf("EHLO failed: %s", err) } if ok, _ := c.Extension("8BITMIME"); !ok { t.Fatalf("Should support 8BITMIME") } if ok, _ := c.Extension("SMTPUTF8"); ok { t.Fatalf("Shouldn't support SMTPUTF8") } if err := c.Mail("user@gmail.com"); err != nil { t.Fatalf("MAIL FROM failed: %s", err) } if err := c.Quit(); err != nil { t.Fatalf("QUIT failed: %s", err) } bcmdbuf.Flush() actualcmds := cmdbuf.String() client := strings.Join(strings.Split(basicClient, "\n"), "\r\n") if client != actualcmds { t.Fatalf("Got:\n%s\nExpected:\n%s", actualcmds, client) } }) t.Run("ehlo smtputf8", func(t *testing.T) { const ( basicServer = `250-mx.google.com at your service 250-SIZE 35651584 250 SMTPUTF8 250 Sender OK 221 Goodbye ` basicClient = `EHLO localhost MAIL FROM:<user+📧@gmail.com> SMTPUTF8 QUIT ` ) c, bcmdbuf, cmdbuf := fake(basicServer) if err := c.Hello("localhost"); err != nil { t.Fatalf("EHLO failed: %s", err) } if ok, _ := c.Extension("8BITMIME"); ok { t.Fatalf("Shouldn't support 8BITMIME") } if ok, _ := c.Extension("SMTPUTF8"); !ok { t.Fatalf("Should support SMTPUTF8") } if err := c.Mail("user+📧@gmail.com"); err != nil { t.Fatalf("MAIL FROM failed: %s", err) } if err := c.Quit(); err != nil { t.Fatalf("QUIT failed: %s", err) } bcmdbuf.Flush() actualcmds := cmdbuf.String() client := strings.Join(strings.Split(basicClient, "\n"), "\r\n") if client != actualcmds { t.Fatalf("Got:\n%s\nExpected:\n%s", actualcmds, client) } }) t.Run("ehlo 8bitmime smtputf8", func(t *testing.T) { const ( basicServer = `250-mx.google.com at your service 250-SIZE 35651584 250-8BITMIME 250 SMTPUTF8 250 Sender OK 221 Goodbye ` basicClient = `EHLO localhost MAIL FROM:<user+📧@gmail.com> BODY=8BITMIME SMTPUTF8 QUIT ` ) c, bcmdbuf, cmdbuf := fake(basicServer) if err := c.Hello("localhost"); err != nil { t.Fatalf("EHLO failed: %s", err) } c.didHello = true if ok, _ := c.Extension("8BITMIME"); !ok { t.Fatalf("Should support 8BITMIME") } if ok, _ := c.Extension("SMTPUTF8"); !ok { t.Fatalf("Should support SMTPUTF8") } if err := c.Mail("user+📧@gmail.com"); err != nil { t.Fatalf("MAIL FROM failed: %s", err) } if err := c.Quit(); err != nil { t.Fatalf("QUIT failed: %s", err) } bcmdbuf.Flush() actualcmds := cmdbuf.String() client := strings.Join(strings.Split(basicClient, "\n"), "\r\n") if client != actualcmds { t.Fatalf("Got:\n%s\nExpected:\n%s", actualcmds, client) } }) } func TestNewClient(t *testing.T) { server := strings.Join(strings.Split(newClientServer, "\n"), "\r\n") client := strings.Join(strings.Split(newClientClient, "\n"), "\r\n") var cmdbuf strings.Builder bcmdbuf := bufio.NewWriter(&cmdbuf) out := func() string { bcmdbuf.Flush() return cmdbuf.String() } var fake faker fake.ReadWriter = bufio.NewReadWriter(bufio.NewReader(strings.NewReader(server)), bcmdbuf) c, err := NewClient(fake, "fake.host") if err != nil { t.Fatalf("NewClient: %v\n(after %v)", err, out()) } defer c.Close() if ok, args := c.Extension("aUtH"); !ok || args != "LOGIN PLAIN" { t.Fatalf("Expected AUTH supported") } if ok, _ := c.Extension("DSN"); ok { t.Fatalf("Shouldn't support DSN") } if err := c.Quit(); err != nil { t.Fatalf("QUIT failed: %s", err) } actualcmds := out() if client != actualcmds { t.Fatalf("Got:\n%s\nExpected:\n%s", actualcmds, client) } } var newClientServer = `220 hello world 250-mx.google.com at your service 250-SIZE 35651584 250-AUTH LOGIN PLAIN 250 8BITMIME 221 OK ` var newClientClient = `EHLO localhost QUIT ` func TestNewClient2(t *testing.T) { server := strings.Join(strings.Split(newClient2Server, "\n"), "\r\n") client := strings.Join(strings.Split(newClient2Client, "\n"), "\r\n") var cmdbuf strings.Builder bcmdbuf := bufio.NewWriter(&cmdbuf) var fake faker fake.ReadWriter = bufio.NewReadWriter(bufio.NewReader(strings.NewReader(server)), bcmdbuf) c, err := NewClient(fake, "fake.host") if err != nil { t.Fatalf("NewClient: %v", err) } defer c.Close() if ok, _ := c.Extension("DSN"); ok { t.Fatalf("Shouldn't support DSN") } if err := c.Quit(); err != nil { t.Fatalf("QUIT failed: %s", err) } bcmdbuf.Flush() actualcmds := cmdbuf.String() if client != actualcmds { t.Fatalf("Got:\n%s\nExpected:\n%s", actualcmds, client) } } var newClient2Server = `220 hello world 502 EH? 250-mx.google.com at your service 250-SIZE 35651584 250-AUTH LOGIN PLAIN 250 8BITMIME 221 OK ` var newClient2Client = `EHLO localhost HELO localhost QUIT ` func TestNewClientWithTLS(t *testing.T) { cert, err := tls.X509KeyPair(localhostCert, localhostKey) if err != nil { t.Fatalf("loadcert: %v", err) } config := tls.Config{Certificates: []tls.Certificate{cert}} ln, err := tls.Listen("tcp", "127.0.0.1:0", &config) if err != nil { ln, err = tls.Listen("tcp", "[::1]:0", &config) if err != nil { t.Fatalf("server: listen: %v", err) } } go func() { conn, err := ln.Accept() if err != nil { t.Errorf("server: accept: %v", err) return } defer conn.Close() _, err = conn.Write([]byte("220 SIGNS\r\n")) if err != nil { t.Errorf("server: write: %v", err) return } }() config.InsecureSkipVerify = true conn, err := tls.Dial("tcp", ln.Addr().String(), &config) if err != nil { t.Fatalf("client: dial: %v", err) } defer conn.Close() client, err := NewClient(conn, ln.Addr().String()) if err != nil { t.Fatalf("smtp: newclient: %v", err) } if !client.tls { t.Errorf("client.tls Got: %t Expected: %t", client.tls, true) } } func TestHello(t *testing.T) { if len(helloServer) != len(helloClient) { t.Fatalf("Hello server and client size mismatch") } for i := 0; i < len(helloServer); i++ { server := strings.Join(strings.Split(baseHelloServer+helloServer[i], "\n"), "\r\n") client := strings.Join(strings.Split(baseHelloClient+helloClient[i], "\n"), "\r\n") var cmdbuf strings.Builder bcmdbuf := bufio.NewWriter(&cmdbuf) var fake faker fake.ReadWriter = bufio.NewReadWriter(bufio.NewReader(strings.NewReader(server)), bcmdbuf) c, err := NewClient(fake, "fake.host") if err != nil { t.Fatalf("NewClient: %v", err) } defer c.Close() c.localName = "customhost" err = nil switch i { case 0: err = c.Hello("hostinjection>\n\rDATA\r\nInjected message body\r\n.\r\nQUIT\r\n") if err == nil { t.Errorf("Expected Hello to be rejected due to a message injection attempt") } err = c.Hello("customhost") case 1: err = c.StartTLS(nil) if err.Error() == "502 Not implemented" { err = nil } case 2: err = c.Verify("test@example.com") case 3: c.tls = true c.serverName = "smtp.google.com" err = c.Auth(PlainAuth("", "user", "pass", "smtp.google.com")) case 4: err = c.Mail("test@example.com") case 5: ok, _ := c.Extension("feature") if ok { t.Errorf("Expected FEATURE not to be supported") } case 6: err = c.Reset() case 7: err = c.Quit() case 8: err = c.Verify("test@example.com") if err != nil { err = c.Hello("customhost") if err != nil { t.Errorf("Want error, got none") } } case 9: err = c.Noop() default: t.Fatalf("Unhandled command") } if err != nil { t.Errorf("Command %d failed: %v", i, err) } bcmdbuf.Flush() actualcmds := cmdbuf.String() if client != actualcmds { t.Errorf("Got:\n%s\nExpected:\n%s", actualcmds, client) } } } var baseHelloServer = `220 hello world 502 EH? 250-mx.google.com at your service 250 FEATURE ` var helloServer = []string{ "", "502 Not implemented\n", "250 User is valid\n", "235 Accepted\n", "250 Sender ok\n", "", "250 Reset ok\n", "221 Goodbye\n", "250 Sender ok\n", "250 ok\n", } var baseHelloClient = `EHLO customhost HELO customhost ` var helloClient = []string{ "", "STARTTLS\n", "VRFY test@example.com\n", "AUTH PLAIN AHVzZXIAcGFzcw==\n", "MAIL FROM:<test@example.com>\n", "", "RSET\n", "QUIT\n", "VRFY test@example.com\n", "NOOP\n", } func TestSendMail(t *testing.T) { server := strings.Join(strings.Split(sendMailServer, "\n"), "\r\n") client := strings.Join(strings.Split(sendMailClient, "\n"), "\r\n") var cmdbuf strings.Builder bcmdbuf := bufio.NewWriter(&cmdbuf) l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatalf("Unable to create listener: %v", err) } defer l.Close() // prevent data race on bcmdbuf var done = make(chan struct{}) go func(data []string) { defer close(done) conn, err := l.Accept() if err != nil { t.Errorf("Accept error: %v", err) return } defer conn.Close() tc := textproto.NewConn(conn) for i := 0; i < len(data) && data[i] != ""; i++ { tc.PrintfLine("%s", data[i]) for len(data[i]) >= 4 && data[i][3] == '-' { i++ tc.PrintfLine("%s", data[i]) } if data[i] == "221 Goodbye" { return } read := false for !read || data[i] == "354 Go ahead" { msg, err := tc.ReadLine() bcmdbuf.Write([]byte(msg + "\r\n")) read = true if err != nil { t.Errorf("Read error: %v", err) return } if data[i] == "354 Go ahead" && msg == "." { break } } } }(strings.Split(server, "\r\n")) err = SendMail(l.Addr().String(), nil, "test@example.com", []string{"other@example.com>\n\rDATA\r\nInjected message body\r\n.\r\nQUIT\r\n"}, []byte(strings.Replace(`From: test@example.com To: other@example.com Subject: SendMail test SendMail is working for me. `, "\n", "\r\n", -1))) if err == nil { t.Errorf("Expected SendMail to be rejected due to a message injection attempt") } err = SendMail(l.Addr().String(), nil, "test@example.com", []string{"other@example.com"}, []byte(strings.Replace(`From: test@example.com To: other@example.com Subject: SendMail test SendMail is working for me. `, "\n", "\r\n", -1))) if err != nil { t.Errorf("%v", err) } <-done bcmdbuf.Flush() actualcmds := cmdbuf.String() if client != actualcmds { t.Errorf("Got:\n%s\nExpected:\n%s", actualcmds, client) } } var sendMailServer = `220 hello world 502 EH? 250 mx.google.com at your service 250 Sender ok 250 Receiver ok 354 Go ahead 250 Data ok 221 Goodbye ` var sendMailClient = `EHLO localhost HELO localhost MAIL FROM:<test@example.com> RCPT TO:<other@example.com> DATA From: test@example.com To: other@example.com Subject: SendMail test SendMail is working for me. . QUIT ` func TestSendMailWithAuth(t *testing.T) { l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatalf("Unable to create listener: %v", err) } defer l.Close() errCh := make(chan error) go func() { defer close(errCh) conn, err := l.Accept() if err != nil { errCh <- fmt.Errorf("Accept: %v", err) return } defer conn.Close() tc := textproto.NewConn(conn) tc.PrintfLine("220 hello world") msg, err := tc.ReadLine() if err != nil { errCh <- fmt.Errorf("ReadLine error: %v", err) return } const wantMsg = "EHLO localhost" if msg != wantMsg { errCh <- fmt.Errorf("unexpected response %q; want %q", msg, wantMsg) return } err = tc.PrintfLine("250 mx.google.com at your service") if err != nil { errCh <- fmt.Errorf("PrintfLine: %v", err) return } }() err = SendMail(l.Addr().String(), PlainAuth("", "user", "pass", "smtp.google.com"), "test@example.com", []string{"other@example.com"}, []byte(strings.Replace(`From: test@example.com To: other@example.com Subject: SendMail test SendMail is working for me. `, "\n", "\r\n", -1))) if err == nil { t.Error("SendMail: Server doesn't support AUTH, expected to get an error, but got none ") } if err.Error() != "smtp: server doesn't support AUTH" { t.Errorf("Expected: smtp: server doesn't support AUTH, got: %s", err) } err = <-errCh if err != nil { t.Fatalf("server error: %v", err) } } func TestAuthFailed(t *testing.T) { server := strings.Join(strings.Split(authFailedServer, "\n"), "\r\n") client := strings.Join(strings.Split(authFailedClient, "\n"), "\r\n") var cmdbuf strings.Builder bcmdbuf := bufio.NewWriter(&cmdbuf) var fake faker fake.ReadWriter = bufio.NewReadWriter(bufio.NewReader(strings.NewReader(server)), bcmdbuf) c, err := NewClient(fake, "fake.host") if err != nil { t.Fatalf("NewClient: %v", err) } defer c.Close() c.tls = true c.serverName = "smtp.google.com" err = c.Auth(PlainAuth("", "user", "pass", "smtp.google.com")) if err == nil { t.Error("Auth: expected error; got none") } else if err.Error() != "535 Invalid credentials\nplease see www.example.com" { t.Errorf("Auth: got error: %v, want: %s", err, "535 Invalid credentials\nplease see www.example.com") } bcmdbuf.Flush() actualcmds := cmdbuf.String() if client != actualcmds { t.Errorf("Got:\n%s\nExpected:\n%s", actualcmds, client) } } var authFailedServer = `220 hello world 250-mx.google.com at your service 250 AUTH LOGIN PLAIN 535-Invalid credentials 535 please see www.example.com 221 Goodbye ` var authFailedClient = `EHLO localhost AUTH PLAIN AHVzZXIAcGFzcw== * QUIT ` func TestTLSClient(t *testing.T) { if runtime.GOOS == "freebsd" || runtime.GOOS == "js" || runtime.GOOS == "wasip1" { testenv.SkipFlaky(t, 19229) } ln := newLocalListener(t) defer ln.Close() errc := make(chan error) go func() { errc <- sendMail(ln.Addr().String()) }() conn, err := ln.Accept() if err != nil { t.Fatalf("failed to accept connection: %v", err) } defer conn.Close() if err := serverHandle(conn, t); err != nil { t.Fatalf("failed to handle connection: %v", err) } if err := <-errc; err != nil { t.Fatalf("client error: %v", err) } } func TestTLSConnState(t *testing.T) { ln := newLocalListener(t) defer ln.Close() clientDone := make(chan bool) serverDone := make(chan bool) go func() { defer close(serverDone) c, err := ln.Accept() if err != nil { t.Errorf("Server accept: %v", err) return } defer c.Close() if err := serverHandle(c, t); err != nil { t.Errorf("server error: %v", err) } }() go func() { defer close(clientDone) c, err := Dial(ln.Addr().String()) if err != nil { t.Errorf("Client dial: %v", err) return } defer c.Quit() cfg := &tls.Config{ServerName: "example.com"} testHookStartTLS(cfg) // set the RootCAs if err := c.StartTLS(cfg); err != nil { t.Errorf("StartTLS: %v", err) return } cs, ok := c.TLSConnectionState() if !ok { t.Errorf("TLSConnectionState returned ok == false; want true") return } if cs.Version == 0 || !cs.HandshakeComplete { t.Errorf("ConnectionState = %#v; expect non-zero Version and HandshakeComplete", cs) } }() <-clientDone <-serverDone } func newLocalListener(t *testing.T) net.Listener { ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { ln, err = net.Listen("tcp6", "[::1]:0") } if err != nil { t.Fatal(err) } return ln } type smtpSender struct { w io.Writer } func (s smtpSender) send(f string) { s.w.Write([]byte(f + "\r\n")) } // smtp server, finely tailored to deal with our own client only! func serverHandle(c net.Conn, t *testing.T) error { send := smtpSender{c}.send send("220 127.0.0.1 ESMTP service ready") s := bufio.NewScanner(c) for s.Scan() { switch s.Text() { case "EHLO localhost": send("250-127.0.0.1 ESMTP offers a warm hug of welcome") send("250-STARTTLS") send("250 Ok") case "STARTTLS": send("220 Go ahead") keypair, err := tls.X509KeyPair(localhostCert, localhostKey) if err != nil { return err } config := &tls.Config{Certificates: []tls.Certificate{keypair}} c = tls.Server(c, config) defer c.Close() return serverHandleTLS(c, t) default: t.Fatalf("unrecognized command: %q", s.Text()) } } return s.Err() } func serverHandleTLS(c net.Conn, t *testing.T) error { send := smtpSender{c}.send s := bufio.NewScanner(c) for s.Scan() { switch s.Text() { case "EHLO localhost": send("250 Ok") case "MAIL FROM:<joe1@example.com>": send("250 Ok") case "RCPT TO:<joe2@example.com>": send("250 Ok") case "DATA": send("354 send the mail data, end with .") send("250 Ok") case "Subject: test": case "": case "howdy!": case ".": case "QUIT": send("221 127.0.0.1 Service closing transmission channel") return nil default: t.Fatalf("unrecognized command during TLS: %q", s.Text()) } } return s.Err() } func init() { testRootCAs := x509.NewCertPool() testRootCAs.AppendCertsFromPEM(localhostCert) testHookStartTLS = func(config *tls.Config) { config.RootCAs = testRootCAs } } func sendMail(hostPort string) error { from := "joe1@example.com" to := []string{"joe2@example.com"} return SendMail(hostPort, nil, from, to, []byte("Subject: test\n\nhowdy!")) } // localhostCert is a PEM-encoded TLS cert generated from src/crypto/tls: // // go run generate_cert.go --rsa-bits 1024 --host 127.0.0.1,::1,example.com \ // --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h var localhostCert = []byte(` -----BEGIN CERTIFICATE----- MIICFDCCAX2gAwIBAgIRAK0xjnaPuNDSreeXb+z+0u4wDQYJKoZIhvcNAQELBQAw EjEQMA4GA1UEChMHQWNtZSBDbzAgFw03MDAxMDEwMDAwMDBaGA8yMDg0MDEyOTE2 MDAwMFowEjEQMA4GA1UEChMHQWNtZSBDbzCBnzANBgkqhkiG9w0BAQEFAAOBjQAw gYkCgYEA0nFbQQuOWsjbGtejcpWz153OlziZM4bVjJ9jYruNw5n2Ry6uYQAffhqa JOInCmmcVe2siJglsyH9aRh6vKiobBbIUXXUU1ABd56ebAzlt0LobLlx7pZEMy30 LqIi9E6zmL3YvdGzpYlkFRnRrqwEtWYbGBf3znO250S56CCWH2UCAwEAAaNoMGYw DgYDVR0PAQH/BAQDAgKkMBMGA1UdJQQMMAoGCCsGAQUFBwMBMA8GA1UdEwEB/wQF MAMBAf8wLgYDVR0RBCcwJYILZXhhbXBsZS5jb22HBH8AAAGHEAAAAAAAAAAAAAAA AAAAAAEwDQYJKoZIhvcNAQELBQADgYEAbZtDS2dVuBYvb+MnolWnCNqvw1w5Gtgi NmvQQPOMgM3m+oQSCPRTNGSg25e1Qbo7bgQDv8ZTnq8FgOJ/rbkyERw2JckkHpD4 n4qcK27WkEDBtQFlPihIM8hLIuzWoi/9wygiElTy/tVL3y7fGCvY2/k1KBthtZGF tN8URjVmyEo= -----END CERTIFICATE-----`) // localhostKey is the private key for localhostCert. var localhostKey = []byte(testingKey(` -----BEGIN RSA TESTING KEY----- MIICXgIBAAKBgQDScVtBC45ayNsa16NylbPXnc6XOJkzhtWMn2Niu43DmfZHLq5h AB9+Gpok4icKaZxV7ayImCWzIf1pGHq8qKhsFshRddRTUAF3np5sDOW3QuhsuXHu lkQzLfQuoiL0TrOYvdi90bOliWQVGdGurAS1ZhsYF/fOc7bnRLnoIJYfZQIDAQAB AoGBAMst7OgpKyFV6c3JwyI/jWqxDySL3caU+RuTTBaodKAUx2ZEmNJIlx9eudLA kucHvoxsM/eRxlxkhdFxdBcwU6J+zqooTnhu/FE3jhrT1lPrbhfGhyKnUrB0KKMM VY3IQZyiehpxaeXAwoAou6TbWoTpl9t8ImAqAMY8hlULCUqlAkEA+9+Ry5FSYK/m 542LujIcCaIGoG1/Te6Sxr3hsPagKC2rH20rDLqXwEedSFOpSS0vpzlPAzy/6Rbb PHTJUhNdwwJBANXkA+TkMdbJI5do9/mn//U0LfrCR9NkcoYohxfKz8JuhgRQxzF2 6jpo3q7CdTuuRixLWVfeJzcrAyNrVcBq87cCQFkTCtOMNC7fZnCTPUv+9q1tcJyB vNjJu3yvoEZeIeuzouX9TJE21/33FaeDdsXbRhQEj23cqR38qFHsF1qAYNMCQQDP QXLEiJoClkR2orAmqjPLVhR3t2oB3INcnEjLNSq8LHyQEfXyaFfu4U9l5+fRPL2i jiC0k/9L5dHUsF0XZothAkEA23ddgRs+Id/HxtojqqUT27B8MT/IGNrYsp4DvS/c qgkeluku4GjxRlDMBuXk94xOBEinUs+p/hwP1Alll80Tpg== -----END RSA TESTING KEY-----`)) func testingKey(s string) string { return strings.ReplaceAll(s, "TESTING KEY", "PRIVATE KEY") }
go/src/net/smtp/smtp_test.go/0
{ "file_path": "go/src/net/smtp/smtp_test.go", "repo_id": "go", "token_count": 12750 }
351
// Copyright 2009 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. //go:build unix || windows package net import ( "internal/bytealg" "runtime" "syscall" ) // Boolean to int. func boolint(b bool) int { if b { return 1 } return 0 } func interfaceToIPv4Addr(ifi *Interface) (IP, error) { if ifi == nil { return IPv4zero, nil } ifat, err := ifi.Addrs() if err != nil { return nil, err } for _, ifa := range ifat { switch v := ifa.(type) { case *IPAddr: if v.IP.To4() != nil { return v.IP, nil } case *IPNet: if v.IP.To4() != nil { return v.IP, nil } } } return nil, errNoSuchInterface } func setIPv4MreqToInterface(mreq *syscall.IPMreq, ifi *Interface) error { if ifi == nil { return nil } ifat, err := ifi.Addrs() if err != nil { return err } for _, ifa := range ifat { switch v := ifa.(type) { case *IPAddr: if a := v.IP.To4(); a != nil { copy(mreq.Interface[:], a) goto done } case *IPNet: if a := v.IP.To4(); a != nil { copy(mreq.Interface[:], a) goto done } } } done: if bytealg.Equal(mreq.Multiaddr[:], IPv4zero.To4()) { return errNoSuchMulticastInterface } return nil } func setReadBuffer(fd *netFD, bytes int) error { err := fd.pfd.SetsockoptInt(syscall.SOL_SOCKET, syscall.SO_RCVBUF, bytes) runtime.KeepAlive(fd) return wrapSyscallError("setsockopt", err) } func setWriteBuffer(fd *netFD, bytes int) error { err := fd.pfd.SetsockoptInt(syscall.SOL_SOCKET, syscall.SO_SNDBUF, bytes) runtime.KeepAlive(fd) return wrapSyscallError("setsockopt", err) } func setKeepAlive(fd *netFD, keepalive bool) error { err := fd.pfd.SetsockoptInt(syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, boolint(keepalive)) runtime.KeepAlive(fd) return wrapSyscallError("setsockopt", err) } func setLinger(fd *netFD, sec int) error { var l syscall.Linger if sec >= 0 { l.Onoff = 1 l.Linger = int32(sec) } else { l.Onoff = 0 l.Linger = 0 } err := fd.pfd.SetsockoptLinger(syscall.SOL_SOCKET, syscall.SO_LINGER, &l) runtime.KeepAlive(fd) return wrapSyscallError("setsockopt", err) }
go/src/net/sockopt_posix.go/0
{ "file_path": "go/src/net/sockopt_posix.go", "repo_id": "go", "token_count": 972 }
352
// 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. //go:build windows package net import ( "internal/syscall/windows" "syscall" "testing" ) const ( syscall_TCP_KEEPIDLE = windows.TCP_KEEPIDLE syscall_TCP_KEEPCNT = windows.TCP_KEEPCNT syscall_TCP_KEEPINTVL = windows.TCP_KEEPINTVL ) type fdType = syscall.Handle func maybeSkipKeepAliveTest(t *testing.T) { // TODO(panjf2000): Unlike Unix-like OS's, old Windows (prior to Windows 10, version 1709) // doesn't provide any ways to retrieve the current TCP keep-alive settings, therefore // we're not able to run the test suite similar to Unix-like OS's on Windows. // Try to find another proper approach to test the keep-alive settings on old Windows. if !windows.SupportTCPKeepAliveIdle() || !windows.SupportTCPKeepAliveInterval() || !windows.SupportTCPKeepAliveCount() { t.Skip("skipping on windows") } }
go/src/net/tcpconn_keepalive_conf_windows_test.go/0
{ "file_path": "go/src/net/tcpconn_keepalive_conf_windows_test.go", "repo_id": "go", "token_count": 341 }
353
// Copyright 2009 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. //go:build unix || windows package net import ( "runtime" "syscall" ) func setNoDelay(fd *netFD, noDelay bool) error { err := fd.pfd.SetsockoptInt(syscall.IPPROTO_TCP, syscall.TCP_NODELAY, boolint(noDelay)) runtime.KeepAlive(fd) return wrapSyscallError("setsockopt", err) }
go/src/net/tcpsockopt_posix.go/0
{ "file_path": "go/src/net/tcpsockopt_posix.go", "repo_id": "go", "token_count": 162 }
354
options ndots:16
go/src/net/testdata/large-ndots-resolv.conf/0
{ "file_path": "go/src/net/testdata/large-ndots-resolv.conf", "repo_id": "go", "token_count": 6 }
355
// Copyright 2010 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. // Package textproto implements generic support for text-based request/response // protocols in the style of HTTP, NNTP, and SMTP. // // The package provides: // // [Error], which represents a numeric error response from // a server. // // [Pipeline], to manage pipelined requests and responses // in a client. // // [Reader], to read numeric response code lines, // key: value headers, lines wrapped with leading spaces // on continuation lines, and whole text blocks ending // with a dot on a line by itself. // // [Writer], to write dot-encoded text blocks. // // [Conn], a convenient packaging of [Reader], [Writer], and [Pipeline] for use // with a single network connection. package textproto import ( "bufio" "fmt" "io" "net" ) // An Error represents a numeric error response from a server. type Error struct { Code int Msg string } func (e *Error) Error() string { return fmt.Sprintf("%03d %s", e.Code, e.Msg) } // A ProtocolError describes a protocol violation such // as an invalid response or a hung-up connection. type ProtocolError string func (p ProtocolError) Error() string { return string(p) } // A Conn represents a textual network protocol connection. // It consists of a [Reader] and [Writer] to manage I/O // and a [Pipeline] to sequence concurrent requests on the connection. // These embedded types carry methods with them; // see the documentation of those types for details. type Conn struct { Reader Writer Pipeline conn io.ReadWriteCloser } // NewConn returns a new [Conn] using conn for I/O. func NewConn(conn io.ReadWriteCloser) *Conn { return &Conn{ Reader: Reader{R: bufio.NewReader(conn)}, Writer: Writer{W: bufio.NewWriter(conn)}, conn: conn, } } // Close closes the connection. func (c *Conn) Close() error { return c.conn.Close() } // Dial connects to the given address on the given network using [net.Dial] // and then returns a new [Conn] for the connection. func Dial(network, addr string) (*Conn, error) { c, err := net.Dial(network, addr) if err != nil { return nil, err } return NewConn(c), nil } // Cmd is a convenience method that sends a command after // waiting its turn in the pipeline. The command text is the // result of formatting format with args and appending \r\n. // Cmd returns the id of the command, for use with StartResponse and EndResponse. // // For example, a client might run a HELP command that returns a dot-body // by using: // // id, err := c.Cmd("HELP") // if err != nil { // return nil, err // } // // c.StartResponse(id) // defer c.EndResponse(id) // // if _, _, err = c.ReadCodeLine(110); err != nil { // return nil, err // } // text, err := c.ReadDotBytes() // if err != nil { // return nil, err // } // return c.ReadCodeLine(250) func (c *Conn) Cmd(format string, args ...any) (id uint, err error) { id = c.Next() c.StartRequest(id) err = c.PrintfLine(format, args...) c.EndRequest(id) if err != nil { return 0, err } return id, nil } // TrimString returns s without leading and trailing ASCII space. func TrimString(s string) string { for len(s) > 0 && isASCIISpace(s[0]) { s = s[1:] } for len(s) > 0 && isASCIISpace(s[len(s)-1]) { s = s[:len(s)-1] } return s } // TrimBytes returns b without leading and trailing ASCII space. func TrimBytes(b []byte) []byte { for len(b) > 0 && isASCIISpace(b[0]) { b = b[1:] } for len(b) > 0 && isASCIISpace(b[len(b)-1]) { b = b[:len(b)-1] } return b } func isASCIISpace(b byte) bool { return b == ' ' || b == '\t' || b == '\n' || b == '\r' } func isASCIILetter(b byte) bool { b |= 0x20 // make lower case return 'a' <= b && b <= 'z' }
go/src/net/textproto/textproto.go/0
{ "file_path": "go/src/net/textproto/textproto.go", "repo_id": "go", "token_count": 1298 }
356
// Copyright 2021 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. //go:build unix package net import ( "internal/syscall/unix" "os" "syscall" "testing" "time" ) func TestUnixConnReadMsgUnixSCMRightsCloseOnExec(t *testing.T) { if !testableNetwork("unix") { t.Skip("not unix system") } scmFile, err := os.Open(os.DevNull) if err != nil { t.Fatalf("file open: %v", err) } defer scmFile.Close() rights := syscall.UnixRights(int(scmFile.Fd())) fds, err := syscall.Socketpair(syscall.AF_LOCAL, syscall.SOCK_STREAM, 0) if err != nil { t.Fatalf("Socketpair: %v", err) } writeFile := os.NewFile(uintptr(fds[0]), "write-socket") defer writeFile.Close() readFile := os.NewFile(uintptr(fds[1]), "read-socket") defer readFile.Close() cw, err := FileConn(writeFile) if err != nil { t.Fatalf("FileConn: %v", err) } defer cw.Close() cr, err := FileConn(readFile) if err != nil { t.Fatalf("FileConn: %v", err) } defer cr.Close() ucw, ok := cw.(*UnixConn) if !ok { t.Fatalf("got %T; want UnixConn", cw) } ucr, ok := cr.(*UnixConn) if !ok { t.Fatalf("got %T; want UnixConn", cr) } oob := make([]byte, syscall.CmsgSpace(4)) err = ucw.SetWriteDeadline(time.Now().Add(5 * time.Second)) if err != nil { t.Fatalf("Can't set unix connection timeout: %v", err) } _, _, err = ucw.WriteMsgUnix(nil, rights, nil) if err != nil { t.Fatalf("UnixConn readMsg: %v", err) } err = ucr.SetReadDeadline(time.Now().Add(5 * time.Second)) if err != nil { t.Fatalf("Can't set unix connection timeout: %v", err) } _, oobn, _, _, err := ucr.ReadMsgUnix(nil, oob) if err != nil { t.Fatalf("UnixConn readMsg: %v", err) } scms, err := syscall.ParseSocketControlMessage(oob[:oobn]) if err != nil { t.Fatalf("ParseSocketControlMessage: %v", err) } if len(scms) != 1 { t.Fatalf("got scms = %#v; expected 1 SocketControlMessage", scms) } scm := scms[0] gotFDs, err := syscall.ParseUnixRights(&scm) if err != nil { t.Fatalf("syscall.ParseUnixRights: %v", err) } if len(gotFDs) != 1 { t.Fatalf("got FDs %#v: wanted only 1 fd", gotFDs) } defer func() { if err := syscall.Close(gotFDs[0]); err != nil { t.Fatalf("fail to close gotFDs: %v", err) } }() flags, err := unix.Fcntl(gotFDs[0], syscall.F_GETFD, 0) if err != nil { t.Fatalf("Can't get flags of fd:%#v, with err:%v", gotFDs[0], err) } if flags&syscall.FD_CLOEXEC == 0 { t.Fatalf("got flags %#x, want %#x (FD_CLOEXEC) set", flags, syscall.FD_CLOEXEC) } }
go/src/net/unixsock_readmsg_test.go/0
{ "file_path": "go/src/net/unixsock_readmsg_test.go", "repo_id": "go", "token_count": 1142 }
357
// Copyright 2020 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. package os import ( "syscall" "unsafe" ) func direntIno(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(syscall.Dirent{}.Fileno), unsafe.Sizeof(syscall.Dirent{}.Fileno)) } func direntReclen(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(syscall.Dirent{}.Reclen), unsafe.Sizeof(syscall.Dirent{}.Reclen)) } func direntNamlen(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(syscall.Dirent{}.Namlen), unsafe.Sizeof(syscall.Dirent{}.Namlen)) } func direntType(buf []byte) FileMode { off := unsafe.Offsetof(syscall.Dirent{}.Type) if off >= uintptr(len(buf)) { return ^FileMode(0) // unknown } typ := buf[off] switch typ { case syscall.DT_BLK: return ModeDevice case syscall.DT_CHR: return ModeDevice | ModeCharDevice case syscall.DT_DIR: return ModeDir case syscall.DT_FIFO: return ModeNamedPipe case syscall.DT_LNK: return ModeSymlink case syscall.DT_REG: return 0 case syscall.DT_SOCK: return ModeSocket } return ^FileMode(0) // unknown }
go/src/os/dirent_freebsd.go/0
{ "file_path": "go/src/os/dirent_freebsd.go", "repo_id": "go", "token_count": 473 }
358
// Copyright 2016 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. package os_test import ( "bytes" "errors" "fmt" "io/fs" "log" "os" "path/filepath" "sync" "time" ) func ExampleOpenFile() { f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0644) if err != nil { log.Fatal(err) } if err := f.Close(); err != nil { log.Fatal(err) } } func ExampleOpenFile_append() { // If the file doesn't exist, create it, or append to the file f, err := os.OpenFile("access.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { log.Fatal(err) } if _, err := f.Write([]byte("appended some data\n")); err != nil { f.Close() // ignore error; Write error takes precedence log.Fatal(err) } if err := f.Close(); err != nil { log.Fatal(err) } } func ExampleChmod() { if err := os.Chmod("some-filename", 0644); err != nil { log.Fatal(err) } } func ExampleChtimes() { mtime := time.Date(2006, time.February, 1, 3, 4, 5, 0, time.UTC) atime := time.Date(2007, time.March, 2, 4, 5, 6, 0, time.UTC) if err := os.Chtimes("some-filename", atime, mtime); err != nil { log.Fatal(err) } } func ExampleFileMode() { fi, err := os.Lstat("some-filename") if err != nil { log.Fatal(err) } fmt.Printf("permissions: %#o\n", fi.Mode().Perm()) // 0o400, 0o777, etc. switch mode := fi.Mode(); { case mode.IsRegular(): fmt.Println("regular file") case mode.IsDir(): fmt.Println("directory") case mode&fs.ModeSymlink != 0: fmt.Println("symbolic link") case mode&fs.ModeNamedPipe != 0: fmt.Println("named pipe") } } func ExampleErrNotExist() { filename := "a-nonexistent-file" if _, err := os.Stat(filename); errors.Is(err, fs.ErrNotExist) { fmt.Println("file does not exist") } // Output: // file does not exist } func ExampleExpand() { mapper := func(placeholderName string) string { switch placeholderName { case "DAY_PART": return "morning" case "NAME": return "Gopher" } return "" } fmt.Println(os.Expand("Good ${DAY_PART}, $NAME!", mapper)) // Output: // Good morning, Gopher! } func ExampleExpandEnv() { os.Setenv("NAME", "gopher") os.Setenv("BURROW", "/usr/gopher") fmt.Println(os.ExpandEnv("$NAME lives in ${BURROW}.")) // Output: // gopher lives in /usr/gopher. } func ExampleLookupEnv() { show := func(key string) { val, ok := os.LookupEnv(key) if !ok { fmt.Printf("%s not set\n", key) } else { fmt.Printf("%s=%s\n", key, val) } } os.Setenv("SOME_KEY", "value") os.Setenv("EMPTY_KEY", "") show("SOME_KEY") show("EMPTY_KEY") show("MISSING_KEY") // Output: // SOME_KEY=value // EMPTY_KEY= // MISSING_KEY not set } func ExampleGetenv() { os.Setenv("NAME", "gopher") os.Setenv("BURROW", "/usr/gopher") fmt.Printf("%s lives in %s.\n", os.Getenv("NAME"), os.Getenv("BURROW")) // Output: // gopher lives in /usr/gopher. } func ExampleUnsetenv() { os.Setenv("TMPDIR", "/my/tmp") defer os.Unsetenv("TMPDIR") } func ExampleReadDir() { files, err := os.ReadDir(".") if err != nil { log.Fatal(err) } for _, file := range files { fmt.Println(file.Name()) } } func ExampleMkdirTemp() { dir, err := os.MkdirTemp("", "example") if err != nil { log.Fatal(err) } defer os.RemoveAll(dir) // clean up file := filepath.Join(dir, "tmpfile") if err := os.WriteFile(file, []byte("content"), 0666); err != nil { log.Fatal(err) } } func ExampleMkdirTemp_suffix() { logsDir, err := os.MkdirTemp("", "*-logs") if err != nil { log.Fatal(err) } defer os.RemoveAll(logsDir) // clean up // Logs can be cleaned out earlier if needed by searching // for all directories whose suffix ends in *-logs. globPattern := filepath.Join(os.TempDir(), "*-logs") matches, err := filepath.Glob(globPattern) if err != nil { log.Fatalf("Failed to match %q: %v", globPattern, err) } for _, match := range matches { if err := os.RemoveAll(match); err != nil { log.Printf("Failed to remove %q: %v", match, err) } } } func ExampleCreateTemp() { f, err := os.CreateTemp("", "example") if err != nil { log.Fatal(err) } defer os.Remove(f.Name()) // clean up if _, err := f.Write([]byte("content")); err != nil { log.Fatal(err) } if err := f.Close(); err != nil { log.Fatal(err) } } func ExampleCreateTemp_suffix() { f, err := os.CreateTemp("", "example.*.txt") if err != nil { log.Fatal(err) } defer os.Remove(f.Name()) // clean up if _, err := f.Write([]byte("content")); err != nil { f.Close() log.Fatal(err) } if err := f.Close(); err != nil { log.Fatal(err) } } func ExampleReadFile() { data, err := os.ReadFile("testdata/hello") if err != nil { log.Fatal(err) } os.Stdout.Write(data) // Output: // Hello, Gophers! } func ExampleWriteFile() { err := os.WriteFile("testdata/hello", []byte("Hello, Gophers!"), 0666) if err != nil { log.Fatal(err) } } func ExampleMkdir() { err := os.Mkdir("testdir", 0750) if err != nil && !os.IsExist(err) { log.Fatal(err) } err = os.WriteFile("testdir/testfile.txt", []byte("Hello, Gophers!"), 0660) if err != nil { log.Fatal(err) } } func ExampleMkdirAll() { err := os.MkdirAll("test/subdir", 0750) if err != nil { log.Fatal(err) } err = os.WriteFile("test/subdir/testfile.txt", []byte("Hello, Gophers!"), 0660) if err != nil { log.Fatal(err) } } func ExampleReadlink() { // First, we create a relative symlink to a file. d, err := os.MkdirTemp("", "") if err != nil { log.Fatal(err) } defer os.RemoveAll(d) targetPath := filepath.Join(d, "hello.txt") if err := os.WriteFile(targetPath, []byte("Hello, Gophers!"), 0644); err != nil { log.Fatal(err) } linkPath := filepath.Join(d, "hello.link") if err := os.Symlink("hello.txt", filepath.Join(d, "hello.link")); err != nil { if errors.Is(err, errors.ErrUnsupported) { // Allow the example to run on platforms that do not support symbolic links. fmt.Printf("%s links to %s\n", filepath.Base(linkPath), "hello.txt") return } log.Fatal(err) } // Readlink returns the relative path as passed to os.Symlink. dst, err := os.Readlink(linkPath) if err != nil { log.Fatal(err) } fmt.Printf("%s links to %s\n", filepath.Base(linkPath), dst) var dstAbs string if filepath.IsAbs(dst) { dstAbs = dst } else { // Symlink targets are relative to the directory containing the link. dstAbs = filepath.Join(filepath.Dir(linkPath), dst) } // Check that the target is correct by comparing it with os.Stat // on the original target path. dstInfo, err := os.Stat(dstAbs) if err != nil { log.Fatal(err) } targetInfo, err := os.Stat(targetPath) if err != nil { log.Fatal(err) } if !os.SameFile(dstInfo, targetInfo) { log.Fatalf("link destination (%s) is not the same file as %s", dstAbs, targetPath) } // Output: // hello.link links to hello.txt } func ExampleUserCacheDir() { dir, dirErr := os.UserCacheDir() if dirErr == nil { dir = filepath.Join(dir, "ExampleUserCacheDir") } getCache := func(name string) ([]byte, error) { if dirErr != nil { return nil, &os.PathError{Op: "getCache", Path: name, Err: os.ErrNotExist} } return os.ReadFile(filepath.Join(dir, name)) } var mkdirOnce sync.Once putCache := func(name string, b []byte) error { if dirErr != nil { return &os.PathError{Op: "putCache", Path: name, Err: dirErr} } mkdirOnce.Do(func() { if err := os.MkdirAll(dir, 0700); err != nil { log.Printf("can't create user cache dir: %v", err) } }) return os.WriteFile(filepath.Join(dir, name), b, 0600) } // Read and store cached data. // … _ = getCache _ = putCache // Output: } func ExampleUserConfigDir() { dir, dirErr := os.UserConfigDir() var ( configPath string origConfig []byte ) if dirErr == nil { configPath = filepath.Join(dir, "ExampleUserConfigDir", "example.conf") var err error origConfig, err = os.ReadFile(configPath) if err != nil && !os.IsNotExist(err) { // The user has a config file but we couldn't read it. // Report the error instead of ignoring their configuration. log.Fatal(err) } } // Use and perhaps make changes to the config. config := bytes.Clone(origConfig) // … // Save changes. if !bytes.Equal(config, origConfig) { if configPath == "" { log.Printf("not saving config changes: %v", dirErr) } else { err := os.MkdirAll(filepath.Dir(configPath), 0700) if err == nil { err = os.WriteFile(configPath, config, 0600) } if err != nil { log.Printf("error saving config changes: %v", err) } } } // Output: }
go/src/os/example_test.go/0
{ "file_path": "go/src/os/example_test.go", "repo_id": "go", "token_count": 3573 }
359
// Copyright 2021 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. //go:build plan9 package fdtest import ( "syscall" ) const errBadFd = syscall.ErrorString("fd out of range or not open") // Exists returns true if fd is a valid file descriptor. func Exists(fd uintptr) bool { var buf [1]byte _, err := syscall.Fstat(int(fd), buf[:]) return err != errBadFd }
go/src/os/exec/internal/fdtest/exists_plan9.go/0
{ "file_path": "go/src/os/exec/internal/fdtest/exists_plan9.go", "repo_id": "go", "token_count": 156 }
360
// Copyright 2009 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. package os import ( "internal/itoa" "runtime" "syscall" "time" ) // The only signal values guaranteed to be present in the os package // on all systems are Interrupt (send the process an interrupt) and // Kill (force the process to exit). Interrupt is not implemented on // Windows; using it with [os.Process.Signal] will return an error. var ( Interrupt Signal = syscall.Note("interrupt") Kill Signal = syscall.Note("kill") ) func startProcess(name string, argv []string, attr *ProcAttr) (p *Process, err error) { sysattr := &syscall.ProcAttr{ Dir: attr.Dir, Env: attr.Env, Sys: attr.Sys, } sysattr.Files = make([]uintptr, 0, len(attr.Files)) for _, f := range attr.Files { sysattr.Files = append(sysattr.Files, f.Fd()) } pid, _, e := syscall.StartProcess(name, argv, sysattr) if e != nil { return nil, &PathError{Op: "fork/exec", Path: name, Err: e} } return newPIDProcess(pid), nil } func (p *Process) writeProcFile(file string, data string) error { f, e := OpenFile("/proc/"+itoa.Itoa(p.Pid)+"/"+file, O_WRONLY, 0) if e != nil { return e } defer f.Close() _, e = f.Write([]byte(data)) return e } func (p *Process) signal(sig Signal) error { switch p.pidStatus() { case statusDone: return ErrProcessDone case statusReleased: return syscall.ENOENT } if e := p.writeProcFile("note", sig.String()); e != nil { return NewSyscallError("signal", e) } return nil } func (p *Process) kill() error { return p.signal(Kill) } func (p *Process) wait() (ps *ProcessState, err error) { var waitmsg syscall.Waitmsg switch p.pidStatus() { case statusReleased: return nil, ErrInvalid } err = syscall.WaitProcess(p.Pid, &waitmsg) if err != nil { return nil, NewSyscallError("wait", err) } p.pidDeactivate(statusDone) ps = &ProcessState{ pid: waitmsg.Pid, status: &waitmsg, } return ps, nil } func (p *Process) release() error { p.Pid = -1 // Just mark the PID unusable. p.pidDeactivate(statusReleased) // no need for a finalizer anymore runtime.SetFinalizer(p, nil) return nil } func findProcess(pid int) (p *Process, err error) { // NOOP for Plan 9. return newPIDProcess(pid), nil } // ProcessState stores information about a process, as reported by Wait. type ProcessState struct { pid int // The process's id. status *syscall.Waitmsg // System-dependent status info. } // Pid returns the process id of the exited process. func (p *ProcessState) Pid() int { return p.pid } func (p *ProcessState) exited() bool { return p.status.Exited() } func (p *ProcessState) success() bool { return p.status.ExitStatus() == 0 } func (p *ProcessState) sys() any { return p.status } func (p *ProcessState) sysUsage() any { return p.status } func (p *ProcessState) userTime() time.Duration { return time.Duration(p.status.Time[0]) * time.Millisecond } func (p *ProcessState) systemTime() time.Duration { return time.Duration(p.status.Time[1]) * time.Millisecond } func (p *ProcessState) String() string { if p == nil { return "<nil>" } return "exit status: " + p.status.Msg } // ExitCode returns the exit code of the exited process, or -1 // if the process hasn't exited or was terminated by a signal. func (p *ProcessState) ExitCode() int { // return -1 if the process hasn't started. if p == nil { return -1 } return p.status.ExitStatus() }
go/src/os/exec_plan9.go/0
{ "file_path": "go/src/os/exec_plan9.go", "repo_id": "go", "token_count": 1287 }
361
// Copyright 2016 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. package os_test import ( "fmt" "internal/testenv" "os" "path/filepath" "runtime" "testing" ) const executable_EnvVar = "OSTEST_OUTPUT_EXECPATH" func TestExecutable(t *testing.T) { testenv.MustHaveExec(t) t.Parallel() ep, err := os.Executable() if err != nil { t.Fatalf("Executable failed: %v", err) } // we want fn to be of the form "dir/prog" dir := filepath.Dir(filepath.Dir(ep)) fn, err := filepath.Rel(dir, ep) if err != nil { t.Fatalf("filepath.Rel: %v", err) } cmd := testenv.Command(t, fn, "-test.run=^$") // make child start with a relative program path cmd.Dir = dir cmd.Path = fn if runtime.GOOS == "openbsd" || runtime.GOOS == "aix" { // OpenBSD and AIX rely on argv[0] } else { // forge argv[0] for child, so that we can verify we could correctly // get real path of the executable without influenced by argv[0]. cmd.Args[0] = "-" } cmd.Env = append(cmd.Environ(), fmt.Sprintf("%s=1", executable_EnvVar)) out, err := cmd.CombinedOutput() if err != nil { t.Fatalf("exec(self) failed: %v", err) } outs := string(out) if !filepath.IsAbs(outs) { t.Fatalf("Child returned %q, want an absolute path", out) } if !sameFile(outs, ep) { t.Fatalf("Child returned %q, not the same file as %q", out, ep) } } func sameFile(fn1, fn2 string) bool { fi1, err := os.Stat(fn1) if err != nil { return false } fi2, err := os.Stat(fn2) if err != nil { return false } return os.SameFile(fi1, fi2) } func init() { if e := os.Getenv(executable_EnvVar); e != "" { // first chdir to another path dir := "/" if runtime.GOOS == "windows" { cwd, err := os.Getwd() if err != nil { panic(err) } dir = filepath.VolumeName(cwd) } os.Chdir(dir) if ep, err := os.Executable(); err != nil { fmt.Fprint(os.Stderr, "ERROR: ", err) } else { fmt.Fprint(os.Stderr, ep) } os.Exit(0) } } func TestExecutableDeleted(t *testing.T) { testenv.MustHaveGoBuild(t) switch runtime.GOOS { case "windows", "plan9": t.Skipf("%v does not support deleting running binary", runtime.GOOS) case "openbsd", "freebsd", "aix": t.Skipf("%v does not support reading deleted binary name", runtime.GOOS) } t.Parallel() dir := t.TempDir() src := filepath.Join(dir, "testdel.go") exe := filepath.Join(dir, "testdel.exe") err := os.WriteFile(src, []byte(testExecutableDeletion), 0666) if err != nil { t.Fatal(err) } out, err := testenv.Command(t, testenv.GoToolPath(t), "build", "-o", exe, src).CombinedOutput() t.Logf("build output:\n%s", out) if err != nil { t.Fatal(err) } out, err = testenv.Command(t, exe).CombinedOutput() t.Logf("exec output:\n%s", out) if err != nil { t.Fatal(err) } } const testExecutableDeletion = `package main import ( "fmt" "os" ) func main() { before, err := os.Executable() if err != nil { fmt.Fprintf(os.Stderr, "failed to read executable name before deletion: %v\n", err) os.Exit(1) } err = os.Remove(before) if err != nil { fmt.Fprintf(os.Stderr, "failed to remove executable: %v\n", err) os.Exit(1) } after, err := os.Executable() if err != nil { fmt.Fprintf(os.Stderr, "failed to read executable name after deletion: %v\n", err) os.Exit(1) } if before != after { fmt.Fprintf(os.Stderr, "before and after do not match: %v != %v\n", before, after) os.Exit(1) } } `
go/src/os/executable_test.go/0
{ "file_path": "go/src/os/executable_test.go", "repo_id": "go", "token_count": 1460 }
362
// Copyright 2009 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. package os import ( "errors" "internal/filepathlite" "internal/godebug" "internal/poll" "internal/syscall/windows" "runtime" "sync" "sync/atomic" "syscall" "unsafe" ) // This matches the value in syscall/syscall_windows.go. const _UTIME_OMIT = -1 // file is the real representation of *File. // The extra level of indirection ensures that no clients of os // can overwrite this data, which could cause the finalizer // to close the wrong file descriptor. type file struct { pfd poll.FD name string dirinfo atomic.Pointer[dirInfo] // nil unless directory being read appendMode bool // whether file is opened for appending } // Fd returns the Windows handle referencing the open file. // If f is closed, the file descriptor becomes invalid. // If f is garbage collected, a finalizer may close the file descriptor, // making it invalid; see [runtime.SetFinalizer] for more information on when // a finalizer might be run. On Unix systems this will cause the [File.SetDeadline] // methods to stop working. func (file *File) Fd() uintptr { if file == nil { return uintptr(syscall.InvalidHandle) } return uintptr(file.pfd.Sysfd) } // newFile returns a new File with the given file handle and name. // Unlike NewFile, it does not check that h is syscall.InvalidHandle. func newFile(h syscall.Handle, name string, kind string) *File { if kind == "file" { var m uint32 if syscall.GetConsoleMode(h, &m) == nil { kind = "console" } if t, err := syscall.GetFileType(h); err == nil && t == syscall.FILE_TYPE_PIPE { kind = "pipe" } } f := &File{&file{ pfd: poll.FD{ Sysfd: h, IsStream: true, ZeroReadIsEOF: true, }, name: name, }} runtime.SetFinalizer(f.file, (*file).close) // Ignore initialization errors. // Assume any problems will show up in later I/O. f.pfd.Init(kind, false) return f } // newConsoleFile creates new File that will be used as console. func newConsoleFile(h syscall.Handle, name string) *File { return newFile(h, name, "console") } // NewFile returns a new File with the given file descriptor and // name. The returned value will be nil if fd is not a valid file // descriptor. func NewFile(fd uintptr, name string) *File { h := syscall.Handle(fd) if h == syscall.InvalidHandle { return nil } return newFile(h, name, "file") } func epipecheck(file *File, e error) { } // DevNull is the name of the operating system's “null device.” // On Unix-like systems, it is "/dev/null"; on Windows, "NUL". const DevNull = "NUL" // openFileNolog is the Windows implementation of OpenFile. func openFileNolog(name string, flag int, perm FileMode) (*File, error) { if name == "" { return nil, &PathError{Op: "open", Path: name, Err: syscall.ENOENT} } path := fixLongPath(name) r, e := syscall.Open(path, flag|syscall.O_CLOEXEC, syscallMode(perm)) if e != nil { // We should return EISDIR when we are trying to open a directory with write access. if e == syscall.ERROR_ACCESS_DENIED && (flag&O_WRONLY != 0 || flag&O_RDWR != 0) { pathp, e1 := syscall.UTF16PtrFromString(path) if e1 == nil { var fa syscall.Win32FileAttributeData e1 = syscall.GetFileAttributesEx(pathp, syscall.GetFileExInfoStandard, (*byte)(unsafe.Pointer(&fa))) if e1 == nil && fa.FileAttributes&syscall.FILE_ATTRIBUTE_DIRECTORY != 0 { e = syscall.EISDIR } } } return nil, &PathError{Op: "open", Path: name, Err: e} } return newFile(r, name, "file"), nil } func openDirNolog(name string) (*File, error) { return openFileNolog(name, O_RDONLY, 0) } func (file *file) close() error { if file == nil { return syscall.EINVAL } if info := file.dirinfo.Swap(nil); info != nil { info.close() } var err error if e := file.pfd.Close(); e != nil { if e == poll.ErrFileClosing { e = ErrClosed } err = &PathError{Op: "close", Path: file.name, Err: e} } // no need for a finalizer anymore runtime.SetFinalizer(file, nil) return err } // seek sets the offset for the next Read or Write on file to offset, interpreted // according to whence: 0 means relative to the origin of the file, 1 means // relative to the current offset, and 2 means relative to the end. // It returns the new offset and an error, if any. func (f *File) seek(offset int64, whence int) (ret int64, err error) { if info := f.dirinfo.Swap(nil); info != nil { // Free cached dirinfo, so we allocate a new one if we // access this file as a directory again. See #35767 and #37161. info.close() } ret, err = f.pfd.Seek(offset, whence) runtime.KeepAlive(f) return ret, err } // Truncate changes the size of the named file. // If the file is a symbolic link, it changes the size of the link's target. func Truncate(name string, size int64) error { f, e := OpenFile(name, O_WRONLY, 0666) if e != nil { return e } defer f.Close() e1 := f.Truncate(size) if e1 != nil { return e1 } return nil } // Remove removes the named file or directory. // If there is an error, it will be of type *PathError. func Remove(name string) error { p, e := syscall.UTF16PtrFromString(fixLongPath(name)) if e != nil { return &PathError{Op: "remove", Path: name, Err: e} } // Go file interface forces us to know whether // name is a file or directory. Try both. e = syscall.DeleteFile(p) if e == nil { return nil } e1 := syscall.RemoveDirectory(p) if e1 == nil { return nil } // Both failed: figure out which error to return. if e1 != e { a, e2 := syscall.GetFileAttributes(p) if e2 != nil { e = e2 } else { if a&syscall.FILE_ATTRIBUTE_DIRECTORY != 0 { e = e1 } else if a&syscall.FILE_ATTRIBUTE_READONLY != 0 { if e1 = syscall.SetFileAttributes(p, a&^syscall.FILE_ATTRIBUTE_READONLY); e1 == nil { if e = syscall.DeleteFile(p); e == nil { return nil } } } } } return &PathError{Op: "remove", Path: name, Err: e} } func rename(oldname, newname string) error { e := windows.Rename(fixLongPath(oldname), fixLongPath(newname)) if e != nil { return &LinkError{"rename", oldname, newname, e} } return nil } // Pipe returns a connected pair of Files; reads from r return bytes written to w. // It returns the files and an error, if any. The Windows handles underlying // the returned files are marked as inheritable by child processes. func Pipe() (r *File, w *File, err error) { var p [2]syscall.Handle e := syscall.Pipe(p[:]) if e != nil { return nil, nil, NewSyscallError("pipe", e) } return newFile(p[0], "|0", "pipe"), newFile(p[1], "|1", "pipe"), nil } var ( useGetTempPath2Once sync.Once useGetTempPath2 bool ) func tempDir() string { useGetTempPath2Once.Do(func() { useGetTempPath2 = (windows.ErrorLoadingGetTempPath2() == nil) }) getTempPath := syscall.GetTempPath if useGetTempPath2 { getTempPath = windows.GetTempPath2 } n := uint32(syscall.MAX_PATH) for { b := make([]uint16, n) n, _ = getTempPath(uint32(len(b)), &b[0]) if n > uint32(len(b)) { continue } if n == 3 && b[1] == ':' && b[2] == '\\' { // Do nothing for path, like C:\. } else if n > 0 && b[n-1] == '\\' { // Otherwise remove terminating \. n-- } return syscall.UTF16ToString(b[:n]) } } // Link creates newname as a hard link to the oldname file. // If there is an error, it will be of type *LinkError. func Link(oldname, newname string) error { n, err := syscall.UTF16PtrFromString(fixLongPath(newname)) if err != nil { return &LinkError{"link", oldname, newname, err} } o, err := syscall.UTF16PtrFromString(fixLongPath(oldname)) if err != nil { return &LinkError{"link", oldname, newname, err} } err = syscall.CreateHardLink(n, o, 0) if err != nil { return &LinkError{"link", oldname, newname, err} } return nil } // Symlink creates newname as a symbolic link to oldname. // On Windows, a symlink to a non-existent oldname creates a file symlink; // if oldname is later created as a directory the symlink will not work. // If there is an error, it will be of type *LinkError. func Symlink(oldname, newname string) error { // '/' does not work in link's content oldname = filepathlite.FromSlash(oldname) // need the exact location of the oldname when it's relative to determine if it's a directory destpath := oldname if v := filepathlite.VolumeName(oldname); v == "" { if len(oldname) > 0 && IsPathSeparator(oldname[0]) { // oldname is relative to the volume containing newname. if v = filepathlite.VolumeName(newname); v != "" { // Prepend the volume explicitly, because it may be different from the // volume of the current working directory. destpath = v + oldname } } else { // oldname is relative to newname. destpath = dirname(newname) + `\` + oldname } } fi, err := Stat(destpath) isdir := err == nil && fi.IsDir() n, err := syscall.UTF16PtrFromString(fixLongPath(newname)) if err != nil { return &LinkError{"symlink", oldname, newname, err} } var o *uint16 if filepathlite.IsAbs(oldname) { o, err = syscall.UTF16PtrFromString(fixLongPath(oldname)) } else { // Do not use fixLongPath on oldname for relative symlinks, // as it would turn the name into an absolute path thus making // an absolute symlink instead. // Notice that CreateSymbolicLinkW does not fail for relative // symlinks beyond MAX_PATH, so this does not prevent the // creation of an arbitrary long path name. o, err = syscall.UTF16PtrFromString(oldname) } if err != nil { return &LinkError{"symlink", oldname, newname, err} } var flags uint32 = windows.SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE if isdir { flags |= syscall.SYMBOLIC_LINK_FLAG_DIRECTORY } err = syscall.CreateSymbolicLink(n, o, flags) if err != nil { // the unprivileged create flag is unsupported // below Windows 10 (1703, v10.0.14972). retry without it. flags &^= windows.SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE err = syscall.CreateSymbolicLink(n, o, flags) if err != nil { return &LinkError{"symlink", oldname, newname, err} } } return nil } // openSymlink calls CreateFile Windows API with FILE_FLAG_OPEN_REPARSE_POINT // parameter, so that Windows does not follow symlink, if path is a symlink. // openSymlink returns opened file handle. func openSymlink(path string) (syscall.Handle, error) { p, err := syscall.UTF16PtrFromString(path) if err != nil { return 0, err } attrs := uint32(syscall.FILE_FLAG_BACKUP_SEMANTICS) // Use FILE_FLAG_OPEN_REPARSE_POINT, otherwise CreateFile will follow symlink. // See https://docs.microsoft.com/en-us/windows/desktop/FileIO/symbolic-link-effects-on-file-systems-functions#createfile-and-createfiletransacted attrs |= syscall.FILE_FLAG_OPEN_REPARSE_POINT h, err := syscall.CreateFile(p, 0, 0, nil, syscall.OPEN_EXISTING, attrs, 0) if err != nil { return 0, err } return h, nil } var winreadlinkvolume = godebug.New("winreadlinkvolume") // normaliseLinkPath converts absolute paths returned by // DeviceIoControl(h, FSCTL_GET_REPARSE_POINT, ...) // into paths acceptable by all Windows APIs. // For example, it converts // // \??\C:\foo\bar into C:\foo\bar // \??\UNC\foo\bar into \\foo\bar // \??\Volume{abc}\ into \\?\Volume{abc}\ func normaliseLinkPath(path string) (string, error) { if len(path) < 4 || path[:4] != `\??\` { // unexpected path, return it as is return path, nil } // we have path that start with \??\ s := path[4:] switch { case len(s) >= 2 && s[1] == ':': // \??\C:\foo\bar return s, nil case len(s) >= 4 && s[:4] == `UNC\`: // \??\UNC\foo\bar return `\\` + s[4:], nil } // \??\Volume{abc}\ if winreadlinkvolume.Value() != "0" { return `\\?\` + path[4:], nil } winreadlinkvolume.IncNonDefault() h, err := openSymlink(path) if err != nil { return "", err } defer syscall.CloseHandle(h) buf := make([]uint16, 100) for { n, err := windows.GetFinalPathNameByHandle(h, &buf[0], uint32(len(buf)), windows.VOLUME_NAME_DOS) if err != nil { return "", err } if n < uint32(len(buf)) { break } buf = make([]uint16, n) } s = syscall.UTF16ToString(buf) if len(s) > 4 && s[:4] == `\\?\` { s = s[4:] if len(s) > 3 && s[:3] == `UNC` { // return path like \\server\share\... return `\` + s[3:], nil } return s, nil } return "", errors.New("GetFinalPathNameByHandle returned unexpected path: " + s) } func readReparseLink(path string) (string, error) { h, err := openSymlink(path) if err != nil { return "", err } defer syscall.CloseHandle(h) rdbbuf := make([]byte, syscall.MAXIMUM_REPARSE_DATA_BUFFER_SIZE) var bytesReturned uint32 err = syscall.DeviceIoControl(h, syscall.FSCTL_GET_REPARSE_POINT, nil, 0, &rdbbuf[0], uint32(len(rdbbuf)), &bytesReturned, nil) if err != nil { return "", err } rdb := (*windows.REPARSE_DATA_BUFFER)(unsafe.Pointer(&rdbbuf[0])) switch rdb.ReparseTag { case syscall.IO_REPARSE_TAG_SYMLINK: rb := (*windows.SymbolicLinkReparseBuffer)(unsafe.Pointer(&rdb.DUMMYUNIONNAME)) s := rb.Path() if rb.Flags&windows.SYMLINK_FLAG_RELATIVE != 0 { return s, nil } return normaliseLinkPath(s) case windows.IO_REPARSE_TAG_MOUNT_POINT: return normaliseLinkPath((*windows.MountPointReparseBuffer)(unsafe.Pointer(&rdb.DUMMYUNIONNAME)).Path()) default: // the path is not a symlink or junction but another type of reparse // point return "", syscall.ENOENT } } func readlink(name string) (string, error) { s, err := readReparseLink(fixLongPath(name)) if err != nil { return "", &PathError{Op: "readlink", Path: name, Err: err} } return s, nil }
go/src/os/file_windows.go/0
{ "file_path": "go/src/os/file_windows.go", "repo_id": "go", "token_count": 5225 }
363
// Copyright 2009 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. //go:build aix || darwin package os import "syscall" // Pipe returns a connected pair of Files; reads from r return bytes written to w. // It returns the files and an error, if any. func Pipe() (r *File, w *File, err error) { var p [2]int // See ../syscall/exec.go for description of lock. syscall.ForkLock.RLock() e := syscall.Pipe(p[0:]) if e != nil { syscall.ForkLock.RUnlock() return nil, nil, NewSyscallError("pipe", e) } syscall.CloseOnExec(p[0]) syscall.CloseOnExec(p[1]) syscall.ForkLock.RUnlock() return newFile(p[0], "|0", kindPipe, false), newFile(p[1], "|1", kindPipe, false), nil }
go/src/os/pipe_unix.go/0
{ "file_path": "go/src/os/pipe_unix.go", "repo_id": "go", "token_count": 286 }
364
// Copyright 2020 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. //go:build linux package signal import ( "os" "syscall" "testing" "time" ) const prSetKeepCaps = 8 // This test validates that syscall.AllThreadsSyscall() can reliably // reach all 'm' (threads) of the nocgo runtime even when one thread // is blocked waiting to receive signals from the kernel. This monitors // for a regression vs. the fix for #43149. func TestAllThreadsSyscallSignals(t *testing.T) { if _, _, err := syscall.AllThreadsSyscall(syscall.SYS_PRCTL, prSetKeepCaps, 0, 0); err == syscall.ENOTSUP { t.Skip("AllThreadsSyscall disabled with cgo") } sig := make(chan os.Signal, 1) Notify(sig, os.Interrupt) for i := 0; i <= 100; i++ { if _, _, errno := syscall.AllThreadsSyscall(syscall.SYS_PRCTL, prSetKeepCaps, uintptr(i&1), 0); errno != 0 { t.Fatalf("[%d] failed to set KEEP_CAPS=%d: %v", i, i&1, errno) } } select { case <-time.After(10 * time.Millisecond): case <-sig: t.Fatal("unexpected signal") } Stop(sig) }
go/src/os/signal/signal_linux_test.go/0
{ "file_path": "go/src/os/signal/signal_linux_test.go", "repo_id": "go", "token_count": 432 }
365
// Copyright 2009 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. package os import ( "internal/syscall/windows" "syscall" ) func hostname() (name string, err error) { // Use PhysicalDnsHostname to uniquely identify host in a cluster const format = windows.ComputerNamePhysicalDnsHostname n := uint32(64) for { b := make([]uint16, n) err := windows.GetComputerNameEx(format, &b[0], &n) if err == nil { return syscall.UTF16ToString(b[:n]), nil } if err != syscall.ERROR_MORE_DATA { return "", NewSyscallError("ComputerNameEx", err) } // If we received an ERROR_MORE_DATA, but n doesn't get larger, // something has gone wrong and we may be in an infinite loop if n <= uint32(len(b)) { return "", NewSyscallError("ComputerNameEx", err) } } }
go/src/os/sys_windows.go/0
{ "file_path": "go/src/os/sys_windows.go", "repo_id": "go", "token_count": 306 }
366
// Copyright 2011 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. //go:build cgo && !osusergo && unix && !android && !darwin package user import ( "syscall" ) /* #cgo solaris CFLAGS: -D_POSIX_PTHREAD_SEMANTICS #cgo CFLAGS: -fno-stack-protector #include <unistd.h> #include <sys/types.h> #include <pwd.h> #include <grp.h> #include <stdlib.h> #include <string.h> static struct passwd mygetpwuid_r(int uid, char *buf, size_t buflen, int *found, int *perr) { struct passwd pwd; struct passwd *result; memset (&pwd, 0, sizeof(pwd)); *perr = getpwuid_r(uid, &pwd, buf, buflen, &result); *found = result != NULL; return pwd; } static struct passwd mygetpwnam_r(const char *name, char *buf, size_t buflen, int *found, int *perr) { struct passwd pwd; struct passwd *result; memset(&pwd, 0, sizeof(pwd)); *perr = getpwnam_r(name, &pwd, buf, buflen, &result); *found = result != NULL; return pwd; } static struct group mygetgrgid_r(int gid, char *buf, size_t buflen, int *found, int *perr) { struct group grp; struct group *result; memset(&grp, 0, sizeof(grp)); *perr = getgrgid_r(gid, &grp, buf, buflen, &result); *found = result != NULL; return grp; } static struct group mygetgrnam_r(const char *name, char *buf, size_t buflen, int *found, int *perr) { struct group grp; struct group *result; memset(&grp, 0, sizeof(grp)); *perr = getgrnam_r(name, &grp, buf, buflen, &result); *found = result != NULL; return grp; } */ import "C" type _C_char = C.char type _C_int = C.int type _C_gid_t = C.gid_t type _C_uid_t = C.uid_t type _C_size_t = C.size_t type _C_struct_group = C.struct_group type _C_struct_passwd = C.struct_passwd type _C_long = C.long func _C_pw_uid(p *_C_struct_passwd) _C_uid_t { return p.pw_uid } func _C_pw_uidp(p *_C_struct_passwd) *_C_uid_t { return &p.pw_uid } func _C_pw_gid(p *_C_struct_passwd) _C_gid_t { return p.pw_gid } func _C_pw_gidp(p *_C_struct_passwd) *_C_gid_t { return &p.pw_gid } func _C_pw_name(p *_C_struct_passwd) *_C_char { return p.pw_name } func _C_pw_gecos(p *_C_struct_passwd) *_C_char { return p.pw_gecos } func _C_pw_dir(p *_C_struct_passwd) *_C_char { return p.pw_dir } func _C_gr_gid(g *_C_struct_group) _C_gid_t { return g.gr_gid } func _C_gr_name(g *_C_struct_group) *_C_char { return g.gr_name } func _C_GoString(p *_C_char) string { return C.GoString(p) } func _C_getpwnam_r(name *_C_char, buf *_C_char, size _C_size_t) (pwd _C_struct_passwd, found bool, errno syscall.Errno) { var f, e _C_int pwd = C.mygetpwnam_r(name, buf, size, &f, &e) return pwd, f != 0, syscall.Errno(e) } func _C_getpwuid_r(uid _C_uid_t, buf *_C_char, size _C_size_t) (pwd _C_struct_passwd, found bool, errno syscall.Errno) { var f, e _C_int pwd = C.mygetpwuid_r(_C_int(uid), buf, size, &f, &e) return pwd, f != 0, syscall.Errno(e) } func _C_getgrnam_r(name *_C_char, buf *_C_char, size _C_size_t) (grp _C_struct_group, found bool, errno syscall.Errno) { var f, e _C_int grp = C.mygetgrnam_r(name, buf, size, &f, &e) return grp, f != 0, syscall.Errno(e) } func _C_getgrgid_r(gid _C_gid_t, buf *_C_char, size _C_size_t) (grp _C_struct_group, found bool, errno syscall.Errno) { var f, e _C_int grp = C.mygetgrgid_r(_C_int(gid), buf, size, &f, &e) return grp, f != 0, syscall.Errno(e) } const ( _C__SC_GETPW_R_SIZE_MAX = C._SC_GETPW_R_SIZE_MAX _C__SC_GETGR_R_SIZE_MAX = C._SC_GETGR_R_SIZE_MAX ) func _C_sysconf(key _C_int) _C_long { return C.sysconf(key) }
go/src/os/user/cgo_lookup_cgo.go/0
{ "file_path": "go/src/os/user/cgo_lookup_cgo.go", "repo_id": "go", "token_count": 1681 }
367
// Copyright 2012 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. package user import ( "fmt" "internal/syscall/windows" "internal/syscall/windows/registry" "syscall" "unsafe" ) func isDomainJoined() (bool, error) { var domain *uint16 var status uint32 err := syscall.NetGetJoinInformation(nil, &domain, &status) if err != nil { return false, err } syscall.NetApiBufferFree((*byte)(unsafe.Pointer(domain))) return status == syscall.NetSetupDomainName, nil } func lookupFullNameDomain(domainAndUser string) (string, error) { return syscall.TranslateAccountName(domainAndUser, syscall.NameSamCompatible, syscall.NameDisplay, 50) } func lookupFullNameServer(servername, username string) (string, error) { s, e := syscall.UTF16PtrFromString(servername) if e != nil { return "", e } u, e := syscall.UTF16PtrFromString(username) if e != nil { return "", e } var p *byte e = syscall.NetUserGetInfo(s, u, 10, &p) if e != nil { return "", e } defer syscall.NetApiBufferFree(p) i := (*syscall.UserInfo10)(unsafe.Pointer(p)) return windows.UTF16PtrToString(i.FullName), nil } func lookupFullName(domain, username, domainAndUser string) (string, error) { joined, err := isDomainJoined() if err == nil && joined { name, err := lookupFullNameDomain(domainAndUser) if err == nil { return name, nil } } name, err := lookupFullNameServer(domain, username) if err == nil { return name, nil } // domain worked neither as a domain nor as a server // could be domain server unavailable // pretend username is fullname return username, nil } // getProfilesDirectory retrieves the path to the root directory // where user profiles are stored. func getProfilesDirectory() (string, error) { n := uint32(100) for { b := make([]uint16, n) e := windows.GetProfilesDirectory(&b[0], &n) if e == nil { return syscall.UTF16ToString(b), nil } if e != syscall.ERROR_INSUFFICIENT_BUFFER { return "", e } if n <= uint32(len(b)) { return "", e } } } // lookupUsernameAndDomain obtains the username and domain for usid. func lookupUsernameAndDomain(usid *syscall.SID) (username, domain string, e error) { username, domain, t, e := usid.LookupAccount("") if e != nil { return "", "", e } if t != syscall.SidTypeUser { return "", "", fmt.Errorf("user: should be user account type, not %d", t) } return username, domain, nil } // findHomeDirInRegistry finds the user home path based on the uid. func findHomeDirInRegistry(uid string) (dir string, e error) { k, e := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\`+uid, registry.QUERY_VALUE) if e != nil { return "", e } defer k.Close() dir, _, e = k.GetStringValue("ProfileImagePath") if e != nil { return "", e } return dir, nil } // lookupGroupName accepts the name of a group and retrieves the group SID. func lookupGroupName(groupname string) (string, error) { sid, _, t, e := syscall.LookupSID("", groupname) if e != nil { return "", e } // https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-samr/7b2aeb27-92fc-41f6-8437-deb65d950921#gt_0387e636-5654-4910-9519-1f8326cf5ec0 // SidTypeAlias should also be treated as a group type next to SidTypeGroup // and SidTypeWellKnownGroup: // "alias object -> resource group: A group object..." // // Tests show that "Administrators" can be considered of type SidTypeAlias. if t != syscall.SidTypeGroup && t != syscall.SidTypeWellKnownGroup && t != syscall.SidTypeAlias { return "", fmt.Errorf("lookupGroupName: should be group account type, not %d", t) } return sid.String() } // listGroupsForUsernameAndDomain accepts username and domain and retrieves // a SID list of the local groups where this user is a member. func listGroupsForUsernameAndDomain(username, domain string) ([]string, error) { // Check if both the domain name and user should be used. var query string joined, err := isDomainJoined() if err == nil && joined && len(domain) != 0 { query = domain + `\` + username } else { query = username } q, err := syscall.UTF16PtrFromString(query) if err != nil { return nil, err } var p0 *byte var entriesRead, totalEntries uint32 // https://learn.microsoft.com/en-us/windows/win32/api/lmaccess/nf-lmaccess-netusergetlocalgroups // NetUserGetLocalGroups() would return a list of LocalGroupUserInfo0 // elements which hold the names of local groups where the user participates. // The list does not follow any sorting order. // // If no groups can be found for this user, NetUserGetLocalGroups() should // always return the SID of a single group called "None", which // also happens to be the primary group for the local user. err = windows.NetUserGetLocalGroups(nil, q, 0, windows.LG_INCLUDE_INDIRECT, &p0, windows.MAX_PREFERRED_LENGTH, &entriesRead, &totalEntries) if err != nil { return nil, err } defer syscall.NetApiBufferFree(p0) if entriesRead == 0 { return nil, fmt.Errorf("listGroupsForUsernameAndDomain: NetUserGetLocalGroups() returned an empty list for domain: %s, username: %s", domain, username) } entries := (*[1024]windows.LocalGroupUserInfo0)(unsafe.Pointer(p0))[:entriesRead:entriesRead] var sids []string for _, entry := range entries { if entry.Name == nil { continue } sid, err := lookupGroupName(windows.UTF16PtrToString(entry.Name)) if err != nil { return nil, err } sids = append(sids, sid) } return sids, nil } func newUser(uid, gid, dir, username, domain string) (*User, error) { domainAndUser := domain + `\` + username name, e := lookupFullName(domain, username, domainAndUser) if e != nil { return nil, e } u := &User{ Uid: uid, Gid: gid, Username: domainAndUser, Name: name, HomeDir: dir, } return u, nil } var ( // unused variables (in this implementation) // modified during test to exercise code paths in the cgo implementation. userBuffer = 0 groupBuffer = 0 ) func current() (*User, error) { t, e := syscall.OpenCurrentProcessToken() if e != nil { return nil, e } defer t.Close() u, e := t.GetTokenUser() if e != nil { return nil, e } pg, e := t.GetTokenPrimaryGroup() if e != nil { return nil, e } uid, e := u.User.Sid.String() if e != nil { return nil, e } gid, e := pg.PrimaryGroup.String() if e != nil { return nil, e } dir, e := t.GetUserProfileDirectory() if e != nil { return nil, e } username, domain, e := lookupUsernameAndDomain(u.User.Sid) if e != nil { return nil, e } return newUser(uid, gid, dir, username, domain) } // lookupUserPrimaryGroup obtains the primary group SID for a user using this method: // https://support.microsoft.com/en-us/help/297951/how-to-use-the-primarygroupid-attribute-to-find-the-primary-group-for // The method follows this formula: domainRID + "-" + primaryGroupRID func lookupUserPrimaryGroup(username, domain string) (string, error) { // get the domain RID sid, _, t, e := syscall.LookupSID("", domain) if e != nil { return "", e } if t != syscall.SidTypeDomain { return "", fmt.Errorf("lookupUserPrimaryGroup: should be domain account type, not %d", t) } domainRID, e := sid.String() if e != nil { return "", e } // If the user has joined a domain use the RID of the default primary group // called "Domain Users": // https://support.microsoft.com/en-us/help/243330/well-known-security-identifiers-in-windows-operating-systems // SID: S-1-5-21domain-513 // // The correct way to obtain the primary group of a domain user is // probing the user primaryGroupID attribute in the server Active Directory: // https://learn.microsoft.com/en-us/windows/win32/adschema/a-primarygroupid // // Note that the primary group of domain users should not be modified // on Windows for performance reasons, even if it's possible to do that. // The .NET Developer's Guide to Directory Services Programming - Page 409 // https://books.google.bg/books?id=kGApqjobEfsC&lpg=PA410&ots=p7oo-eOQL7&dq=primary%20group%20RID&hl=bg&pg=PA409#v=onepage&q&f=false joined, err := isDomainJoined() if err == nil && joined { return domainRID + "-513", nil } // For non-domain users call NetUserGetInfo() with level 4, which // in this case would not have any network overhead. // The primary group should not change from RID 513 here either // but the group will be called "None" instead: // https://www.adampalmer.me/iodigitalsec/2013/08/10/windows-null-session-enumeration/ // "Group 'None' (RID: 513)" u, e := syscall.UTF16PtrFromString(username) if e != nil { return "", e } d, e := syscall.UTF16PtrFromString(domain) if e != nil { return "", e } var p *byte e = syscall.NetUserGetInfo(d, u, 4, &p) if e != nil { return "", e } defer syscall.NetApiBufferFree(p) i := (*windows.UserInfo4)(unsafe.Pointer(p)) return fmt.Sprintf("%s-%d", domainRID, i.PrimaryGroupID), nil } func newUserFromSid(usid *syscall.SID) (*User, error) { username, domain, e := lookupUsernameAndDomain(usid) if e != nil { return nil, e } gid, e := lookupUserPrimaryGroup(username, domain) if e != nil { return nil, e } uid, e := usid.String() if e != nil { return nil, e } // If this user has logged in at least once their home path should be stored // in the registry under the specified SID. References: // https://social.technet.microsoft.com/wiki/contents/articles/13895.how-to-remove-a-corrupted-user-profile-from-the-registry.aspx // https://support.asperasoft.com/hc/en-us/articles/216127438-How-to-delete-Windows-user-profiles // // The registry is the most reliable way to find the home path as the user // might have decided to move it outside of the default location, // (e.g. C:\users). Reference: // https://answers.microsoft.com/en-us/windows/forum/windows_7-security/how-do-i-set-a-home-directory-outside-cusers-for-a/aed68262-1bf4-4a4d-93dc-7495193a440f dir, e := findHomeDirInRegistry(uid) if e != nil { // If the home path does not exist in the registry, the user might // have not logged in yet; fall back to using getProfilesDirectory(). // Find the username based on a SID and append that to the result of // getProfilesDirectory(). The domain is not relevant here. dir, e = getProfilesDirectory() if e != nil { return nil, e } dir += `\` + username } return newUser(uid, gid, dir, username, domain) } func lookupUser(username string) (*User, error) { sid, _, t, e := syscall.LookupSID("", username) if e != nil { return nil, e } if t != syscall.SidTypeUser { return nil, fmt.Errorf("user: should be user account type, not %d", t) } return newUserFromSid(sid) } func lookupUserId(uid string) (*User, error) { sid, e := syscall.StringToSid(uid) if e != nil { return nil, e } return newUserFromSid(sid) } func lookupGroup(groupname string) (*Group, error) { sid, err := lookupGroupName(groupname) if err != nil { return nil, err } return &Group{Name: groupname, Gid: sid}, nil } func lookupGroupId(gid string) (*Group, error) { sid, err := syscall.StringToSid(gid) if err != nil { return nil, err } groupname, _, t, err := sid.LookupAccount("") if err != nil { return nil, err } if t != syscall.SidTypeGroup && t != syscall.SidTypeWellKnownGroup && t != syscall.SidTypeAlias { return nil, fmt.Errorf("lookupGroupId: should be group account type, not %d", t) } return &Group{Name: groupname, Gid: gid}, nil } func listGroups(user *User) ([]string, error) { sid, err := syscall.StringToSid(user.Uid) if err != nil { return nil, err } username, domain, err := lookupUsernameAndDomain(sid) if err != nil { return nil, err } sids, err := listGroupsForUsernameAndDomain(username, domain) if err != nil { return nil, err } // Add the primary group of the user to the list if it is not already there. // This is done only to comply with the POSIX concept of a primary group. for _, sid := range sids { if sid == user.Gid { return sids, nil } } return append(sids, user.Gid), nil }
go/src/os/user/lookup_windows.go/0
{ "file_path": "go/src/os/user/lookup_windows.go", "repo_id": "go", "token_count": 4387 }
368
// Copyright 2013 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. //go:build !windows && !plan9 package filepath_test import ( "fmt" "path/filepath" ) func ExampleSplitList() { fmt.Println("On Unix:", filepath.SplitList("/a/b/c:/usr/bin")) // Output: // On Unix: [/a/b/c /usr/bin] } func ExampleRel() { paths := []string{ "/a/b/c", "/b/c", "./b/c", } base := "/a" fmt.Println("On Unix:") for _, p := range paths { rel, err := filepath.Rel(base, p) fmt.Printf("%q: %q %v\n", p, rel, err) } // Output: // On Unix: // "/a/b/c": "b/c" <nil> // "/b/c": "../b/c" <nil> // "./b/c": "" Rel: can't make ./b/c relative to /a } func ExampleSplit() { paths := []string{ "/home/arnie/amelia.jpg", "/mnt/photos/", "rabbit.jpg", "/usr/local//go", } fmt.Println("On Unix:") for _, p := range paths { dir, file := filepath.Split(p) fmt.Printf("input: %q\n\tdir: %q\n\tfile: %q\n", p, dir, file) } // Output: // On Unix: // input: "/home/arnie/amelia.jpg" // dir: "/home/arnie/" // file: "amelia.jpg" // input: "/mnt/photos/" // dir: "/mnt/photos/" // file: "" // input: "rabbit.jpg" // dir: "" // file: "rabbit.jpg" // input: "/usr/local//go" // dir: "/usr/local//" // file: "go" } func ExampleJoin() { fmt.Println("On Unix:") fmt.Println(filepath.Join("a", "b", "c")) fmt.Println(filepath.Join("a", "b/c")) fmt.Println(filepath.Join("a/b", "c")) fmt.Println(filepath.Join("a/b", "/c")) fmt.Println(filepath.Join("a/b", "../../../xyz")) // Output: // On Unix: // a/b/c // a/b/c // a/b/c // a/b/c // ../xyz } func ExampleMatch() { fmt.Println("On Unix:") fmt.Println(filepath.Match("/home/catch/*", "/home/catch/foo")) fmt.Println(filepath.Match("/home/catch/*", "/home/catch/foo/bar")) fmt.Println(filepath.Match("/home/?opher", "/home/gopher")) fmt.Println(filepath.Match("/home/\\*", "/home/*")) // Output: // On Unix: // true <nil> // false <nil> // true <nil> // true <nil> } func ExampleBase() { fmt.Println("On Unix:") fmt.Println(filepath.Base("/foo/bar/baz.js")) fmt.Println(filepath.Base("/foo/bar/baz")) fmt.Println(filepath.Base("/foo/bar/baz/")) fmt.Println(filepath.Base("dev.txt")) fmt.Println(filepath.Base("../todo.txt")) fmt.Println(filepath.Base("..")) fmt.Println(filepath.Base(".")) fmt.Println(filepath.Base("/")) fmt.Println(filepath.Base("")) // Output: // On Unix: // baz.js // baz // baz // dev.txt // todo.txt // .. // . // / // . } func ExampleDir() { fmt.Println("On Unix:") fmt.Println(filepath.Dir("/foo/bar/baz.js")) fmt.Println(filepath.Dir("/foo/bar/baz")) fmt.Println(filepath.Dir("/foo/bar/baz/")) fmt.Println(filepath.Dir("/dirty//path///")) fmt.Println(filepath.Dir("dev.txt")) fmt.Println(filepath.Dir("../todo.txt")) fmt.Println(filepath.Dir("..")) fmt.Println(filepath.Dir(".")) fmt.Println(filepath.Dir("/")) fmt.Println(filepath.Dir("")) // Output: // On Unix: // /foo/bar // /foo/bar // /foo/bar/baz // /dirty/path // . // .. // . // . // / // . } func ExampleIsAbs() { fmt.Println("On Unix:") fmt.Println(filepath.IsAbs("/home/gopher")) fmt.Println(filepath.IsAbs(".bashrc")) fmt.Println(filepath.IsAbs("..")) fmt.Println(filepath.IsAbs(".")) fmt.Println(filepath.IsAbs("/")) fmt.Println(filepath.IsAbs("")) // Output: // On Unix: // true // false // false // false // true // false }
go/src/path/filepath/example_unix_test.go/0
{ "file_path": "go/src/path/filepath/example_unix_test.go", "repo_id": "go", "token_count": 1627 }
369
// Copyright 2010 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. package path import ( "errors" "internal/bytealg" "unicode/utf8" ) // ErrBadPattern indicates a pattern was malformed. var ErrBadPattern = errors.New("syntax error in pattern") // Match reports whether name matches the shell pattern. // The pattern syntax is: // // pattern: // { term } // term: // '*' matches any sequence of non-/ characters // '?' matches any single non-/ character // '[' [ '^' ] { character-range } ']' // character class (must be non-empty) // c matches character c (c != '*', '?', '\\', '[') // '\\' c matches character c // // character-range: // c matches character c (c != '\\', '-', ']') // '\\' c matches character c // lo '-' hi matches character c for lo <= c <= hi // // Match requires pattern to match all of name, not just a substring. // The only possible returned error is [ErrBadPattern], when pattern // is malformed. func Match(pattern, name string) (matched bool, err error) { Pattern: for len(pattern) > 0 { var star bool var chunk string star, chunk, pattern = scanChunk(pattern) if star && chunk == "" { // Trailing * matches rest of string unless it has a /. return bytealg.IndexByteString(name, '/') < 0, nil } // Look for match at current position. t, ok, err := matchChunk(chunk, name) // if we're the last chunk, make sure we've exhausted the name // otherwise we'll give a false result even if we could still match // using the star if ok && (len(t) == 0 || len(pattern) > 0) { name = t continue } if err != nil { return false, err } if star { // Look for match skipping i+1 bytes. // Cannot skip /. for i := 0; i < len(name) && name[i] != '/'; i++ { t, ok, err := matchChunk(chunk, name[i+1:]) if ok { // if we're the last chunk, make sure we exhausted the name if len(pattern) == 0 && len(t) > 0 { continue } name = t continue Pattern } if err != nil { return false, err } } } // Before returning false with no error, // check that the remainder of the pattern is syntactically valid. for len(pattern) > 0 { _, chunk, pattern = scanChunk(pattern) if _, _, err := matchChunk(chunk, ""); err != nil { return false, err } } return false, nil } return len(name) == 0, nil } // scanChunk gets the next segment of pattern, which is a non-star string // possibly preceded by a star. func scanChunk(pattern string) (star bool, chunk, rest string) { for len(pattern) > 0 && pattern[0] == '*' { pattern = pattern[1:] star = true } inrange := false var i int Scan: for i = 0; i < len(pattern); i++ { switch pattern[i] { case '\\': // error check handled in matchChunk: bad pattern. if i+1 < len(pattern) { i++ } case '[': inrange = true case ']': inrange = false case '*': if !inrange { break Scan } } } return star, pattern[0:i], pattern[i:] } // matchChunk checks whether chunk matches the beginning of s. // If so, it returns the remainder of s (after the match). // Chunk is all single-character operators: literals, char classes, and ?. func matchChunk(chunk, s string) (rest string, ok bool, err error) { // failed records whether the match has failed. // After the match fails, the loop continues on processing chunk, // checking that the pattern is well-formed but no longer reading s. failed := false for len(chunk) > 0 { if !failed && len(s) == 0 { failed = true } switch chunk[0] { case '[': // character class var r rune if !failed { var n int r, n = utf8.DecodeRuneInString(s) s = s[n:] } chunk = chunk[1:] // possibly negated negated := false if len(chunk) > 0 && chunk[0] == '^' { negated = true chunk = chunk[1:] } // parse all ranges match := false nrange := 0 for { if len(chunk) > 0 && chunk[0] == ']' && nrange > 0 { chunk = chunk[1:] break } var lo, hi rune if lo, chunk, err = getEsc(chunk); err != nil { return "", false, err } hi = lo if chunk[0] == '-' { if hi, chunk, err = getEsc(chunk[1:]); err != nil { return "", false, err } } if lo <= r && r <= hi { match = true } nrange++ } if match == negated { failed = true } case '?': if !failed { if s[0] == '/' { failed = true } _, n := utf8.DecodeRuneInString(s) s = s[n:] } chunk = chunk[1:] case '\\': chunk = chunk[1:] if len(chunk) == 0 { return "", false, ErrBadPattern } fallthrough default: if !failed { if chunk[0] != s[0] { failed = true } s = s[1:] } chunk = chunk[1:] } } if failed { return "", false, nil } return s, true, nil } // getEsc gets a possibly-escaped character from chunk, for a character class. func getEsc(chunk string) (r rune, nchunk string, err error) { if len(chunk) == 0 || chunk[0] == '-' || chunk[0] == ']' { err = ErrBadPattern return } if chunk[0] == '\\' { chunk = chunk[1:] if len(chunk) == 0 { err = ErrBadPattern return } } r, n := utf8.DecodeRuneInString(chunk) if r == utf8.RuneError && n == 1 { err = ErrBadPattern } nchunk = chunk[n:] if len(nchunk) == 0 { err = ErrBadPattern } return }
go/src/path/match.go/0
{ "file_path": "go/src/path/match.go", "repo_id": "go", "token_count": 2266 }
370
// Copyright 2012 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. #include "textflag.h" #include "funcdata.h" // makeFuncStub is jumped to by the code generated by MakeFunc. // See the comment on the declaration of makeFuncStub in makefunc.go // for more details. // No argsize here, gc generates argsize info at call site. TEXT ·makeFuncStub(SB),(NOSPLIT|WRAPPER),$20 NO_LOCAL_POINTERS MOVW R7, 4(R13) MOVW $argframe+0(FP), R1 MOVW R1, 8(R13) MOVW $0, R1 MOVB R1, 20(R13) ADD $20, R13, R1 MOVW R1, 12(R13) MOVW $0, R1 MOVW R1, 16(R13) BL ·callReflect(SB) RET // methodValueCall is the code half of the function returned by makeMethodValue. // See the comment on the declaration of methodValueCall in makefunc.go // for more details. // No argsize here, gc generates argsize info at call site. TEXT ·methodValueCall(SB),(NOSPLIT|WRAPPER),$20 NO_LOCAL_POINTERS MOVW R7, 4(R13) MOVW $argframe+0(FP), R1 MOVW R1, 8(R13) MOVW $0, R1 MOVB R1, 20(R13) ADD $20, R13, R1 MOVW R1, 12(R13) MOVW $0, R1 MOVW R1, 16(R13) BL ·callMethod(SB) RET
go/src/reflect/asm_arm.s/0
{ "file_path": "go/src/reflect/asm_arm.s", "repo_id": "go", "token_count": 511 }
371
// Copyright 2022 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. #include "textflag.h" // riscv64 allows 32-bit floats to live in the bottom // part of the register, it expects them to be NaN-boxed. // These functions are needed to ensure correct conversions // on riscv64. // Convert float32->uint64 TEXT ·archFloat32ToReg(SB),NOSPLIT,$0-16 MOVF val+0(FP), F1 MOVD F1, ret+8(FP) RET // Convert uint64->float32 TEXT ·archFloat32FromReg(SB),NOSPLIT,$0-12 // Normally a float64->float32 conversion // would need rounding, but riscv64 store valid // float32 in the lower 32 bits, thus we only need to // unboxed the NaN-box by store a float32. MOVD reg+0(FP), F1 MOVF F1, ret+8(FP) RET
go/src/reflect/float32reg_riscv64.s/0
{ "file_path": "go/src/reflect/float32reg_riscv64.s", "repo_id": "go", "token_count": 283 }
372
// Copyright 2021 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. package reflect_test import ( . "reflect" "strings" "testing" ) type structField struct { name string index []int } var fieldsTests = []struct { testName string val any expect []structField }{{ testName: "SimpleStruct", val: struct { A int B string C bool }{}, expect: []structField{{ name: "A", index: []int{0}, }, { name: "B", index: []int{1}, }, { name: "C", index: []int{2}, }}, }, { testName: "NonEmbeddedStructMember", val: struct { A struct { X int } }{}, expect: []structField{{ name: "A", index: []int{0}, }}, }, { testName: "EmbeddedExportedStruct", val: struct { SFG }{}, expect: []structField{{ name: "SFG", index: []int{0}, }, { name: "F", index: []int{0, 0}, }, { name: "G", index: []int{0, 1}, }}, }, { testName: "EmbeddedUnexportedStruct", val: struct { sFG }{}, expect: []structField{{ name: "sFG", index: []int{0}, }, { name: "F", index: []int{0, 0}, }, { name: "G", index: []int{0, 1}, }}, }, { testName: "TwoEmbeddedStructsWithCancelingMembers", val: struct { SFG SF }{}, expect: []structField{{ name: "SFG", index: []int{0}, }, { name: "G", index: []int{0, 1}, }, { name: "SF", index: []int{1}, }}, }, { testName: "EmbeddedStructsWithSameFieldsAtDifferentDepths", val: struct { SFGH3 SG1 SFG2 SF2 L int }{}, expect: []structField{{ name: "SFGH3", index: []int{0}, }, { name: "SFGH2", index: []int{0, 0}, }, { name: "SFGH1", index: []int{0, 0, 0}, }, { name: "SFGH", index: []int{0, 0, 0, 0}, }, { name: "H", index: []int{0, 0, 0, 0, 2}, }, { name: "SG1", index: []int{1}, }, { name: "SG", index: []int{1, 0}, }, { name: "G", index: []int{1, 0, 0}, }, { name: "SFG2", index: []int{2}, }, { name: "SFG1", index: []int{2, 0}, }, { name: "SFG", index: []int{2, 0, 0}, }, { name: "SF2", index: []int{3}, }, { name: "SF1", index: []int{3, 0}, }, { name: "SF", index: []int{3, 0, 0}, }, { name: "L", index: []int{4}, }}, }, { testName: "EmbeddedPointerStruct", val: struct { *SF }{}, expect: []structField{{ name: "SF", index: []int{0}, }, { name: "F", index: []int{0, 0}, }}, }, { testName: "EmbeddedNotAPointer", val: struct { M }{}, expect: []structField{{ name: "M", index: []int{0}, }}, }, { testName: "RecursiveEmbedding", val: Rec1{}, expect: []structField{{ name: "Rec2", index: []int{0}, }, { name: "F", index: []int{0, 0}, }, { name: "Rec1", index: []int{0, 1}, }}, }, { testName: "RecursiveEmbedding2", val: Rec2{}, expect: []structField{{ name: "F", index: []int{0}, }, { name: "Rec1", index: []int{1}, }, { name: "Rec2", index: []int{1, 0}, }}, }, { testName: "RecursiveEmbedding3", val: RS3{}, expect: []structField{{ name: "RS2", index: []int{0}, }, { name: "RS1", index: []int{1}, }, { name: "i", index: []int{1, 0}, }}, }} type SFG struct { F int G int } type SFG1 struct { SFG } type SFG2 struct { SFG1 } type SFGH struct { F int G int H int } type SFGH1 struct { SFGH } type SFGH2 struct { SFGH1 } type SFGH3 struct { SFGH2 } type SF struct { F int } type SF1 struct { SF } type SF2 struct { SF1 } type SG struct { G int } type SG1 struct { SG } type sFG struct { F int G int } type RS1 struct { i int } type RS2 struct { RS1 } type RS3 struct { RS2 RS1 } type M map[string]any type Rec1 struct { *Rec2 } type Rec2 struct { F string *Rec1 } func TestFields(t *testing.T) { for _, test := range fieldsTests { test := test t.Run(test.testName, func(t *testing.T) { typ := TypeOf(test.val) fields := VisibleFields(typ) if got, want := len(fields), len(test.expect); got != want { t.Fatalf("unexpected field count; got %d want %d", got, want) } for j, field := range fields { expect := test.expect[j] t.Logf("field %d: %s", j, expect.name) gotField := typ.FieldByIndex(field.Index) // Unfortunately, FieldByIndex does not return // a field with the same index that we passed in, // so we set it to the expected value so that // it can be compared later with the result of FieldByName. gotField.Index = field.Index expectField := typ.FieldByIndex(expect.index) // ditto. expectField.Index = expect.index if !DeepEqual(gotField, expectField) { t.Fatalf("unexpected field result\ngot %#v\nwant %#v", gotField, expectField) } // Sanity check that we can actually access the field by the // expected name. gotField1, ok := typ.FieldByName(expect.name) if !ok { t.Fatalf("field %q not accessible by name", expect.name) } if !DeepEqual(gotField1, expectField) { t.Fatalf("unexpected FieldByName result; got %#v want %#v", gotField1, expectField) } } }) } } // Must not panic with nil embedded pointer. func TestFieldByIndexErr(t *testing.T) { type A struct { S string } type B struct { *A } v := ValueOf(B{}) _, err := v.FieldByIndexErr([]int{0, 0}) if err == nil { t.Fatal("expected error") } if !strings.Contains(err.Error(), "embedded struct field A") { t.Fatal(err) } }
go/src/reflect/visiblefields_test.go/0
{ "file_path": "go/src/reflect/visiblefields_test.go", "repo_id": "go", "token_count": 2563 }
373
// Copyright 2011 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. package syntax import ( "fmt" "strings" "testing" "unicode" ) type parseTest struct { Regexp string Dump string } var parseTests = []parseTest{ // Base cases {`a`, `lit{a}`}, {`a.`, `cat{lit{a}dot{}}`}, {`a.b`, `cat{lit{a}dot{}lit{b}}`}, {`ab`, `str{ab}`}, {`a.b.c`, `cat{lit{a}dot{}lit{b}dot{}lit{c}}`}, {`abc`, `str{abc}`}, {`a|^`, `alt{lit{a}bol{}}`}, {`a|b`, `cc{0x61-0x62}`}, {`(a)`, `cap{lit{a}}`}, {`(a)|b`, `alt{cap{lit{a}}lit{b}}`}, {`a*`, `star{lit{a}}`}, {`a+`, `plus{lit{a}}`}, {`a?`, `que{lit{a}}`}, {`a{2}`, `rep{2,2 lit{a}}`}, {`a{2,3}`, `rep{2,3 lit{a}}`}, {`a{2,}`, `rep{2,-1 lit{a}}`}, {`a*?`, `nstar{lit{a}}`}, {`a+?`, `nplus{lit{a}}`}, {`a??`, `nque{lit{a}}`}, {`a{2}?`, `nrep{2,2 lit{a}}`}, {`a{2,3}?`, `nrep{2,3 lit{a}}`}, {`a{2,}?`, `nrep{2,-1 lit{a}}`}, // Malformed { } are treated as literals. {`x{1001`, `str{x{1001}`}, {`x{9876543210`, `str{x{9876543210}`}, {`x{9876543210,`, `str{x{9876543210,}`}, {`x{2,1`, `str{x{2,1}`}, {`x{1,9876543210`, `str{x{1,9876543210}`}, {``, `emp{}`}, {`|`, `emp{}`}, // alt{emp{}emp{}} but got factored {`|x|`, `alt{emp{}lit{x}emp{}}`}, {`.`, `dot{}`}, {`^`, `bol{}`}, {`$`, `eol{}`}, {`\|`, `lit{|}`}, {`\(`, `lit{(}`}, {`\)`, `lit{)}`}, {`\*`, `lit{*}`}, {`\+`, `lit{+}`}, {`\?`, `lit{?}`}, {`{`, `lit{{}`}, {`}`, `lit{}}`}, {`\.`, `lit{.}`}, {`\^`, `lit{^}`}, {`\$`, `lit{$}`}, {`\\`, `lit{\}`}, {`[ace]`, `cc{0x61 0x63 0x65}`}, {`[abc]`, `cc{0x61-0x63}`}, {`[a-z]`, `cc{0x61-0x7a}`}, {`[a]`, `lit{a}`}, {`\-`, `lit{-}`}, {`-`, `lit{-}`}, {`\_`, `lit{_}`}, {`abc`, `str{abc}`}, {`abc|def`, `alt{str{abc}str{def}}`}, {`abc|def|ghi`, `alt{str{abc}str{def}str{ghi}}`}, // Posix and Perl extensions {`[[:lower:]]`, `cc{0x61-0x7a}`}, {`[a-z]`, `cc{0x61-0x7a}`}, {`[^[:lower:]]`, `cc{0x0-0x60 0x7b-0x10ffff}`}, {`[[:^lower:]]`, `cc{0x0-0x60 0x7b-0x10ffff}`}, {`(?i)[[:lower:]]`, `cc{0x41-0x5a 0x61-0x7a 0x17f 0x212a}`}, {`(?i)[a-z]`, `cc{0x41-0x5a 0x61-0x7a 0x17f 0x212a}`}, {`(?i)[^[:lower:]]`, `cc{0x0-0x40 0x5b-0x60 0x7b-0x17e 0x180-0x2129 0x212b-0x10ffff}`}, {`(?i)[[:^lower:]]`, `cc{0x0-0x40 0x5b-0x60 0x7b-0x17e 0x180-0x2129 0x212b-0x10ffff}`}, {`\d`, `cc{0x30-0x39}`}, {`\D`, `cc{0x0-0x2f 0x3a-0x10ffff}`}, {`\s`, `cc{0x9-0xa 0xc-0xd 0x20}`}, {`\S`, `cc{0x0-0x8 0xb 0xe-0x1f 0x21-0x10ffff}`}, {`\w`, `cc{0x30-0x39 0x41-0x5a 0x5f 0x61-0x7a}`}, {`\W`, `cc{0x0-0x2f 0x3a-0x40 0x5b-0x5e 0x60 0x7b-0x10ffff}`}, {`(?i)\w`, `cc{0x30-0x39 0x41-0x5a 0x5f 0x61-0x7a 0x17f 0x212a}`}, {`(?i)\W`, `cc{0x0-0x2f 0x3a-0x40 0x5b-0x5e 0x60 0x7b-0x17e 0x180-0x2129 0x212b-0x10ffff}`}, {`[^\\]`, `cc{0x0-0x5b 0x5d-0x10ffff}`}, // { `\C`, `byte{}` }, // probably never // Unicode, negatives, and a double negative. {`\p{Braille}`, `cc{0x2800-0x28ff}`}, {`\P{Braille}`, `cc{0x0-0x27ff 0x2900-0x10ffff}`}, {`\p{^Braille}`, `cc{0x0-0x27ff 0x2900-0x10ffff}`}, {`\P{^Braille}`, `cc{0x2800-0x28ff}`}, {`\pZ`, `cc{0x20 0xa0 0x1680 0x2000-0x200a 0x2028-0x2029 0x202f 0x205f 0x3000}`}, {`[\p{Braille}]`, `cc{0x2800-0x28ff}`}, {`[\P{Braille}]`, `cc{0x0-0x27ff 0x2900-0x10ffff}`}, {`[\p{^Braille}]`, `cc{0x0-0x27ff 0x2900-0x10ffff}`}, {`[\P{^Braille}]`, `cc{0x2800-0x28ff}`}, {`[\pZ]`, `cc{0x20 0xa0 0x1680 0x2000-0x200a 0x2028-0x2029 0x202f 0x205f 0x3000}`}, {`\p{Lu}`, mkCharClass(unicode.IsUpper)}, {`[\p{Lu}]`, mkCharClass(unicode.IsUpper)}, {`(?i)[\p{Lu}]`, mkCharClass(isUpperFold)}, {`\p{Any}`, `dot{}`}, {`\p{^Any}`, `cc{}`}, // Hex, octal. {`[\012-\234]\141`, `cat{cc{0xa-0x9c}lit{a}}`}, {`[\x{41}-\x7a]\x61`, `cat{cc{0x41-0x7a}lit{a}}`}, // More interesting regular expressions. {`a{,2}`, `str{a{,2}}`}, {`\.\^\$\\`, `str{.^$\}`}, {`[a-zABC]`, `cc{0x41-0x43 0x61-0x7a}`}, {`[^a]`, `cc{0x0-0x60 0x62-0x10ffff}`}, {`[α-ε☺]`, `cc{0x3b1-0x3b5 0x263a}`}, // utf-8 {`a*{`, `cat{star{lit{a}}lit{{}}`}, // Test precedences {`(?:ab)*`, `star{str{ab}}`}, {`(ab)*`, `star{cap{str{ab}}}`}, {`ab|cd`, `alt{str{ab}str{cd}}`}, {`a(b|c)d`, `cat{lit{a}cap{cc{0x62-0x63}}lit{d}}`}, // Test flattening. {`(?:a)`, `lit{a}`}, {`(?:ab)(?:cd)`, `str{abcd}`}, {`(?:a+b+)(?:c+d+)`, `cat{plus{lit{a}}plus{lit{b}}plus{lit{c}}plus{lit{d}}}`}, {`(?:a+|b+)|(?:c+|d+)`, `alt{plus{lit{a}}plus{lit{b}}plus{lit{c}}plus{lit{d}}}`}, {`(?:a|b)|(?:c|d)`, `cc{0x61-0x64}`}, {`a|.`, `dot{}`}, {`.|a`, `dot{}`}, {`(?:[abc]|A|Z|hello|world)`, `alt{cc{0x41 0x5a 0x61-0x63}str{hello}str{world}}`}, {`(?:[abc]|A|Z)`, `cc{0x41 0x5a 0x61-0x63}`}, // Test Perl quoted literals {`\Q+|*?{[\E`, `str{+|*?{[}`}, {`\Q+\E+`, `plus{lit{+}}`}, {`\Qab\E+`, `cat{lit{a}plus{lit{b}}}`}, {`\Q\\E`, `lit{\}`}, {`\Q\\\E`, `str{\\}`}, // Test Perl \A and \z {`(?m)^`, `bol{}`}, {`(?m)$`, `eol{}`}, {`(?-m)^`, `bot{}`}, {`(?-m)$`, `eot{}`}, {`(?m)\A`, `bot{}`}, {`(?m)\z`, `eot{\z}`}, {`(?-m)\A`, `bot{}`}, {`(?-m)\z`, `eot{\z}`}, // Test named captures {`(?P<name>a)`, `cap{name:lit{a}}`}, {`(?<name>a)`, `cap{name:lit{a}}`}, // Case-folded literals {`[Aa]`, `litfold{A}`}, {`[\x{100}\x{101}]`, `litfold{Ā}`}, {`[Δδ]`, `litfold{Δ}`}, // Strings {`abcde`, `str{abcde}`}, {`[Aa][Bb]cd`, `cat{strfold{AB}str{cd}}`}, // Factoring. {`abc|abd|aef|bcx|bcy`, `alt{cat{lit{a}alt{cat{lit{b}cc{0x63-0x64}}str{ef}}}cat{str{bc}cc{0x78-0x79}}}`}, {`ax+y|ax+z|ay+w`, `cat{lit{a}alt{cat{plus{lit{x}}lit{y}}cat{plus{lit{x}}lit{z}}cat{plus{lit{y}}lit{w}}}}`}, // Bug fixes. {`(?:.)`, `dot{}`}, {`(?:x|(?:xa))`, `cat{lit{x}alt{emp{}lit{a}}}`}, {`(?:.|(?:.a))`, `cat{dot{}alt{emp{}lit{a}}}`}, {`(?:A(?:A|a))`, `cat{lit{A}litfold{A}}`}, {`(?:A|a)`, `litfold{A}`}, {`A|(?:A|a)`, `litfold{A}`}, {`(?s).`, `dot{}`}, {`(?-s).`, `dnl{}`}, {`(?:(?:^).)`, `cat{bol{}dot{}}`}, {`(?-s)(?:(?:^).)`, `cat{bol{}dnl{}}`}, {`[\s\S]a`, `cat{cc{0x0-0x10ffff}lit{a}}`}, // RE2 prefix_tests {`abc|abd`, `cat{str{ab}cc{0x63-0x64}}`}, {`a(?:b)c|abd`, `cat{str{ab}cc{0x63-0x64}}`}, {`abc|abd|aef|bcx|bcy`, `alt{cat{lit{a}alt{cat{lit{b}cc{0x63-0x64}}str{ef}}}` + `cat{str{bc}cc{0x78-0x79}}}`}, {`abc|x|abd`, `alt{str{abc}lit{x}str{abd}}`}, {`(?i)abc|ABD`, `cat{strfold{AB}cc{0x43-0x44 0x63-0x64}}`}, {`[ab]c|[ab]d`, `cat{cc{0x61-0x62}cc{0x63-0x64}}`}, {`.c|.d`, `cat{dot{}cc{0x63-0x64}}`}, {`x{2}|x{2}[0-9]`, `cat{rep{2,2 lit{x}}alt{emp{}cc{0x30-0x39}}}`}, {`x{2}y|x{2}[0-9]y`, `cat{rep{2,2 lit{x}}alt{lit{y}cat{cc{0x30-0x39}lit{y}}}}`}, {`a.*?c|a.*?b`, `cat{lit{a}alt{cat{nstar{dot{}}lit{c}}cat{nstar{dot{}}lit{b}}}}`}, // Valid repetitions. {`((((((((((x{2}){2}){2}){2}){2}){2}){2}){2}){2}))`, ``}, {`((((((((((x{1}){2}){2}){2}){2}){2}){2}){2}){2}){2})`, ``}, // Valid nesting. {strings.Repeat("(", 999) + strings.Repeat(")", 999), ``}, {strings.Repeat("(?:", 999) + strings.Repeat(")*", 999), ``}, {"(" + strings.Repeat("|", 12345) + ")", ``}, // not nested at all } const testFlags = MatchNL | PerlX | UnicodeGroups func TestParseSimple(t *testing.T) { testParseDump(t, parseTests, testFlags) } var foldcaseTests = []parseTest{ {`AbCdE`, `strfold{ABCDE}`}, {`[Aa]`, `litfold{A}`}, {`a`, `litfold{A}`}, // 0x17F is an old English long s (looks like an f) and folds to s. // 0x212A is the Kelvin symbol and folds to k. {`A[F-g]`, `cat{litfold{A}cc{0x41-0x7a 0x17f 0x212a}}`}, // [Aa][A-z...] {`[[:upper:]]`, `cc{0x41-0x5a 0x61-0x7a 0x17f 0x212a}`}, {`[[:lower:]]`, `cc{0x41-0x5a 0x61-0x7a 0x17f 0x212a}`}, } func TestParseFoldCase(t *testing.T) { testParseDump(t, foldcaseTests, FoldCase) } var literalTests = []parseTest{ {"(|)^$.[*+?]{5,10},\\", "str{(|)^$.[*+?]{5,10},\\}"}, } func TestParseLiteral(t *testing.T) { testParseDump(t, literalTests, Literal) } var matchnlTests = []parseTest{ {`.`, `dot{}`}, {"\n", "lit{\n}"}, {`[^a]`, `cc{0x0-0x60 0x62-0x10ffff}`}, {`[a\n]`, `cc{0xa 0x61}`}, } func TestParseMatchNL(t *testing.T) { testParseDump(t, matchnlTests, MatchNL) } var nomatchnlTests = []parseTest{ {`.`, `dnl{}`}, {"\n", "lit{\n}"}, {`[^a]`, `cc{0x0-0x9 0xb-0x60 0x62-0x10ffff}`}, {`[a\n]`, `cc{0xa 0x61}`}, } func TestParseNoMatchNL(t *testing.T) { testParseDump(t, nomatchnlTests, 0) } // Test Parse -> Dump. func testParseDump(t *testing.T, tests []parseTest, flags Flags) { for _, tt := range tests { re, err := Parse(tt.Regexp, flags) if err != nil { t.Errorf("Parse(%#q): %v", tt.Regexp, err) continue } if tt.Dump == "" { // It parsed. That's all we care about. continue } d := dump(re) if d != tt.Dump { t.Errorf("Parse(%#q).Dump() = %#q want %#q", tt.Regexp, d, tt.Dump) } } } // dump prints a string representation of the regexp showing // the structure explicitly. func dump(re *Regexp) string { var b strings.Builder dumpRegexp(&b, re) return b.String() } var opNames = []string{ OpNoMatch: "no", OpEmptyMatch: "emp", OpLiteral: "lit", OpCharClass: "cc", OpAnyCharNotNL: "dnl", OpAnyChar: "dot", OpBeginLine: "bol", OpEndLine: "eol", OpBeginText: "bot", OpEndText: "eot", OpWordBoundary: "wb", OpNoWordBoundary: "nwb", OpCapture: "cap", OpStar: "star", OpPlus: "plus", OpQuest: "que", OpRepeat: "rep", OpConcat: "cat", OpAlternate: "alt", } // dumpRegexp writes an encoding of the syntax tree for the regexp re to b. // It is used during testing to distinguish between parses that might print // the same using re's String method. func dumpRegexp(b *strings.Builder, re *Regexp) { if int(re.Op) >= len(opNames) || opNames[re.Op] == "" { fmt.Fprintf(b, "op%d", re.Op) } else { switch re.Op { default: b.WriteString(opNames[re.Op]) case OpStar, OpPlus, OpQuest, OpRepeat: if re.Flags&NonGreedy != 0 { b.WriteByte('n') } b.WriteString(opNames[re.Op]) case OpLiteral: if len(re.Rune) > 1 { b.WriteString("str") } else { b.WriteString("lit") } if re.Flags&FoldCase != 0 { for _, r := range re.Rune { if unicode.SimpleFold(r) != r { b.WriteString("fold") break } } } } } b.WriteByte('{') switch re.Op { case OpEndText: if re.Flags&WasDollar == 0 { b.WriteString(`\z`) } case OpLiteral: for _, r := range re.Rune { b.WriteRune(r) } case OpConcat, OpAlternate: for _, sub := range re.Sub { dumpRegexp(b, sub) } case OpStar, OpPlus, OpQuest: dumpRegexp(b, re.Sub[0]) case OpRepeat: fmt.Fprintf(b, "%d,%d ", re.Min, re.Max) dumpRegexp(b, re.Sub[0]) case OpCapture: if re.Name != "" { b.WriteString(re.Name) b.WriteByte(':') } dumpRegexp(b, re.Sub[0]) case OpCharClass: sep := "" for i := 0; i < len(re.Rune); i += 2 { b.WriteString(sep) sep = " " lo, hi := re.Rune[i], re.Rune[i+1] if lo == hi { fmt.Fprintf(b, "%#x", lo) } else { fmt.Fprintf(b, "%#x-%#x", lo, hi) } } } b.WriteByte('}') } func mkCharClass(f func(rune) bool) string { re := &Regexp{Op: OpCharClass} lo := rune(-1) for i := rune(0); i <= unicode.MaxRune; i++ { if f(i) { if lo < 0 { lo = i } } else { if lo >= 0 { re.Rune = append(re.Rune, lo, i-1) lo = -1 } } } if lo >= 0 { re.Rune = append(re.Rune, lo, unicode.MaxRune) } return dump(re) } func isUpperFold(r rune) bool { if unicode.IsUpper(r) { return true } c := unicode.SimpleFold(r) for c != r { if unicode.IsUpper(c) { return true } c = unicode.SimpleFold(c) } return false } func TestFoldConstants(t *testing.T) { last := rune(-1) for i := rune(0); i <= unicode.MaxRune; i++ { if unicode.SimpleFold(i) == i { continue } if last == -1 && minFold != i { t.Errorf("minFold=%#U should be %#U", minFold, i) } last = i } if maxFold != last { t.Errorf("maxFold=%#U should be %#U", maxFold, last) } } func TestAppendRangeCollapse(t *testing.T) { // AppendRange should collapse each of the new ranges // into the earlier ones (it looks back two ranges), so that // the slice never grows very large. // Note that we are not calling cleanClass. var r []rune for i := rune('A'); i <= 'Z'; i++ { r = appendRange(r, i, i) r = appendRange(r, i+'a'-'A', i+'a'-'A') } if string(r) != "AZaz" { t.Errorf("appendRange interlaced A-Z a-z = %s, want AZaz", string(r)) } } var invalidRegexps = []string{ `(`, `)`, `(a`, `a)`, `(a))`, `(a|b|`, `a|b|)`, `(a|b|))`, `(a|b`, `a|b)`, `(a|b))`, `[a-z`, `([a-z)`, `[a-z)`, `([a-z]))`, `x{1001}`, `x{9876543210}`, `x{2,1}`, `x{1,9876543210}`, "\xff", // Invalid UTF-8 "[\xff]", "[\\\xff]", "\\\xff", `(?P<name>a`, `(?P<name>`, `(?P<name`, `(?P<x y>a)`, `(?P<>a)`, `(?<name>a`, `(?<name>`, `(?<name`, `(?<x y>a)`, `(?<>a)`, `[a-Z]`, `(?i)[a-Z]`, `\Q\E*`, `a{100000}`, // too much repetition `a{100000,}`, // too much repetition "((((((((((x{2}){2}){2}){2}){2}){2}){2}){2}){2}){2})", // too much repetition strings.Repeat("(", 1000) + strings.Repeat(")", 1000), // too deep strings.Repeat("(?:", 1000) + strings.Repeat(")*", 1000), // too deep "(" + strings.Repeat("(xx?)", 1000) + "){1000}", // too long strings.Repeat("(xx?){1000}", 1000), // too long strings.Repeat(`\pL`, 27000), // too many runes } var onlyPerl = []string{ `[a-b-c]`, `\Qabc\E`, `\Q*+?{[\E`, `\Q\\E`, `\Q\\\E`, `\Q\\\\E`, `\Q\\\\\E`, `(?:a)`, `(?P<name>a)`, } var onlyPOSIX = []string{ "a++", "a**", "a?*", "a+*", "a{1}*", ".{1}{2}.{3}", } func TestParseInvalidRegexps(t *testing.T) { for _, regexp := range invalidRegexps { if re, err := Parse(regexp, Perl); err == nil { t.Errorf("Parse(%#q, Perl) = %s, should have failed", regexp, dump(re)) } if re, err := Parse(regexp, POSIX); err == nil { t.Errorf("Parse(%#q, POSIX) = %s, should have failed", regexp, dump(re)) } } for _, regexp := range onlyPerl { if _, err := Parse(regexp, Perl); err != nil { t.Errorf("Parse(%#q, Perl): %v", regexp, err) } if re, err := Parse(regexp, POSIX); err == nil { t.Errorf("Parse(%#q, POSIX) = %s, should have failed", regexp, dump(re)) } } for _, regexp := range onlyPOSIX { if re, err := Parse(regexp, Perl); err == nil { t.Errorf("Parse(%#q, Perl) = %s, should have failed", regexp, dump(re)) } if _, err := Parse(regexp, POSIX); err != nil { t.Errorf("Parse(%#q, POSIX): %v", regexp, err) } } } func TestToStringEquivalentParse(t *testing.T) { for _, tt := range parseTests { re, err := Parse(tt.Regexp, testFlags) if err != nil { t.Errorf("Parse(%#q): %v", tt.Regexp, err) continue } if tt.Dump == "" { // It parsed. That's all we care about. continue } d := dump(re) if d != tt.Dump { t.Errorf("Parse(%#q).Dump() = %#q want %#q", tt.Regexp, d, tt.Dump) continue } s := re.String() if s != tt.Regexp { // If ToString didn't return the original regexp, // it must have found one with fewer parens. // Unfortunately we can't check the length here, because // ToString produces "\\{" for a literal brace, // but "{" is a shorter equivalent in some contexts. nre, err := Parse(s, testFlags) if err != nil { t.Errorf("Parse(%#q.String() = %#q): %v", tt.Regexp, s, err) continue } nd := dump(nre) if d != nd { t.Errorf("Parse(%#q) -> %#q; %#q vs %#q", tt.Regexp, s, d, nd) } ns := nre.String() if s != ns { t.Errorf("Parse(%#q) -> %#q -> %#q", tt.Regexp, s, ns) } } } } var stringTests = []struct { re string out string }{ {`x(?i:ab*c|d?e)1`, `x(?i:AB*C|D?E)1`}, {`x(?i:ab*cd?e)1`, `x(?i:AB*CD?E)1`}, {`0(?i:ab*c|d?e)1`, `(?i:0(?:AB*C|D?E)1)`}, {`0(?i:ab*cd?e)1`, `(?i:0AB*CD?E1)`}, {`x(?i:ab*c|d?e)`, `x(?i:AB*C|D?E)`}, {`x(?i:ab*cd?e)`, `x(?i:AB*CD?E)`}, {`0(?i:ab*c|d?e)`, `(?i:0(?:AB*C|D?E))`}, {`0(?i:ab*cd?e)`, `(?i:0AB*CD?E)`}, {`(?i:ab*c|d?e)1`, `(?i:(?:AB*C|D?E)1)`}, {`(?i:ab*cd?e)1`, `(?i:AB*CD?E1)`}, {`(?i:ab)[123](?i:cd)`, `(?i:AB[1-3]CD)`}, {`(?i:ab*c|d?e)`, `(?i:AB*C|D?E)`}, {`[Aa][Bb]`, `(?i:AB)`}, {`[Aa][Bb]*[Cc]`, `(?i:AB*C)`}, {`A(?:[Bb][Cc]|[Dd])[Zz]`, `A(?i:(?:BC|D)Z)`}, {`[Aa](?:[Bb][Cc]|[Dd])Z`, `(?i:A(?:BC|D))Z`}, } func TestString(t *testing.T) { for _, tt := range stringTests { re, err := Parse(tt.re, Perl) if err != nil { t.Errorf("Parse(%#q): %v", tt.re, err) continue } out := re.String() if out != tt.out { t.Errorf("Parse(%#q).String() = %#q, want %#q", tt.re, out, tt.out) } } }
go/src/regexp/syntax/parse_test.go/0
{ "file_path": "go/src/regexp/syntax/parse_test.go", "repo_id": "go", "token_count": 9436 }
374
#!/bin/rc -e # Copyright 2012 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. rfork e if(! test -f ../bin/go){ echo 'run.rc must be run from $GOROOT/src after installing cmd/go' >[1=2] exit wrongdir } GOENV=off eval `{../bin/go tool dist env} GOPATH=/nonexist-gopath exec ../bin/go tool dist test -rebuild $*
go/src/run.rc/0
{ "file_path": "go/src/run.rc", "repo_id": "go", "token_count": 149 }
375
// Copyright 2022 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. //go:build asan #include "go_asm.h" #include "textflag.h" // Called from instrumented code. // func runtime·doasanread(addr unsafe.Pointer, sz, sp, pc uintptr) TEXT runtime·doasanread(SB), NOSPLIT, $0-32 MOV addr+0(FP), X10 MOV sz+8(FP), X11 MOV sp+16(FP), X12 MOV pc+24(FP), X13 // void __asan_read_go(void *addr, uintptr_t sz); MOV $__asan_read_go(SB), X14 JMP asancall<>(SB) // func runtime·doasanwrite(addr unsafe.Pointer, sz, sp, pc uintptr) TEXT runtime·doasanwrite(SB), NOSPLIT, $0-32 MOV addr+0(FP), X10 MOV sz+8(FP), X11 MOV sp+16(FP), X12 MOV pc+24(FP), X13 // void __asan_write_go(void *addr, uintptr_t sz); MOV $__asan_write_go(SB), X14 JMP asancall<>(SB) // func runtime·asanunpoison(addr unsafe.Pointer, sz uintptr) TEXT runtime·asanunpoison(SB), NOSPLIT, $0-16 MOV addr+0(FP), X10 MOV sz+8(FP), X11 // void __asan_unpoison_go(void *addr, uintptr_t sz); MOV $__asan_unpoison_go(SB), X14 JMP asancall<>(SB) // func runtime·asanpoison(addr unsafe.Pointer, sz uintptr) TEXT runtime·asanpoison(SB), NOSPLIT, $0-16 MOV addr+0(FP), X10 MOV sz+8(FP), X11 // void __asan_poison_go(void *addr, uintptr_t sz); MOV $__asan_poison_go(SB), X14 JMP asancall<>(SB) // func runtime·asanregisterglobals(addr unsafe.Pointer, n uintptr) TEXT runtime·asanregisterglobals(SB), NOSPLIT, $0-16 MOV addr+0(FP), X10 MOV n+8(FP), X11 // void __asan_register_globals_go(void *addr, uintptr_t n); MOV $__asan_register_globals_go(SB), X14 JMP asancall<>(SB) // Switches SP to g0 stack and calls (X14). Arguments already set. TEXT asancall<>(SB), NOSPLIT, $0-0 MOV X2, X8 // callee-saved BEQZ g, g0stack // no g, still on a system stack MOV g_m(g), X21 MOV m_g0(X21), X21 BEQ X21, g, g0stack MOV (g_sched+gobuf_sp)(X21), X2 g0stack: JALR RA, X14 MOV X8, X2 RET
go/src/runtime/asan_riscv64.s/0
{ "file_path": "go/src/runtime/asan_riscv64.s", "repo_id": "go", "token_count": 938 }
376
// Copyright 2009 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. #include "textflag.h" #include "abi_amd64.h" // Set the x_crosscall2_ptr C function pointer variable point to crosscall2. // It's such a pointer chain: _crosscall2_ptr -> x_crosscall2_ptr -> crosscall2 // Use a local trampoline, to avoid taking the address of a dynamically exported // function. TEXT ·set_crosscall2(SB),NOSPLIT,$0-0 MOVQ _crosscall2_ptr(SB), AX MOVQ $crosscall2_trampoline<>(SB), BX MOVQ BX, (AX) RET TEXT crosscall2_trampoline<>(SB),NOSPLIT,$0-0 JMP crosscall2(SB) // Called by C code generated by cmd/cgo. // func crosscall2(fn, a unsafe.Pointer, n int32, ctxt uintptr) // Saves C callee-saved registers and calls cgocallback with three arguments. // fn is the PC of a func(a unsafe.Pointer) function. // This signature is known to SWIG, so we can't change it. TEXT crosscall2(SB),NOSPLIT,$0-0 PUSH_REGS_HOST_TO_ABI0() // Make room for arguments to cgocallback. ADJSP $0x18 #ifndef GOOS_windows MOVQ DI, 0x0(SP) /* fn */ MOVQ SI, 0x8(SP) /* arg */ // Skip n in DX. MOVQ CX, 0x10(SP) /* ctxt */ #else MOVQ CX, 0x0(SP) /* fn */ MOVQ DX, 0x8(SP) /* arg */ // Skip n in R8. MOVQ R9, 0x10(SP) /* ctxt */ #endif CALL runtime·cgocallback(SB) ADJSP $-0x18 POP_REGS_HOST_TO_ABI0() RET
go/src/runtime/cgo/asm_amd64.s/0
{ "file_path": "go/src/runtime/cgo/asm_amd64.s", "repo_id": "go", "token_count": 581 }
377
// Copyright 2009 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. .file "gcc_386.S" /* * Windows still insists on underscore prefixes for C function names. */ #if defined(_WIN32) #define EXT(s) _##s #else #define EXT(s) s #endif /* * void crosscall1(void (*fn)(void), void (*setg_gcc)(void*), void *g) * * Calling into the gc tool chain, where all registers are caller save. * Called from standard x86 ABI, where %ebp, %ebx, %esi, * and %edi are callee-save, so they must be saved explicitly. */ .globl EXT(crosscall1) EXT(crosscall1): pushl %ebp movl %esp, %ebp pushl %ebx pushl %esi pushl %edi movl 16(%ebp), %eax /* g */ pushl %eax movl 12(%ebp), %eax /* setg_gcc */ call *%eax popl %eax movl 8(%ebp), %eax /* fn */ call *%eax popl %edi popl %esi popl %ebx popl %ebp ret #ifdef __ELF__ .section .note.GNU-stack,"",@progbits #endif
go/src/runtime/cgo/gcc_386.S/0
{ "file_path": "go/src/runtime/cgo/gcc_386.S", "repo_id": "go", "token_count": 391 }
378
// Copyright 2015 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. #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <process.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include "libcgo.h" #include "libcgo_windows.h" // Ensure there's one symbol marked __declspec(dllexport). // If there are no exported symbols, the unfortunate behavior of // the binutils linker is to also strip the relocations table, // resulting in non-PIE binary. The other option is the // --export-all-symbols flag, but we don't need to export all symbols // and this may overflow the export table (#40795). // See https://sourceware.org/bugzilla/show_bug.cgi?id=19011 __declspec(dllexport) int _cgo_dummy_export; static volatile LONG runtime_init_once_gate = 0; static volatile LONG runtime_init_once_done = 0; static CRITICAL_SECTION runtime_init_cs; static HANDLE runtime_init_wait; static int runtime_init_done; uintptr_t x_cgo_pthread_key_created; void (*x_crosscall2_ptr)(void (*fn)(void *), void *, int, size_t); // Pre-initialize the runtime synchronization objects void _cgo_preinit_init() { runtime_init_wait = CreateEvent(NULL, TRUE, FALSE, NULL); if (runtime_init_wait == NULL) { fprintf(stderr, "runtime: failed to create runtime initialization wait event.\n"); abort(); } InitializeCriticalSection(&runtime_init_cs); } // Make sure that the preinit sequence has run. void _cgo_maybe_run_preinit() { if (!InterlockedExchangeAdd(&runtime_init_once_done, 0)) { if (InterlockedIncrement(&runtime_init_once_gate) == 1) { _cgo_preinit_init(); InterlockedIncrement(&runtime_init_once_done); } else { // Decrement to avoid overflow. InterlockedDecrement(&runtime_init_once_gate); while(!InterlockedExchangeAdd(&runtime_init_once_done, 0)) { Sleep(0); } } } } void x_cgo_sys_thread_create(void (*func)(void*), void* arg) { _cgo_beginthread(func, arg); } int _cgo_is_runtime_initialized() { EnterCriticalSection(&runtime_init_cs); int status = runtime_init_done; LeaveCriticalSection(&runtime_init_cs); return status; } uintptr_t _cgo_wait_runtime_init_done(void) { void (*pfn)(struct context_arg*); _cgo_maybe_run_preinit(); while (!_cgo_is_runtime_initialized()) { WaitForSingleObject(runtime_init_wait, INFINITE); } pfn = _cgo_get_context_function(); if (pfn != nil) { struct context_arg arg; arg.Context = 0; (*pfn)(&arg); return arg.Context; } return 0; } // Should not be used since x_cgo_pthread_key_created will always be zero. void x_cgo_bindm(void* dummy) { fprintf(stderr, "unexpected cgo_bindm on Windows\n"); abort(); } void x_cgo_notify_runtime_init_done(void* dummy) { _cgo_maybe_run_preinit(); EnterCriticalSection(&runtime_init_cs); runtime_init_done = 1; LeaveCriticalSection(&runtime_init_cs); if (!SetEvent(runtime_init_wait)) { fprintf(stderr, "runtime: failed to signal runtime initialization complete.\n"); abort(); } } // The context function, used when tracing back C calls into Go. static void (*cgo_context_function)(struct context_arg*); // Sets the context function to call to record the traceback context // when calling a Go function from C code. Called from runtime.SetCgoTraceback. void x_cgo_set_context_function(void (*context)(struct context_arg*)) { EnterCriticalSection(&runtime_init_cs); cgo_context_function = context; LeaveCriticalSection(&runtime_init_cs); } // Gets the context function. void (*(_cgo_get_context_function(void)))(struct context_arg*) { void (*ret)(struct context_arg*); EnterCriticalSection(&runtime_init_cs); ret = cgo_context_function; LeaveCriticalSection(&runtime_init_cs); return ret; } void _cgo_beginthread(void (*func)(void*), void* arg) { int tries; uintptr_t thandle; for (tries = 0; tries < 20; tries++) { thandle = _beginthread(func, 0, arg); if (thandle == -1 && errno == EACCES) { // "Insufficient resources", try again in a bit. // // Note that the first Sleep(0) is a yield. Sleep(tries); // milliseconds continue; } else if (thandle == -1) { break; } return; // Success! } fprintf(stderr, "runtime: failed to create new OS thread (%d)\n", errno); abort(); }
go/src/runtime/cgo/gcc_libinit_windows.c/0
{ "file_path": "go/src/runtime/cgo/gcc_libinit_windows.c", "repo_id": "go", "token_count": 1535 }
379
// Copyright 2016 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. //go:build linux && (amd64 || arm64 || ppc64le) #include <errno.h> #include <stddef.h> #include <stdint.h> #include <string.h> #include <signal.h> #include "libcgo.h" // go_sigaction_t is a C version of the sigactiont struct from // defs_linux_amd64.go. This definition — and its conversion to and from struct // sigaction — are specific to linux/amd64. typedef struct { uintptr_t handler; uint64_t flags; uintptr_t restorer; uint64_t mask; } go_sigaction_t; // SA_RESTORER is part of the kernel interface. // This is Linux i386/amd64 specific. #ifndef SA_RESTORER #define SA_RESTORER 0x4000000 #endif int32_t x_cgo_sigaction(intptr_t signum, const go_sigaction_t *goact, go_sigaction_t *oldgoact) { int32_t ret; struct sigaction act; struct sigaction oldact; size_t i; _cgo_tsan_acquire(); memset(&act, 0, sizeof act); memset(&oldact, 0, sizeof oldact); if (goact) { if (goact->flags & SA_SIGINFO) { act.sa_sigaction = (void(*)(int, siginfo_t*, void*))(goact->handler); } else { act.sa_handler = (void(*)(int))(goact->handler); } sigemptyset(&act.sa_mask); for (i = 0; i < 8 * sizeof(goact->mask); i++) { if (goact->mask & ((uint64_t)(1)<<i)) { sigaddset(&act.sa_mask, (int)(i+1)); } } act.sa_flags = (int)(goact->flags & ~(uint64_t)SA_RESTORER); } ret = sigaction((int)signum, goact ? &act : NULL, oldgoact ? &oldact : NULL); if (ret == -1) { // runtime.rt_sigaction expects _cgo_sigaction to return errno on error. _cgo_tsan_release(); return errno; } if (oldgoact) { if (oldact.sa_flags & SA_SIGINFO) { oldgoact->handler = (uintptr_t)(oldact.sa_sigaction); } else { oldgoact->handler = (uintptr_t)(oldact.sa_handler); } oldgoact->mask = 0; for (i = 0; i < 8 * sizeof(oldgoact->mask); i++) { if (sigismember(&oldact.sa_mask, (int)(i+1)) == 1) { oldgoact->mask |= (uint64_t)(1)<<i; } } oldgoact->flags = (uint64_t)oldact.sa_flags; } _cgo_tsan_release(); return ret; }
go/src/runtime/cgo/gcc_sigaction.c/0
{ "file_path": "go/src/runtime/cgo/gcc_sigaction.c", "repo_id": "go", "token_count": 923 }
380
// Copyright 2009 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. #include <stdint.h> #include <stdlib.h> #include <stdio.h> #undef nil #define nil ((void*)0) #define nelem(x) (sizeof(x)/sizeof((x)[0])) typedef uint32_t uint32; typedef uint64_t uint64; typedef uintptr_t uintptr; /* * The beginning of the per-goroutine structure, * as defined in ../pkg/runtime/runtime.h. * Just enough to edit these two fields. */ typedef struct G G; struct G { uintptr stacklo; uintptr stackhi; }; /* * Arguments to the _cgo_thread_start call. * Also known to ../pkg/runtime/runtime.h. */ typedef struct ThreadStart ThreadStart; struct ThreadStart { G *g; uintptr *tls; void (*fn)(void); }; /* * Called by 5c/6c/8c world. * Makes a local copy of the ThreadStart and * calls _cgo_sys_thread_start(ts). */ extern void (*_cgo_thread_start)(ThreadStart *ts); /* * Creates a new operating system thread without updating any Go state * (OS dependent). */ extern void (*_cgo_sys_thread_create)(void* (*func)(void*), void* arg); /* * Indicates whether a dummy pthread per-thread variable is allocated. */ extern uintptr_t *_cgo_pthread_key_created; /* * Creates the new operating system thread (OS, arch dependent). */ void _cgo_sys_thread_start(ThreadStart *ts); /* * Waits for the Go runtime to be initialized (OS dependent). * If runtime.SetCgoTraceback is used to set a context function, * calls the context function and returns the context value. */ uintptr_t _cgo_wait_runtime_init_done(void); /* * Get the low and high boundaries of the stack. */ void x_cgo_getstackbound(uintptr bounds[2]); /* * Prints error then calls abort. For linux and android. */ void fatalf(const char* format, ...) __attribute__ ((noreturn)); /* * Registers the current mach thread port for EXC_BAD_ACCESS processing. */ void darwin_arm_init_thread_exception_port(void); /* * Starts a mach message server processing EXC_BAD_ACCESS. */ void darwin_arm_init_mach_exception_handler(void); /* * The cgo context function. See runtime.SetCgoTraceback. */ struct context_arg { uintptr_t Context; }; extern void (*(_cgo_get_context_function(void)))(struct context_arg*); /* * The argument for the cgo traceback callback. See runtime.SetCgoTraceback. */ struct cgoTracebackArg { uintptr_t Context; uintptr_t SigContext; uintptr_t* Buf; uintptr_t Max; }; /* * TSAN support. This is only useful when building with * CGO_CFLAGS="-fsanitize=thread" CGO_LDFLAGS="-fsanitize=thread" go install */ #undef CGO_TSAN #if defined(__has_feature) # if __has_feature(thread_sanitizer) # define CGO_TSAN # endif #elif defined(__SANITIZE_THREAD__) # define CGO_TSAN #endif #ifdef CGO_TSAN // These must match the definitions in yesTsanProlog in cmd/cgo/out.go. // In general we should call _cgo_tsan_acquire when we enter C code, // and call _cgo_tsan_release when we return to Go code. // This is only necessary when calling code that might be instrumented // by TSAN, which mostly means system library calls that TSAN intercepts. // See the comment in cmd/cgo/out.go for more details. long long _cgo_sync __attribute__ ((common)); extern void __tsan_acquire(void*); extern void __tsan_release(void*); __attribute__ ((unused)) static void _cgo_tsan_acquire() { __tsan_acquire(&_cgo_sync); } __attribute__ ((unused)) static void _cgo_tsan_release() { __tsan_release(&_cgo_sync); } #else // !defined(CGO_TSAN) #define _cgo_tsan_acquire() #define _cgo_tsan_release() #endif // !defined(CGO_TSAN)
go/src/runtime/cgo/libcgo.h/0
{ "file_path": "go/src/runtime/cgo/libcgo.h", "repo_id": "go", "token_count": 1271 }
381
// Copyright 2022 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. package runtime import ( "internal/coverage/rtcov" "unsafe" ) // The compiler emits calls to runtime.addCovMeta // but this code has moved to rtcov.AddMeta. func addCovMeta(p unsafe.Pointer, dlen uint32, hash [16]byte, pkgpath string, pkgid int, cmode uint8, cgran uint8) uint32 { id := rtcov.AddMeta(p, dlen, hash, pkgpath, pkgid, cmode, cgran) if id == 0 { throw("runtime.addCovMeta: coverage package map collision") } return id }
go/src/runtime/covermeta.go/0
{ "file_path": "go/src/runtime/covermeta.go", "repo_id": "go", "token_count": 209 }
382
// Copyright 2014 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. package debug_test import ( "os" "runtime" . "runtime/debug" "testing" ) func TestWriteHeapDumpNonempty(t *testing.T) { if runtime.GOOS == "js" { t.Skipf("WriteHeapDump is not available on %s.", runtime.GOOS) } f, err := os.CreateTemp("", "heapdumptest") if err != nil { t.Fatalf("TempFile failed: %v", err) } defer os.Remove(f.Name()) defer f.Close() WriteHeapDump(f.Fd()) fi, err := f.Stat() if err != nil { t.Fatalf("Stat failed: %v", err) } const minSize = 1 if size := fi.Size(); size < minSize { t.Fatalf("Heap dump size %d bytes, expected at least %d bytes", size, minSize) } } type Obj struct { x, y int } func objfin(x *Obj) { //println("finalized", x) } func TestWriteHeapDumpFinalizers(t *testing.T) { if runtime.GOOS == "js" { t.Skipf("WriteHeapDump is not available on %s.", runtime.GOOS) } f, err := os.CreateTemp("", "heapdumptest") if err != nil { t.Fatalf("TempFile failed: %v", err) } defer os.Remove(f.Name()) defer f.Close() // bug 9172: WriteHeapDump couldn't handle more than one finalizer println("allocating objects") x := &Obj{} runtime.SetFinalizer(x, objfin) y := &Obj{} runtime.SetFinalizer(y, objfin) // Trigger collection of x and y, queueing of their finalizers. println("starting gc") runtime.GC() // Make sure WriteHeapDump doesn't fail with multiple queued finalizers. println("starting dump") WriteHeapDump(f.Fd()) println("done dump") } type G[T any] struct{} type I interface { M() } //go:noinline func (g G[T]) M() {} var dummy I = G[int]{} var dummy2 I = G[G[int]]{} func TestWriteHeapDumpTypeName(t *testing.T) { if runtime.GOOS == "js" { t.Skipf("WriteHeapDump is not available on %s.", runtime.GOOS) } f, err := os.CreateTemp("", "heapdumptest") if err != nil { t.Fatalf("TempFile failed: %v", err) } defer os.Remove(f.Name()) defer f.Close() WriteHeapDump(f.Fd()) dummy.M() dummy2.M() }
go/src/runtime/debug/heapdump_test.go/0
{ "file_path": "go/src/runtime/debug/heapdump_test.go", "repo_id": "go", "token_count": 839 }
383
// Copyright 2019 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. package runtime_test import ( "runtime" "slices" "testing" ) // Make sure open-coded defer exit code is not lost, even when there is an // unconditional panic (hence no return from the function) func TestUnconditionalPanic(t *testing.T) { defer func() { if recover() != "testUnconditional" { t.Fatal("expected unconditional panic") } }() panic("testUnconditional") } var glob int = 3 // Test an open-coded defer and non-open-coded defer - make sure both defers run // and call recover() func TestOpenAndNonOpenDefers(t *testing.T) { for { // Non-open defer because in a loop defer func(n int) { if recover() != "testNonOpenDefer" { t.Fatal("expected testNonOpen panic") } }(3) if glob > 2 { break } } testOpen(t, 47) panic("testNonOpenDefer") } //go:noinline func testOpen(t *testing.T, arg int) { defer func(n int) { if recover() != "testOpenDefer" { t.Fatal("expected testOpen panic") } }(4) if arg > 2 { panic("testOpenDefer") } } // Test a non-open-coded defer and an open-coded defer - make sure both defers run // and call recover() func TestNonOpenAndOpenDefers(t *testing.T) { testOpen(t, 47) for { // Non-open defer because in a loop defer func(n int) { if recover() != "testNonOpenDefer" { t.Fatal("expected testNonOpen panic") } }(3) if glob > 2 { break } } panic("testNonOpenDefer") } var list []int // Make sure that conditional open-coded defers are activated correctly and run in // the correct order. func TestConditionalDefers(t *testing.T) { list = make([]int, 0, 10) defer func() { if recover() != "testConditional" { t.Fatal("expected panic") } want := []int{4, 2, 1} if !slices.Equal(want, list) { t.Fatalf("wanted %v, got %v", want, list) } }() testConditionalDefers(8) } func testConditionalDefers(n int) { doappend := func(i int) { list = append(list, i) } defer doappend(1) if n > 5 { defer doappend(2) if n > 8 { defer doappend(3) } else { defer doappend(4) } } panic("testConditional") } // Test that there is no compile-time or run-time error if an open-coded defer // call is removed by constant propagation and dead-code elimination. func TestDisappearingDefer(t *testing.T) { switch runtime.GOOS { case "invalidOS": defer func() { t.Fatal("Defer shouldn't run") }() } } // This tests an extra recursive panic behavior that is only specified in the // code. Suppose a first panic P1 happens and starts processing defer calls. If a // second panic P2 happens while processing defer call D in frame F, then defer // call processing is restarted (with some potentially new defer calls created by // D or its callees). If the defer processing reaches the started defer call D // again in the defer stack, then the original panic P1 is aborted and cannot // continue panic processing or be recovered. If the panic P2 does a recover at // some point, it will naturally remove the original panic P1 from the stack // (since the original panic had to be in frame F or a descendant of F). func TestAbortedPanic(t *testing.T) { defer func() { r := recover() if r != nil { t.Fatalf("wanted nil recover, got %v", r) } }() defer func() { r := recover() if r != "panic2" { t.Fatalf("wanted %v, got %v", "panic2", r) } }() defer func() { panic("panic2") }() panic("panic1") } // This tests that recover() does not succeed unless it is called directly from a // defer function that is directly called by the panic. Here, we first call it // from a defer function that is created by the defer function called directly by // the panic. In func TestRecoverMatching(t *testing.T) { defer func() { r := recover() if r != "panic1" { t.Fatalf("wanted %v, got %v", "panic1", r) } }() defer func() { defer func() { // Shouldn't succeed, even though it is called directly // from a defer function, since this defer function was // not directly called by the panic. r := recover() if r != nil { t.Fatalf("wanted nil recover, got %v", r) } }() }() panic("panic1") } type nonSSAable [128]byte type bigStruct struct { x, y, z, w, p, q int64 } type containsBigStruct struct { element bigStruct } func mknonSSAable() nonSSAable { globint1++ return nonSSAable{0, 0, 0, 0, 5} } var globint1, globint2, globint3 int //go:noinline func sideeffect(n int64) int64 { globint2++ return n } func sideeffect2(in containsBigStruct) containsBigStruct { globint3++ return in } // Test that nonSSAable arguments to defer are handled correctly and only evaluated once. func TestNonSSAableArgs(t *testing.T) { globint1 = 0 globint2 = 0 globint3 = 0 var save1 byte var save2 int64 var save3 int64 var save4 int64 defer func() { if globint1 != 1 { t.Fatalf("globint1: wanted: 1, got %v", globint1) } if save1 != 5 { t.Fatalf("save1: wanted: 5, got %v", save1) } if globint2 != 1 { t.Fatalf("globint2: wanted: 1, got %v", globint2) } if save2 != 2 { t.Fatalf("save2: wanted: 2, got %v", save2) } if save3 != 4 { t.Fatalf("save3: wanted: 4, got %v", save3) } if globint3 != 1 { t.Fatalf("globint3: wanted: 1, got %v", globint3) } if save4 != 4 { t.Fatalf("save1: wanted: 4, got %v", save4) } }() // Test function returning a non-SSAable arg defer func(n nonSSAable) { save1 = n[4] }(mknonSSAable()) // Test composite literal that is not SSAable defer func(b bigStruct) { save2 = b.y }(bigStruct{1, 2, 3, 4, 5, sideeffect(6)}) // Test struct field reference that is non-SSAable foo := containsBigStruct{} foo.element.z = 4 defer func(element bigStruct) { save3 = element.z }(foo.element) defer func(element bigStruct) { save4 = element.z }(sideeffect2(foo).element) } //go:noinline func doPanic() { panic("Test panic") } func TestDeferForFuncWithNoExit(t *testing.T) { cond := 1 defer func() { if cond != 2 { t.Fatalf("cond: wanted 2, got %v", cond) } if recover() != "Test panic" { t.Fatal("Didn't find expected panic") } }() x := 0 // Force a stack copy, to make sure that the &cond pointer passed to defer // function is properly updated. growStackIter(&x, 1000) cond = 2 doPanic() // This function has no exit/return, since it ends with an infinite loop for { } } // Test case approximating issue #37664, where a recursive function (interpreter) // may do repeated recovers/re-panics until it reaches the frame where the panic // can actually be handled. The recurseFnPanicRec() function is testing that there // are no stale defer structs on the defer chain after the interpreter() sequence, // by writing a bunch of 0xffffffffs into several recursive stack frames, and then // doing a single panic-recover which would invoke any such stale defer structs. func TestDeferWithRepeatedRepanics(t *testing.T) { interpreter(0, 6, 2) recurseFnPanicRec(0, 10) interpreter(0, 5, 1) recurseFnPanicRec(0, 10) interpreter(0, 6, 3) recurseFnPanicRec(0, 10) } func interpreter(level int, maxlevel int, rec int) { defer func() { e := recover() if e == nil { return } if level != e.(int) { //fmt.Fprintln(os.Stderr, "re-panicing, level", level) panic(e) } //fmt.Fprintln(os.Stderr, "Recovered, level", level) }() if level+1 < maxlevel { interpreter(level+1, maxlevel, rec) } else { //fmt.Fprintln(os.Stderr, "Initiating panic") panic(rec) } } func recurseFnPanicRec(level int, maxlevel int) { defer func() { recover() }() recurseFn(level, maxlevel) } var saveInt uint32 func recurseFn(level int, maxlevel int) { a := [40]uint32{0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff} if level+1 < maxlevel { // Make sure a array is referenced, so it is not optimized away saveInt = a[4] recurseFn(level+1, maxlevel) } else { panic("recurseFn panic") } } // Try to reproduce issue #37688, where a pointer to an open-coded defer struct is // mistakenly held, and that struct keeps a pointer to a stack-allocated defer // struct, and that stack-allocated struct gets overwritten or the stack gets // moved, so a memory error happens on GC. func TestIssue37688(t *testing.T) { for j := 0; j < 10; j++ { g2() g3() } } type foo struct { } //go:noinline func (f *foo) method1() { } //go:noinline func (f *foo) method2() { } func g2() { var a foo ap := &a // The loop forces this defer to be heap-allocated and the remaining two // to be stack-allocated. for i := 0; i < 1; i++ { defer ap.method1() } defer ap.method2() defer ap.method1() ff1(ap, 1, 2, 3, 4, 5, 6, 7, 8, 9) // Try to get the stack to be moved by growing it too large, so // existing stack-allocated defer becomes invalid. rec1(2000) } func g3() { // Mix up the stack layout by adding in an extra function frame g2() } var globstruct struct { a, b, c, d, e, f, g, h, i int } func ff1(ap *foo, a, b, c, d, e, f, g, h, i int) { defer ap.method1() // Make a defer that has a very large set of args, hence big size for the // defer record for the open-coded frame (which means it won't use the // defer pool) defer func(ap *foo, a, b, c, d, e, f, g, h, i int) { if v := recover(); v != nil { } globstruct.a = a globstruct.b = b globstruct.c = c globstruct.d = d globstruct.e = e globstruct.f = f globstruct.g = g globstruct.h = h }(ap, a, b, c, d, e, f, g, h, i) panic("ff1 panic") } func rec1(max int) { if max > 0 { rec1(max - 1) } } func TestIssue43921(t *testing.T) { defer func() { expect(t, 1, recover()) }() func() { // Prevent open-coded defers for { defer func() {}() break } defer func() { defer func() { expect(t, 4, recover()) }() panic(4) }() panic(1) }() } func expect(t *testing.T, n int, err any) { if n != err { t.Fatalf("have %v, want %v", err, n) } } func TestIssue43920(t *testing.T) { var steps int defer func() { expect(t, 1, recover()) }() defer func() { defer func() { defer func() { expect(t, 5, recover()) }() defer panic(5) func() { panic(4) }() }() defer func() { expect(t, 3, recover()) }() defer panic(3) }() func() { defer step(t, &steps, 1) panic(1) }() } func step(t *testing.T, steps *int, want int) { *steps++ if *steps != want { t.Fatalf("have %v, want %v", *steps, want) } } func TestIssue43941(t *testing.T) { var steps int = 7 defer func() { step(t, &steps, 14) expect(t, 4, recover()) }() func() { func() { defer func() { defer func() { expect(t, 3, recover()) }() defer panic(3) panic(2) }() defer func() { expect(t, 1, recover()) }() defer panic(1) }() defer func() {}() defer func() {}() defer step(t, &steps, 10) defer step(t, &steps, 9) step(t, &steps, 8) }() func() { defer step(t, &steps, 13) defer step(t, &steps, 12) func() { defer step(t, &steps, 11) panic(4) }() // Code below isn't executed, // but removing it breaks the test case. defer func() {}() defer panic(-1) defer step(t, &steps, -1) defer step(t, &steps, -1) defer func() {}() }() }
go/src/runtime/defer_test.go/0
{ "file_path": "go/src/runtime/defer_test.go", "repo_id": "go", "token_count": 4716 }
384
// created by cgo -cdefs and then converted to Go // cgo -cdefs defs_dragonfly.go package runtime import "unsafe" const ( _EINTR = 0x4 _EFAULT = 0xe _EBUSY = 0x10 _EAGAIN = 0x23 _ETIMEDOUT = 0x3c _O_WRONLY = 0x1 _O_NONBLOCK = 0x4 _O_CREAT = 0x200 _O_TRUNC = 0x400 _O_CLOEXEC = 0x20000 _PROT_NONE = 0x0 _PROT_READ = 0x1 _PROT_WRITE = 0x2 _PROT_EXEC = 0x4 _MAP_ANON = 0x1000 _MAP_PRIVATE = 0x2 _MAP_FIXED = 0x10 _MADV_DONTNEED = 0x4 _MADV_FREE = 0x5 _SA_SIGINFO = 0x40 _SA_RESTART = 0x2 _SA_ONSTACK = 0x1 _SIGHUP = 0x1 _SIGINT = 0x2 _SIGQUIT = 0x3 _SIGILL = 0x4 _SIGTRAP = 0x5 _SIGABRT = 0x6 _SIGEMT = 0x7 _SIGFPE = 0x8 _SIGKILL = 0x9 _SIGBUS = 0xa _SIGSEGV = 0xb _SIGSYS = 0xc _SIGPIPE = 0xd _SIGALRM = 0xe _SIGTERM = 0xf _SIGURG = 0x10 _SIGSTOP = 0x11 _SIGTSTP = 0x12 _SIGCONT = 0x13 _SIGCHLD = 0x14 _SIGTTIN = 0x15 _SIGTTOU = 0x16 _SIGIO = 0x17 _SIGXCPU = 0x18 _SIGXFSZ = 0x19 _SIGVTALRM = 0x1a _SIGPROF = 0x1b _SIGWINCH = 0x1c _SIGINFO = 0x1d _SIGUSR1 = 0x1e _SIGUSR2 = 0x1f _FPE_INTDIV = 0x2 _FPE_INTOVF = 0x1 _FPE_FLTDIV = 0x3 _FPE_FLTOVF = 0x4 _FPE_FLTUND = 0x5 _FPE_FLTRES = 0x6 _FPE_FLTINV = 0x7 _FPE_FLTSUB = 0x8 _BUS_ADRALN = 0x1 _BUS_ADRERR = 0x2 _BUS_OBJERR = 0x3 _SEGV_MAPERR = 0x1 _SEGV_ACCERR = 0x2 _ITIMER_REAL = 0x0 _ITIMER_VIRTUAL = 0x1 _ITIMER_PROF = 0x2 _EV_ADD = 0x1 _EV_DELETE = 0x2 _EV_ENABLE = 0x4 _EV_DISABLE = 0x8 _EV_CLEAR = 0x20 _EV_ERROR = 0x4000 _EV_EOF = 0x8000 _EVFILT_READ = -0x1 _EVFILT_WRITE = -0x2 _EVFILT_USER = -0x9 _NOTE_TRIGGER = 0x1000000 ) type rtprio struct { _type uint16 prio uint16 } type lwpparams struct { start_func uintptr arg unsafe.Pointer stack uintptr tid1 unsafe.Pointer // *int32 tid2 unsafe.Pointer // *int32 } type sigset struct { __bits [4]uint32 } type stackt struct { ss_sp uintptr ss_size uintptr ss_flags int32 pad_cgo_0 [4]byte } type siginfo struct { si_signo int32 si_errno int32 si_code int32 si_pid int32 si_uid uint32 si_status int32 si_addr uint64 si_value [8]byte si_band int64 __spare__ [7]int32 pad_cgo_0 [4]byte } type mcontext struct { mc_onstack uint64 mc_rdi uint64 mc_rsi uint64 mc_rdx uint64 mc_rcx uint64 mc_r8 uint64 mc_r9 uint64 mc_rax uint64 mc_rbx uint64 mc_rbp uint64 mc_r10 uint64 mc_r11 uint64 mc_r12 uint64 mc_r13 uint64 mc_r14 uint64 mc_r15 uint64 mc_xflags uint64 mc_trapno uint64 mc_addr uint64 mc_flags uint64 mc_err uint64 mc_rip uint64 mc_cs uint64 mc_rflags uint64 mc_rsp uint64 mc_ss uint64 mc_len uint32 mc_fpformat uint32 mc_ownedfp uint32 mc_reserved uint32 mc_unused [8]uint32 mc_fpregs [256]int32 } type ucontext struct { uc_sigmask sigset pad_cgo_0 [48]byte uc_mcontext mcontext uc_link *ucontext uc_stack stackt __spare__ [8]int32 } type timespec struct { tv_sec int64 tv_nsec int64 } //go:nosplit func (ts *timespec) setNsec(ns int64) { ts.tv_sec = ns / 1e9 ts.tv_nsec = ns % 1e9 } type timeval struct { tv_sec int64 tv_usec int64 } func (tv *timeval) set_usec(x int32) { tv.tv_usec = int64(x) } type itimerval struct { it_interval timeval it_value timeval } type keventt struct { ident uint64 filter int16 flags uint16 fflags uint32 data int64 udata *byte }
go/src/runtime/defs_dragonfly_amd64.go/0
{ "file_path": "go/src/runtime/defs_dragonfly_amd64.go", "repo_id": "go", "token_count": 2092 }
385
// Copyright 2014 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. package runtime const _PAGESIZE = 0x1000 type ureg struct { di uint32 /* general registers */ si uint32 /* ... */ bp uint32 /* ... */ nsp uint32 bx uint32 /* ... */ dx uint32 /* ... */ cx uint32 /* ... */ ax uint32 /* ... */ gs uint32 /* data segments */ fs uint32 /* ... */ es uint32 /* ... */ ds uint32 /* ... */ trap uint32 /* trap _type */ ecode uint32 /* error code (or zero) */ pc uint32 /* pc */ cs uint32 /* old context */ flags uint32 /* old flags */ sp uint32 ss uint32 /* old stack segment */ } type sigctxt struct { u *ureg } //go:nosplit //go:nowritebarrierrec func (c *sigctxt) pc() uintptr { return uintptr(c.u.pc) } func (c *sigctxt) sp() uintptr { return uintptr(c.u.sp) } func (c *sigctxt) lr() uintptr { return uintptr(0) } func (c *sigctxt) setpc(x uintptr) { c.u.pc = uint32(x) } func (c *sigctxt) setsp(x uintptr) { c.u.sp = uint32(x) } func (c *sigctxt) setlr(x uintptr) {} func (c *sigctxt) savelr(x uintptr) {} func dumpregs(u *ureg) { print("ax ", hex(u.ax), "\n") print("bx ", hex(u.bx), "\n") print("cx ", hex(u.cx), "\n") print("dx ", hex(u.dx), "\n") print("di ", hex(u.di), "\n") print("si ", hex(u.si), "\n") print("bp ", hex(u.bp), "\n") print("sp ", hex(u.sp), "\n") print("pc ", hex(u.pc), "\n") print("flags ", hex(u.flags), "\n") print("cs ", hex(u.cs), "\n") print("fs ", hex(u.fs), "\n") print("gs ", hex(u.gs), "\n") } func sigpanictramp()
go/src/runtime/defs_plan9_386.go/0
{ "file_path": "go/src/runtime/defs_plan9_386.go", "repo_id": "go", "token_count": 742 }
386
// Code generated by mkduff.go; DO NOT EDIT. // Run go generate from src/runtime to update. // See mkduff.go for comments. //go:build ppc64 || ppc64le #include "textflag.h" TEXT runtime·duffzero<ABIInternal>(SB), NOSPLIT|NOFRAME, $0-0 MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) MOVDU R0, 8(R20) RET TEXT runtime·duffcopy<ABIInternal>(SB), NOSPLIT|NOFRAME, $0-0 MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) MOVDU 8(R20), R5 MOVDU R5, 8(R21) RET
go/src/runtime/duff_ppc64x.s/0
{ "file_path": "go/src/runtime/duff_ppc64x.s", "repo_id": "go", "token_count": 5756 }
387
// Copyright 2019 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. // Export debuglog guts for testing. package runtime const DlogEnabled = dlogEnabled const DebugLogBytes = debugLogBytes const DebugLogStringLimit = debugLogStringLimit var Dlog = dlog func (l *dlogger) End() { l.end() } func (l *dlogger) B(x bool) *dlogger { return l.b(x) } func (l *dlogger) I(x int) *dlogger { return l.i(x) } func (l *dlogger) I16(x int16) *dlogger { return l.i16(x) } func (l *dlogger) U64(x uint64) *dlogger { return l.u64(x) } func (l *dlogger) Hex(x uint64) *dlogger { return l.hex(x) } func (l *dlogger) P(x any) *dlogger { return l.p(x) } func (l *dlogger) S(x string) *dlogger { return l.s(x) } func (l *dlogger) PC(x uintptr) *dlogger { return l.pc(x) } func DumpDebugLog() string { gp := getg() gp.writebuf = make([]byte, 0, 1<<20) printDebugLog() buf := gp.writebuf gp.writebuf = nil return string(buf) } func ResetDebugLog() { stw := stopTheWorld(stwForTestResetDebugLog) for l := allDloggers; l != nil; l = l.allLink { l.w.write = 0 l.w.tick, l.w.nano = 0, 0 l.w.r.begin, l.w.r.end = 0, 0 l.w.r.tick, l.w.r.nano = 0, 0 } startTheWorld(stw) }
go/src/runtime/export_debuglog_test.go/0
{ "file_path": "go/src/runtime/export_debuglog_test.go", "repo_id": "go", "token_count": 571 }
388
// Copyright 2021 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. package runtime_test import ( "testing" ) func TestIssue48807(t *testing.T) { for _, i := range []uint64{ 0x8234508000000001, // from issue48807 1<<56 + 1<<32 + 1, } { got := float32(i) dontwant := float32(float64(i)) if got == dontwant { // The test cases above should be uint64s such that // this equality doesn't hold. These examples trigger // the case where using an intermediate float64 doesn't work. t.Errorf("direct float32 conversion doesn't work: arg=%x got=%x dontwant=%x", i, got, dontwant) } } }
go/src/runtime/float_test.go/0
{ "file_path": "go/src/runtime/float_test.go", "repo_id": "go", "token_count": 246 }
389
// Copyright 2022 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. // Package startlinetest contains helpers for runtime_test.TestStartLineAsm. package startlinetest // Defined in func_amd64.s, this is a trivial assembly function that calls // runtime_test.callerStartLine. func AsmFunc() int // Provided by runtime_test. var CallerStartLine func(bool) int
go/src/runtime/internal/startlinetest/func_amd64.go/0
{ "file_path": "go/src/runtime/internal/startlinetest/func_amd64.go", "repo_id": "go", "token_count": 126 }
390
// Copyright 2011 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. //go:build aix || darwin || netbsd || openbsd || plan9 || solaris || windows package runtime import ( "internal/runtime/atomic" "unsafe" ) // This implementation depends on OS-specific implementations of // // func semacreate(mp *m) // Create a semaphore for mp, if it does not already have one. // // func semasleep(ns int64) int32 // If ns < 0, acquire m's semaphore and return 0. // If ns >= 0, try to acquire m's semaphore for at most ns nanoseconds. // Return 0 if the semaphore was acquired, -1 if interrupted or timed out. // // func semawakeup(mp *m) // Wake up mp, which is or will soon be sleeping on its semaphore. const ( locked uintptr = 1 active_spin = 4 active_spin_cnt = 30 passive_spin = 1 ) func mutexContended(l *mutex) bool { return atomic.Loaduintptr(&l.key) > locked } func lock(l *mutex) { lockWithRank(l, getLockRank(l)) } func lock2(l *mutex) { gp := getg() if gp.m.locks < 0 { throw("runtime·lock: lock count") } gp.m.locks++ // Speculative grab for lock. if atomic.Casuintptr(&l.key, 0, locked) { return } semacreate(gp.m) timer := &lockTimer{lock: l} timer.begin() // On uniprocessor's, no point spinning. // On multiprocessors, spin for ACTIVE_SPIN attempts. spin := 0 if ncpu > 1 { spin = active_spin } Loop: for i := 0; ; i++ { v := atomic.Loaduintptr(&l.key) if v&locked == 0 { // Unlocked. Try to lock. if atomic.Casuintptr(&l.key, v, v|locked) { timer.end() return } i = 0 } if i < spin { procyield(active_spin_cnt) } else if i < spin+passive_spin { osyield() } else { // Someone else has it. // l->waitm points to a linked list of M's waiting // for this lock, chained through m->nextwaitm. // Queue this M. for { gp.m.nextwaitm = muintptr(v &^ locked) if atomic.Casuintptr(&l.key, v, uintptr(unsafe.Pointer(gp.m))|locked) { break } v = atomic.Loaduintptr(&l.key) if v&locked == 0 { continue Loop } } if v&locked != 0 { // Queued. Wait. semasleep(-1) i = 0 } } } } func unlock(l *mutex) { unlockWithRank(l) } // We might not be holding a p in this code. // //go:nowritebarrier func unlock2(l *mutex) { gp := getg() var mp *m for { v := atomic.Loaduintptr(&l.key) if v == locked { if atomic.Casuintptr(&l.key, locked, 0) { break } } else { // Other M's are waiting for the lock. // Dequeue an M. mp = muintptr(v &^ locked).ptr() if atomic.Casuintptr(&l.key, v, uintptr(mp.nextwaitm)) { // Dequeued an M. Wake it. semawakeup(mp) break } } } gp.m.mLockProfile.recordUnlock(l) gp.m.locks-- if gp.m.locks < 0 { throw("runtime·unlock: lock count") } if gp.m.locks == 0 && gp.preempt { // restore the preemption request in case we've cleared it in newstack gp.stackguard0 = stackPreempt } } // One-time notifications. func noteclear(n *note) { n.key = 0 } func notewakeup(n *note) { var v uintptr for { v = atomic.Loaduintptr(&n.key) if atomic.Casuintptr(&n.key, v, locked) { break } } // Successfully set waitm to locked. // What was it before? switch { case v == 0: // Nothing was waiting. Done. case v == locked: // Two notewakeups! Not allowed. throw("notewakeup - double wakeup") default: // Must be the waiting m. Wake it up. semawakeup((*m)(unsafe.Pointer(v))) } } func notesleep(n *note) { gp := getg() if gp != gp.m.g0 { throw("notesleep not on g0") } semacreate(gp.m) if !atomic.Casuintptr(&n.key, 0, uintptr(unsafe.Pointer(gp.m))) { // Must be locked (got wakeup). if n.key != locked { throw("notesleep - waitm out of sync") } return } // Queued. Sleep. gp.m.blocked = true if *cgo_yield == nil { semasleep(-1) } else { // Sleep for an arbitrary-but-moderate interval to poll libc interceptors. const ns = 10e6 for atomic.Loaduintptr(&n.key) == 0 { semasleep(ns) asmcgocall(*cgo_yield, nil) } } gp.m.blocked = false } //go:nosplit func notetsleep_internal(n *note, ns int64, gp *g, deadline int64) bool { // gp and deadline are logically local variables, but they are written // as parameters so that the stack space they require is charged // to the caller. // This reduces the nosplit footprint of notetsleep_internal. gp = getg() // Register for wakeup on n->waitm. if !atomic.Casuintptr(&n.key, 0, uintptr(unsafe.Pointer(gp.m))) { // Must be locked (got wakeup). if n.key != locked { throw("notetsleep - waitm out of sync") } return true } if ns < 0 { // Queued. Sleep. gp.m.blocked = true if *cgo_yield == nil { semasleep(-1) } else { // Sleep in arbitrary-but-moderate intervals to poll libc interceptors. const ns = 10e6 for semasleep(ns) < 0 { asmcgocall(*cgo_yield, nil) } } gp.m.blocked = false return true } deadline = nanotime() + ns for { // Registered. Sleep. gp.m.blocked = true if *cgo_yield != nil && ns > 10e6 { ns = 10e6 } if semasleep(ns) >= 0 { gp.m.blocked = false // Acquired semaphore, semawakeup unregistered us. // Done. return true } if *cgo_yield != nil { asmcgocall(*cgo_yield, nil) } gp.m.blocked = false // Interrupted or timed out. Still registered. Semaphore not acquired. ns = deadline - nanotime() if ns <= 0 { break } // Deadline hasn't arrived. Keep sleeping. } // Deadline arrived. Still registered. Semaphore not acquired. // Want to give up and return, but have to unregister first, // so that any notewakeup racing with the return does not // try to grant us the semaphore when we don't expect it. for { v := atomic.Loaduintptr(&n.key) switch v { case uintptr(unsafe.Pointer(gp.m)): // No wakeup yet; unregister if possible. if atomic.Casuintptr(&n.key, v, 0) { return false } case locked: // Wakeup happened so semaphore is available. // Grab it to avoid getting out of sync. gp.m.blocked = true if semasleep(-1) < 0 { throw("runtime: unable to acquire - semaphore out of sync") } gp.m.blocked = false return true default: throw("runtime: unexpected waitm - semaphore out of sync") } } } func notetsleep(n *note, ns int64) bool { gp := getg() if gp != gp.m.g0 { throw("notetsleep not on g0") } semacreate(gp.m) return notetsleep_internal(n, ns, nil, 0) } // same as runtime·notetsleep, but called on user g (not g0) // calls only nosplit functions between entersyscallblock/exitsyscall. func notetsleepg(n *note, ns int64) bool { gp := getg() if gp == gp.m.g0 { throw("notetsleepg on g0") } semacreate(gp.m) entersyscallblock() ok := notetsleep_internal(n, ns, nil, 0) exitsyscall() return ok } func beforeIdle(int64, int64) (*g, bool) { return nil, false } func checkTimeouts() {}
go/src/runtime/lock_sema.go/0
{ "file_path": "go/src/runtime/lock_sema.go", "repo_id": "go", "token_count": 2883 }
391
// Copyright 2009 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. package runtime import ( "internal/runtime/atomic" "internal/runtime/sys" "unsafe" ) // Per-thread (in Go, per-P) cache for small objects. // This includes a small object cache and local allocation stats. // No locking needed because it is per-thread (per-P). // // mcaches are allocated from non-GC'd memory, so any heap pointers // must be specially handled. type mcache struct { _ sys.NotInHeap // The following members are accessed on every malloc, // so they are grouped here for better caching. nextSample uintptr // trigger heap sample after allocating this many bytes scanAlloc uintptr // bytes of scannable heap allocated // Allocator cache for tiny objects w/o pointers. // See "Tiny allocator" comment in malloc.go. // tiny points to the beginning of the current tiny block, or // nil if there is no current tiny block. // // tiny is a heap pointer. Since mcache is in non-GC'd memory, // we handle it by clearing it in releaseAll during mark // termination. // // tinyAllocs is the number of tiny allocations performed // by the P that owns this mcache. tiny uintptr tinyoffset uintptr tinyAllocs uintptr // The rest is not accessed on every malloc. alloc [numSpanClasses]*mspan // spans to allocate from, indexed by spanClass stackcache [_NumStackOrders]stackfreelist // flushGen indicates the sweepgen during which this mcache // was last flushed. If flushGen != mheap_.sweepgen, the spans // in this mcache are stale and need to the flushed so they // can be swept. This is done in acquirep. flushGen atomic.Uint32 } // A gclink is a node in a linked list of blocks, like mlink, // but it is opaque to the garbage collector. // The GC does not trace the pointers during collection, // and the compiler does not emit write barriers for assignments // of gclinkptr values. Code should store references to gclinks // as gclinkptr, not as *gclink. type gclink struct { next gclinkptr } // A gclinkptr is a pointer to a gclink, but it is opaque // to the garbage collector. type gclinkptr uintptr // ptr returns the *gclink form of p. // The result should be used for accessing fields, not stored // in other data structures. func (p gclinkptr) ptr() *gclink { return (*gclink)(unsafe.Pointer(p)) } type stackfreelist struct { list gclinkptr // linked list of free stacks size uintptr // total size of stacks in list } // dummy mspan that contains no free objects. var emptymspan mspan func allocmcache() *mcache { var c *mcache systemstack(func() { lock(&mheap_.lock) c = (*mcache)(mheap_.cachealloc.alloc()) c.flushGen.Store(mheap_.sweepgen) unlock(&mheap_.lock) }) for i := range c.alloc { c.alloc[i] = &emptymspan } c.nextSample = nextSample() return c } // freemcache releases resources associated with this // mcache and puts the object onto a free list. // // In some cases there is no way to simply release // resources, such as statistics, so donate them to // a different mcache (the recipient). func freemcache(c *mcache) { systemstack(func() { c.releaseAll() stackcache_clear(c) // NOTE(rsc,rlh): If gcworkbuffree comes back, we need to coordinate // with the stealing of gcworkbufs during garbage collection to avoid // a race where the workbuf is double-freed. // gcworkbuffree(c.gcworkbuf) lock(&mheap_.lock) mheap_.cachealloc.free(unsafe.Pointer(c)) unlock(&mheap_.lock) }) } // getMCache is a convenience function which tries to obtain an mcache. // // Returns nil if we're not bootstrapping or we don't have a P. The caller's // P must not change, so we must be in a non-preemptible state. func getMCache(mp *m) *mcache { // Grab the mcache, since that's where stats live. pp := mp.p.ptr() var c *mcache if pp == nil { // We will be called without a P while bootstrapping, // in which case we use mcache0, which is set in mallocinit. // mcache0 is cleared when bootstrapping is complete, // by procresize. c = mcache0 } else { c = pp.mcache } return c } // refill acquires a new span of span class spc for c. This span will // have at least one free object. The current span in c must be full. // // Must run in a non-preemptible context since otherwise the owner of // c could change. func (c *mcache) refill(spc spanClass) { // Return the current cached span to the central lists. s := c.alloc[spc] if s.allocCount != s.nelems { throw("refill of span with free space remaining") } if s != &emptymspan { // Mark this span as no longer cached. if s.sweepgen != mheap_.sweepgen+3 { throw("bad sweepgen in refill") } mheap_.central[spc].mcentral.uncacheSpan(s) // Count up how many slots were used and record it. stats := memstats.heapStats.acquire() slotsUsed := int64(s.allocCount) - int64(s.allocCountBeforeCache) atomic.Xadd64(&stats.smallAllocCount[spc.sizeclass()], slotsUsed) // Flush tinyAllocs. if spc == tinySpanClass { atomic.Xadd64(&stats.tinyAllocCount, int64(c.tinyAllocs)) c.tinyAllocs = 0 } memstats.heapStats.release() // Count the allocs in inconsistent, internal stats. bytesAllocated := slotsUsed * int64(s.elemsize) gcController.totalAlloc.Add(bytesAllocated) // Clear the second allocCount just to be safe. s.allocCountBeforeCache = 0 } // Get a new cached span from the central lists. s = mheap_.central[spc].mcentral.cacheSpan() if s == nil { throw("out of memory") } if s.allocCount == s.nelems { throw("span has no free space") } // Indicate that this span is cached and prevent asynchronous // sweeping in the next sweep phase. s.sweepgen = mheap_.sweepgen + 3 // Store the current alloc count for accounting later. s.allocCountBeforeCache = s.allocCount // Update heapLive and flush scanAlloc. // // We have not yet allocated anything new into the span, but we // assume that all of its slots will get used, so this makes // heapLive an overestimate. // // When the span gets uncached, we'll fix up this overestimate // if necessary (see releaseAll). // // We pick an overestimate here because an underestimate leads // the pacer to believe that it's in better shape than it is, // which appears to lead to more memory used. See #53738 for // more details. usedBytes := uintptr(s.allocCount) * s.elemsize gcController.update(int64(s.npages*pageSize)-int64(usedBytes), int64(c.scanAlloc)) c.scanAlloc = 0 c.alloc[spc] = s } // allocLarge allocates a span for a large object. func (c *mcache) allocLarge(size uintptr, noscan bool) *mspan { if size+_PageSize < size { throw("out of memory") } npages := size >> _PageShift if size&_PageMask != 0 { npages++ } // Deduct credit for this span allocation and sweep if // necessary. mHeap_Alloc will also sweep npages, so this only // pays the debt down to npage pages. deductSweepCredit(npages*_PageSize, npages) spc := makeSpanClass(0, noscan) s := mheap_.alloc(npages, spc) if s == nil { throw("out of memory") } // Count the alloc in consistent, external stats. stats := memstats.heapStats.acquire() atomic.Xadd64(&stats.largeAlloc, int64(npages*pageSize)) atomic.Xadd64(&stats.largeAllocCount, 1) memstats.heapStats.release() // Count the alloc in inconsistent, internal stats. gcController.totalAlloc.Add(int64(npages * pageSize)) // Update heapLive. gcController.update(int64(s.npages*pageSize), 0) // Put the large span in the mcentral swept list so that it's // visible to the background sweeper. mheap_.central[spc].mcentral.fullSwept(mheap_.sweepgen).push(s) s.limit = s.base() + size s.initHeapBits(false) return s } func (c *mcache) releaseAll() { // Take this opportunity to flush scanAlloc. scanAlloc := int64(c.scanAlloc) c.scanAlloc = 0 sg := mheap_.sweepgen dHeapLive := int64(0) for i := range c.alloc { s := c.alloc[i] if s != &emptymspan { slotsUsed := int64(s.allocCount) - int64(s.allocCountBeforeCache) s.allocCountBeforeCache = 0 // Adjust smallAllocCount for whatever was allocated. stats := memstats.heapStats.acquire() atomic.Xadd64(&stats.smallAllocCount[spanClass(i).sizeclass()], slotsUsed) memstats.heapStats.release() // Adjust the actual allocs in inconsistent, internal stats. // We assumed earlier that the full span gets allocated. gcController.totalAlloc.Add(slotsUsed * int64(s.elemsize)) if s.sweepgen != sg+1 { // refill conservatively counted unallocated slots in gcController.heapLive. // Undo this. // // If this span was cached before sweep, then gcController.heapLive was totally // recomputed since caching this span, so we don't do this for stale spans. dHeapLive -= int64(s.nelems-s.allocCount) * int64(s.elemsize) } // Release the span to the mcentral. mheap_.central[i].mcentral.uncacheSpan(s) c.alloc[i] = &emptymspan } } // Clear tinyalloc pool. c.tiny = 0 c.tinyoffset = 0 // Flush tinyAllocs. stats := memstats.heapStats.acquire() atomic.Xadd64(&stats.tinyAllocCount, int64(c.tinyAllocs)) c.tinyAllocs = 0 memstats.heapStats.release() // Update heapLive and heapScan. gcController.update(dHeapLive, scanAlloc) } // prepareForSweep flushes c if the system has entered a new sweep phase // since c was populated. This must happen between the sweep phase // starting and the first allocation from c. func (c *mcache) prepareForSweep() { // Alternatively, instead of making sure we do this on every P // between starting the world and allocating on that P, we // could leave allocate-black on, allow allocation to continue // as usual, use a ragged barrier at the beginning of sweep to // ensure all cached spans are swept, and then disable // allocate-black. However, with this approach it's difficult // to avoid spilling mark bits into the *next* GC cycle. sg := mheap_.sweepgen flushGen := c.flushGen.Load() if flushGen == sg { return } else if flushGen != sg-2 { println("bad flushGen", flushGen, "in prepareForSweep; sweepgen", sg) throw("bad flushGen") } c.releaseAll() stackcache_clear(c) c.flushGen.Store(mheap_.sweepgen) // Synchronizes with gcStart }
go/src/runtime/mcache.go/0
{ "file_path": "go/src/runtime/mcache.go", "repo_id": "go", "token_count": 3445 }
392
// Inferno's libkern/memset-arm.s // https://bitbucket.org/inferno-os/inferno-os/src/master/libkern/memset-arm.s // // Copyright © 1994-1999 Lucent Technologies Inc. All rights reserved. // Revisions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com). All rights reserved. // Portions Copyright 2009 The Go Authors. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "textflag.h" #define TO R8 #define TOE R11 #define N R12 #define TMP R12 /* N and TMP don't overlap */ // See memclrNoHeapPointers Go doc for important implementation constraints. // func memclrNoHeapPointers(ptr unsafe.Pointer, n uintptr) // Also called from assembly in sys_windows_arm.s without g (but using Go stack convention). TEXT runtime·memclrNoHeapPointers(SB),NOSPLIT,$0-8 MOVW ptr+0(FP), TO MOVW n+4(FP), N MOVW $0, R0 ADD N, TO, TOE /* to end pointer */ CMP $4, N /* need at least 4 bytes to copy */ BLT _1tail _4align: /* align on 4 */ AND.S $3, TO, TMP BEQ _4aligned MOVBU.P R0, 1(TO) /* implicit write back */ B _4align _4aligned: SUB $31, TOE, TMP /* do 32-byte chunks if possible */ CMP TMP, TO BHS _4tail MOVW R0, R1 /* replicate */ MOVW R0, R2 MOVW R0, R3 MOVW R0, R4 MOVW R0, R5 MOVW R0, R6 MOVW R0, R7 _f32loop: CMP TMP, TO BHS _4tail MOVM.IA.W [R0-R7], (TO) B _f32loop _4tail: SUB $3, TOE, TMP /* do remaining words if possible */ _4loop: CMP TMP, TO BHS _1tail MOVW.P R0, 4(TO) /* implicit write back */ B _4loop _1tail: CMP TO, TOE BEQ _return MOVBU.P R0, 1(TO) /* implicit write back */ B _1tail _return: RET
go/src/runtime/memclr_arm.s/0
{ "file_path": "go/src/runtime/memclr_arm.s", "repo_id": "go", "token_count": 1012 }
393
// Copyright 2022 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. #include "textflag.h" // See memmove Go doc for important implementation constraints. // func memmove(to, from unsafe.Pointer, n uintptr) TEXT runtime·memmove<ABIInternal>(SB), NOSPLIT|NOFRAME, $0-24 BNE R6, check RET check: SGTU R4, R5, R7 BNE R7, backward ADDV R4, R6, R9 // end pointer // if the two pointers are not of same alignments, do byte copying SUBVU R5, R4, R7 AND $7, R7 BNE R7, out // if less than 8 bytes, do byte copying SGTU $8, R6, R7 BNE R7, out // do one byte at a time until 8-aligned AND $7, R4, R8 BEQ R8, words MOVB (R5), R7 ADDV $1, R5 MOVB R7, (R4) ADDV $1, R4 JMP -6(PC) words: // do 8 bytes at a time if there is room ADDV $-7, R9, R6 // R6 is end pointer-7 PCALIGN $16 SGTU R6, R4, R8 BEQ R8, out MOVV (R5), R7 ADDV $8, R5 MOVV R7, (R4) ADDV $8, R4 JMP -6(PC) out: BEQ R4, R9, done MOVB (R5), R7 ADDV $1, R5 MOVB R7, (R4) ADDV $1, R4 JMP -5(PC) done: RET backward: ADDV R6, R5 // from-end pointer ADDV R4, R6, R9 // to-end pointer // if the two pointers are not of same alignments, do byte copying SUBVU R9, R5, R7 AND $7, R7 BNE R7, out1 // if less than 8 bytes, do byte copying SGTU $8, R6, R7 BNE R7, out1 // do one byte at a time until 8-aligned AND $7, R9, R8 BEQ R8, words1 ADDV $-1, R5 MOVB (R5), R7 ADDV $-1, R9 MOVB R7, (R9) JMP -6(PC) words1: // do 8 bytes at a time if there is room ADDV $7, R4, R6 // R6 is start pointer+7 PCALIGN $16 SGTU R9, R6, R8 BEQ R8, out1 ADDV $-8, R5 MOVV (R5), R7 ADDV $-8, R9 MOVV R7, (R9) JMP -6(PC) out1: BEQ R4, R9, done1 ADDV $-1, R5 MOVB (R5), R7 ADDV $-1, R9 MOVB R7, (R9) JMP -5(PC) done1: RET
go/src/runtime/memmove_loong64.s/0
{ "file_path": "go/src/runtime/memmove_loong64.s", "repo_id": "go", "token_count": 966 }
394
// Copyright 2020 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. package metrics import ( _ "runtime" // depends on the runtime via a linkname'd function "unsafe" ) // Sample captures a single metric sample. type Sample struct { // Name is the name of the metric sampled. // // It must correspond to a name in one of the metric descriptions // returned by All. Name string // Value is the value of the metric sample. Value Value } // Implemented in the runtime. func runtime_readMetrics(unsafe.Pointer, int, int) // Read populates each [Value] field in the given slice of metric samples. // // Desired metrics should be present in the slice with the appropriate name. // The user of this API is encouraged to re-use the same slice between calls for // efficiency, but is not required to do so. // // Note that re-use has some caveats. Notably, Values should not be read or // manipulated while a Read with that value is outstanding; that is a data race. // This property includes pointer-typed Values (for example, [Float64Histogram]) // whose underlying storage will be reused by Read when possible. To safely use // such values in a concurrent setting, all data must be deep-copied. // // It is safe to execute multiple Read calls concurrently, but their arguments // must share no underlying memory. When in doubt, create a new []Sample from // scratch, which is always safe, though may be inefficient. // // Sample values with names not appearing in [All] will have their Value populated // as KindBad to indicate that the name is unknown. func Read(m []Sample) { runtime_readMetrics(unsafe.Pointer(&m[0]), len(m), cap(m)) }
go/src/runtime/metrics/sample.go/0
{ "file_path": "go/src/runtime/metrics/sample.go", "repo_id": "go", "token_count": 454 }
395
// Copyright 2009 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. package runtime import ( "internal/goarch" "internal/runtime/atomic" "internal/runtime/sys" "unsafe" ) const ( _WorkbufSize = 2048 // in bytes; larger values result in less contention // workbufAlloc is the number of bytes to allocate at a time // for new workbufs. This must be a multiple of pageSize and // should be a multiple of _WorkbufSize. // // Larger values reduce workbuf allocation overhead. Smaller // values reduce heap fragmentation. workbufAlloc = 32 << 10 ) func init() { if workbufAlloc%pageSize != 0 || workbufAlloc%_WorkbufSize != 0 { throw("bad workbufAlloc") } } // Garbage collector work pool abstraction. // // This implements a producer/consumer model for pointers to grey // objects. A grey object is one that is marked and on a work // queue. A black object is marked and not on a work queue. // // Write barriers, root discovery, stack scanning, and object scanning // produce pointers to grey objects. Scanning consumes pointers to // grey objects, thus blackening them, and then scans them, // potentially producing new pointers to grey objects. // A gcWork provides the interface to produce and consume work for the // garbage collector. // // A gcWork can be used on the stack as follows: // // (preemption must be disabled) // gcw := &getg().m.p.ptr().gcw // .. call gcw.put() to produce and gcw.tryGet() to consume .. // // It's important that any use of gcWork during the mark phase prevent // the garbage collector from transitioning to mark termination since // gcWork may locally hold GC work buffers. This can be done by // disabling preemption (systemstack or acquirem). type gcWork struct { // wbuf1 and wbuf2 are the primary and secondary work buffers. // // This can be thought of as a stack of both work buffers' // pointers concatenated. When we pop the last pointer, we // shift the stack up by one work buffer by bringing in a new // full buffer and discarding an empty one. When we fill both // buffers, we shift the stack down by one work buffer by // bringing in a new empty buffer and discarding a full one. // This way we have one buffer's worth of hysteresis, which // amortizes the cost of getting or putting a work buffer over // at least one buffer of work and reduces contention on the // global work lists. // // wbuf1 is always the buffer we're currently pushing to and // popping from and wbuf2 is the buffer that will be discarded // next. // // Invariant: Both wbuf1 and wbuf2 are nil or neither are. wbuf1, wbuf2 *workbuf // Bytes marked (blackened) on this gcWork. This is aggregated // into work.bytesMarked by dispose. bytesMarked uint64 // Heap scan work performed on this gcWork. This is aggregated into // gcController by dispose and may also be flushed by callers. // Other types of scan work are flushed immediately. heapScanWork int64 // flushedWork indicates that a non-empty work buffer was // flushed to the global work list since the last gcMarkDone // termination check. Specifically, this indicates that this // gcWork may have communicated work to another gcWork. flushedWork bool } // Most of the methods of gcWork are go:nowritebarrierrec because the // write barrier itself can invoke gcWork methods but the methods are // not generally re-entrant. Hence, if a gcWork method invoked the // write barrier while the gcWork was in an inconsistent state, and // the write barrier in turn invoked a gcWork method, it could // permanently corrupt the gcWork. func (w *gcWork) init() { w.wbuf1 = getempty() wbuf2 := trygetfull() if wbuf2 == nil { wbuf2 = getempty() } w.wbuf2 = wbuf2 } // put enqueues a pointer for the garbage collector to trace. // obj must point to the beginning of a heap object or an oblet. // //go:nowritebarrierrec func (w *gcWork) put(obj uintptr) { flushed := false wbuf := w.wbuf1 // Record that this may acquire the wbufSpans or heap lock to // allocate a workbuf. lockWithRankMayAcquire(&work.wbufSpans.lock, lockRankWbufSpans) lockWithRankMayAcquire(&mheap_.lock, lockRankMheap) if wbuf == nil { w.init() wbuf = w.wbuf1 // wbuf is empty at this point. } else if wbuf.nobj == len(wbuf.obj) { w.wbuf1, w.wbuf2 = w.wbuf2, w.wbuf1 wbuf = w.wbuf1 if wbuf.nobj == len(wbuf.obj) { putfull(wbuf) w.flushedWork = true wbuf = getempty() w.wbuf1 = wbuf flushed = true } } wbuf.obj[wbuf.nobj] = obj wbuf.nobj++ // If we put a buffer on full, let the GC controller know so // it can encourage more workers to run. We delay this until // the end of put so that w is in a consistent state, since // enlistWorker may itself manipulate w. if flushed && gcphase == _GCmark { gcController.enlistWorker() } } // putFast does a put and reports whether it can be done quickly // otherwise it returns false and the caller needs to call put. // //go:nowritebarrierrec func (w *gcWork) putFast(obj uintptr) bool { wbuf := w.wbuf1 if wbuf == nil || wbuf.nobj == len(wbuf.obj) { return false } wbuf.obj[wbuf.nobj] = obj wbuf.nobj++ return true } // putBatch performs a put on every pointer in obj. See put for // constraints on these pointers. // //go:nowritebarrierrec func (w *gcWork) putBatch(obj []uintptr) { if len(obj) == 0 { return } flushed := false wbuf := w.wbuf1 if wbuf == nil { w.init() wbuf = w.wbuf1 } for len(obj) > 0 { for wbuf.nobj == len(wbuf.obj) { putfull(wbuf) w.flushedWork = true w.wbuf1, w.wbuf2 = w.wbuf2, getempty() wbuf = w.wbuf1 flushed = true } n := copy(wbuf.obj[wbuf.nobj:], obj) wbuf.nobj += n obj = obj[n:] } if flushed && gcphase == _GCmark { gcController.enlistWorker() } } // tryGet dequeues a pointer for the garbage collector to trace. // // If there are no pointers remaining in this gcWork or in the global // queue, tryGet returns 0. Note that there may still be pointers in // other gcWork instances or other caches. // //go:nowritebarrierrec func (w *gcWork) tryGet() uintptr { wbuf := w.wbuf1 if wbuf == nil { w.init() wbuf = w.wbuf1 // wbuf is empty at this point. } if wbuf.nobj == 0 { w.wbuf1, w.wbuf2 = w.wbuf2, w.wbuf1 wbuf = w.wbuf1 if wbuf.nobj == 0 { owbuf := wbuf wbuf = trygetfull() if wbuf == nil { return 0 } putempty(owbuf) w.wbuf1 = wbuf } } wbuf.nobj-- return wbuf.obj[wbuf.nobj] } // tryGetFast dequeues a pointer for the garbage collector to trace // if one is readily available. Otherwise it returns 0 and // the caller is expected to call tryGet(). // //go:nowritebarrierrec func (w *gcWork) tryGetFast() uintptr { wbuf := w.wbuf1 if wbuf == nil || wbuf.nobj == 0 { return 0 } wbuf.nobj-- return wbuf.obj[wbuf.nobj] } // dispose returns any cached pointers to the global queue. // The buffers are being put on the full queue so that the // write barriers will not simply reacquire them before the // GC can inspect them. This helps reduce the mutator's // ability to hide pointers during the concurrent mark phase. // //go:nowritebarrierrec func (w *gcWork) dispose() { if wbuf := w.wbuf1; wbuf != nil { if wbuf.nobj == 0 { putempty(wbuf) } else { putfull(wbuf) w.flushedWork = true } w.wbuf1 = nil wbuf = w.wbuf2 if wbuf.nobj == 0 { putempty(wbuf) } else { putfull(wbuf) w.flushedWork = true } w.wbuf2 = nil } if w.bytesMarked != 0 { // dispose happens relatively infrequently. If this // atomic becomes a problem, we should first try to // dispose less and if necessary aggregate in a per-P // counter. atomic.Xadd64(&work.bytesMarked, int64(w.bytesMarked)) w.bytesMarked = 0 } if w.heapScanWork != 0 { gcController.heapScanWork.Add(w.heapScanWork) w.heapScanWork = 0 } } // balance moves some work that's cached in this gcWork back on the // global queue. // //go:nowritebarrierrec func (w *gcWork) balance() { if w.wbuf1 == nil { return } if wbuf := w.wbuf2; wbuf.nobj != 0 { putfull(wbuf) w.flushedWork = true w.wbuf2 = getempty() } else if wbuf := w.wbuf1; wbuf.nobj > 4 { w.wbuf1 = handoff(wbuf) w.flushedWork = true // handoff did putfull } else { return } // We flushed a buffer to the full list, so wake a worker. if gcphase == _GCmark { gcController.enlistWorker() } } // empty reports whether w has no mark work available. // //go:nowritebarrierrec func (w *gcWork) empty() bool { return w.wbuf1 == nil || (w.wbuf1.nobj == 0 && w.wbuf2.nobj == 0) } // Internally, the GC work pool is kept in arrays in work buffers. // The gcWork interface caches a work buffer until full (or empty) to // avoid contending on the global work buffer lists. type workbufhdr struct { node lfnode // must be first nobj int } type workbuf struct { _ sys.NotInHeap workbufhdr // account for the above fields obj [(_WorkbufSize - unsafe.Sizeof(workbufhdr{})) / goarch.PtrSize]uintptr } // workbuf factory routines. These funcs are used to manage the // workbufs. // If the GC asks for some work these are the only routines that // make wbufs available to the GC. func (b *workbuf) checknonempty() { if b.nobj == 0 { throw("workbuf is empty") } } func (b *workbuf) checkempty() { if b.nobj != 0 { throw("workbuf is not empty") } } // getempty pops an empty work buffer off the work.empty list, // allocating new buffers if none are available. // //go:nowritebarrier func getempty() *workbuf { var b *workbuf if work.empty != 0 { b = (*workbuf)(work.empty.pop()) if b != nil { b.checkempty() } } // Record that this may acquire the wbufSpans or heap lock to // allocate a workbuf. lockWithRankMayAcquire(&work.wbufSpans.lock, lockRankWbufSpans) lockWithRankMayAcquire(&mheap_.lock, lockRankMheap) if b == nil { // Allocate more workbufs. var s *mspan if work.wbufSpans.free.first != nil { lock(&work.wbufSpans.lock) s = work.wbufSpans.free.first if s != nil { work.wbufSpans.free.remove(s) work.wbufSpans.busy.insert(s) } unlock(&work.wbufSpans.lock) } if s == nil { systemstack(func() { s = mheap_.allocManual(workbufAlloc/pageSize, spanAllocWorkBuf) }) if s == nil { throw("out of memory") } // Record the new span in the busy list. lock(&work.wbufSpans.lock) work.wbufSpans.busy.insert(s) unlock(&work.wbufSpans.lock) } // Slice up the span into new workbufs. Return one and // put the rest on the empty list. for i := uintptr(0); i+_WorkbufSize <= workbufAlloc; i += _WorkbufSize { newb := (*workbuf)(unsafe.Pointer(s.base() + i)) newb.nobj = 0 lfnodeValidate(&newb.node) if i == 0 { b = newb } else { putempty(newb) } } } return b } // putempty puts a workbuf onto the work.empty list. // Upon entry this goroutine owns b. The lfstack.push relinquishes ownership. // //go:nowritebarrier func putempty(b *workbuf) { b.checkempty() work.empty.push(&b.node) } // putfull puts the workbuf on the work.full list for the GC. // putfull accepts partially full buffers so the GC can avoid competing // with the mutators for ownership of partially full buffers. // //go:nowritebarrier func putfull(b *workbuf) { b.checknonempty() work.full.push(&b.node) } // trygetfull tries to get a full or partially empty workbuffer. // If one is not immediately available return nil. // //go:nowritebarrier func trygetfull() *workbuf { b := (*workbuf)(work.full.pop()) if b != nil { b.checknonempty() return b } return b } //go:nowritebarrier func handoff(b *workbuf) *workbuf { // Make new buffer with half of b's pointers. b1 := getempty() n := b.nobj / 2 b.nobj -= n b1.nobj = n memmove(unsafe.Pointer(&b1.obj[0]), unsafe.Pointer(&b.obj[b.nobj]), uintptr(n)*unsafe.Sizeof(b1.obj[0])) // Put b on full list - let first half of b get stolen. putfull(b) return b1 } // prepareFreeWorkbufs moves busy workbuf spans to free list so they // can be freed to the heap. This must only be called when all // workbufs are on the empty list. func prepareFreeWorkbufs() { lock(&work.wbufSpans.lock) if work.full != 0 { throw("cannot free workbufs when work.full != 0") } // Since all workbufs are on the empty list, we don't care // which ones are in which spans. We can wipe the entire empty // list and move all workbuf spans to the free list. work.empty = 0 work.wbufSpans.free.takeAll(&work.wbufSpans.busy) unlock(&work.wbufSpans.lock) } // freeSomeWbufs frees some workbufs back to the heap and returns // true if it should be called again to free more. func freeSomeWbufs(preemptible bool) bool { const batchSize = 64 // ~1–2 µs per span. lock(&work.wbufSpans.lock) if gcphase != _GCoff || work.wbufSpans.free.isEmpty() { unlock(&work.wbufSpans.lock) return false } systemstack(func() { gp := getg().m.curg for i := 0; i < batchSize && !(preemptible && gp.preempt); i++ { span := work.wbufSpans.free.first if span == nil { break } work.wbufSpans.free.remove(span) mheap_.freeManual(span, spanAllocWorkBuf) } }) more := !work.wbufSpans.free.isEmpty() unlock(&work.wbufSpans.lock) return more }
go/src/runtime/mgcwork.go/0
{ "file_path": "go/src/runtime/mgcwork.go", "repo_id": "go", "token_count": 4816 }
396
// Copyright 2019 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. package runtime import ( "internal/runtime/sys" ) // pageBits is a bitmap representing one bit per page in a palloc chunk. type pageBits [pallocChunkPages / 64]uint64 // get returns the value of the i'th bit in the bitmap. func (b *pageBits) get(i uint) uint { return uint((b[i/64] >> (i % 64)) & 1) } // block64 returns the 64-bit aligned block of bits containing the i'th bit. func (b *pageBits) block64(i uint) uint64 { return b[i/64] } // set sets bit i of pageBits. func (b *pageBits) set(i uint) { b[i/64] |= 1 << (i % 64) } // setRange sets bits in the range [i, i+n). func (b *pageBits) setRange(i, n uint) { _ = b[i/64] if n == 1 { // Fast path for the n == 1 case. b.set(i) return } // Set bits [i, j]. j := i + n - 1 if i/64 == j/64 { b[i/64] |= ((uint64(1) << n) - 1) << (i % 64) return } _ = b[j/64] // Set leading bits. b[i/64] |= ^uint64(0) << (i % 64) for k := i/64 + 1; k < j/64; k++ { b[k] = ^uint64(0) } // Set trailing bits. b[j/64] |= (uint64(1) << (j%64 + 1)) - 1 } // setAll sets all the bits of b. func (b *pageBits) setAll() { for i := range b { b[i] = ^uint64(0) } } // setBlock64 sets the 64-bit aligned block of bits containing the i'th bit that // are set in v. func (b *pageBits) setBlock64(i uint, v uint64) { b[i/64] |= v } // clear clears bit i of pageBits. func (b *pageBits) clear(i uint) { b[i/64] &^= 1 << (i % 64) } // clearRange clears bits in the range [i, i+n). func (b *pageBits) clearRange(i, n uint) { _ = b[i/64] if n == 1 { // Fast path for the n == 1 case. b.clear(i) return } // Clear bits [i, j]. j := i + n - 1 if i/64 == j/64 { b[i/64] &^= ((uint64(1) << n) - 1) << (i % 64) return } _ = b[j/64] // Clear leading bits. b[i/64] &^= ^uint64(0) << (i % 64) clear(b[i/64+1 : j/64]) // Clear trailing bits. b[j/64] &^= (uint64(1) << (j%64 + 1)) - 1 } // clearAll frees all the bits of b. func (b *pageBits) clearAll() { clear(b[:]) } // clearBlock64 clears the 64-bit aligned block of bits containing the i'th bit that // are set in v. func (b *pageBits) clearBlock64(i uint, v uint64) { b[i/64] &^= v } // popcntRange counts the number of set bits in the // range [i, i+n). func (b *pageBits) popcntRange(i, n uint) (s uint) { if n == 1 { return uint((b[i/64] >> (i % 64)) & 1) } _ = b[i/64] j := i + n - 1 if i/64 == j/64 { return uint(sys.OnesCount64((b[i/64] >> (i % 64)) & ((1 << n) - 1))) } _ = b[j/64] s += uint(sys.OnesCount64(b[i/64] >> (i % 64))) for k := i/64 + 1; k < j/64; k++ { s += uint(sys.OnesCount64(b[k])) } s += uint(sys.OnesCount64(b[j/64] & ((1 << (j%64 + 1)) - 1))) return } // pallocBits is a bitmap that tracks page allocations for at most one // palloc chunk. // // The precise representation is an implementation detail, but for the // sake of documentation, 0s are free pages and 1s are allocated pages. type pallocBits pageBits // summarize returns a packed summary of the bitmap in pallocBits. func (b *pallocBits) summarize() pallocSum { var start, most, cur uint const notSetYet = ^uint(0) // sentinel for start value start = notSetYet for i := 0; i < len(b); i++ { x := b[i] if x == 0 { cur += 64 continue } t := uint(sys.TrailingZeros64(x)) l := uint(sys.LeadingZeros64(x)) // Finish any region spanning the uint64s cur += t if start == notSetYet { start = cur } most = max(most, cur) // Final region that might span to next uint64 cur = l } if start == notSetYet { // Made it all the way through without finding a single 1 bit. const n = uint(64 * len(b)) return packPallocSum(n, n, n) } most = max(most, cur) if most >= 64-2 { // There is no way an internal run of zeros could beat max. return packPallocSum(start, most, cur) } // Now look inside each uint64 for runs of zeros. // All uint64s must be nonzero, or we would have aborted above. outer: for i := 0; i < len(b); i++ { x := b[i] // Look inside this uint64. We have a pattern like // 000000 1xxxxx1 000000 // We need to look inside the 1xxxxx1 for any contiguous // region of zeros. // We already know the trailing zeros are no larger than max. Remove them. x >>= sys.TrailingZeros64(x) & 63 if x&(x+1) == 0 { // no more zeros (except at the top). continue } // Strategy: shrink all runs of zeros by max. If any runs of zero // remain, then we've identified a larger maximum zero run. p := most // number of zeros we still need to shrink by. k := uint(1) // current minimum length of runs of ones in x. for { // Shrink all runs of zeros by p places (except the top zeros). for p > 0 { if p <= k { // Shift p ones down into the top of each run of zeros. x |= x >> (p & 63) if x&(x+1) == 0 { // no more zeros (except at the top). continue outer } break } // Shift k ones down into the top of each run of zeros. x |= x >> (k & 63) if x&(x+1) == 0 { // no more zeros (except at the top). continue outer } p -= k // We've just doubled the minimum length of 1-runs. // This allows us to shift farther in the next iteration. k *= 2 } // The length of the lowest-order zero run is an increment to our maximum. j := uint(sys.TrailingZeros64(^x)) // count contiguous trailing ones x >>= j & 63 // remove trailing ones j = uint(sys.TrailingZeros64(x)) // count contiguous trailing zeros x >>= j & 63 // remove zeros most += j // we have a new maximum! if x&(x+1) == 0 { // no more zeros (except at the top). continue outer } p = j // remove j more zeros from each zero run. } } return packPallocSum(start, most, cur) } // find searches for npages contiguous free pages in pallocBits and returns // the index where that run starts, as well as the index of the first free page // it found in the search. searchIdx represents the first known free page and // where to begin the next search from. // // If find fails to find any free space, it returns an index of ^uint(0) and // the new searchIdx should be ignored. // // Note that if npages == 1, the two returned values will always be identical. func (b *pallocBits) find(npages uintptr, searchIdx uint) (uint, uint) { if npages == 1 { addr := b.find1(searchIdx) return addr, addr } else if npages <= 64 { return b.findSmallN(npages, searchIdx) } return b.findLargeN(npages, searchIdx) } // find1 is a helper for find which searches for a single free page // in the pallocBits and returns the index. // // See find for an explanation of the searchIdx parameter. func (b *pallocBits) find1(searchIdx uint) uint { _ = b[0] // lift nil check out of loop for i := searchIdx / 64; i < uint(len(b)); i++ { x := b[i] if ^x == 0 { continue } return i*64 + uint(sys.TrailingZeros64(^x)) } return ^uint(0) } // findSmallN is a helper for find which searches for npages contiguous free pages // in this pallocBits and returns the index where that run of contiguous pages // starts as well as the index of the first free page it finds in its search. // // See find for an explanation of the searchIdx parameter. // // Returns a ^uint(0) index on failure and the new searchIdx should be ignored. // // findSmallN assumes npages <= 64, where any such contiguous run of pages // crosses at most one aligned 64-bit boundary in the bits. func (b *pallocBits) findSmallN(npages uintptr, searchIdx uint) (uint, uint) { end, newSearchIdx := uint(0), ^uint(0) for i := searchIdx / 64; i < uint(len(b)); i++ { bi := b[i] if ^bi == 0 { end = 0 continue } // First see if we can pack our allocation in the trailing // zeros plus the end of the last 64 bits. if newSearchIdx == ^uint(0) { // The new searchIdx is going to be at these 64 bits after any // 1s we file, so count trailing 1s. newSearchIdx = i*64 + uint(sys.TrailingZeros64(^bi)) } start := uint(sys.TrailingZeros64(bi)) if end+start >= uint(npages) { return i*64 - end, newSearchIdx } // Next, check the interior of the 64-bit chunk. j := findBitRange64(^bi, uint(npages)) if j < 64 { return i*64 + j, newSearchIdx } end = uint(sys.LeadingZeros64(bi)) } return ^uint(0), newSearchIdx } // findLargeN is a helper for find which searches for npages contiguous free pages // in this pallocBits and returns the index where that run starts, as well as the // index of the first free page it found it its search. // // See alloc for an explanation of the searchIdx parameter. // // Returns a ^uint(0) index on failure and the new searchIdx should be ignored. // // findLargeN assumes npages > 64, where any such run of free pages // crosses at least one aligned 64-bit boundary in the bits. func (b *pallocBits) findLargeN(npages uintptr, searchIdx uint) (uint, uint) { start, size, newSearchIdx := ^uint(0), uint(0), ^uint(0) for i := searchIdx / 64; i < uint(len(b)); i++ { x := b[i] if x == ^uint64(0) { size = 0 continue } if newSearchIdx == ^uint(0) { // The new searchIdx is going to be at these 64 bits after any // 1s we file, so count trailing 1s. newSearchIdx = i*64 + uint(sys.TrailingZeros64(^x)) } if size == 0 { size = uint(sys.LeadingZeros64(x)) start = i*64 + 64 - size continue } s := uint(sys.TrailingZeros64(x)) if s+size >= uint(npages) { return start, newSearchIdx } if s < 64 { size = uint(sys.LeadingZeros64(x)) start = i*64 + 64 - size continue } size += 64 } if size < uint(npages) { return ^uint(0), newSearchIdx } return start, newSearchIdx } // allocRange allocates the range [i, i+n). func (b *pallocBits) allocRange(i, n uint) { (*pageBits)(b).setRange(i, n) } // allocAll allocates all the bits of b. func (b *pallocBits) allocAll() { (*pageBits)(b).setAll() } // free1 frees a single page in the pallocBits at i. func (b *pallocBits) free1(i uint) { (*pageBits)(b).clear(i) } // free frees the range [i, i+n) of pages in the pallocBits. func (b *pallocBits) free(i, n uint) { (*pageBits)(b).clearRange(i, n) } // freeAll frees all the bits of b. func (b *pallocBits) freeAll() { (*pageBits)(b).clearAll() } // pages64 returns a 64-bit bitmap representing a block of 64 pages aligned // to 64 pages. The returned block of pages is the one containing the i'th // page in this pallocBits. Each bit represents whether the page is in-use. func (b *pallocBits) pages64(i uint) uint64 { return (*pageBits)(b).block64(i) } // allocPages64 allocates a 64-bit block of 64 pages aligned to 64 pages according // to the bits set in alloc. The block set is the one containing the i'th page. func (b *pallocBits) allocPages64(i uint, alloc uint64) { (*pageBits)(b).setBlock64(i, alloc) } // findBitRange64 returns the bit index of the first set of // n consecutive 1 bits. If no consecutive set of 1 bits of // size n may be found in c, then it returns an integer >= 64. // n must be > 0. func findBitRange64(c uint64, n uint) uint { // This implementation is based on shrinking the length of // runs of contiguous 1 bits. We remove the top n-1 1 bits // from each run of 1s, then look for the first remaining 1 bit. p := n - 1 // number of 1s we want to remove. k := uint(1) // current minimum width of runs of 0 in c. for p > 0 { if p <= k { // Shift p 0s down into the top of each run of 1s. c &= c >> (p & 63) break } // Shift k 0s down into the top of each run of 1s. c &= c >> (k & 63) if c == 0 { return 64 } p -= k // We've just doubled the minimum length of 0-runs. // This allows us to shift farther in the next iteration. k *= 2 } // Find first remaining 1. // Since we shrunk from the top down, the first 1 is in // its correct original position. return uint(sys.TrailingZeros64(c)) } // pallocData encapsulates pallocBits and a bitmap for // whether or not a given page is scavenged in a single // structure. It's effectively a pallocBits with // additional functionality. // // Update the comment on (*pageAlloc).chunks should this // structure change. type pallocData struct { pallocBits scavenged pageBits } // allocRange sets bits [i, i+n) in the bitmap to 1 and // updates the scavenged bits appropriately. func (m *pallocData) allocRange(i, n uint) { // Clear the scavenged bits when we alloc the range. m.pallocBits.allocRange(i, n) m.scavenged.clearRange(i, n) } // allocAll sets every bit in the bitmap to 1 and updates // the scavenged bits appropriately. func (m *pallocData) allocAll() { // Clear the scavenged bits when we alloc the range. m.pallocBits.allocAll() m.scavenged.clearAll() }
go/src/runtime/mpallocbits.go/0
{ "file_path": "go/src/runtime/mpallocbits.go", "repo_id": "go", "token_count": 4936 }
397
// Copyright 2017 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. //go:build !windows package runtime // osRelaxMinNS is the number of nanoseconds of idleness to tolerate // without performing an osRelax. Since osRelax may reduce the // precision of timers, this should be enough larger than the relaxed // timer precision to keep the timer error acceptable. const osRelaxMinNS = 0 var haveHighResSleep = true // osRelax is called by the scheduler when transitioning to and from // all Ps being idle. func osRelax(relax bool) {} // enableWER is called by setTraceback("wer"). // Windows Error Reporting (WER) is only supported on Windows. func enableWER() {} // winlibcall is not implemented on non-Windows systems, // but it is used in non-OS-specific parts of the runtime. // Define it as an empty struct to avoid wasting stack space. type winlibcall struct{}
go/src/runtime/nonwindows_stub.go/0
{ "file_path": "go/src/runtime/nonwindows_stub.go", "repo_id": "go", "token_count": 257 }
398
// Copyright 2011 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. package runtime import ( "internal/abi" "internal/goarch" "unsafe" ) type mOS struct{} //go:noescape func thr_new(param *thrparam, size int32) int32 //go:noescape func sigaltstack(new, old *stackt) //go:noescape func sigprocmask(how int32, new, old *sigset) //go:noescape func setitimer(mode int32, new, old *itimerval) //go:noescape func sysctl(mib *uint32, miblen uint32, out *byte, size *uintptr, dst *byte, ndst uintptr) int32 func raiseproc(sig uint32) func thr_self() thread func thr_kill(tid thread, sig int) //go:noescape func sys_umtx_op(addr *uint32, mode int32, val uint32, uaddr1 uintptr, ut *umtx_time) int32 func osyield() //go:nosplit func osyield_no_g() { osyield() } func kqueue() int32 //go:noescape func kevent(kq int32, ch *keventt, nch int32, ev *keventt, nev int32, ts *timespec) int32 func pipe2(flags int32) (r, w int32, errno int32) func fcntl(fd, cmd, arg int32) (ret int32, errno int32) func issetugid() int32 // From FreeBSD's <sys/sysctl.h> const ( _CTL_HW = 6 _HW_PAGESIZE = 7 ) var sigset_all = sigset{[4]uint32{^uint32(0), ^uint32(0), ^uint32(0), ^uint32(0)}} // Undocumented numbers from FreeBSD's lib/libc/gen/sysctlnametomib.c. const ( _CTL_QUERY = 0 _CTL_QUERY_MIB = 3 ) // sysctlnametomib fill mib with dynamically assigned sysctl entries of name, // return count of effected mib slots, return 0 on error. func sysctlnametomib(name []byte, mib *[_CTL_MAXNAME]uint32) uint32 { oid := [2]uint32{_CTL_QUERY, _CTL_QUERY_MIB} miblen := uintptr(_CTL_MAXNAME) if sysctl(&oid[0], 2, (*byte)(unsafe.Pointer(mib)), &miblen, (*byte)(unsafe.Pointer(&name[0])), (uintptr)(len(name))) < 0 { return 0 } miblen /= unsafe.Sizeof(uint32(0)) if miblen <= 0 { return 0 } return uint32(miblen) } const ( _CPU_CURRENT_PID = -1 // Current process ID. ) //go:noescape func cpuset_getaffinity(level int, which int, id int64, size int, mask *byte) int32 //go:systemstack func getncpu() int32 { // Use a large buffer for the CPU mask. We're on the system // stack, so this is fine, and we can't allocate memory for a // dynamically-sized buffer at this point. const maxCPUs = 64 * 1024 var mask [maxCPUs / 8]byte var mib [_CTL_MAXNAME]uint32 // According to FreeBSD's /usr/src/sys/kern/kern_cpuset.c, // cpuset_getaffinity return ERANGE when provided buffer size exceed the limits in kernel. // Querying kern.smp.maxcpus to calculate maximum buffer size. // See https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=200802 // Variable kern.smp.maxcpus introduced at Dec 23 2003, revision 123766, // with dynamically assigned sysctl entries. miblen := sysctlnametomib([]byte("kern.smp.maxcpus"), &mib) if miblen == 0 { return 1 } // Query kern.smp.maxcpus. dstsize := uintptr(4) maxcpus := uint32(0) if sysctl(&mib[0], miblen, (*byte)(unsafe.Pointer(&maxcpus)), &dstsize, nil, 0) != 0 { return 1 } maskSize := int(maxcpus+7) / 8 if maskSize < goarch.PtrSize { maskSize = goarch.PtrSize } if maskSize > len(mask) { maskSize = len(mask) } if cpuset_getaffinity(_CPU_LEVEL_WHICH, _CPU_WHICH_PID, _CPU_CURRENT_PID, maskSize, (*byte)(unsafe.Pointer(&mask[0]))) != 0 { return 1 } n := int32(0) for _, v := range mask[:maskSize] { for v != 0 { n += int32(v & 1) v >>= 1 } } if n == 0 { return 1 } return n } func getPageSize() uintptr { mib := [2]uint32{_CTL_HW, _HW_PAGESIZE} out := uint32(0) nout := unsafe.Sizeof(out) ret := sysctl(&mib[0], 2, (*byte)(unsafe.Pointer(&out)), &nout, nil, 0) if ret >= 0 { return uintptr(out) } return 0 } // FreeBSD's umtx_op syscall is effectively the same as Linux's futex, and // thus the code is largely similar. See Linux implementation // and lock_futex.go for comments. //go:nosplit func futexsleep(addr *uint32, val uint32, ns int64) { systemstack(func() { futexsleep1(addr, val, ns) }) } func futexsleep1(addr *uint32, val uint32, ns int64) { var utp *umtx_time if ns >= 0 { var ut umtx_time ut._clockid = _CLOCK_MONOTONIC ut._timeout.setNsec(ns) utp = &ut } ret := sys_umtx_op(addr, _UMTX_OP_WAIT_UINT_PRIVATE, val, unsafe.Sizeof(*utp), utp) if ret >= 0 || ret == -_EINTR || ret == -_ETIMEDOUT { return } print("umtx_wait addr=", addr, " val=", val, " ret=", ret, "\n") *(*int32)(unsafe.Pointer(uintptr(0x1005))) = 0x1005 } //go:nosplit func futexwakeup(addr *uint32, cnt uint32) { ret := sys_umtx_op(addr, _UMTX_OP_WAKE_PRIVATE, cnt, 0, nil) if ret >= 0 { return } systemstack(func() { print("umtx_wake_addr=", addr, " ret=", ret, "\n") }) } func thr_start() // May run with m.p==nil, so write barriers are not allowed. // //go:nowritebarrier func newosproc(mp *m) { stk := unsafe.Pointer(mp.g0.stack.hi) if false { print("newosproc stk=", stk, " m=", mp, " g=", mp.g0, " thr_start=", abi.FuncPCABI0(thr_start), " id=", mp.id, " ostk=", &mp, "\n") } param := thrparam{ start_func: abi.FuncPCABI0(thr_start), arg: unsafe.Pointer(mp), stack_base: mp.g0.stack.lo, stack_size: uintptr(stk) - mp.g0.stack.lo, child_tid: nil, // minit will record tid parent_tid: nil, tls_base: unsafe.Pointer(&mp.tls[0]), tls_size: unsafe.Sizeof(mp.tls), } var oset sigset sigprocmask(_SIG_SETMASK, &sigset_all, &oset) ret := retryOnEAGAIN(func() int32 { errno := thr_new(&param, int32(unsafe.Sizeof(param))) // thr_new returns negative errno return -errno }) sigprocmask(_SIG_SETMASK, &oset, nil) if ret != 0 { print("runtime: failed to create new OS thread (have ", mcount(), " already; errno=", ret, ")\n") throw("newosproc") } } // Version of newosproc that doesn't require a valid G. // //go:nosplit func newosproc0(stacksize uintptr, fn unsafe.Pointer) { stack := sysAlloc(stacksize, &memstats.stacks_sys) if stack == nil { writeErrStr(failallocatestack) exit(1) } // This code "knows" it's being called once from the library // initialization code, and so it's using the static m0 for the // tls and procid (thread) pointers. thr_new() requires the tls // pointers, though the tid pointers can be nil. // However, newosproc0 is currently unreachable because builds // utilizing c-shared/c-archive force external linking. param := thrparam{ start_func: uintptr(fn), arg: nil, stack_base: uintptr(stack), //+stacksize? stack_size: stacksize, child_tid: nil, // minit will record tid parent_tid: nil, tls_base: unsafe.Pointer(&m0.tls[0]), tls_size: unsafe.Sizeof(m0.tls), } var oset sigset sigprocmask(_SIG_SETMASK, &sigset_all, &oset) ret := thr_new(&param, int32(unsafe.Sizeof(param))) sigprocmask(_SIG_SETMASK, &oset, nil) if ret < 0 { writeErrStr(failthreadcreate) exit(1) } } // Called to do synchronous initialization of Go code built with // -buildmode=c-archive or -buildmode=c-shared. // None of the Go runtime is initialized. // //go:nosplit //go:nowritebarrierrec func libpreinit() { initsig(true) } func osinit() { ncpu = getncpu() if physPageSize == 0 { physPageSize = getPageSize() } } var urandom_dev = []byte("/dev/urandom\x00") //go:nosplit func readRandom(r []byte) int { fd := open(&urandom_dev[0], 0 /* O_RDONLY */, 0) n := read(fd, unsafe.Pointer(&r[0]), int32(len(r))) closefd(fd) return int(n) } func goenvs() { goenvs_unix() } // Called to initialize a new m (including the bootstrap m). // Called on the parent thread (main thread in case of bootstrap), can allocate memory. func mpreinit(mp *m) { mp.gsignal = malg(32 * 1024) mp.gsignal.m = mp } // Called to initialize a new m (including the bootstrap m). // Called on the new thread, cannot allocate memory. func minit() { getg().m.procid = uint64(thr_self()) // On FreeBSD before about April 2017 there was a bug such // that calling execve from a thread other than the main // thread did not reset the signal stack. That would confuse // minitSignals, which calls minitSignalStack, which checks // whether there is currently a signal stack and uses it if // present. To avoid this confusion, explicitly disable the // signal stack on the main thread when not running in a // library. This can be removed when we are confident that all // FreeBSD users are running a patched kernel. See issue #15658. if gp := getg(); !isarchive && !islibrary && gp.m == &m0 && gp == gp.m.g0 { st := stackt{ss_flags: _SS_DISABLE} sigaltstack(&st, nil) } minitSignals() } // Called from dropm to undo the effect of an minit. // //go:nosplit func unminit() { unminitSignals() getg().m.procid = 0 } // Called from exitm, but not from drop, to undo the effect of thread-owned // resources in minit, semacreate, or elsewhere. Do not take locks after calling this. func mdestroy(mp *m) { } func sigtramp() type sigactiont struct { sa_handler uintptr sa_flags int32 sa_mask sigset } // See os_freebsd2.go, os_freebsd_amd64.go for setsig function //go:nosplit //go:nowritebarrierrec func setsigstack(i uint32) { var sa sigactiont sigaction(i, nil, &sa) if sa.sa_flags&_SA_ONSTACK != 0 { return } sa.sa_flags |= _SA_ONSTACK sigaction(i, &sa, nil) } //go:nosplit //go:nowritebarrierrec func getsig(i uint32) uintptr { var sa sigactiont sigaction(i, nil, &sa) return sa.sa_handler } // setSignalstackSP sets the ss_sp field of a stackt. // //go:nosplit func setSignalstackSP(s *stackt, sp uintptr) { s.ss_sp = sp } //go:nosplit //go:nowritebarrierrec func sigaddset(mask *sigset, i int) { mask.__bits[(i-1)/32] |= 1 << ((uint32(i) - 1) & 31) } func sigdelset(mask *sigset, i int) { mask.__bits[(i-1)/32] &^= 1 << ((uint32(i) - 1) & 31) } //go:nosplit func (c *sigctxt) fixsigcode(sig uint32) { } func setProcessCPUProfiler(hz int32) { setProcessCPUProfilerTimer(hz) } func setThreadCPUProfiler(hz int32) { setThreadCPUProfilerHz(hz) } //go:nosplit func validSIGPROF(mp *m, c *sigctxt) bool { return true } func sysargs(argc int32, argv **byte) { n := argc + 1 // skip over argv, envp to get to auxv for argv_index(argv, n) != nil { n++ } // skip NULL separator n++ // now argv+n is auxv auxvp := (*[1 << 28]uintptr)(add(unsafe.Pointer(argv), uintptr(n)*goarch.PtrSize)) pairs := sysauxv(auxvp[:]) auxv = auxvp[: pairs*2 : pairs*2] } const ( _AT_NULL = 0 // Terminates the vector _AT_PAGESZ = 6 // Page size in bytes _AT_PLATFORM = 15 // string identifying platform _AT_TIMEKEEP = 22 // Pointer to timehands. _AT_HWCAP = 25 // CPU feature flags _AT_HWCAP2 = 26 // CPU feature flags 2 ) func sysauxv(auxv []uintptr) (pairs int) { var i int for i = 0; auxv[i] != _AT_NULL; i += 2 { tag, val := auxv[i], auxv[i+1] switch tag { // _AT_NCPUS from auxv shouldn't be used due to golang.org/issue/15206 case _AT_PAGESZ: physPageSize = val case _AT_TIMEKEEP: timekeepSharedPage = (*vdsoTimekeep)(unsafe.Pointer(val)) } archauxv(tag, val) } return i / 2 } // sysSigaction calls the sigaction system call. // //go:nosplit func sysSigaction(sig uint32, new, old *sigactiont) { // Use system stack to avoid split stack overflow on amd64 if asmSigaction(uintptr(sig), new, old) != 0 { systemstack(func() { throw("sigaction failed") }) } } // asmSigaction is implemented in assembly. // //go:noescape func asmSigaction(sig uintptr, new, old *sigactiont) int32 // raise sends a signal to the calling thread. // // It must be nosplit because it is used by the signal handler before // it definitely has a Go stack. // //go:nosplit func raise(sig uint32) { thr_kill(thr_self(), int(sig)) } func signalM(mp *m, sig int) { thr_kill(thread(mp.procid), sig) } // sigPerThreadSyscall is only used on linux, so we assign a bogus signal // number. const sigPerThreadSyscall = 1 << 31 //go:nosplit func runPerThreadSyscall() { throw("runPerThreadSyscall only valid on linux") }
go/src/runtime/os_freebsd.go/0
{ "file_path": "go/src/runtime/os_freebsd.go", "repo_id": "go", "token_count": 4885 }
399