github.com/danbrough/mobile@v0.0.3-beta03/internal/mobileinit/mobileinit_linux.go (about) 1 // Copyright 2014 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 //go:build linux && !android 6 // +build linux,!android 7 8 package mobileinit 9 10 /* 11 To view the log output run: 12 adb logcat GoLog:I *:S 13 */ 14 15 // Android redirects stdout and stderr to /dev/null. 16 // As these are common debugging utilities in Go, 17 // we redirect them to logcat. 18 // 19 // Unfortunately, logcat is line oriented, so we must buffer. 20 21 /* 22 #include <stdlib.h> 23 #include <string.h> 24 */ 25 26 import "C" 27 import ( 28 "bufio" 29 "os" 30 "runtime" 31 ) 32 33 var ( 34 ctag = C.CString("GoLog") 35 // Store the writer end of the redirected stderr and stdout 36 // so that they are not garbage collected and closed. 37 stderr, stdout *os.File 38 ) 39 40 type infoWriter struct{} 41 42 func (infoWriter) Write(p []byte) (n int, err error) { 43 println("%s: %s", ctag, string(p)) 44 return len(p), nil 45 } 46 47 func lineLog(f *os.File, priority C.int) { 48 const logSize = 1024 // matches android/log.h. 49 r := bufio.NewReaderSize(f, logSize) 50 for { 51 line, _, err := r.ReadLine() 52 str := string(line) 53 if err != nil { 54 str += " " + err.Error() 55 } 56 57 println("%s: %s", ctag, str) 58 59 if err != nil { 60 break 61 } 62 } 63 } 64 65 /* 66 func (infoWriter) Write(p []byte) (n int, err error) { 67 cstr := C.CString(string(p)) 68 C.__android_log_write(C.ANDROID_LOG_INFO, ctag, cstr) 69 C.free(unsafe.Pointer(cstr)) 70 return len(p), nil 71 } 72 73 func lineLog(f *os.File, priority C.int) { 74 const logSize = 1024 // matches android/log.h. 75 r := bufio.NewReaderSize(f, logSize) 76 for { 77 line, _, err := r.ReadLine() 78 str := string(line) 79 if err != nil { 80 str += " " + err.Error() 81 } 82 cstr := C.CString(str) 83 C.__android_log_write(priority, ctag, cstr) 84 C.free(unsafe.Pointer(cstr)) 85 if err != nil { 86 break 87 } 88 } 89 } 90 */ 91 func init() { 92 println("init() GOOS:", runtime.GOOS) 93 /* log.SetOutput(infoWriter{}) 94 // android logcat includes all of log.LstdFlags 95 log.SetFlags(log.Flags() &^ log.LstdFlags) 96 97 r, w, err := os.Pipe() 98 if err != nil { 99 panic(err) 100 } 101 stderr = w 102 if err := syscall.Dup3(int(w.Fd()), int(os.Stderr.Fd()), 0); err != nil { 103 panic(err) 104 } 105 //go lineLog(r, C.ANDROID_LOG_ERROR) 106 go lineLog(r, 4) 107 108 r, w, err = os.Pipe() 109 if err != nil { 110 panic(err) 111 } 112 stdout = w 113 if err := syscall.Dup3(int(w.Fd()), int(os.Stdout.Fd()), 0); err != nil { 114 panic(err) 115 } 116 //go lineLog(r, C.ANDROID_LOG_INFO) 117 go lineLog(r, 6)*/ 118 }