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 // anchor after backslash character 267 anchor = nextc + 1; 268 break; 269 case '\'': 270 case '"': 271 if (pctx->state == IN_QUOTE && pctx->quote_char != ch) { 272 // not matching quote 273 continue; 274 } 275 // partial before quote 276 if (anchor != nextc) { 277 JLI_List_addSubstring(pctx->parts, anchor, nextc - anchor); 278 } 279 // anchor after quote character 280 anchor = nextc + 1; 281 if (pctx->state == IN_TOKEN) { 282 pctx->quote_char = ch; 283 pctx->state = IN_QUOTE; 284 } else { 285 pctx->state = IN_TOKEN; 286 } 287 break; 288 default: 289 break; 290 } 291 } 292 293 assert(nextc == eob); 294 if (anchor != nextc) { 295 // not yet return until end of stream, we have part of a token. 296 JLI_List_addSubstring(pctx->parts, anchor, nextc - anchor); 297 } 298 return NULL; 299 } 300 301 static JLI_List readArgFile(FILE *file) { 302 char buf[4096]; 303 JLI_List rv; 304 __ctx_args ctx; 305 size_t size; 306 char *token; 307 308 ctx.state = FIND_NEXT; 309 ctx.parts = JLI_List_new(4); 310 // initialize to avoid -Werror=maybe-uninitialized issues from gcc 7.3 onwards. 311 ctx.quote_char = '"'; 312 313 /* arbitrarily pick 8, seems to be a reasonable number of arguments */ 314 rv = JLI_List_new(8); 315 316 while (!feof(file)) { 317 size = fread(buf, sizeof(char), sizeof(buf), file); 318 if (ferror(file)) { 319 JLI_List_free(rv); 320 return NULL; 321 } 322 323 /* nextc is next character to read from the buffer 324 * eob is the end of input 325 * token is the copied token value, NULL if no a complete token 326 */ 327 ctx.cptr = buf; 328 ctx.eob = buf + size; 329 token = nextToken(&ctx); 330 while (token != NULL) { 331 checkArg(token); 332 JLI_List_add(rv, token); 333 token = nextToken(&ctx); 334 } 335 } 336 337 // remaining partial token 338 if (ctx.state == IN_TOKEN || ctx.state == IN_QUOTE) { 339 if (ctx.parts->size != 0) { 340 token = JLI_List_combine(ctx.parts); 341 checkArg(token); 342 JLI_List_add(rv, token); 343 } 344 } 345 JLI_List_free(ctx.parts); 346 347 return rv; 348 } 349 350 /* 351 * if the arg represent a file, that is, prefix with a single '@', 352 * return a list of arguments from the file. 353 * otherwise, return NULL. 354 */ 355 static JLI_List expandArgFile(const char *arg) { 356 FILE *fptr; 357 struct stat st; 358 JLI_List rv; 359 360 /* failed to access the file */ 361 if (stat(arg, &st) != 0) { 362 JLI_ReportMessage(CFG_ERROR6, arg); 363 exit(1); 364 } 365 366 if (st.st_size > MAX_ARGF_SIZE) { 367 JLI_ReportMessage(CFG_ERROR10, MAX_ARGF_SIZE); 368 exit(1); 369 } 370 371 fptr = fopen(arg, "r"); 372 /* arg file cannot be openned */ 373 if (fptr == NULL) { 374 JLI_ReportMessage(CFG_ERROR6, arg); 375 exit(1); 376 } 377 378 rv = readArgFile(fptr); 379 fclose(fptr); 380 381 /* error occurred reading the file */ 382 if (rv == NULL) { 383 JLI_ReportMessage(DLL_ERROR4, arg); 384 exit(1); 385 } 386 387 return rv; 388 } 389 390 /* 391 * expand a string into a list of words separated by whitespace. 392 */ 393 static JLI_List expandArg(const char *arg) { 394 JLI_List rv; 395 396 /* arbitrarily pick 8, seems to be a reasonable number of arguments */ 397 rv = JLI_List_new(8); 398 399 expand(rv, arg, NULL); 400 401 return rv; 402 } 403 404 JNIEXPORT JLI_List JNICALL 405 JLI_PreprocessArg(const char *arg, jboolean expandSourceOpt) { 406 JLI_List rv; 407 408 if (firstAppArgIndex > 0) { 409 // In user application arg, no more work. 410 return NULL; 411 } 412 413 if (stopExpansion) { 414 // still looking for user application arg 415 checkArg(arg); 416 return NULL; 417 } 418 419 if (expandSourceOpt 420 && JLI_StrCCmp(arg, "--source") == 0 421 && JLI_StrChr(arg, ' ') != NULL) { 422 return expandArg(arg); 423 } 424 425 if (arg[0] != '@') { 426 checkArg(arg); 427 return NULL; 428 } 429 430 if (arg[1] == '\0') { 431 // @ by itself is an argument 432 checkArg(arg); 433 return NULL; 434 } 435 436 arg++; 437 if (arg[0] == '@') { 438 // escaped @argument 439 rv = JLI_List_new(1); 440 checkArg(arg); 441 JLI_List_add(rv, JLI_StringDup(arg)); 442 } else { 443 rv = expandArgFile(arg); 444 } 445 return rv; 446 } 447 448 int isTerminalOpt(char *arg) { 449 return JLI_StrCmp(arg, "-jar") == 0 || 450 JLI_StrCmp(arg, "-m") == 0 || 451 JLI_StrCmp(arg, "--module") == 0 || 452 JLI_StrCmp(arg, "--dry-run") == 0 || 453 JLI_StrCmp(arg, "-h") == 0 || 454 JLI_StrCmp(arg, "-?") == 0 || 455 JLI_StrCmp(arg, "-help") == 0 || 456 JLI_StrCmp(arg, "--help") == 0 || 457 JLI_StrCmp(arg, "-X") == 0 || 458 JLI_StrCmp(arg, "--help-extra") == 0 || 459 JLI_StrCmp(arg, "-version") == 0 || 460 JLI_StrCmp(arg, "--version") == 0 || 461 JLI_StrCmp(arg, "-fullversion") == 0 || 462 JLI_StrCmp(arg, "--full-version") == 0; 463 } 464 465 JNIEXPORT jboolean JNICALL 466 JLI_AddArgsFromEnvVar(JLI_List args, const char *var_name) { 467 char *env = getenv(var_name); 468 469 if (firstAppArgIndex == 0) { 470 // Not 'java', return 471 return JNI_FALSE; 472 } 473 474 if (relaunch) { 475 return JNI_FALSE; 476 } 477 478 if (NULL == env) { 479 return JNI_FALSE; 480 } 481 482 JLI_ReportMessage(ARG_INFO_ENVVAR, var_name, env); 483 return expand(args, env, var_name); 484 } 485 486 /* 487 * Expand a string into a list of args. 488 * If the string is the result of looking up an environment variable, 489 * var_name should be set to the name of that environment variable, 490 * for use if needed in error messages. 491 */ 492 493 static jboolean expand(JLI_List args, const char *str, const char *var_name) { 494 jboolean inEnvVar = (var_name != NULL); 495 496 char *p, *arg; 497 char quote; 498 JLI_List argsInFile; 499 500 // This is retained until the process terminates as it is saved as the args 501 p = JLI_MemAlloc(JLI_StrLen(str) + 1); 502 while (*str != '\0') { 503 while (*str != '\0' && isspace(*str)) { 504 str++; 505 } 506 507 // Trailing space 508 if (*str == '\0') { 509 break; 510 } 511 512 arg = p; 513 while (*str != '\0' && !isspace(*str)) { 514 if (inEnvVar && (*str == '"' || *str == '\'')) { 515 quote = *str++; 516 while (*str != quote && *str != '\0') { 517 *p++ = *str++; 518 } 519 520 if (*str == '\0') { 521 JLI_ReportMessage(ARG_ERROR8, var_name); 522 exit(1); 523 } 524 str++; 525 } else { 526 *p++ = *str++; 527 } 528 } 529 530 *p++ = '\0'; 531 532 argsInFile = JLI_PreprocessArg(arg, JNI_FALSE); 533 534 if (NULL == argsInFile) { 535 if (isTerminalOpt(arg)) { 536 if (inEnvVar) { 537 JLI_ReportMessage(ARG_ERROR9, arg, var_name); 538 } else { 539 JLI_ReportMessage(ARG_ERROR15, arg); 540 } 541 exit(1); 542 } 543 JLI_List_add(args, arg); 544 } else { 545 size_t cnt, idx; 546 char *argFile = arg; 547 cnt = argsInFile->size; 548 for (idx = 0; idx < cnt; idx++) { 549 arg = argsInFile->elements[idx]; 550 if (isTerminalOpt(arg)) { 551 if (inEnvVar) { 552 JLI_ReportMessage(ARG_ERROR10, arg, argFile, var_name); 553 } else { 554 JLI_ReportMessage(ARG_ERROR16, arg, argFile); 555 } 556 exit(1); 557 } 558 JLI_List_add(args, arg); 559 } 560 // Shallow free, we reuse the string to avoid copy 561 JLI_MemFree(argsInFile->elements); 562 JLI_MemFree(argsInFile); 563 } 564 /* 565 * Check if main-class is specified after argument being checked. It 566 * must always appear after expansion, as a main-class could be specified 567 * indirectly into environment variable via an @argfile, and it must be 568 * caught now. 569 */ 570 if (firstAppArgIndex != NOT_FOUND) { 571 if (inEnvVar) { 572 JLI_ReportMessage(ARG_ERROR11, var_name); 573 } else { 574 JLI_ReportMessage(ARG_ERROR17); 575 } 576 exit(1); 577 } 578 579 assert (*str == '\0' || isspace(*str)); 580 } 581 582 return JNI_TRUE; 583 } 584 585 #ifdef DEBUG_ARGFILE 586 /* 587 * Stand-alone sanity test, build with following command line 588 * $ CC -DDEBUG_ARGFILE -DNO_JNI -g args.c jli_util.c 589 */ 590 591 void fail(char *expected, char *actual, size_t idx) { 592 printf("FAILED: Token[%lu] expected to be <%s>, got <%s>\n", idx, expected, actual); 593 exit(1); 594 } 595 596 void test_case(char *case_data, char **tokens, size_t cnt_tokens) { 597 size_t actual_cnt; 598 char *token; 599 __ctx_args ctx; 600 601 actual_cnt = 0; 602 603 ctx.state = FIND_NEXT; 604 ctx.parts = JLI_List_new(4); 605 ctx.cptr = case_data; 606 ctx.eob = case_data + strlen(case_data); 607 608 printf("Test case: <%s>, expected %lu tokens.\n", case_data, cnt_tokens); 609 610 for (token = nextToken(&ctx); token != NULL; token = nextToken(&ctx)) { 611 // should not have more tokens than expected 612 if (actual_cnt >= cnt_tokens) { 613 printf("FAILED: Extra token detected: <%s>\n", token); 614 exit(2); 615 } 616 if (JLI_StrCmp(token, tokens[actual_cnt]) != 0) { 617 fail(tokens[actual_cnt], token, actual_cnt); 618 } 619 actual_cnt++; 620 } 621 622 char* last = NULL; 623 if (ctx.parts->size != 0) { 624 last = JLI_List_combine(ctx.parts); 625 } 626 JLI_List_free(ctx.parts); 627 628 if (actual_cnt >= cnt_tokens) { 629 // same number of tokens, should have nothing left to parse 630 if (last != NULL) { 631 if (*last != '#') { 632 printf("Leftover detected: %s", last); 633 exit(2); 634 } 635 } 636 } else { 637 if (JLI_StrCmp(last, tokens[actual_cnt]) != 0) { 638 fail(tokens[actual_cnt], last, actual_cnt); 639 } 640 actual_cnt++; 641 } 642 if (actual_cnt != cnt_tokens) { 643 printf("FAILED: Number of tokens not match, expected %lu, got %lu\n", 644 cnt_tokens, actual_cnt); 645 exit(3); 646 } 647 648 printf("PASS\n"); 649 } 650 651 #define DO_CASE(name) \ 652 test_case(name[0], name + 1, sizeof(name)/sizeof(char*) - 1) 653 654 int main(int argc, char** argv) { 655 size_t i, j; 656 657 char* case1[] = { "-version -cp \"c:\\\\java libs\\\\one.jar\" \n", 658 "-version", "-cp", "c:\\java libs\\one.jar" }; 659 DO_CASE(case1); 660 661 // note the open quote at the end 662 char* case2[] = { "com.foo.Panda \"Furious 5\"\fand\t'Shi Fu' \"escape\tprison", 663 "com.foo.Panda", "Furious 5", "and", "Shi Fu", "escape\tprison"}; 664 DO_CASE(case2); 665 666 char* escaped_chars[] = { "escaped chars testing \"\\a\\b\\c\\f\\n\\r\\t\\v\\9\\6\\23\\82\\28\\377\\477\\278\\287\"", 667 "escaped", "chars", "testing", "abc\f\n\r\tv96238228377477278287"}; 668 DO_CASE(escaped_chars); 669 670 char* mixed_quote[] = { "\"mix 'single quote' in double\" 'mix \"double quote\" in single' partial\"quote me\"this", 671 "mix 'single quote' in double", "mix \"double quote\" in single", "partialquote methis"}; 672 DO_CASE(mixed_quote); 673 674 char* comments[] = { "line one #comment\n'line #2' #rest are comment\r\n#comment on line 3\nline 4 #comment to eof", 675 "line", "one", "line #2", "line", "4"}; 676 DO_CASE(comments); 677 678 char* open_quote[] = { "This is an \"open quote \n across line\n\t, note for WS.", 679 "This", "is", "an", "open quote ", "across", "line", ",", "note", "for", "WS." }; 680 DO_CASE(open_quote); 681 682 char* escape_in_open_quote[] = { "Try \"this \\\\\\\\ escape\\n double quote \\\" in open quote", 683 "Try", "this \\\\ escape\n double quote \" in open quote" }; 684 DO_CASE(escape_in_open_quote); 685 686 char* quote[] = { "'-Dmy.quote.single'='Property in single quote. Here a double quote\" Add some slashes \\\\/'", 687 "-Dmy.quote.single=Property in single quote. Here a double quote\" Add some slashes \\/" }; 688 DO_CASE(quote); 689 690 char* multi[] = { "\"Open quote to \n new \"line \\\n\r third\\\n\r\\\tand\ffourth\"", 691 "Open quote to ", "new", "line third\tand\ffourth" }; 692 DO_CASE(multi); 693 694 char* escape_quote[] = { "c:\\\"partial quote\"\\lib", 695 "c:\\partial quote\\lib" }; 696 DO_CASE(escape_quote); 697 698 if (argc > 1) { 699 for (i = 0; i < argc; i++) { 700 JLI_List tokens = JLI_PreprocessArg(argv[i], JNI_FALSE); 701 if (NULL != tokens) { 702 for (j = 0; j < tokens->size; j++) { 703 printf("Token[%lu]: <%s>\n", (unsigned long) j, tokens->elements[j]); 704 } 705 } 706 } 707 } 708 } 709 710 #endif // DEBUG_ARGFILE