golang.zx2c4.com/wireguard/windows@v0.5.4-0.20230123132234-dcc0eb72a04b/ringlogger/global.go (about)

     1  /* SPDX-License-Identifier: MIT
     2   *
     3   * Copyright (C) 2019-2022 WireGuard LLC. All Rights Reserved.
     4   */
     5  
     6  package ringlogger
     7  
     8  import (
     9  	"log"
    10  	"unsafe"
    11  )
    12  
    13  var Global *Ringlogger
    14  
    15  func InitGlobalLogger(file, tag string) error {
    16  	if Global != nil {
    17  		return nil
    18  	}
    19  	var err error
    20  	Global, err = NewRinglogger(file, tag)
    21  	if err != nil {
    22  		return err
    23  	}
    24  	log.SetOutput(Global)
    25  	log.SetFlags(0)
    26  	overrideWrite = globalWrite
    27  	return nil
    28  }
    29  
    30  //go:linkname overrideWrite runtime.overrideWrite
    31  var overrideWrite func(fd uintptr, p unsafe.Pointer, n int32) int32
    32  
    33  var (
    34  	globalBuffer         [maxLogLineLength - 1 - maxTagLength - 3]byte
    35  	globalBufferLocation int
    36  )
    37  
    38  //go:nosplit
    39  func globalWrite(fd uintptr, p unsafe.Pointer, n int32) int32 {
    40  	b := (*[1 << 30]byte)(p)[:n]
    41  	for len(b) > 0 {
    42  		amountAvailable := len(globalBuffer) - globalBufferLocation
    43  		amountToCopy := len(b)
    44  		if amountToCopy > amountAvailable {
    45  			amountToCopy = amountAvailable
    46  		}
    47  		copy(globalBuffer[globalBufferLocation:], b[:amountToCopy])
    48  		b = b[amountToCopy:]
    49  		globalBufferLocation += amountToCopy
    50  		foundNl := false
    51  		for i := globalBufferLocation - amountToCopy; i < globalBufferLocation; i++ {
    52  			if globalBuffer[i] == '\n' {
    53  				foundNl = true
    54  				break
    55  			}
    56  		}
    57  		if foundNl || len(b) > 0 {
    58  			Global.Write(globalBuffer[:globalBufferLocation])
    59  			globalBufferLocation = 0
    60  		}
    61  	}
    62  	return n
    63  }