pack.go 8.0 KB

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