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.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "jimage.hpp"
  28 #include "classfile/classListParser.hpp"
  29 #include "classfile/classLoaderExt.hpp"
  30 #include "classfile/symbolTable.hpp"
  31 #include "classfile/systemDictionary.hpp"
  32 #include "classfile/systemDictionaryShared.hpp"
  33 #include "logging/log.hpp"
  34 #include "logging/logTag.hpp"
  35 #include "memory/metaspaceShared.hpp"
  36 #include "memory/resourceArea.hpp"
  37 #include "runtime/fieldType.hpp"
  38 #include "runtime/handles.inline.hpp"
  39 #include "runtime/javaCalls.hpp"
  40 #include "utilities/defaultStream.hpp"
  41 #include "utilities/hashtable.inline.hpp"
  42 #include "utilities/macros.hpp"
  43 
  44 ClassListParser* ClassListParser::_instance = NULL;
  45 
  46 ClassListParser::ClassListParser(const char* file) {
  47   assert(_instance == NULL, "must be singleton");
  48   _instance = this;
  49   _classlist_file = file;
  50   _file = fopen(file, "r");
  51   if (_file == NULL) {
  52     char errmsg[JVM_MAXPATHLEN];
  53     os::lasterror(errmsg, JVM_MAXPATHLEN);
  54     vm_exit_during_initialization("Loading classlist failed", errmsg);
  55   } 
  56   _line_no = 0;
  57   _interfaces = new (ResourceObj::C_HEAP, mtClass) GrowableArray<int>(10, true);
  58 }
  59 
  60 ClassListParser::~ClassListParser() {
  61   if (_file) {
  62     fclose(_file);
  63   }
  64   _instance = NULL;
  65 }
  66 
  67 bool ClassListParser::parse_one_line() {
  68   for (;;) {
  69     if (fgets(_line, sizeof(_line), _file) == NULL) {
  70       return false;
  71     }
  72     ++ _line_no;
  73     _line_len = (int)strlen(_line);
  74     if (_line_len > _max_allowed_line_len) {
  75       error("input line too long (must be no longer than %d chars)", _max_allowed_line_len);
  76     }
  77     if (*_line == '#') { // comment
  78       continue;
  79     }
  80     break;
  81   }
  82 
  83   _id = _unspecified;
  84   _super = _unspecified;
  85   _interfaces->clear();
  86   _source = NULL;
  87   _interfaces_specified = false;
  88 
  89   {
  90     int len = (int)strlen(_line);
  91     int i;
  92     // Replace \t\r\n with ' '
  93     for (i=0; i<len; i++) {
  94       if (_line[i] == '\t' || _line[i] == '\r' || _line[i] == '\n') {
  95         _line[i] = ' ';
  96       }
  97     }
  98 
  99     // Remove trailing newline/space
 100     while (len > 0) {
 101       if (_line[len-1] == ' ') {
 102         _line[len-1] = '\0';
 103         len --;
 104       } else {
 105         break;
 106       }
 107     }
 108     _line_len = len;
 109     _class_name = _line;
 110   }
 111 
 112   if ((_token = strchr(_line, ' ')) == NULL) {
 113     // No optional arguments are specified.
 114     return true;
 115   }
 116 
 117   // Mark the end of the name, and go to the next input char
 118   *_token++ = '\0';
 119 
 120   while (*_token) {
 121     skip_whitespaces();
 122 
 123     if (parse_int_option("id:", &_id)) {
 124       continue;
 125     } else if (parse_int_option("super:", &_super)) {
 126       check_already_loaded("Super class", _super);
 127       continue;
 128     } else if (skip_token("interfaces:")) {
 129       int i;
 130       while (try_parse_int(&i)) {
 131         check_already_loaded("Interface", i);
 132         _interfaces->append(i);
 133       }
 134     } else if (skip_token("source:")) {
 135       skip_whitespaces();
 136       _source = _token;
 137       char* s = strchr(_token, ' ');
 138       if (s == NULL) {
 139         break; // end of input line
 140       } else {
 141         *s = '\0'; // mark the end of _source
 142         _token = s+1;
 143       }
 144     } else {
 145       error("Unknown input");
 146     }
 147   }
 148 
 149   // if src is specified
 150   //     id super interfaces must all be specified
 151   //     loader may be specified
 152   // else
 153   //     # the class is loaded from classpath
 154   //     id may be specified
 155   //     super, interfaces, loader must not be specified
 156   return true;
 157 }
 158 
 159 void ClassListParser::skip_whitespaces() {
 160   while (*_token == ' ' || *_token == '\t') {
 161     _token ++;
 162   }
 163 }
 164 
 165 void ClassListParser::skip_non_whitespaces() {
 166   while (*_token && *_token != ' ' && *_token != '\t') {
 167     _token ++;
 168   }
 169 }
 170 
 171 void ClassListParser::parse_int(int* value) {
 172   skip_whitespaces();
 173   if (sscanf(_token, "%i", value) == 1) {
 174     skip_non_whitespaces();
 175     if (*value < 0) {
 176       error("Error: negative integers not allowed (%d)", *value);
 177     }
 178   } else {
 179     error("Error: expected integer");
 180   }
 181 }
 182 
 183 bool ClassListParser::try_parse_int(int* value) {
 184   skip_whitespaces();
 185   if (sscanf(_token, "%i", value) == 1) {
 186     skip_non_whitespaces();
 187     return true;
 188   }
 189   return false;
 190 }
 191 
 192 bool ClassListParser::skip_token(const char* option_name) {
 193   size_t len = strlen(option_name);
 194   if (strncmp(_token, option_name, len) == 0) {
 195     _token += len;
 196     return true;
 197   } else {
 198     return false;
 199   }
 200 }
 201 
 202 bool ClassListParser::parse_int_option(const char* option_name, int* value) {
 203   if (skip_token(option_name)) {
 204     if (*value != _unspecified) {
 205       error("%s specified twice", option_name);
 206     } else {
 207       parse_int(value);
 208       return true;
 209     }
 210   }
 211   return false;
 212 }
 213 
 214 void ClassListParser::print_specified_interfaces() {
 215   const int n = _interfaces->length();
 216   jio_fprintf(defaultStream::error_stream(), "Currently specified interfaces[%d] = {\n", n);
 217   for (int i=0; i<n; i++) {
 218     InstanceKlass* k = lookup_class_by_id(_interfaces->at(i));
 219     jio_fprintf(defaultStream::error_stream(), "  %4d = %s\n", _interfaces->at(i), k->name()->as_klass_external_name());
 220   }
 221   jio_fprintf(defaultStream::error_stream(), "}\n");
 222 }
 223 
 224 void ClassListParser::print_actual_interfaces(InstanceKlass *ik) {
 225   int n = ik->local_interfaces()->length();
 226   jio_fprintf(defaultStream::error_stream(), "Actual interfaces[%d] = {\n", n);
 227   for (int i = 0; i < n; i++) {
 228     InstanceKlass* e = InstanceKlass::cast(ik->local_interfaces()->at(i));
 229     jio_fprintf(defaultStream::error_stream(), "  %s\n", e->name()->as_klass_external_name());
 230   }
 231   jio_fprintf(defaultStream::error_stream(), "}\n");
 232 }
 233 
 234 void ClassListParser::error(const char *msg, ...) {
 235   va_list ap;
 236   va_start(ap, msg);
 237   int error_index = _token - _line;
 238   if (error_index >= _line_len) {
 239     error_index = _line_len - 1;
 240   }
 241   if (error_index < 0) {
 242     error_index = 0;
 243   }
 244 
 245   jio_fprintf(defaultStream::error_stream(),
 246               "An error has occurred while processing class list file %s %d:%d.\n",
 247               _classlist_file, _line_no, (error_index + 1));
 248   jio_vfprintf(defaultStream::error_stream(), msg, ap);
 249 
 250   if (_line_len <= 0) {
 251     jio_fprintf(defaultStream::error_stream(), "\n");
 252   } else {
 253     jio_fprintf(defaultStream::error_stream(), ":\n");
 254     for (int i=0; i<_line_len; i++) {
 255       char c = _line[i];
 256       if (c == '\0') {
 257         jio_fprintf(defaultStream::error_stream(), "%s", " ");
 258       } else {
 259         jio_fprintf(defaultStream::error_stream(), "%c", c);
 260       }
 261     }
 262     jio_fprintf(defaultStream::error_stream(), "\n");
 263     for (int i=0; i<error_index; i++) {
 264       jio_fprintf(defaultStream::error_stream(), "%s", " ");
 265     }
 266     jio_fprintf(defaultStream::error_stream(), "^\n");
 267   }
 268 
 269   vm_exit_during_initialization("class list format error.", NULL);
 270   va_end(ap);
 271 }
 272 
 273 // This function is used for loading classes for customized class loaders
 274 // during archive dumping.
 275 InstanceKlass* ClassListParser::load_class_from_source(Symbol* class_name, TRAPS) {
 276 #if !(defined(_LP64) && (defined(LINUX)|| defined(SOLARIS)))
 277   // The only supported platforms are: (1) Linux/64-bit and (2) Solaris/64-bit
 278   //
 279   // This #if condition should be in sync with the areCustomLoadersSupportedForCDS
 280   // method in test/lib/jdk/test/lib/Platform.java.
 281   error("AppCDS custom class loaders not supported on this platform");
 282 #endif
 283 
 284   if (!is_super_specified()) {
 285     error("If source location is specified, super class must be also specified");
 286   }
 287   if (!is_id_specified()) {
 288     error("If source location is specified, id must be also specified");
 289   }
 290   InstanceKlass* k = ClassLoaderExt::load_class(class_name, _source, THREAD);
 291 
 292   if (strncmp(_class_name, "java/", 5) == 0) {
 293     log_info(cds)("Prohibited package for non-bootstrap classes: %s.class from %s",
 294           _class_name, _source);
 295     return NULL;
 296   }
 297 
 298   if (k != NULL) {
 299     if (k->local_interfaces()->length() != _interfaces->length()) {
 300       print_specified_interfaces();
 301       print_actual_interfaces(k);
 302       error("The number of interfaces (%d) specified in class list does not match the class file (%d)",
 303             _interfaces->length(), k->local_interfaces()->length());
 304     }
 305 
 306     if (!SystemDictionaryShared::add_non_builtin_klass(class_name, ClassLoaderData::the_null_class_loader_data(),
 307                                                        k, THREAD)) {
 308       error("Duplicated class %s", _class_name);
 309     }
 310 
 311     // This tells JVM_FindLoadedClass to not find this class.
 312     k->set_shared_classpath_index(UNREGISTERED_INDEX);
 313     k->clear_class_loader_type();
 314   }
 315 
 316   return k;
 317 }
 318 
 319 Klass* ClassListParser::load_current_class(TRAPS) {
 320   TempNewSymbol class_name_symbol = SymbolTable::new_symbol(_class_name, THREAD);
 321   guarantee(!HAS_PENDING_EXCEPTION, "Exception creating a symbol.");
 322 
 323   Klass *klass = NULL;
 324   if (!is_loading_from_source()) {
 325     // Load classes for the boot/platform/app loaders only.
 326     if (is_super_specified()) {
 327       error("If source location is not specified, super class must not be specified");
 328     }
 329     if (are_interfaces_specified()) {
 330       error("If source location is not specified, interface(s) must not be specified");
 331     }
 332 
 333     bool non_array = !FieldType::is_array(class_name_symbol);
 334 
 335     JavaValue result(T_OBJECT);
 336     if (non_array) {
 337       // At this point, we are executing in the context of the boot loader. We
 338       // cannot call Class.forName because that is context dependent and
 339       // would load only classes for the boot loader.
 340       //
 341       // Instead, let's call java_system_loader().loadClass() directly, which will
 342       // delegate to the correct loader (boot, platform or app) depending on
 343       // the class name.
 344 
 345       Handle s = java_lang_String::create_from_symbol(class_name_symbol, CHECK_0);
 346       // ClassLoader.loadClass() wants external class name format, i.e., convert '/' chars to '.'
 347       Handle ext_class_name = java_lang_String::externalize_classname(s, CHECK_0);
 348       Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
 349 
 350       JavaCalls::call_virtual(&result,
 351                               loader, //SystemDictionary::java_system_loader(),
 352                               SystemDictionary::ClassLoader_klass(),
 353                               vmSymbols::loadClass_name(),
 354                               vmSymbols::string_class_signature(),
 355                               ext_class_name,
 356                               THREAD);
 357     } else {
 358       // array classes are not supported in class list.
 359       THROW_NULL(vmSymbols::java_lang_ClassNotFoundException());
 360     }
 361     assert(result.get_type() == T_OBJECT, "just checking");
 362     oop obj = (oop) result.get_jobject();
 363     if (!HAS_PENDING_EXCEPTION && (obj != NULL)) {
 364       klass = java_lang_Class::as_Klass(obj);
 365     } else { // load classes in bootclasspath/a
 366       if (HAS_PENDING_EXCEPTION) {
 367         CLEAR_PENDING_EXCEPTION;
 368       }
 369 
 370       if (non_array) {
 371         Klass* k = SystemDictionary::resolve_or_null(class_name_symbol, CHECK_NULL);
 372         if (k != NULL) {
 373           klass = k;
 374         } else {
 375           if (!HAS_PENDING_EXCEPTION) {
 376             THROW_NULL(vmSymbols::java_lang_ClassNotFoundException());
 377           }
 378         }
 379       }
 380     }
 381   } else {
 382     // If "source:" tag is specified, all super class and super interfaces must be specified in the
 383     // class list file.
 384     klass = load_class_from_source(class_name_symbol, CHECK_NULL);
 385   }
 386 
 387   if (klass != NULL && klass->is_instance_klass() && is_id_specified()) {
 388     InstanceKlass* ik = InstanceKlass::cast(klass);
 389     int id = this->id();
 390     SystemDictionaryShared::update_shared_entry(ik, id);
 391     InstanceKlass* old = table()->lookup(id);
 392     if (old != NULL && old != ik) {
 393       error("Duplicated ID %d for class %s", id, _class_name);
 394     }
 395     table()->add(id, ik);
 396   }
 397 
 398   return klass;
 399 }
 400 
 401 bool ClassListParser::is_loading_from_source() {
 402   return (_source != NULL);
 403 }
 404 
 405 InstanceKlass* ClassListParser::lookup_class_by_id(int id) {
 406   InstanceKlass* klass = table()->lookup(id);
 407   if (klass == NULL) {
 408     error("Class ID %d has not been defined", id);
 409   }
 410   return klass;
 411 }
 412 
 413 
 414 InstanceKlass* ClassListParser::lookup_super_for_current_class(Symbol* super_name) {
 415   if (!is_loading_from_source()) {
 416     return NULL;
 417   }
 418 
 419   InstanceKlass* k = lookup_class_by_id(super());
 420   if (super_name != k->name()) {
 421     error("The specified super class %s (id %d) does not match actual super class %s",
 422           k->name()->as_klass_external_name(), super(),
 423           super_name->as_klass_external_name());
 424   }
 425   return k;
 426 }
 427 
 428 InstanceKlass* ClassListParser::lookup_interface_for_current_class(Symbol* interface_name) {
 429   if (!is_loading_from_source()) {
 430     return NULL;
 431   }
 432 
 433   const int n = _interfaces->length();
 434   if (n == 0) {
 435     error("Class %s implements the interface %s, but no interface has been specified in the input line",
 436           _class_name, interface_name->as_klass_external_name());
 437     ShouldNotReachHere();
 438   }
 439 
 440   int i;
 441   for (i=0; i<n; i++) {
 442     InstanceKlass* k = lookup_class_by_id(_interfaces->at(i));
 443     if (interface_name == k->name()) {
 444       return k;
 445     }
 446   }
 447 
 448   // interface_name is not specified by the "interfaces:" keyword.
 449   print_specified_interfaces();
 450   error("The interface %s implemented by class %s does not match any of the specified interface IDs",
 451         interface_name->as_klass_external_name(), _class_name);
 452   ShouldNotReachHere();
 453   return NULL;
 454 }
 455