1 /*
   2  * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * Class-Path Wildcards
  28  *
  29  * The syntax for wildcards is a single asterisk. The class path
  30  * foo/"*", e.g., loads all jar files in the directory named foo.
  31  * (This requires careful quotation when used in shell scripts.)
  32  *
  33  * Only files whose names end in .jar or .JAR are matched.
  34  * Files whose names end in .zip, or which have a particular
  35  * magic number, regardless of filename extension, are not
  36  * matched.
  37  *
  38  * Files are considered regardless of whether or not they are
  39  * "hidden" in the UNIX sense, i.e., have names beginning with '.'.
  40  *
  41  * A wildcard only matches jar files, not class files in the same
  42  * directory.  If you want to load both class files and jar files from
  43  * a single directory foo then you can say foo:foo/"*", or foo/"*":foo
  44  * if you want the jar files to take precedence.
  45  *
  46  * Subdirectories are not searched recursively, i.e., foo/"*" only
  47  * looks for jar files in foo, not in foo/bar, foo/baz, etc.
  48  *
  49  * Expansion of wildcards is done early, prior to the invocation of a
  50  * program's main method, rather than late, during the class-loading
  51  * process itself.  Each element of the input class path containing a
  52  * wildcard is replaced by the (possibly empty) sequence of elements
  53  * generated by enumerating the jar files in the named directory.  If
  54  * the directory foo contains a.jar, b.jar, and c.jar,
  55  * e.g., then the class path foo/"*" is expanded into
  56  * foo/a.jar:foo/b.jar:foo/c.jar, and that string would be the value
  57  * of the system property java.class.path.
  58  *
  59  * The order in which the jar files in a directory are enumerated in
  60  * the expanded class path is not specified and may vary from platform
  61  * to platform and even from moment to moment on the same machine.  A
  62  * well-constructed application should not depend upon any particular
  63  * order.  If a specific order is required then the jar files can be
  64  * enumerated explicitly in the class path.
  65  *
  66  * The CLASSPATH environment variable is not treated any differently
  67  * from the -classpath (equiv. -cp) command-line option,
  68  * i.e. wildcards are honored in all these cases.
  69  *
  70  * Class-path wildcards are not honored in the Class-Path jar-manifest
  71  * header.
  72  *
  73  * Class-path wildcards are honored not only by the Java launcher but
  74  * also by most other command-line tools that accept class paths, and
  75  * in particular by javac and javadoc.
  76  *
  77  * Class-path wildcards are not honored in any other kind of path, and
  78  * especially not in the bootstrap class path, which is a mere
  79  * artifact of our implementation and not something that developers
  80  * should use.
  81  *
  82  * Classpath wildcards are only expanded in the Java launcher code,
  83  * supporting the use of wildcards on the command line and in the
  84  * CLASSPATH environment variable.  We do not support the use of
  85  * wildcards by applications that embed the JVM.
  86  */
  87 
  88 #include <stddef.h>
  89 #include <stdio.h>
  90 #include <stdlib.h>
  91 #include <string.h>
  92 #include <sys/types.h>
  93 #include "java.h"       /* Strictly for PATH_SEPARATOR/FILE_SEPARATOR */
  94 #include "jli_util.h"
  95 
  96 #ifdef _WIN32
  97 #include <windows.h>
  98 #else /* Unix */
  99 #include <unistd.h>
 100 #include <dirent.h>
 101 #endif /* Unix */
 102 
 103 static int
 104 exists(const char* filename)
 105 {
 106 #ifdef _WIN32
 107     return _access(filename, 0) == 0;
 108 #else
 109     return access(filename, F_OK) == 0;
 110 #endif
 111 }
 112 
 113 #define NEW_(TYPE) ((TYPE) JLI_MemAlloc(sizeof(struct TYPE##_)))
 114 
 115 /*
 116  * Wildcard directory iteration.
 117  * WildcardIterator_for(wildcard) returns an iterator.
 118  * Each call to that iterator's next() method returns the basename
 119  * of an entry in the wildcard's directory.  The basename's memory
 120  * belongs to the iterator.  The caller is responsible for prepending
 121  * the directory name and file separator, if necessary.
 122  * When done with the iterator, call the close method to clean up.
 123  */
 124 typedef struct WildcardIterator_* WildcardIterator;
 125 
 126 #ifdef _WIN32
 127 struct WildcardIterator_
 128 {
 129     HANDLE handle;
 130     char *firstFile; /* Stupid FindFirstFile...FindNextFile */
 131 };
 132 // since this is used repeatedly we keep it here.
 133 static WIN32_FIND_DATA find_data;
 134 static WildcardIterator
 135 WildcardIterator_for(const char *wildcard)
 136 {
 137     WildcardIterator it = NEW_(WildcardIterator);
 138     HANDLE handle = FindFirstFile(wildcard, &find_data);
 139     if (handle == INVALID_HANDLE_VALUE) {
 140         JLI_MemFree(it);
 141         return NULL;
 142     }
 143     it->handle = handle;
 144     it->firstFile = find_data.cFileName;
 145     return it;
 146 }
 147 
 148 static char *
 149 WildcardIterator_next(WildcardIterator it)
 150 {
 151     if (it->firstFile != NULL) {
 152         char *firstFile = it->firstFile;
 153         it->firstFile = NULL;
 154         return firstFile;
 155     }
 156     return FindNextFile(it->handle, &find_data)
 157         ? find_data.cFileName : NULL;
 158 }
 159 
 160 static void
 161 WildcardIterator_close(WildcardIterator it)
 162 {
 163     if (it) {
 164         FindClose(it->handle);
 165         JLI_MemFree(it->firstFile);
 166         JLI_MemFree(it);
 167     }
 168 }
 169 
 170 #else /* Unix */
 171 struct WildcardIterator_
 172 {
 173     DIR *dir;
 174 };
 175 
 176 static WildcardIterator
 177 WildcardIterator_for(const char *wildcard)
 178 {
 179     DIR *dir;
 180     int wildlen = JLI_StrLen(wildcard);
 181     if (wildlen < 2) {
 182         dir = opendir(".");
 183     } else {
 184         char *dirname = JLI_StringDup(wildcard);
 185         dirname[wildlen - 1] = '\0';
 186         dir = opendir(dirname);
 187         JLI_MemFree(dirname);
 188     }
 189     if (dir == NULL)
 190         return NULL;
 191     else {
 192         WildcardIterator it = NEW_(WildcardIterator);
 193         it->dir = dir;
 194         return it;
 195     }
 196 }
 197 
 198 static char *
 199 WildcardIterator_next(WildcardIterator it)
 200 {
 201     struct dirent* dirp = readdir(it->dir);
 202     return dirp ? dirp->d_name : NULL;
 203 }
 204 
 205 static void
 206 WildcardIterator_close(WildcardIterator it)
 207 {
 208     if (it) {
 209         closedir(it->dir);
 210         JLI_MemFree(it);
 211     }
 212 }
 213 #endif /* Unix */
 214 
 215 static int
 216 equal(const char *s1, const char *s2)
 217 {
 218     return JLI_StrCmp(s1, s2) == 0;
 219 }
 220 
 221 static int
 222 isJarFileName(const char *filename)
 223 {
 224     int len = (int)JLI_StrLen(filename);
 225     return (len >= 4) &&
 226         (filename[len - 4] == '.') &&
 227         (equal(filename + len - 3, "jar") ||
 228          equal(filename + len - 3, "JAR")) &&
 229         /* Paranoia: Maybe filename is "DIR:foo.jar" */
 230         (JLI_StrChr(filename, PATH_SEPARATOR) == NULL);
 231 }
 232 
 233 static char *
 234 wildcardConcat(const char *wildcard, const char *basename)
 235 {
 236     int wildlen = (int)JLI_StrLen(wildcard);
 237     int baselen = (int)JLI_StrLen(basename);
 238     char *filename = (char *) JLI_MemAlloc(wildlen + baselen);
 239     /* Replace the trailing '*' with basename */
 240     memcpy(filename, wildcard, wildlen-1);
 241     memcpy(filename+wildlen-1, basename, baselen+1);
 242     return filename;
 243 }
 244 
 245 static JLI_List
 246 wildcardFileList(const char *wildcard)
 247 {
 248     const char *basename;
 249     JLI_List fl = JLI_List_new(16);
 250     WildcardIterator it = WildcardIterator_for(wildcard);
 251 
 252     if (it == NULL)
 253     {
 254         JLI_List_free(fl);
 255         return NULL;
 256     }
 257 
 258     while ((basename = WildcardIterator_next(it)) != NULL)
 259         if (isJarFileName(basename))
 260             JLI_List_add(fl, wildcardConcat(wildcard, basename));
 261     WildcardIterator_close(it);
 262     return fl;
 263 }
 264 
 265 static int
 266 isWildcard(const char *filename)
 267 {
 268     int len = (int)JLI_StrLen(filename);
 269     return (len > 0) &&
 270         (filename[len - 1] == '*') &&
 271         (len == 1 || IS_FILE_SEPARATOR(filename[len - 2])) &&
 272         (! exists(filename));
 273 }
 274 
 275 static int
 276 FileList_expandWildcards(JLI_List fl)
 277 {
 278     size_t i, j;
 279     int expandedCnt = 0;
 280     for (i = 0; i < fl->size; i++) {
 281         if (isWildcard(fl->elements[i])) {
 282             JLI_List expanded = wildcardFileList(fl->elements[i]);
 283             if (expanded != NULL && expanded->size > 0) {
 284                 expandedCnt++;
 285                 JLI_MemFree(fl->elements[i]);
 286                 JLI_List_ensureCapacity(fl, fl->size + expanded->size);
 287                 for (j = fl->size - 1; j >= i+1; j--)
 288                     fl->elements[j+expanded->size-1] = fl->elements[j];
 289                 for (j = 0; j < expanded->size; j++)
 290                     fl->elements[i+j] = expanded->elements[j];
 291                 i += expanded->size - 1;
 292                 fl->size += expanded->size - 1;
 293                 /* fl expropriates expanded's elements. */
 294                 expanded->size = 0;
 295             }
 296             JLI_List_free(expanded);
 297         }
 298     }
 299     return expandedCnt;
 300 }
 301 
 302 const char *
 303 JLI_WildcardExpandClasspath(const char *classpath)
 304 {
 305     const char *expanded;
 306     JLI_List fl;
 307 
 308     if (JLI_StrChr(classpath, '*') == NULL)
 309         return classpath;
 310     fl = JLI_List_split(classpath, PATH_SEPARATOR);
 311     expanded = FileList_expandWildcards(fl) ?
 312         JLI_List_join(fl, PATH_SEPARATOR) : classpath;
 313     JLI_List_free(fl);
 314     if (getenv(JLDEBUG_ENV_ENTRY) != 0)
 315         printf("Expanded wildcards:\n"
 316                "    before: \"%s\"\n"
 317                "    after : \"%s\"\n",
 318                classpath, expanded);
 319     return expanded;
 320 }
 321 
 322 #ifdef DEBUG_WILDCARD
 323 static void
 324 FileList_print(JLI_List fl)
 325 {
 326     size_t i;
 327     putchar('[');
 328     for (i = 0; i < fl->size; i++) {
 329         if (i > 0) printf(", ");
 330         printf("\"%s\"",fl->elements[i]);
 331     }
 332     putchar(']');
 333 }
 334 
 335 static void
 336 wildcardExpandArgv(const char ***argv)
 337 {
 338     int i;
 339     for (i = 0; (*argv)[i]; i++) {
 340         if (equal((*argv)[i], "-cp") ||
 341             equal((*argv)[i], "-classpath")) {
 342             i++;
 343             (*argv)[i] = wildcardExpandClasspath((*argv)[i]);
 344         }
 345     }
 346 }
 347 
 348 static void
 349 debugPrintArgv(char *argv[])
 350 {
 351     int i;
 352     putchar('[');
 353     for (i = 0; argv[i]; i++) {
 354         if (i > 0) printf(", ");
 355         printf("\"%s\"", argv[i]);
 356     }
 357     printf("]\n");
 358 }
 359 
 360 int
 361 main(int argc, char *argv[])
 362 {
 363     argv[0] = "java";
 364     wildcardExpandArgv((const char***)&argv);
 365     debugPrintArgv(argv);
 366     /* execvp("java", argv); */
 367     return 0;
 368 }
 369 #endif /* DEBUG_WILDCARD */
 370 
 371 /* Cute little perl prototype implementation....
 372 
 373 my $sep = ($^O =~ /^(Windows|cygwin)/) ? ";" : ":";
 374 
 375 sub expand($) {
 376   opendir DIR, $_[0] or return $_[0];
 377   join $sep, map {"$_[0]/$_"} grep {/\.(jar|JAR)$/} readdir DIR;
 378 }
 379 
 380 sub munge($) {
 381   join $sep,
 382     map {(! -r $_ and s/[\/\\]+\*$//) ? expand $_ : $_} split $sep, $_[0];
 383 }
 384 
 385 for (my $i = 0; $i < @ARGV - 1; $i++) {
 386   $ARGV[$i+1] = munge $ARGV[$i+1] if $ARGV[$i] =~ /^-c(p|lasspath)$/;
 387 }
 388 
 389 $ENV{CLASSPATH} = munge $ENV{CLASSPATH} if exists $ENV{CLASSPATH};
 390 @ARGV = ("java", @ARGV);
 391 print "@ARGV\n";
 392 exec @ARGV;
 393 
 394 */