1 /* 2 * Copyright (c) 2015, 2018, 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 #include <stdlib.h> 27 #include <stdio.h> 28 #include <assert.h> 29 #include <sys/stat.h> 30 #include <ctype.h> 31 32 #ifdef DEBUG_ARGFILE 33 #ifndef NO_JNI 34 #define NO_JNI 35 #endif 36 #define JLI_ReportMessage(...) printf(__VA_ARGS__) 37 #define JDK_JAVA_OPTIONS "JDK_JAVA_OPTIONS" 38 int IsWhiteSpaceOption(const char* name) { return 1; } 39 #else 40 #include "java.h" 41 #include "jni.h" 42 #endif 43 44 #include "jli_util.h" 45 #include "emessages.h" 46 47 #define MAX_ARGF_SIZE 0x7fffffffL 48 49 static char* clone_substring(const char *begin, size_t len) { 50 char *rv = (char *) JLI_MemAlloc(len + 1); 51 memcpy(rv, begin, len); 52 rv[len] = '\0'; 53 return rv; 54 } 55 56 enum STATE { 57 FIND_NEXT, 58 IN_COMMENT, 59 IN_QUOTE, 60 IN_ESCAPE, 61 SKIP_LEAD_WS, 62 IN_TOKEN 63 }; 64 65 typedef struct { 66 enum STATE state; 67 const char* cptr; 68 const char* eob; 69 char quote_char; 70 JLI_List parts; 71 } __ctx_args; 72 73 #define NOT_FOUND -1 74 static int firstAppArgIndex = NOT_FOUND; 75 76 static jboolean expectingNoDashArg = JNI_FALSE; 77 // Initialize to 1, as the first argument is the app name and not preprocessed 78 static size_t argsCount = 1; 79 static jboolean stopExpansion = JNI_FALSE; 80 static jboolean relaunch = JNI_FALSE; 81 82 /* 83 * Prototypes for internal functions. 84 */ 85 static jboolean expand(JLI_List args, const char *str, const char *var_name); 86 87 JNIEXPORT void JNICALL 88 JLI_InitArgProcessing(jboolean hasJavaArgs, jboolean disableArgFile) { 89 // No expansion for relaunch 90 if (argsCount != 1) { 91 relaunch = JNI_TRUE; 92 stopExpansion = JNI_TRUE; 93 argsCount = 1; 94 } else { 95 stopExpansion = disableArgFile; 96 } 97 98 expectingNoDashArg = JNI_FALSE; 99 100 // for tools, this value remains 0 all the time. 101 firstAppArgIndex = hasJavaArgs ? 0: NOT_FOUND; 102 } 103 104 JNIEXPORT int JNICALL 105 JLI_GetAppArgIndex() { 106 // Will be 0 for tools 107 return firstAppArgIndex; 108 } 109 110 static void checkArg(const char *arg) { 111 size_t idx = 0; 112 argsCount++; 113 114 // All arguments arrive here must be a launcher argument, 115 // ie. by now, all argfile expansions must have been performed. 116 if (*arg == '-') { 117 expectingNoDashArg = JNI_FALSE; 118 if (IsWhiteSpaceOption(arg)) { 119 // expect an argument 120 expectingNoDashArg = JNI_TRUE; 121 122 if (JLI_StrCmp(arg, "-jar") == 0 || 123 JLI_StrCmp(arg, "--module") == 0 || 124 JLI_StrCmp(arg, "-m") == 0) { 125 // This is tricky, we do expect NoDashArg 126 // But that is considered main class to stop expansion 127 expectingNoDashArg = JNI_FALSE; 128 // We can not just update the idx here because if -jar @file 129 // still need expansion of @file to get the argument for -jar 130 } 131 } else if (JLI_StrCmp(arg, "--disable-@files") == 0) { 132 stopExpansion = JNI_TRUE; 133 } 134 } else { 135 if (!expectingNoDashArg) { 136 // this is main class, argsCount is index to next arg 137 idx = argsCount; 138 } 139 expectingNoDashArg = JNI_FALSE; 140 } 141 // only update on java mode and not yet found main class 142 if (firstAppArgIndex == NOT_FOUND && idx != 0) { 143 firstAppArgIndex = (int) idx; 144 } 145 } 146 147 /* 148 [\n\r] +------------+ +------------+ [\n\r] 149 +---------+ IN_COMMENT +<------+ | IN_ESCAPE +---------+ 150 | +------------+ | +------------+ | 151 | [#] ^ |[#] ^ | | 152 | +----------+ | [\\]| |[^\n\r] | 153 v | | | v | 154 +------------+ [^ \t\n\r\f] +------------+['"]> +------------+ | 155 | FIND_NEXT +-------------->+ IN_TOKEN +-----------+ IN_QUOTE + | 156 +------------+ +------------+ <[quote]+------------+ | 157 | ^ | | ^ ^ | 158 | | [ \t\n\r\f]| [\n\r]| | |[^ \t\n\r\f]v 159 | +--------------------------+-----------------------+ | +--------------+ 160 | ['"] | | SKIP_LEAD_WS | 161 +---------------------------------------------------------+ +--------------+ 162 */ 163 static char* nextToken(__ctx_args *pctx) { 164 const char* nextc = pctx->cptr; 165 const char* const eob = pctx->eob; 166 const char* anchor = nextc; 167 char *token; 168 169 for (; nextc < eob; nextc++) { 170 register char ch = *nextc; 171 172 // Skip white space characters 173 if (pctx->state == FIND_NEXT || pctx->state == SKIP_LEAD_WS) { 174 while (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' || ch == '\f') { 175 nextc++; 176 if (nextc >= eob) { 177 return NULL; 178 } 179 ch = *nextc; 180 } 181 pctx->state = (pctx->state == FIND_NEXT) ? IN_TOKEN : IN_QUOTE; 182 anchor = nextc; 183 // Deal with escape sequences 184 } else if (pctx->state == IN_ESCAPE) { 185 // concatenation directive 186 if (ch == '\n' || ch == '\r') { 187 pctx->state = SKIP_LEAD_WS; 188 } else { 189 // escaped character 190 char* escaped = (char*) JLI_MemAlloc(2 * sizeof(char)); 191 escaped[1] = '\0'; 192 switch (ch) { 193 case 'n': 194 escaped[0] = '\n'; 195 break; 196 case 'r': 197 escaped[0] = '\r'; 198 break; 199 case 't': 200 escaped[0] = '\t'; 201 break; 202 case 'f': 203 escaped[0] = '\f'; 204 break; 205 default: 206 escaped[0] = ch; 207 break; 208 } 209 JLI_List_add(pctx->parts, escaped); 210 pctx->state = IN_QUOTE; 211 } 212 // anchor to next character 213 anchor = nextc + 1; 214 continue; 215 // ignore comment to EOL 216 } else if (pctx->state == IN_COMMENT) { 217 while (ch != '\n' && ch != '\r') { 218 nextc++; 219 if (nextc > eob) { 220 return NULL; 221 } 222 ch = *nextc; 223 } 224 pctx->state = FIND_NEXT; 225 continue; 226 } 227 228 assert(pctx->state != IN_ESCAPE); 229 assert(pctx->state != FIND_NEXT); 230 assert(pctx->state != SKIP_LEAD_WS); 231 assert(pctx->state != IN_COMMENT); 232 233 switch(ch) { 234 case ' ': 235 case '\t': 236 case '\f': 237 if (pctx->state == IN_QUOTE) { 238 continue; 239 } 240 // fall through 241 case '\n': 242 case '\r': 243 if (pctx->parts->size == 0) { 244 token = clone_substring(anchor, nextc - anchor); 245 } else { 246 JLI_List_addSubstring(pctx->parts, anchor, nextc - anchor); 247 token = JLI_List_combine(pctx->parts); 248 JLI_List_free(pctx->parts); 249 pctx->parts = JLI_List_new(4); 250 } 251 pctx->cptr = nextc + 1; 252 pctx->state = FIND_NEXT; 253 return token; 254 case '#': 255 if (pctx->state == IN_QUOTE) { 256 continue; 257 } 258 pctx->state = IN_COMMENT; 259 break; 260 case '\\': 261 if (pctx->state != IN_QUOTE) { 262 continue; 263 } 264 JLI_List_addSubstring(pctx->parts, anchor, nextc - anchor); 265 pctx->state = IN_ESCAPE; 266 break; 267 case '\'': 268 case '"': 269 if (pctx->state == IN_QUOTE && pctx->quote_char != ch) { 270 // not matching quote 271 continue; 272 } 273 // partial before quote 274 if (anchor != nextc) { 275 JLI_List_addSubstring(pctx->parts, anchor, nextc - anchor); 276 } 277 // anchor after quote character 278 anchor = nextc + 1; 279 if (pctx->state == IN_TOKEN) { 280 pctx->quote_char = ch; 281 pctx->state = IN_QUOTE; 282 } else { 283 pctx->state = IN_TOKEN; 284 } 285 break; 286 default: 287 break; 288 } 289 } 290 291 assert(nextc == eob); 292 if (anchor != nextc) { 293 // not yet return until end of stream, we have part of a token. 294 JLI_List_addSubstring(pctx->parts, anchor, nextc - anchor); 295 } 296 return NULL; 297 } 298 299 static JLI_List readArgFile(FILE *file) { 300 char buf[4096]; 301 JLI_List rv; 302 __ctx_args ctx; 303 size_t size; 304 char *token; 305 306 ctx.state = FIND_NEXT; 307 ctx.parts = JLI_List_new(4); 308 309 /* arbitrarily pick 8, seems to be a reasonable number of arguments */ 310 rv = JLI_List_new(8); 311 312 while (!feof(file)) { 313 size = fread(buf, sizeof(char), sizeof(buf), file); 314 if (ferror(file)) { 315 JLI_List_free(rv); 316 return NULL; 317 } 318 319 /* nextc is next character to read from the buffer 320 * eob is the end of input 321 * token is the copied token value, NULL if no a complete token 322 */ 323 ctx.cptr = buf; 324 ctx.eob = buf + size; 325 token = nextToken(&ctx); 326 while (token != NULL) { 327 checkArg(token); 328 JLI_List_add(rv, token); 329 token = nextToken(&ctx); 330 } 331 } 332 333 // remaining partial token 334 if (ctx.state == IN_TOKEN || ctx.state == IN_QUOTE) { 335 if (ctx.parts->size != 0) { 336 JLI_List_add(rv, JLI_List_combine(ctx.parts)); 337 } 338 } 339 JLI_List_free(ctx.parts); 340 341 return rv; 342 } 343 344 /* 345 * if the arg represent a file, that is, prefix with a single '@', 346 * return a list of arguments from the file. 347 * otherwise, return NULL. 348 */ 349 static JLI_List expandArgFile(const char *arg) { 350 FILE *fptr; 351 struct stat st; 352 JLI_List rv; 353 354 /* failed to access the file */ 355 if (stat(arg, &st) != 0) { 356 JLI_ReportMessage(CFG_ERROR6, arg); 357 exit(1); 358 } 359 360 if (st.st_size > MAX_ARGF_SIZE) { 361 JLI_ReportMessage(CFG_ERROR10, MAX_ARGF_SIZE); 362 exit(1); 363 } 364 365 fptr = fopen(arg, "r"); 366 /* arg file cannot be openned */ 367 if (fptr == NULL) { 368 JLI_ReportMessage(CFG_ERROR6, arg); 369 exit(1); 370 } 371 372 rv = readArgFile(fptr); 373 fclose(fptr); 374 375 /* error occurred reading the file */ 376 if (rv == NULL) { 377 JLI_ReportMessage(DLL_ERROR4, arg); 378 exit(1); 379 } 380 381 return rv; 382 } 383 384 /* 385 * expand a string into a list of words separated by whitespace. 386 */ 387 static JLI_List expandArg(const char *arg) { 388 JLI_List rv; 389 390 /* arbitrarily pick 8, seems to be a reasonable number of arguments */ 391 rv = JLI_List_new(8); 392 393 expand(rv, arg, NULL); 394 395 return rv; 396 } 397 398 JNIEXPORT JLI_List JNICALL 399 JLI_PreprocessArg(const char *arg, jboolean expandSourceOpt) { 400 JLI_List rv; 401 402 if (firstAppArgIndex > 0) { 403 // In user application arg, no more work. 404 return NULL; 405 } 406 407 if (stopExpansion) { 408 // still looking for user application arg 409 checkArg(arg); 410 return NULL; 411 } 412 413 if (expandSourceOpt 414 && JLI_StrCCmp(arg, "--source") == 0 415 && JLI_StrChr(arg, ' ') != NULL) { 416 return expandArg(arg); 417 } 418 419 if (arg[0] != '@') { 420 checkArg(arg); 421 return NULL; 422 } 423 424 if (arg[1] == '\0') { 425 // @ by itself is an argument 426 checkArg(arg); 427 return NULL; 428 } 429 430 arg++; 431 if (arg[0] == '@') { 432 // escaped @argument 433 rv = JLI_List_new(1); 434 checkArg(arg); 435 JLI_List_add(rv, JLI_StringDup(arg)); 436 } else { 437 rv = expandArgFile(arg); 438 } 439 return rv; 440 } 441 442 int isTerminalOpt(char *arg) { 443 return JLI_StrCmp(arg, "-jar") == 0 || 444 JLI_StrCmp(arg, "-m") == 0 || 445 JLI_StrCmp(arg, "--module") == 0 || 446 JLI_StrCmp(arg, "--dry-run") == 0 || 447 JLI_StrCmp(arg, "-h") == 0 || 448 JLI_StrCmp(arg, "-?") == 0 || 449 JLI_StrCmp(arg, "-help") == 0 || 450 JLI_StrCmp(arg, "--help") == 0 || 451 JLI_StrCmp(arg, "-X") == 0 || 452 JLI_StrCmp(arg, "--help-extra") == 0 || 453 JLI_StrCmp(arg, "-version") == 0 || 454 JLI_StrCmp(arg, "--version") == 0 || 455 JLI_StrCmp(arg, "-fullversion") == 0 || 456 JLI_StrCmp(arg, "--full-version") == 0; 457 } 458 459 JNIEXPORT jboolean JNICALL 460 JLI_AddArgsFromEnvVar(JLI_List args, const char *var_name) { 461 char *env = getenv(var_name); 462 463 if (firstAppArgIndex == 0) { 464 // Not 'java', return 465 return JNI_FALSE; 466 } 467 468 if (relaunch) { 469 return JNI_FALSE; 470 } 471 472 if (NULL == env) { 473 return JNI_FALSE; 474 } 475 476 JLI_ReportMessage(ARG_INFO_ENVVAR, var_name, env); 477 return expand(args, env, var_name); 478 } 479 480 /* 481 * Expand a string into a list of args. 482 * If the string is the result of looking up an environment variable, 483 * var_name should be set to the name of that environment variable, 484 * for use if needed in error messages. 485 */ 486 487 static jboolean expand(JLI_List args, const char *str, const char *var_name) { 488 jboolean inEnvVar = (var_name != NULL); 489 490 char *p, *arg; 491 char quote; 492 JLI_List argsInFile; 493 494 // This is retained until the process terminates as it is saved as the args 495 p = JLI_MemAlloc(JLI_StrLen(str) + 1); 496 while (*str != '\0') { 497 while (*str != '\0' && isspace(*str)) { 498 str++; 499 } 500 501 // Trailing space 502 if (*str == '\0') { 503 break; 504 } 505 506 arg = p; 507 while (*str != '\0' && !isspace(*str)) { 508 if (inEnvVar && (*str == '"' || *str == '\'')) { 509 quote = *str++; 510 while (*str != quote && *str != '\0') { 511 *p++ = *str++; 512 } 513 514 if (*str == '\0') { 515 JLI_ReportMessage(ARG_ERROR8, var_name); 516 exit(1); 517 } 518 str++; 519 } else { 520 *p++ = *str++; 521 } 522 } 523 524 *p++ = '\0'; 525 526 argsInFile = JLI_PreprocessArg(arg, JNI_FALSE); 527 528 if (NULL == argsInFile) { 529 if (isTerminalOpt(arg)) { 530 if (inEnvVar) { 531 JLI_ReportMessage(ARG_ERROR9, arg, var_name); 532 } else { 533 JLI_ReportMessage(ARG_ERROR15, arg); 534 } 535 exit(1); 536 } 537 JLI_List_add(args, arg); 538 } else { 539 size_t cnt, idx; 540 char *argFile = arg; 541 cnt = argsInFile->size; 542 for (idx = 0; idx < cnt; idx++) { 543 arg = argsInFile->elements[idx]; 544 if (isTerminalOpt(arg)) { 545 if (inEnvVar) { 546 JLI_ReportMessage(ARG_ERROR10, arg, argFile, var_name); 547 } else { 548 JLI_ReportMessage(ARG_ERROR16, arg, argFile); 549 } 550 exit(1); 551 } 552 JLI_List_add(args, arg); 553 } 554 // Shallow free, we reuse the string to avoid copy 555 JLI_MemFree(argsInFile->elements); 556 JLI_MemFree(argsInFile); 557 } 558 /* 559 * Check if main-class is specified after argument being checked. It 560 * must always appear after expansion, as a main-class could be specified 561 * indirectly into environment variable via an @argfile, and it must be 562 * caught now. 563 */ 564 if (firstAppArgIndex != NOT_FOUND) { 565 if (inEnvVar) { 566 JLI_ReportMessage(ARG_ERROR11, var_name); 567 } else { 568 JLI_ReportMessage(ARG_ERROR17); 569 } 570 exit(1); 571 } 572 573 assert (*str == '\0' || isspace(*str)); 574 } 575 576 return JNI_TRUE; 577 } 578 579 #ifdef DEBUG_ARGFILE 580 /* 581 * Stand-alone sanity test, build with following command line 582 * $ CC -DDEBUG_ARGFILE -DNO_JNI -g args.c jli_util.c 583 */ 584 585 void fail(char *expected, char *actual, size_t idx) { 586 printf("FAILED: Token[%lu] expected to be <%s>, got <%s>\n", idx, expected, actual); 587 exit(1); 588 } 589 590 void test_case(char *case_data, char **tokens, size_t cnt_tokens) { 591 size_t actual_cnt; 592 char *token; 593 __ctx_args ctx; 594 595 actual_cnt = 0; 596 597 ctx.state = FIND_NEXT; 598 ctx.parts = JLI_List_new(4); 599 ctx.cptr = case_data; 600 ctx.eob = case_data + strlen(case_data); 601 602 printf("Test case: <%s>, expected %lu tokens.\n", case_data, cnt_tokens); 603 604 for (token = nextToken(&ctx); token != NULL; token = nextToken(&ctx)) { 605 // should not have more tokens than expected 606 if (actual_cnt >= cnt_tokens) { 607 printf("FAILED: Extra token detected: <%s>\n", token); 608 exit(2); 609 } 610 if (JLI_StrCmp(token, tokens[actual_cnt]) != 0) { 611 fail(tokens[actual_cnt], token, actual_cnt); 612 } 613 actual_cnt++; 614 } 615 616 char* last = NULL; 617 if (ctx.parts->size != 0) { 618 last = JLI_List_combine(ctx.parts); 619 } 620 JLI_List_free(ctx.parts); 621 622 if (actual_cnt >= cnt_tokens) { 623 // same number of tokens, should have nothing left to parse 624 if (last != NULL) { 625 if (*last != '#') { 626 printf("Leftover detected: %s", last); 627 exit(2); 628 } 629 } 630 } else { 631 if (JLI_StrCmp(last, tokens[actual_cnt]) != 0) { 632 fail(tokens[actual_cnt], last, actual_cnt); 633 } 634 actual_cnt++; 635 } 636 if (actual_cnt != cnt_tokens) { 637 printf("FAILED: Number of tokens not match, expected %lu, got %lu\n", 638 cnt_tokens, actual_cnt); 639 exit(3); 640 } 641 642 printf("PASS\n"); 643 } 644 645 #define DO_CASE(name) \ 646 test_case(name[0], name + 1, sizeof(name)/sizeof(char*) - 1) 647 648 int main(int argc, char** argv) { 649 size_t i, j; 650 651 char* case1[] = { "-version -cp \"c:\\\\java libs\\\\one.jar\" \n", 652 "-version", "-cp", "c:\\java libs\\one.jar" }; 653 DO_CASE(case1); 654 655 // note the open quote at the end 656 char* case2[] = { "com.foo.Panda \"Furious 5\"\fand\t'Shi Fu' \"escape\tprison", 657 "com.foo.Panda", "Furious 5", "and", "Shi Fu", "escape\tprison"}; 658 DO_CASE(case2); 659 660 char* escaped_chars[] = { "escaped chars testing \"\\a\\b\\c\\f\\n\\r\\t\\v\\9\\6\\23\\82\\28\\377\\477\\278\\287\"", 661 "escaped", "chars", "testing", "abc\f\n\r\tv96238228377477278287"}; 662 DO_CASE(escaped_chars); 663 664 char* mixed_quote[] = { "\"mix 'single quote' in double\" 'mix \"double quote\" in single' partial\"quote me\"this", 665 "mix 'single quote' in double", "mix \"double quote\" in single", "partialquote methis"}; 666 DO_CASE(mixed_quote); 667 668 char* comments[] = { "line one #comment\n'line #2' #rest are comment\r\n#comment on line 3\nline 4 #comment to eof", 669 "line", "one", "line #2", "line", "4"}; 670 DO_CASE(comments); 671 672 char* open_quote[] = { "This is an \"open quote \n across line\n\t, note for WS.", 673 "This", "is", "an", "open quote ", "across", "line", ",", "note", "for", "WS." }; 674 DO_CASE(open_quote); 675 676 char* escape_in_open_quote[] = { "Try \"this \\\\\\\\ escape\\n double quote \\\" in open quote", 677 "Try", "this \\\\ escape\n double quote \" in open quote" }; 678 DO_CASE(escape_in_open_quote); 679 680 char* quote[] = { "'-Dmy.quote.single'='Property in single quote. Here a double quote\" Add some slashes \\\\/'", 681 "-Dmy.quote.single=Property in single quote. Here a double quote\" Add some slashes \\/" }; 682 DO_CASE(quote); 683 684 char* multi[] = { "\"Open quote to \n new \"line \\\n\r third\\\n\r\\\tand\ffourth\"", 685 "Open quote to ", "new", "line third\tand\ffourth" }; 686 DO_CASE(multi); 687 688 char* escape_quote[] = { "c:\\\"partial quote\"\\lib", 689 "c:\\partial quote\\lib" }; 690 DO_CASE(escape_quote); 691 692 if (argc > 1) { 693 for (i = 0; i < argc; i++) { 694 JLI_List tokens = JLI_PreprocessArg(argv[i], JNI_FALSE); 695 if (NULL != tokens) { 696 for (j = 0; j < tokens->size; j++) { 697 printf("Token[%lu]: <%s>\n", (unsigned long) j, tokens->elements[j]); 698 } 699 } 700 } 701 } 702 } 703 704 #endif // DEBUG_ARGFILE