Debian Codegraph @

texk/texlive/windows_mingw_wrapper/runscript.tlu

raw
1
2
3 local svnrevision = string.match("$Revision: 49485 $", "%d+") or "0"
4 local svndate = string.match("$Date: 2018-12-23 16:28:08 +0100 (Sun, 23 Dec 2018) $", "[-%d]+") or "2009-12-04"
5 local bannerstr = "runscript wrapper utility (rev. " ..
6 svnrevision .. ", " .. svndate .. ")\n" ..
7 "usage: runscript script-name [arguments]\n" ..
8 "try -help [-v] for more information"
9
10 local helpstr = [[
11
12 Script wrappers in TeX Live on Windows
13
14 Rationale
15
16 Wrappers enable use of scripts on Windows as regular programs.
17 They are also required for some binary programs to set up the
18 right environment for them.
19
20 Batch scripts can be used for wrapping but they are not as universal
21 as binaries (there are some odd cases where they don't work) and
22 it is hard to make them robust and secure. Compiled binary wrappers
23 don't suffer from these problems but they are harder to write, debug
24 and maintain in comparison to scripts. For these reasons a hybrid
25 approach is taken that combines a binary stub with a launcher script.
26
27 Adding wrappers for user scripts
28
29 The script wrapping machinery is not limited to scripts shipped with
30 TeX Live. You can also use it for script programs from manually
31 installed packages. This should minimize problems when using them
32 with TeX Live.
33
34 First, make sure that there is an interpreter program available
35 on your system for the script you want to use. Interpreters for
36 Perl, Lua and Tcl/Tk (GUI scripts only) are bundled with TeX
37 Live, all others have to be installed independently. Lua
38 scripts are the most efficient to run, so if you consider
39 writing a new script, that would be the recommended choice.
40
41 The following script types and their file extensions are currently
42 supported and searched in that order:
43
44 Lua (.tlu;.texlua;.lua) -- included
45 Perl (.pl) -- included
46 Ruby (.rb) -- requires installation
47 Python (.py) -- requires installation
48 Tcl (.tcl) -- included (GUI scripts only)
49 Java (.jar) -- requires installation
50 VBScript (.vbs) -- part of Windows
51 JScript (.js) -- part of Windows
52 Batch (.bat;.cmd) -- part of Windows
53
54 Finally, Unix-style extensionless scripts are searched as last and
55 the interpreter program is established based on the she-bang (#!)
56 specification on the very first line of the script. This can be
57 an arbitrary program but it must be present on the search path.
58
59 Next, the script program needs to be installed somewhere below the
60 'scripts' directory under one of the TEXMF trees (consult the
61 documentation or texmf/web2c/texmf.cnf file for a list). You may
62 need to update the file search database afterwards with:
63
64 mktexlsr [TEXMFDIR]
65
66 It is also possible to use scripts that are outside of TEXMF hierarchy
67 by adjusting TEXMFSCRIPTS environment or kpathsea variable, see
68 kpathsea documentation for more information on setting its variables.
69
70 Test if the script can be located with:
71
72 kpsewhich --format=texmfscripts <script-name>.<ext>
73
74 This should output the full path to the script if everything is
75 properly installed and configured. If this test is successful,
76 the script can be run immediately with:
77
78 runscript <script-name> [script arguments]
79
80 If you prefer to call the script program simply by its name, copy
81 and rename bin/win32/runscript.exe (or bin/win64/runscript.exe for
82 64-bit Windows) to <script-name>.exe and put it somewhere on the
83 search path.]]
84
85 local docstr = [[
86
87 Wrapper structure
88
89 Wrappers consist of small binary stubs and a common texlua script.
90 The binary stubs are all the same, just different names (but CLI
91 and GUI stubs differ, see below, and GUI stubs are actually all
92 different due to different embedded icons).
93
94 The job of the binary stub is twofold: (a) call the texlua launcher
95 script 'runscript.tlu' from the same directory (or more precisely
96 from the directory containing 'runscript.dll') and (b) pass to it
97 argv[0] and the unparsed argument string as the last two arguments
98 (after adding a sentinel argument, which ends with a new line
99 character). Arbitrary C strings can be passed, because the script
100 is executed by linking with luatex.dll and calling the lua
101 interpreter internally rather than by spawning a new process.
102
103 There are two flavours of the binary stub: one for CLI programs
104 and another one for GUI programs. The GUI variant does not open
105 a console window nor does it block the command prompt if started
106 from there. It also uses a dialog box to display an error message
107 in addition to outputting to stderr.
108
109 The stubs are further split into a common DLL and EXE proxies
110 to it. This is for maintenance reasons - updates can be done by
111 replacement of a single DLL rather than all binary stubs.
112
113 The launcher script knows, which variant has been used to invoke it
114 based on the sentinel argument. The lack of this argument means
115 that it was invoked in a standard way, i.e., through texlua.exe.
116
117 All the hard work of locating a script/program to execute happens
118 in the launcher script. The located script/program is always
119 executed directly by spawning its interpreter (or binary) in a new
120 process. The system shell (cmd.exe) is never called (except for
121 batch scripts, of course). If the located script happens to be
122 a (tex)lua script, it is loaded and called internally from within
123 this script, i.e. no new process is spawned. Execution is done
124 using a protected call, so any compile or runtime errors are caught.
125
126 Source files
127
128 runscript.tlu launcher script for locating and dispatching
129 target scripts/programs
130 runscript_dll.c common DLL part of the binary stubs; locates and
131 calls the launcher script
132 runscript_exe.c EXE proxy to the common DLL for CLI mode stubs
133 wrunscript_exe.c EXE proxy to the common DLL for GUI mode stubs
134
135 Compilation of binaries (requires luatex.dll in the same directory)
136
137 with gcc (size optimized):
138
139 gcc -Os -s -shared -o runscript.dll runscript_dll.c -L./ -lluatex
140 gcc -Os -s -o runscript.exe runscript_exe.c -L./ -lrunscript
141 gcc -mwindows -Os -s -o wrunscript.exe wrunscript_exe.c -L./ -lrunscript
142
143 with tcc (extra small size):
144
145 tiny_impdef luatex.dll
146 tcc -shared -o runscript.dll runscript_dll.c luatex.def
147 tcc -o runscript.exe runscript_exe.c runscript.def
148 tcc -o wrunscript.exe wrunscript_exe.c runscript.def
149
150 License
151
152 Originally written in 2009 by Tomasz M. Trzeciak, Public Domain.
153
154 Prior work:
155 'tl-w32-wrapper.texlua' by Reinhard Kotucha and Norbert Preining.
156 'tl-w32-wrapper.cmd' by Tomasz M. Trzeciak.
157
158 Changelog
159
160 2009/12/04
161 - initial version
162 2009/12/15
163 - minor fixes for path & extension list parsing
164 2010/01/09
165 - added support for GUI mode stubs
166 2010/02/28
167 - enable GUI mode stubs for dviout, psv and texworks;
168 - added generic handling of sys programs
169 - added restricted repstopdf to alias_table
170 2010/03/13
171 - added 'readme.txt' and changelog
172 - added support and docs for calling user added scripts;
173 (use path of 'runscript.dll' instead of .exe stub to
174 locate 'runscript.tlu' script)
175 - limit search for shell_escape_commands to system trees
176 - added function for creating directory hierarchy
177 - fixed directory creation for dviout & texworks aliases
178 - fixed arg[0] of repstopdf & rpdfcrop
179 2010/03/28
180 - restructured docs, added --help and --version options
181 (available only when invoked under 'runscript' name)
182 - use TEXMF_RESTRICTED_SCRIPTS kpse var for searching
183 shell_escape_commands
184 - changed command validation to handle a list of commands
185 - prepend GUI mode command(s) to the command list
186 - added support for .tcl scripts
187 2010/03/31
188 - fixed fatal bug in extention_map definition for GUI mode
189 2010/04/15
190 - encapsulated main chunk in a function to execute with
191 pcall for more robustness and better error catching
192 - added texdoctk to scripts4tlperl table
193 - added tlgs and tlperl to alias_table; callable as e.g.:
194 runscript tlperl ...
195 - doc tweaks
196 2010/04/22
197 - ensure only backslash is used in USERPROFILE variable
198 (Adobe Reader crash case)
199 - fixed argument processing for direct execution under texlua
200 - more doc tweaks
201 2010/05/30
202 - Windows XP or newer required to run TeXworks
203 2010/06/04
204 - added support for Perl scripts starting with eval-exec-perl
205 construct in place of she-bang (#!)
206 2010/06/25
207 - run internal tlperl only with our Perl
208 - added fontinst to alias_table
209 - added support for all tex4ht commands from mk4ht.pl
210 - removed some unsued aliases
211 - some code refactoring and cleanup
212 2010/12/28
213 - use of external Perl now requires kpathsea variable
214 TEXLIVE_WINDOWS_TRY_EXTERNAL_PERL to be explicitly set to 1
215 - alias_table replaced with if-elseif-end tests to streamline
216 special cases and to avoid hardcoding of texmf* file paths
217 - added a2ping to special cases (requires -x switch to Perl)
218 - set ASYMPTOTE_GS (for asy) to full path to tlgs
219 2011/01/09
220 - removed tex4ht commands starting with ht from mk4ht aliases;
221 they have their own scripts and mk4ht calls them internally,
222 so aliasing results in an infinite recursion
223 - removed alias for fontinst (no fontinst.exe any more)
224 - fixed GUI-mode interpreter for Ruby
225 2011/09/10
226 - added -dDisableFAPI=true to psview argument list. Needed by
227 gs-9.xx
228 2012/03/12
229 - added '-i', '.' to psview argument list (author's request)
230 - added environment clean up from Perl specific variables
231 (when not using external Perl)
232 2012/08/05
233 - added alias for fmtutil
234 2013/05/09
235 - added alias mkluatexfontdb -> luaotfload-tool
236 2013/07/03
237 - fix for psview and UNC paths in unix-style
238 - remove not needed is_abs_path function
239 2013/08/07
240 - handle updmap-sys via updmap --sys
241 2013/08/08
242 - allow overriding gs/gs_dll/gs_lib with kpse variables
243 TEXLIVE_WINDOWS_EXTERNAL_GS, ..._GS_LIB, ..._GS_DLL
244 2013/08/30
245 - do not pass -NULL to dviout, to allow users changing and
246 saving settings. Patch by Yusuke KUROKI
247 2013/09/22
248 - add TEXMFDIST/fonts to the GS_LIB path. Patch by Yusuke KUROKI
249 2014/04/30
250 - fix for argument duplication in fmtutil
251 2015/04/12
252 - handle fmtutil-sys via fmtutil --sys
253 2015/09/10
254 - more slash flipping for the sake of vbscript and unc paths
255 2015/12/11
256 - fix spurious arguments for updmap and fmtutil
257 2016/04/22
258 - Warning if external perl is requested but missing
259 2017/04/22 (exactly one year later ;-)
260 - Cater for fmtutil-user and updmap-user => -user arg
261 2017/04/24
262 - GS_LIB setting for tlgs.
263 2017/05/06
264 - introduce sys_user_progs, make checks for updmap/fmtutil
265 use sys_user_progs instead, add kanji-config-updmap
266 2018/03/12
267 - introduce a new function gettexmfdist() for security.
268 2018/04/06
269 - introduce a new function is_64bit_windows_os() to
270 check Windows OS.
271 2018/06/20
272 - support also scripts in trees other than TEXMFDIST:
273 https://tug.org/pipermail/tex-live/2018-June/041922.html
274 2018/10/10
275 - support cluttex scripts
276 2018/11/08
277 - use included tcltk interpreter
278
279 ]]
280
281 -- HELPER SUBROUTINES --
282
283 local TEXDIR
284 local guimode
285
286 local function show_error(msg)
287 if guimode then
288 os.setenv('RUNSCRIPT_ERROR_MESSAGE', msg)
289 if lfs.isfile(TEXDIR..'/tlpkg/tltcl/tclkit.exe') and
290 lfs.isfile(TEXDIR..'/tlpkg/tltcl/gui_err.tcl') then
291 os.spawn{TEXDIR..'/tlpkg/tltcl/tclkit.exe',
292 TEXDIR..'/tlpkg/tltcl/gui_err.tcl'}
293 end
294 else
295 io.stderr:write(msg, '\n')
296 end
297 end
298
299 -- quotes string with spaces
300 local function _q(str)
301 str = string.gsub(str, '"', '') -- disallow embedded double quotes
302 return string.find(str, "%s") and '"'..str..'"' or str
303 end
304
305 -- prepends directories to path if they are not already there
306 local function prepend_path(path, ...)
307 local pathcmp = string.lower(string.gsub(path, '/', '\\'))..';'
308 for k = 1, select('#', ...) do
309 local dir = string.lower(string.gsub(select(k, ...), '/', '\\'))..';'
310 if not string.find(pathcmp, dir, 1, true) then path = dir..path end
311 end
312 return path
313 end
314
315 -- searches the PATH for a file
316 local function search_path(fname, PATH, PATHEXT)
317 if string.find(fname, '[/\\]') then
318 return nil, "directory part not allowed for PATH search: "..fname
319 end
320 PATH = PATH or os.getenv('PATH')
321 PATHEXT = PATHEXT or '\0' -- '\0' for no extension
322 for dir in string.gmatch(PATH, '[^;]+') do
323 local dirsep = (string.find(dir, '\\') and '\\' or '/')
324 for ext in string.gmatch(PATHEXT, '[^;]+') do
325 local f = dir..dirsep..fname..ext
326 if lfs.isfile(f) then return f, ext end
327 end
328 end
329 return nil, "file or program not on PATH: "..fname
330 end
331
332 -- tests for tex4ht command (as given in mk4ht.pl)
333 -- except for commands starting with 'ht' (they have their own scripts)
334 local function is_tex4ht_command(progname)
335 local prefixes = 'xh uxh xhm mz oo es js jm tei teim db dbm w jh jh1'
336 local formats = 'context latex tex texi xelatex xetex'
337 for p in string.gmatch(prefixes, '%S+') do
338 for q in string.gmatch(formats, '%S+') do
339 if (progname == p..q) then
340 -- we have a hit, but not all combinations are valid
341 return (p ~= 'teim' and p ~= 'dbm') or (q ~= 'xelatex' and q~= 'xetex')
342 end
343 end
344 end
345 return false
346 end
347
348 -- checks whether an item is in an array
349 local function contains (tab, val)
350 for index, value in ipairs(tab) do
351 if value == val then
352 return true
353 end
354 end
355 return false
356 end
357
358 -- locates texmfscript to execute
359 local function find_texmfscript(progname, ext_list)
360 ext_list = ext_list or '\0'
361 for ext in string.gmatch(ext_list, '[^;]+') do
362 local progfullname = kpse.find_file(progname..ext, 'texmfscripts')
363 if progfullname then return progfullname, ext end
364 end
365 return nil, "no appropriate script or program found: "..progname
366 end
367
368 -- converts the #! line to arg table
369 -- used for scripts w/o extension
370 -- only the two most common cases are considered:
371 -- #! /path/to/command [options]
372 -- #! /usr/bin/env command [options]
373 -- ([options] after the command are retained as well)
374 local function shebang_to_argv(progfullname)
375 local fid, errmsg = io.open(progfullname, 'r')
376 if not fid then return nil, errmsg end
377 local fstln = fid:read('*line')
378 fid:close()
379 if string.find(fstln, "eval.*exit.*exec.*perl") then
380 -- special case of Perl's time-honoured "totally devious construct":
381 -- eval '(exit $?0)' && eval 'exec perl -S $0 ${1+"$@"}' && eval 'exec perl -S $0 $argv:q'
382 return {"perl"}
383 elseif (string.sub(fstln, 1, 2) ~= '#!') then
384 return nil, "don't know how to execute script: "..progfullname
385 end
386 local argv = string.explode( string.sub(fstln, 3) ) -- split on spaces
387 argv[1] = string.match(argv[1], '[^/]+$')
388 if (argv[1] == 'env') then table.remove(argv, 1) end
389 return argv
390 end
391
392 -- checks if command exists on the path and returns its full path
393 local function check_command(cmdlist, PATH)
394 for cmd in string.gmatch(cmdlist, '%S+') do
395 local cmdext = cmd..(string.find(cmd, '%.[^\\/.]*$') and '' or '.exe')
396 local fullcmd = search_path(cmdext, PATH)
397 if fullcmd then
398 return fullcmd, cmd
399 end
400 end
401 return nil, 'program not found (not part of TeX Live): '..cmdlist
402 end
403
404 -- creates directory or directory hierarchy
405 local function mkdir_plus(dir)
406 if lfs.mkdir(dir) then
407 return true
408 end
409 -- try with system's mkdir in case we need to create intermediate dirs too
410 local ret = os.spawn({[0]=search_path("cmd.exe"),
411 string.format('cmd.exe /x /c mkdir "%s"', dir)})
412 if ret == 0 then
413 return true
414 else
415 return nil, string.format("cannot create directory (error code %d): %s", ret, dir)
416 end
417 end
418
419 --
420 -- return the TEXMFDIST directory in TeX Live
421 --
422 local function gettexmfdist()
423 local ffi = require("ffi")
424 ffi.cdef[[
425 typedef void* HANDLE;
426 typedef char* LPCSTR;
427 int GetModuleFileNameA(HANDLE h, LPCSTR l, int i);
428 HANDLE GetModuleHandleA(const char *a);
429 ]]
430 local buffer = ffi.new("char[?]", 512)
431 local runscripthandle = ffi.C.GetModuleHandleA("runscript.dll")
432 if runscripthandle == nil then
433 return nil
434 end
435 local err = ffi.C.GetModuleFileNameA(runscripthandle, buffer, 256)
436 if err == 0 then
437 return nil
438 end
439 local str = ffi.string(buffer)
440 str = string.gsub(str, "\\","/")
441 str = string.reverse(str)
442 local a, b
443 -- remove '/runscript.dll'
444 a, b = string.find(str, '/', 1, true)
445 str = string.sub(str,a+1)
446 -- remove '/win32'
447 a, b = string.find(str, '/', 1, true)
448 str = string.sub(str,a+1)
449 -- remove '/bin'
450 a, b = string.find(str, '/', 1, true)
451 str = string.sub(str,a+1)
452 str = string.reverse(str)
453 str = str .. '/texmf-dist'
454 return str
455 end
456
457 --
458 -- Is the Windows OS 64bit?
459 --
460 local function is_64bit_windows_os()
461 local return_val = false
462 -- 32 bit binaries always work, thus the default is false
463 local architecture = os.getenv('PROCESSOR_ARCHITECTURE')
464 if architecture ~= nil then
465 if architecture == 'x86' then
466 local is_wow64 = os.getenv('PROCESSOR_ARCHITEW6432')
467 if is_wow64 == nil then
468 return_val = false
469 else
470 return_val = true
471 end
472 else
473 return_val = true
474 end
475 end
476 return return_val
477 end
478
479 -- MAIN_CHUNK -- encapsulated in a function for more robust execution with pcall
480
481 local function MAIN_CHUNK()
482
483 --[[
484
485 OVERVIEW OF MAIN_CHUNK
486
487 We start out with a lot of housekeeping, especially with respect to
488 perl and ghostscript: if we are going to use the built-in versions,
489 then the search path and other environment variables must be set or
490 unset to make these findable and working right.
491
492 Next we compose an ARGV table for os.spawn, unless the script turns
493 out to be a [tex]lua script; see further down this comment block.
494
495 The parameter table ARGV can have the following elements (see the
496 luatex manual on os.exec and os.spawn):
497
498 - ARGV[0]: the full path to the interpreter
499 - ARGV[1]: the filename part of the interpreter. The interpreter choice
500 depends on the detected script extension and also on gui mode.
501 - ARGV[2]: progfulname, the full path to the script
502 - ARGV[3]: argline, i.e. the unparsed arguments for the script.
503 This is normally the last argument passed to runscript.tlu.
504 See the actual code for when this is not the case.
505
506 ARGV[0] gets priority over ARGV[1] if it is present.
507
508 After everything has been set up, a call os.spawn(ARGV) runs the
509 right program with the right arguments.
510
511 But in case the script to be run is a texlua script, we run the script
512 in the current texlua process using the dofile function. The original arg
513 argument table may have been modified before then.
514
515 Some variables:
516
517 - ARGV, see above
518 - arg, the texlua argument table of runscript.tlu
519 - progname, the name under which [w]runscript.exe was called
520 - progfullname, the full path of the script to be run. This variable
521 is introduced only after some special cases have been dealt with.
522 - argline, unparsed arguments to the script; may get modified
523
524 --]]
525
526 -- set the system-default value for LC_CTYPE
527 -- http://tug.org/pipermail/tex-live/2018-May/041628.html
528 os.setlocale("", "ctype")
529
530 -- preprocess arguments: arg[-1] => texlua.exe, arg[0] => scriptname
531
532 -- guimode already declared local
533 guimode = false
534 local argline = ''
535 -- check for the sentinel argment coming from the .exe stub
536 if arg[#arg-2] and ( string.sub(arg[#arg-2], -1) == '\n' ) then
537 -- argv[0] and unparsed argument line are passed
538 -- from the .exe stub as the two last arguments
539 -- pop them up from the arg table
540 argline = table.remove(arg) -- pop unparsed arguments
541 arg[0] = table.remove(arg) -- pop C stub's argv[0]
542 guimode = (table.remove(arg) == 'GUI_MODE\n') -- pop sentinel argument
543 else
544 -- we must be called as: texlua runscript.tlu progname ...
545 -- this is treated the same as: runscript[.exe] progname ...
546 -- we don't have the unparsed arument line in this case, so construct one
547 for k = #arg, 1, -1 do argline = _q(arg[k]) .. ' ' .. argline end
548 end
549
550 -- program name
551
552 -- lower arg[0] : get file name part : remove extension
553 local progname, substcount = string.lower(arg[0]):gsub('^.*[\\/]', ''):gsub('%.[^.]*$', '')
554 -- special behaviour when called under 'runscript' name
555 if (progname == 'runscript') then
556 -- we are called as: runscript progname ...
557 -- or as: runscript --help|-h|--version ...
558 -- handle options first (only --help and --version)
559 local opt, param = {}, nil
560 while true do
561 -- remove the first argument from the arg table and from the argline string
562 -- (this argument should have no embedded spaces!)
563 param = table.remove(arg, 1)
564 if not param then break end
565 argline = string.gsub(argline, '^%S+%s*', '')
566 local optname = string.lower(param):match('^%-%-?(.*)$')
567 if not optname then
568 break
569 elseif (optname == 'h') or (optname == 'help') then
570 opt.help = true
571 elseif (optname == 'v') then
572 opt.v = true
573 elseif (optname == 'version') then
574 opt.version = true
575 else
576 error("unknown option: "..param.."\n"..bannerstr)
577 end
578 end
579 if opt.help then
580 print(helpstr)
581 if opt.v then print(docstr) end
582 os.exit(0)
583 elseif opt.version or opt.v then
584 print(bannerstr)
585 os.exit(0)
586 end
587 -- make sure progname is valid
588 arg[0] = assert(param, "not enough arguments!\n"..bannerstr)
589 progname = string.lower(arg[0]):gsub('^.*[\\/]', ''):gsub('%.[^.]*$', '')
590 assert(progname == string.lower(arg[0]), "bad command name: " .. arg[0])
591 end
592 -- special case of sys programs
593 progname, substcount = string.gsub(progname, '%-sys$', '')
594 local sysprog = (substcount > 0) -- true if there was a -sys suffix removed
595 -- special case of user programs
596 -- we do not guard against programs foobar-user-sys ... we don't ship them
597 progname, substcount = string.gsub(progname, '%-user$', '')
598 local userprog = (substcount > 0) -- true if there was a -user suffix removed
599 -- prevent recursive calls to this script
600 assert(progname ~= 'runscript', "oops! wrapping the wrapper?")
601
602
603 -- kpse and environment set-up
604
605 -- init kpathsea
606 local k = -1
607 while arg[k-1] do k = k - 1 end -- in case of a call: luatex --luaonly ...
608 local lua_binary = arg[k]
609 kpse.set_program_name(lua_binary, progname)
610
611 -- various dir-vars
612 -- TEXDIR already declared local
613 TEXDIR = kpse.var_value('SELFAUTOPARENT')
614 -- local TEXMFDIST = kpse.var_value('TEXMFDIST')
615 -- use a new function to obtain TEXMFDIST
616 local TEXMFDIST = gettexmfdist()
617 if TEXMFDIST == nil then
618 TEXMFDIST = kpse.var_value('TEXMFDIST')
619 end
620 local BINDIR = kpse.var_value('SELFAUTOLOC')
621 local PATH = os.getenv('PATH') or ''
622
623 -- list of programs that have -sys and -user variants
624 local sys_user_progs = { 'updmap', 'fmtutil', 'kanji-config-updmap' }
625
626 -- restricted programs
627 local shell_escape_commands = string.lower(kpse.var_value('shell_escape_commands') or '')
628 local is_restricted_progname = string.find( ','..shell_escape_commands..',',
629 ','..progname..',', 1, true)
630 if is_restricted_progname then
631 -- limit search path to the restricted (system) trees
632 -- (not really necessary for entries in the alias_table,
633 -- because they are not searched for with kpathsea)
634 os.setenv('TEXMFSCRIPTS', kpse.var_value('TEXMF_RESTRICTED_SCRIPTS'))
635 end
636 -- perl stuff
637 local scripts4tlperl = {
638 tlperl = true,
639 updmap = true,
640 fmtutil = true,
641 ['updmap-sys'] = true,
642 ['fmtutil-sys'] = true,
643 }
644 local try_extern_perl = (kpse.var_value('TEXLIVE_WINDOWS_TRY_EXTERNAL_PERL') == '1') and
645 not (guimode or is_restricted_progname or scripts4tlperl[progname])
646 local PERLEXE = try_extern_perl and search_path('perl.exe', PATH)
647 local extperl_warn
648 if not PERLEXE then
649 if try_extern_perl then extperl_warn = [[
650 External Perl missing or outdated. Please install a recent Perl, or configure
651 TeX Live to always use the builtin Perl:
652 tlmgr conf texmf TEXLIVE_WINDOWS_TRY_EXTERNAL_PERL 0
653 Meanwhile, continuing with built-in Perl...
654 ]]
655 end -- if try_extern_perl
656 PERLEXE = TEXDIR..'/tlpkg/tlperl/bin/perl.exe'
657 os.setenv('PERL5LIB', TEXDIR..'/tlpkg/tlperl/lib')
658 PATH = prepend_path(PATH, TEXDIR..'/tlpkg/tlperl/bin')
659 local PERLENV = 'PERL5OPT;PERLIO;PERLIO_DEBUG;PERLLIB;PERL5DB;PERL5DB_THREADED;' ..
660 'PERL5SHELL;PERL_ALLOW_NON_IFS_LSP;PERL_DEBUG_MSTATS;' ..
661 'PERL_DESTRUCT_LEVEL;PERL_DL_NONLAZY;PERL_ENCODING;PERL_HASH_SEED;' ..
662 'PERL_HASH_SEED_DEBUG;PERL_ROOT;PERL_SIGNALS;PERL_UNICODE'
663 for var in string.gmatch(PERLENV, '[^;]+') do os.setenv(var, nil) end
664 end
665 -- gs stuff
666 local override_gs
667 if not is_restricted_progname then
668 override_gs = kpse.var_value('TEXLIVE_WINDOWS_EXTERNAL_GS')
669 end
670 -- the full path to the executable
671 local GSEXE
672 -- the directory where the gs executable resides
673 local GSDIR
674 -- the name of the gs executable
675 local GSNAME
676 if override_gs then
677 -- first check whether we got an absolute path or only executable name
678 if string.find(override_gs, '[/\\]') then
679 GSEXE = override_gs
680 else
681 -- search in the path
682 GSEXE = search_path(override_gs, PATH)
683 end
684 end
685 if GSEXE then
686 -- split the dir and progname part so that we can set the path
687 -- work on a string with all forward slashes
688 local foo = string.lower(string.gsub(GSEXE, '\\', '/'))
689 GSNAME = string.gsub(foo, '^.*[\\/]', '')
690 GSDIR = string.gsub(foo, '^(.*)[\\/].*$', '%1')
691 -- search also for a GS_DLL setting
692 -- we do not need to check for is_restricted_progname, since
693 -- GSEXE is only defined when it is not set
694 local GSDLL = kpse.var_value('TEXLIVE_WINDOWS_EXTERNAL_GS_DLL')
695 if GSDLL then
696 os.setenv('GS_DLL', GSDLL)
697 end
698 local GSLIB = kpse.var_value('TEXLIVE_WINDOWS_EXTERNAL_GS_LIB')
699 if GSLIB then
700 os.setenv('GS_LIB', GSLIB)
701 end
702 else
703 -- use built in gs
704 os.setenv('GS_LIB', TEXDIR..'/tlpkg/tlgs/lib;'
705 ..TEXDIR..'/tlpkg/tlgs/fonts;'
706 ..TEXDIR..'/tlpkg/tlgs/Resource/Init;'
707 ..TEXDIR..'/tlpkg/tlgs/Resource;'
708 ..TEXDIR..'/tlpkg/tlgs/kanji;'
709 ..os.getenv('WINDIR')..'/Fonts;'..TEXMFDIST..'/fonts')
710 os.setenv('GS_DLL', TEXDIR..'/tlpkg/tlgs/bin/gsdll32.dll')
711 GSEXE = TEXDIR..'/tlpkg/tlgs/bin/gswin32c.exe'
712 GSNAME = 'gswin32c.exe'
713 GSDIR = TEXDIR..'/tlpkg/tlgs/bin'
714 end
715 -- now setup the path so that the gs program will be found
716 PATH = prepend_path(PATH, GSDIR, BINDIR)
717 os.setenv('PATH', PATH);
718
719 -- sys stuff
720 if (sysprog and not contains(sys_user_progs, progname)) then
721 os.setenv('TEXMFVAR', kpse.var_value('TEXMFSYSVAR'))
722 os.setenv('TEXMFCONFIG', kpse.var_value('TEXMFSYSCONFIG'))
723 end
724 -- Adobe Reader crash case: make sure USERPROFILE is not "slashed"
725 os.setenv("USERPROFILE", os.getenv("USERPROFILE"):gsub('/', '\\'))
726
727 -- extension to interpreter mapping
728
729 -- the extension is mapped to an argument table.
730 -- the command to execute is given as the first element of the table,
731 -- which can be a whitespace separated list of names to try.
732 local extension_map = {
733 ['.bat'] = {'cmd', '/c', 'call'},
734 ['.jar'] = {'java.exe', '-jar'},
735 ['.pl' ] = {'perl.exe'},
736 ['.py' ] = {'python.exe'},
737 ['.rb' ] = {'ruby.exe'},
738 ['.tcl'] = {'tclsh.exe tclsh86.exe tclsh85.exe tclkitsh.exe'},
739 ['.vbs'] = {'cscript.exe', '-nologo'},
740 }
741 if guimode then
742 -- for GUI mode wrappers we try GUI mode interpeters where possible
743 extension_map['.jar'][1] = 'javaw.exe ' .. extension_map['.jar'][1]
744 extension_map['.pl' ][1] = 'wperl.exe ' .. extension_map['.pl' ][1]
745 extension_map['.py' ][1] = 'pythonw.exe ' .. extension_map['.py' ][1]
746 extension_map['.rb' ][1] = 'rubyw.exe ' .. extension_map['.rb' ][1]
747 -- gui tcl shares no interpreters with non-gui tcl
748 extension_map['.tcl'] = {'wish.exe wish86.exe wish85.exe tclkit.exe'}
749 extension_map['.vbs'][1] = 'wscript.exe ' .. extension_map['.vbs'][1]
750 end
751 extension_map['.cmd'] = extension_map['.bat']
752 extension_map['.js'] = extension_map['.vbs']
753
754 -- set up ARGV table
755
756 local ARGV = nil
757
758 -- special cases (aliases)
759
760 if is_tex4ht_command(progname) then
761 argline = progname .. ' ' .. argline
762 progname = 'mk4ht'
763 elseif progname == 'a2ping' then
764 table.insert(extension_map['.pl'], '-x')
765 elseif contains(sys_user_progs, progname) then
766 if sysprog then
767 argline = ' --sys ' .. argline
768 elseif userprog then
769 argline = ' --user ' .. argline
770 end
771 -- do not guess input encoding in format creation for ptex
772 -- and friends since guessing is not complete
773 os.setenv('GUESS_INPUT_KANJI_ENCODING', '0')
774 elseif progname == 'asy' then
775 os.setenv('ASYMPTOTE_GS', GSEXE)
776 os.setenv('CYGWIN', 'nodosfilewarning')
777 if is_64bit_windows_os() then
778 ARGV = {[0]=TEXDIR..'/tlpkg/asymptote64/asy.exe', 'asy'}
779 else
780 ARGV = {[0]=TEXDIR..'/tlpkg/asymptote/asy.exe', 'asy'}
781 end
782 elseif progname == 'dviout' then
783 local fontsdir = kpse.var_value('TEXMFVAR') .. '/fonts'
784 if (lfs.attributes(fontsdir, 'mode') ~= 'directory') then
785 assert(mkdir_plus(fontsdir))
786 end
787 local tfmpath = kpse.show_path('tfm')
788 tfmpath = string.gsub(tfmpath, '!!', '')
789 tfmpath = string.gsub(tfmpath, '/', '\\')
790 local texrt = {}
791 for d in string.gmatch(tfmpath, '([^;]+\\fonts)\\tfm[^;]*') do
792 if (lfs.attributes(d, 'mode') == 'directory') then
793 table.insert(texrt, d)
794 end
795 end
796 local par = [["-gen=']] .. string.gsub(TEXDIR, '/', '\\') ..
797 [[\tlpkg\dviout\gen_pk'" "-TEXROOT=']] ..
798 table.concat(texrt, ';') .. [['" "-gsx=']] .. GSEXE .. [['"]];
799 ARGV = {[0]=TEXDIR..'/tlpkg/dviout/dviout.exe', 'dviout', par}
800 elseif progname == 'mkluatexfontdb' then
801 progname = 'luaotfload-tool'
802 table.insert(arg, '--alias=mkluatexfontdb')
803 elseif progname == 'psv' then
804 argline = '-sINPUT='..argline
805 ARGV = {[0]=TEXDIR..'/tlpkg/tlpsv/gswxlua.exe', 'gswxlua',
806 '-dDisableFAPI=true',
807 '-l', (_q(TEXDIR..'/tlpkg/tlpsv/psv.wx.lua'):gsub('/','\\')),
808 '-p', (_q(TEXDIR..'/tlpkg/tlpsv/psv_view.ps'):gsub('/','\\')),
809 '-i', '.'}
810 elseif progname == 'repstopdf' or progname == 'rpdfcrop' then
811 argline = '--restricted ' .. argline
812 progname = string.sub(progname, 2, -1)
813 elseif progname == 'texworks' then
814 local winver = tonumber(string.match(os.uname().version, '%D*(%d+%.?%d*)'))
815 assert(winver >= 5.01, "Windows XP or newer required to run TeXworks")
816 local TW_LIBPATH = kpse.var_value('TW_LIBPATH') or
817 kpse.var_value('TEXMFCONFIG')..'/texworks'
818 local TW_INIPATH = kpse.var_value('TW_INIPATH') or TW_LIBPATH
819 os.setenv('TW_LIBPATH', TW_LIBPATH)
820 os.setenv('TW_INIPATH', TW_INIPATH)
821 if (TW_INIPATH and lfs.attributes(TW_INIPATH, 'mode') ~= 'directory') then
822 -- TeXworks needs directory holding its configuration to exist
823 assert(mkdir_plus(TW_INIPATH))
824 end
825 ARGV = {[0]=TEXDIR..'/tlpkg/texworks/texworks.exe', 'texworks'}
826 elseif progname == 'tlgs' then
827 ARGV = {[0]=GSEXE, GSNAME}
828 elseif progname == 'tlperl' then
829 ARGV = {[0]=PERLEXE, 'perl'}
830 elseif progname == 'latexdef' then
831 progname = 'texdef'
832 argline = ' --tex latex ' .. argline
833 elseif progname == 'cllualatex' then
834 progname = 'cluttex'
835 argline = ' --engine=lualatex ' .. argline
836 elseif progname == 'clxelatex' then
837 progname = 'cluttex'
838 argline = ' --engine=xelatex ' .. argline
839 end
840
841 -- general case
842
843 if not ARGV then
844 os.setenv('TEXMF', TEXMFDIST)
845 local extlist = '.tlu;.texlua;.pl;.lua;.rb;.py;.tcl;.jar;.vbs;.js;.bat;.cmd;\0'
846 local progfullname = search_path(progname, BINDIR, '.tlu;.bat;.cmd') or
847 find_texmfscript(progname, extlist)
848 os.setenv('TEXMF', nil)
849 if progfullname == nil then
850 -- scripts in $TEXMFLOCAL etc. can't be found without the following
851 -- line !!
852 kpse.set_program_name('runscript')
853 progfullname = assert(find_texmfscript(progname, extlist))
854 end
855 local ext = string.match(string.lower(progfullname), '%.[^\\/.]*$') or ''
856 if (ext == '.lua') or (ext == '.tlu') or (ext == '.texlua') then -- lua script
857 arg[0] = progfullname
858 elseif (ext == '.tcl' and guimode) then -- tcl script; use built-in tclkit?
859 local try_extern_tcl =
860 (kpse.var_value('TEXLIVE_WINDOWS_TRY_EXTERNAL_TCL') == '1') and
861 not is_restricted_progname
862 local TCLEXENAME, TCLEXE
863 if try_extern_tcl then
864 TCLEXENAME, TCLEXE = check_command(extension_map['.tcl'][1], PATH)
865 end
866 if try_extern_tcl and not TCLEXENAME then
867 local exttcl_warn = [[
868 External Tcl missing or outdated. Please install a recent Tcl, or configure
869 TeX Live to always use the builtin Tcl for gui scripts:
870 tlmgr conf texmf TEXLIVE_WINDOWS_TRY_EXTERNAL_TCL 0
871 Meanwhile, continuing with built-in Tcl...
872 ]]
873 show_error(exttcl_warn)
874 else -- did find something
875 ARGV = {[0]=TCLEXE, TCLEXENAME}
876 end
877 if not TCLEXENAME then
878 ARGV = {[0]=TEXDIR..'/tlpkg/tltcl/tclkit.exe', 'tclkit.exe'}
879 PATH = prepend_path(PATH, TEXDIR:gsub('/','\\')..'\\tlpkg\\tltcl')
880 end
881 table.insert(ARGV, _q(progfullname:gsub('/','\\')))
882 if (argline and argline ~= '') then argline = '-- '..argline end
883 else -- not gui tcl or not tcl at all
884 ARGV = extension_map[ext] or assert(shebang_to_argv(progfullname))
885 -- [w|c]script, for one, mistakes a forward-slashed UNC script path
886 -- for an option even when quoted
887 table.insert(ARGV, _q(progfullname:gsub('/','\\')))
888 if not ARGV[0] then
889 ARGV[0], ARGV[1] = assert(check_command(ARGV[1], PATH))
890 end
891 end
892 end
893
894 -- run the program/script
895
896 if ARGV then
897 table.insert(ARGV, argline) -- pass through original arguments
898 if string.find (table.concat(ARGV, ' '), 'perl.exe') and extperl_warn then
899
900 show_error(extperl_warn)
901 end
902 local ret = assert(os.spawn(ARGV))
903 if ret ~= 0 then
904 local dbginfo = debug.getinfo(1)
905 local errormsg = string.format("%s:%d: command failed with exit code %d:\n%s",
906 dbginfo.short_src, dbginfo.currentline - 2,
907 ret, table.concat(ARGV, ' ') )
908 show_error(errormsg)
909 end
910 os.exit(ret)
911 else -- must be a lua script
912 dofile(arg[0])
913 end
914
915 end -- MAIN_CHUNK
916
917 -- execute MAIN_CHUNK with pcall to catch any runtime errors
918
919 local success, errormsg = pcall(MAIN_CHUNK)
920 if not success then
921 os.setenv('RUNSCRIPT_ERROR_MESSAGE', errormsg)
922 error(errormsg)
923 end
924
925 -- about RUNSCRIPT_ERROR_MESSAGE environment variable:
926 -- it stores an error message that is caught and displayed
927 -- in a message box on the C side at process exit
928 -- (currently used only by gui mode stubs)