pack.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. /*
  2. * ECAL
  3. *
  4. * Copyright 2020 Matthias Ladkau. All rights reserved.
  5. *
  6. * This Source Code Form is subject to the terms of the MIT
  7. * License, If a copy of the MIT License was not distributed with this
  8. * file, You can obtain one at https://opensource.org/licenses/MIT.
  9. */
  10. package tool
  11. import (
  12. "archive/zip"
  13. "flag"
  14. "fmt"
  15. "io"
  16. "io/ioutil"
  17. "os"
  18. "path/filepath"
  19. "strings"
  20. "unicode"
  21. "devt.de/krotik/common/errorutil"
  22. "devt.de/krotik/common/fileutil"
  23. "devt.de/krotik/ecal/interpreter"
  24. "devt.de/krotik/ecal/parser"
  25. "devt.de/krotik/ecal/scope"
  26. "devt.de/krotik/ecal/util"
  27. )
  28. /*
  29. CLIPacker is a commandline packing tool for ECAL. This tool can build a self
  30. contained executable.
  31. */
  32. type CLIPacker struct {
  33. EntryFile string // Entry file for the program
  34. // Parameter these can either be set programmatically or via CLI args
  35. Dir *string // Root dir for interpreter (all files will be collected)
  36. SourceBinary *string // Binary which is used by the packer
  37. TargetBinary *string // Binary which will be build by the packer
  38. // Log output
  39. LogOut io.Writer
  40. }
  41. var packmarkerend = "####"
  42. var packmarker = fmt.Sprintf("\n%v%v%v\n", packmarkerend, "ECALSRC", packmarkerend)
  43. /*
  44. NewCLIPacker creates a new commandline packer.
  45. */
  46. func NewCLIPacker() *CLIPacker {
  47. return &CLIPacker{"", nil, nil, nil, os.Stdout}
  48. }
  49. /*
  50. ParseArgs parses the command line arguments. Returns true if the program should exit.
  51. */
  52. func (p *CLIPacker) ParseArgs() bool {
  53. if p.Dir != nil && p.TargetBinary != nil && p.EntryFile != "" {
  54. return false
  55. }
  56. binname, err := filepath.Abs(osArgs[0])
  57. errorutil.AssertOk(err)
  58. wd, _ := os.Getwd()
  59. p.Dir = flag.String("dir", wd, "Root directory for ECAL interpreter")
  60. p.SourceBinary = flag.String("source", binname, "Filename for source binary")
  61. p.TargetBinary = flag.String("target", "out.bin", "Filename for target binary")
  62. showHelp := flag.Bool("help", false, "Show this help message")
  63. flag.Usage = func() {
  64. fmt.Fprintln(flag.CommandLine.Output())
  65. fmt.Fprintln(flag.CommandLine.Output(), fmt.Sprintf("Usage of %s pack [options] [entry file]", os.Args[0]))
  66. fmt.Fprintln(flag.CommandLine.Output())
  67. flag.PrintDefaults()
  68. fmt.Fprintln(flag.CommandLine.Output())
  69. fmt.Fprintln(flag.CommandLine.Output(), "This tool will collect all files in the root directory and "+
  70. "build a standalone executable from the given source binary and the collected files.")
  71. fmt.Fprintln(flag.CommandLine.Output())
  72. }
  73. if len(os.Args) >= 2 {
  74. flag.CommandLine.Parse(osArgs[2:])
  75. if cargs := flag.Args(); len(cargs) > 0 {
  76. p.EntryFile = flag.Arg(0)
  77. } else {
  78. *showHelp = true
  79. }
  80. if *showHelp {
  81. flag.Usage()
  82. }
  83. }
  84. return *showHelp
  85. }
  86. /*
  87. Pack builds a standalone executable from a given source binary and collected files.
  88. */
  89. func (p *CLIPacker) Pack() error {
  90. if p.ParseArgs() {
  91. return nil
  92. }
  93. fmt.Fprintln(p.LogOut, fmt.Sprintf("Packing %v -> %v from %v with entry: %v", *p.Dir,
  94. *p.TargetBinary, *p.SourceBinary, p.EntryFile))
  95. source, err := os.Open(*p.SourceBinary)
  96. if err == nil {
  97. var dest *os.File
  98. defer source.Close()
  99. if dest, err = os.Create(*p.TargetBinary); err == nil {
  100. var bytes int64
  101. defer dest.Close()
  102. // First copy the binary
  103. if bytes, err = io.Copy(dest, source); err == nil {
  104. fmt.Fprintln(p.LogOut, fmt.Sprintf("Copied %v bytes for interpreter.", bytes))
  105. var bytes int
  106. if bytes, err = dest.WriteString(packmarker); err == nil {
  107. var data []byte
  108. fmt.Fprintln(p.LogOut, fmt.Sprintf("Writing marker %v bytes for source archive.", bytes))
  109. // Create a new zip archive.
  110. w := zip.NewWriter(dest)
  111. if data, err = ioutil.ReadFile(p.EntryFile); err == nil {
  112. var f io.Writer
  113. if f, err = w.Create(".ecalsrc-entry"); err == nil {
  114. if bytes, err = f.Write(data); err == nil {
  115. fmt.Fprintln(p.LogOut, fmt.Sprintf("Writing %v bytes for intro", bytes))
  116. // Add files to the archive
  117. defer func() {
  118. w.Close()
  119. os.Chmod(*p.TargetBinary, 0775) // Try a chmod but don't care about any errors
  120. }()
  121. err = p.packFiles(w, *p.Dir, "")
  122. }
  123. }
  124. }
  125. }
  126. }
  127. }
  128. }
  129. return err
  130. }
  131. /*
  132. packFiles walk through a given file structure and copies all files into a given zip writer.
  133. */
  134. func (p *CLIPacker) packFiles(w *zip.Writer, filePath string, zipPath string) error {
  135. var bytes int
  136. files, err := ioutil.ReadDir(filePath)
  137. if err == nil {
  138. for _, file := range files {
  139. if !file.IsDir() {
  140. var data []byte
  141. if data, err = ioutil.ReadFile(filepath.Join(filePath, file.Name())); err == nil {
  142. var f io.Writer
  143. if f, err = w.Create(filepath.Join(zipPath, file.Name())); err == nil {
  144. if bytes, err = f.Write(data); err == nil {
  145. fmt.Fprintln(p.LogOut, fmt.Sprintf("Writing %v bytes for %v",
  146. bytes, filepath.Join(filePath, file.Name())))
  147. }
  148. }
  149. }
  150. } else if file.IsDir() {
  151. p.packFiles(w, filepath.Join(filePath, file.Name()),
  152. filepath.Join(zipPath, file.Name()))
  153. }
  154. }
  155. }
  156. return err
  157. }
  158. var ( // Internal reading buffers
  159. b1 = 4096
  160. b2 = len(packmarker) + 11
  161. )
  162. /*
  163. handleError is the error handling function for runtime errors in packed binaries.
  164. */
  165. var handleError func(error) = errorutil.AssertOk
  166. /*
  167. RunPackedBinary runs ECAL code is it has been attached to the currently running binary.
  168. Exits if attached ECAL code has been executed.
  169. */
  170. func RunPackedBinary() {
  171. var retCode = 0
  172. var result bool
  173. exename, err := filepath.Abs(osArgs[0])
  174. errorutil.AssertOk(err)
  175. if ok, _ := fileutil.PathExists(exename); !ok {
  176. // Try an optional .exe suffix which might work on Windows
  177. exename += ".exe"
  178. }
  179. stat, err := os.Stat(exename)
  180. if err == nil {
  181. var f *os.File
  182. if f, err = os.Open(exename); err == nil {
  183. var pos int64
  184. defer f.Close()
  185. found := false
  186. buf := make([]byte, b1)
  187. buf2 := make([]byte, b2)
  188. // Look for the marker which marks the beginning of the attached zip file
  189. for i, err := f.Read(buf); err == nil; i, err = f.Read(buf) {
  190. // Check if the marker could be in the read string
  191. if strings.Contains(string(buf), "#") {
  192. // Marker was found - read a bit more to ensure we got the full marker
  193. if i2, err := f.Read(buf2); err == nil || err == io.EOF {
  194. candidateString := string(append(buf, buf2...))
  195. // Now determine the position of the zip file
  196. markerIndex := strings.Index(candidateString, packmarker)
  197. if found = markerIndex >= 0; found {
  198. start := int64(markerIndex + len(packmarker))
  199. for unicode.IsSpace(rune(candidateString[start])) || unicode.IsControl(rune(candidateString[start])) {
  200. start++ // Skip final control characters \n or \r\n
  201. }
  202. pos += start
  203. break
  204. }
  205. pos += int64(i2)
  206. }
  207. }
  208. pos += int64(i)
  209. }
  210. if err == nil && found {
  211. // Extract the zip
  212. if _, err = f.Seek(pos, 0); err == nil {
  213. var ret interface{}
  214. zipLen := stat.Size() - pos
  215. ret, err = runInterpreter(io.NewSectionReader(f, pos, zipLen), zipLen)
  216. retNum, _ := ret.(float64)
  217. retCode = int(retNum)
  218. result = err == nil
  219. }
  220. }
  221. }
  222. }
  223. handleError(err)
  224. if result {
  225. osExit(retCode)
  226. }
  227. }
  228. func runInterpreter(reader io.ReaderAt, size int64) (interface{}, error) {
  229. var res interface{}
  230. var rc io.ReadCloser
  231. il := &util.MemoryImportLocator{Files: make(map[string]string)}
  232. r, err := zip.NewReader(reader, size)
  233. if err == nil {
  234. for _, f := range r.File {
  235. if err == nil {
  236. if rc, err = f.Open(); err == nil {
  237. var data []byte
  238. defer rc.Close()
  239. if data, err = ioutil.ReadAll(rc); err == nil {
  240. il.Files[f.Name] = string(data)
  241. }
  242. }
  243. }
  244. }
  245. }
  246. if err == nil {
  247. var ast *parser.ASTNode
  248. erp := interpreter.NewECALRuntimeProvider(osArgs[0], il, util.NewStdOutLogger())
  249. if ast, err = parser.ParseWithRuntime(os.Args[0], il.Files[".ecalsrc-entry"], erp); err == nil {
  250. if err = ast.Runtime.Validate(); err == nil {
  251. var osArgs []interface{}
  252. vs := scope.NewScope(scope.GlobalScope)
  253. for _, arg := range os.Args {
  254. osArgs = append(osArgs, arg)
  255. }
  256. vs.SetValue("osArgs", osArgs)
  257. res, err = ast.Runtime.Eval(vs, make(map[string]interface{}), erp.NewThreadID())
  258. if err != nil {
  259. fmt.Fprintln(osStderr, err.Error())
  260. if terr, ok := err.(util.TraceableRuntimeError); ok {
  261. fmt.Fprintln(osStderr, fmt.Sprint(" ", strings.Join(terr.GetTraceString(), fmt.Sprint(fmt.Sprintln(), " "))))
  262. }
  263. err = nil
  264. }
  265. }
  266. }
  267. }
  268. return res, err
  269. }