Debian Codegraph @

texk/texlive/windows_wrapper/runscript.tlu

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