pack.go 8.4 KB

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