pack.go 8.1 KB

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