6 * Written by Keith Marshall <keithmarshall@users.sourceforge.net>
7 * Copyright (C) 2009, 2010, 2011, MinGW Project
10 * Initiation stub for command line invocation of mingw-get
13 * This is free software. Permission is granted to copy, modify and
14 * redistribute this software, under the provisions of the GNU General
15 * Public License, Version 3, (or, at your option, any later version),
16 * as published by the Free Software Foundation; see the file COPYING
17 * for licensing details.
19 * Note, in particular, that this software is provided "as is", in the
20 * hope that it may prove useful, but WITHOUT WARRANTY OF ANY KIND; not
21 * even an implied WARRANTY OF MERCHANTABILITY, nor of FITNESS FOR ANY
22 * PARTICULAR PURPOSE. Under no circumstances will the author, or the
23 * MinGW Project, accept liability for any damages, however caused,
24 * arising from the use of this software.
27 #define _WIN32_WINNT 0x500
28 #define WIN32_LEAN_AND_MEAN
41 #define EXIT_FATAL EXIT_FAILURE + 1
43 wchar_t *AppPathNameW( const wchar_t *relpath )
45 /* UTF-16LE implementation; NOT thread safe...
47 * Map "relpath" into the file system hierarchy with logical root
48 * at the prefix where the application suite is installed, such that
49 * it becomes "d:\prefix\relpath".
51 * If the application's executables are installed in a directory called
52 * "bin" or "sbin", then this final directory is excluded from the mapped
53 * prefix, (i.e. a program installed as "d:\prefix\bin\prog.exe" returns
54 * the mapped path as "d:\prefix\relpath", rather than as the inclusive
55 * path "d:\prefix\bin\relpath"); in any other case, the prefix is taken
56 * as the path to the directory in which the program file is installed,
57 * (i.e. a program installed as "d:\prefix\foo\prog.exe" returns the
58 * mapped path as "d:\prefix\foo\relpath".
60 * Mapped path is returned in this static buffer...
62 static wchar_t retpath[MAX_PATH], *tail = NULL;
66 /* First time initialisation...
68 * Fill in the static local buffer, with the appropriate "prefix"
69 * string, marking the point at which "relpath" is to be appended.
71 * On subsequent calls, we reuse this static buffer, leaving the
72 * "prefix" element unchanged, but simply overwriting the "relpath"
73 * element from any prior call; this is NOT thread safe!
76 wchar_t bindir[] = L"bin", *bindir_p = bindir;
77 wchar_t *mark, *scan = mark = tail = retpath;
79 /* Ascertain the installation path of the calling executable.
81 int chk = GetModuleFileNameW( NULL, retpath, MAX_PATH );
83 /* Validate it; reject any result which doesn't fit in "retpath".
85 if( (chk == 0) || ((chk == MAX_PATH) && (retpath[--chk] != L'\0')) )
88 /* Parse it, to locate the end of the effective "prefix" string...
90 do { if( *scan == L'/' )
92 * This is a sanity check; it should not be necessary, but...
94 * Enforce use of "\" rather than "/" as path component separator;
95 * ( "LoadLibrary" may be broken, since it seems to care! )
99 if( *scan && (prev == L'\\') )
101 /* We found the start a new path name component directory,
102 * (or maybe the file name, at the end); mark it as a possible
103 * final element of the path name, leaving "tail" pointing to
104 * the previously marked element.
109 } while( (prev = *scan++) != L'\0' );
111 /* When we get to here, "mark" should point to the executable file name,
112 * at the end of the path name string, while "tail" should point to the
113 * last directory in the installation path; we now check, without regard
114 * to case, if this final directory name is "bin" or "sbin"...
116 if( (*(scan = tail) == L's') || (*scan == L'S') )
118 * Might be "sbin"; skip the initial "s", and check for "bin"...
122 while( *bindir_p && ((*scan++ | L'\x20') == *bindir_p++) )
124 * ...could still match "bin"...
126 if( *bindir_p || (*scan != L'\\') )
128 * No, it didn't match; adjust "tail", so we leave the final
129 * directory name as part of "prefix".
134 if( relpath == NULL )
136 * No "relpath" argument given; simply truncate, to return only
137 * the effective "prefix" string...
142 { wchar_t *append = tail;
144 * Append the specified path to the application's root,
145 * again, taking care to use "\" as the separator character...
147 *append++ = (*relpath == L'/') ? L'\\' : *relpath;
148 } while( *relpath++ && ((append - retpath) < MAX_PATH) );
150 if( *--append != L'\0' )
152 * Abort, if we didn't properly terminate the return string.
159 extern const char *version_identification;
161 static const char *help_text =
162 "Manage MinGW and MSYS installations (command line user interface).\n\n"
165 " mingw-get [OPTIONS] ACTION [package-spec ...]\n\n"
167 " mingw-get update\n"
168 " mingw-get [OPTIONS] {install | upgrade | remove} package-spec ...\n"
169 " mingw-get [OPTIONS] {show | list} [package-spec ...]\n\n"
172 " --help, -h Show this help text\n"
174 " --version, -V Show version and licence information\n"
176 " --verbose, -v Increase verbosity of diagnostic or\n"
177 " progress reporting output; repeat up\n"
178 " to three times for maximum verbosity\n"
179 " --verbose=N Set verbosity level to N; (0 <= N <= 3)\n"
182 /* The "--trace" option is available only when dynamic tracing
183 * debugging support is compiled in; don't advertise it otherwise.
185 #if DEBUG_ENABLED( DEBUG_TRACE_DYNAMIC )
186 " --trace=N Enable tracing feature N; (debugging aid)\n"
190 /* The following are always available...
192 " --reinstall When performing an install or upgrade\n"
193 " operation, reinstall any named package\n"
194 " for which the most recent release is\n"
195 " already installed\n"
197 " --download-only Download the package archive files which\n"
198 " would be required to complete the specified\n"
199 " install, upgrade, or source operation, but\n"
200 " do not unpack them, or otherwise proceed\n"
201 " to complete the operation\n"
203 " --print-uris Display the repository URIs from which\n"
204 " package archive files would be retrieved\n"
205 " prior to performing the specified install,\n"
206 " upgrade, or source operation, but do not\n"
207 " download any package file, or otherwise\n"
208 " proceed with the operation\n"
211 " --all-related When performing source or licence operations,\n"
212 " causes mingw-get to retrieve, and optionally to\n"
213 " unpack the source or licence archives for all\n"
214 " runtime prerequisites of, and in addition to,\n"
215 " the nominated package\n"
218 " update Update local copy of repository catalogues\n"
219 " list, show List and show details of available packages\n"
220 " source Download and optionally unpack package sources\n"
221 " licence Download and optionally unpack licence packages,\n"
222 " handling them as if they are source packages\n"
223 " install Install new packages\n"
224 " upgrade Upgrade previously installed packages\n"
225 " remove Remove previously installed packages\n\n"
227 "Package Specifications:\n"
228 " [subsystem-]name[-component]:\n"
229 " msys-bash-doc The 'doc' component of the bash package for MSYS\n"
230 " mingw32-gdb All components of the gdb package for MinGW\n\n"
232 "Use 'mingw-get list' to identify possible package names\n"
233 "and the components associated with each.\n\n";
235 #define IMPLEMENT_INITIATION_RITES PHASE_ONE_RITES
238 static __inline__ __attribute__((__always_inline__))
239 char **cli_setargv( HMODULE my_dll, struct pkgopts *opts, char **argv )
241 /* A local wrapper function to facilitate passing pre-parsed
242 * command line options while performing the "climain()" call
243 * into mingw-get-0.dll
245 * Note that this requires a version of mingw-get-0.dll which
246 * provides the "cli_setopts()" hook...
248 typedef void (*dll_hook)(struct pkgopts *);
249 dll_hook cli_setopts = (dll_hook)(GetProcAddress( my_dll, "cli_setopts" ));
250 if( cli_setopts != NULL )
252 * ...which allows us to pass the pre-parsed options.
256 /* In any case, we always return the argument vector which is
257 * to be passed in the "climain()" call itself.
262 /* FIXME: We may ultimately choose to factor the following atoi() replacement
263 * into a separate, free-standing module. For now we keep it here, as a static
264 * function, but we keep the required #include adjacent.
268 static int xatoi( const char *input )
270 /* A replacement for the standard atoi() function; this implementation
271 * supports conversion of octal or hexadecimal representations, in addition
272 * to the decimal representation required by standard atoi().
274 * We begin by initialising the result accumulator to zero...
278 /* ...then, provided we have an input string to interpret...
282 /* ...we proceed with interpretation and accumulation of the result,
283 * noting that we may have to handle an initial minus sign, (but we
284 * don't know yet, so assume that not for now).
287 while( isspace( *input ) )
289 * Ignore leading white space.
295 * An initial minus sign requires negation
296 * of the accumulated result...
300 else if( *input == '+' )
302 * ...while an initial plus sign is redundant,
303 * and may simply be ignored.
309 /* An initial zero signifies either hexadecimal
310 * or octal representation...
312 if( (*++input | '\x20') == 'x' )
314 * ...with following 'x' or 'X' indicating
315 * the hexadecimal case.
317 while( isxdigit( *++input ) )
319 /* Interpret sequence of hexadecimal digits...
321 result = (result << 4) + *input;
324 * ...with ASCII to binary conversion for
325 * lower case digits 'a'..'f',...
329 else if( *input > '9' )
331 * ...ASCII to binary conversion for
332 * upper case digits 'A'..'F',...
337 /* ...or ASCII to decimal conversion,
342 else while( (*input >= '0') && (*input < '8') )
344 * Interpret sequence of octal digits...
346 result = (result << 3) + *input++ - '0';
349 else while( isdigit( *input ) )
351 * Interpret sequence of decimal digits...
353 result = (result << 1) + (result << 3) + *input++ - '0';
357 * We had an initial minus sign, so we must
358 * return the negated result...
362 /* ...otherwise, we simply return the accumulated result
367 #define atmost( lim, val ) ((lim) < (val)) ? (lim) : (val)
369 int main( int argc, char **argv )
373 const char *progname = basename( *argv ); /* ...this program's name */
374 wchar_t *approot; /* and where it is installed */
376 /* Provide storage for interpretation of any parsed command line options.
377 * Note that we could also initialise them here, but then we would need to
378 * give attention to the number of initialisers required; to save us that
379 * concern we will defer to an initialisation loop, below.
381 struct pkgopts parsed_options;
385 /* The user specified arguments on the command line...
386 * Interpret any which specify processing options for this application,
387 * (these are all specified in GNU `long only' style).
390 struct option options[] =
392 /* Option Name Argument Category Store To Return Value
393 * -------------- ------------------ -------- ------------------
395 { "version", no_argument, NULL, 'V' },
396 { "help", no_argument, NULL, 'h' },
397 { "verbose", optional_argument, NULL, OPTION_VERBOSE },
399 { "recursive", no_argument, &optref, OPTION_ALL_DEPS },
400 { "reinstall", no_argument, &optref, OPTION_REINSTALL },
401 { "download-only", no_argument, &optref, OPTION_DNLOAD_ONLY },
402 { "print-uris", no_argument, &optref, OPTION_PRINT_URIS },
404 { "all-related", no_argument, &optref, OPTION_ALL_DEPS },
406 # if DEBUG_ENABLED( DEBUG_TRACE_DYNAMIC )
407 /* The "--trace" option is supported only when dynamic tracing
408 * debugging support has been compiled in.
410 { "trace", required_argument, &optref, OPTION_TRACE },
413 /* This list must be terminated by a null definition...
419 for( opt = OPTION_FLAGS; opt < OPTION_TABLE_SIZE; ++opt )
421 * Ensure that all entries within the options table are initialised
422 * to zero, (equivalent to NULL for pointer entries)...
424 parsed_options.flags[opt].numeric = 0;
426 while( (opt = getopt_long_only( argc, argv, "vVh", options, &offset )) != -1 )
428 * Parse any user specified options from the command line...
433 /* This is a request to display the version of the application;
434 * emit the requisite informational message, and quit.
436 printf( version_identification );
440 /* This is a request to display help text and quit.
446 /* This is a request to set an explicit verbosity level,
447 * (minimum zero, maximum three), or if no explicit argument
448 * is specified, to increment verbosity as does "-v".
452 /* This is the case where an explicit level was specified...
454 parsed_options.flags[OPTION_FLAGS].numeric =
455 (parsed_options.flags[OPTION_FLAGS].numeric & ~OPTION_VERBOSE)
456 | atmost( OPTION_VERBOSE_MAX, xatoi( optarg ));
461 /* This is a request to increment the verbosity level
462 * from its initial zero setting, to a maximum of three.
464 if( (parsed_options.flags[OPTION_FLAGS].numeric & OPTION_VERBOSE) < 3 )
465 ++parsed_options.flags[OPTION_FLAGS].numeric;
469 switch( optref & OPTION_STORAGE_CLASS )
471 /* This represents a generic option specification,
472 * allowing for storage of a option argument of the
473 * specified class into a specified option slot...
477 case OPTION_STORE_STRING:
478 /* This is a simple store of a option argument
479 * which represents a character string.
481 parsed_options.flags[optref & 0xfff].string = optarg;
484 case OPTION_STORE_NUMBER:
485 /* This is also a simple store of the argument value,
486 * in this case interpreted as a number.
488 parsed_options.flags[optref & 0xfff].numeric = xatoi( optarg );
491 case OPTION_MERGE_NUMBER:
492 /* In this case, we combine the value of the argument,
493 * again interpreted as a number, with the original value
494 * stored in the option slot, forming the bitwise logical
495 * .OR. of the pair of values.
497 parsed_options.flags[optref & 0xfff].numeric |= xatoi( optarg );
501 /* This is a mask and store operation for a specified
502 * bit-field within the first pair of flags slots; in
503 * this case, the optref value itself specifies a 12-bit
504 * value, a 12-bit combining mask, and an alignment shift
505 * count between 0 and 52, in 4-bit increments.
507 if( (shift = (optref & OPTION_SHIFT_MASK) >> 22) < 53 )
509 uint64_t value = optref & 0xfff;
510 uint64_t mask = (optref & 0xfff000) >> 12;
511 *(uint64_t *)(parsed_options.flags) &= ~(mask << shift);
512 *(uint64_t *)(parsed_options.flags) |= value << shift;
518 /* User specified an invalid or unsupported option...
521 fprintf( stderr, "%s: option '-%s' not yet supported\n",
522 progname, options[offset].name
528 /* Establish the installation path for the mingw-get application...
530 if( (approot = AppPathNameW( NULL )) != NULL )
532 /* ...and set up the APPROOT environment variable to refer to
533 * the associated installation prefix...
535 char approot_setup[1 + snprintf( NULL, 0, "APPROOT=%S", approot )];
536 snprintf( approot_setup, sizeof( approot_setup ), "APPROOT=%S", approot );
537 putenv( approot_setup );
542 /* The user specified arguments on the command line...
543 * we load the supporting DLL into the current process context,
544 * then, remaining in command line mode, we jump to its main
545 * command line processing routine...
548 char *argv_base = *argv;
549 typedef int (*dll_entry)( int, char ** );
550 HMODULE my_dll = LoadLibraryW( AppPathNameW( MINGW_GET_DLL ) );
551 dll_entry climain = (dll_entry)(GetProcAddress( my_dll, "climain" ));
552 if( climain == NULL )
554 /* ...bailing out, on failure to load the DLL.
556 fprintf( stderr, "%s: %S: shared library load failed\n",
557 progname, MINGW_GET_DLL
562 /* Adjust argc and argv to discount parsed options...
567 * ...while preserving the original argv[0] reference within
568 * the first remaining argument to be passed to climain().
572 /* We want only one mingw-get process accessing the XML database
573 * at any time; attempt to acquire an exclusive access lock...
575 if( (lock = pkgInitRites( progname )) >= 0 )
577 /* ...and proceed, only if successful.
578 * A non-zero return value indicates that a fatal error occurred.
580 int rc = climain( argc, cli_setargv( my_dll, &parsed_options, argv ) );
582 /* We must release the mingw-get DLL code, BEFORE we invoke
583 * last rites processing, (otherwise the last rites clean-up
584 * handler exhibits abnormal behaviour when it is exec'd).
586 FreeLibrary( my_dll );
588 return pkgLastRites( lock, progname );
591 (void) pkgLastRites( lock, progname );
595 /* If we get to here, then we failed to acquire a lock;
602 { /* No arguments were specified on the command line...
603 * we interpret this as a request to start up in GUI mode...
605 wchar_t *libexec_path = AppPathNameW( MINGW_GET_GUI );
606 char gui_program[1 + snprintf( NULL, 0, "%S", libexec_path )];
607 snprintf( gui_program, sizeof( gui_program ), "%S", libexec_path );
608 int status = execv( gui_program, (const char* const*)(argv) );
610 /* If we get to here, then the GUI could not be started...
611 * Issue a diagnostic message, before abnormal termination.
614 "%s: %S: unable to start GUI; helper program not installed\n",
615 progname, MINGW_GET_GUI
621 /* $RCSfile$: end of file */