pack.go 7.9 KB

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