link.cc 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106
  1. // link.cc - Code for linking and resolving classes and pool entries.
  2. /* Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
  3. Free Software Foundation
  4. This file is part of libgcj.
  5. This software is copyrighted work licensed under the terms of the
  6. Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
  7. details. */
  8. /* Author: Kresten Krab Thorup <krab@gnu.org> */
  9. #include <config.h>
  10. #include <platform.h>
  11. #include <stdio.h>
  12. #ifdef USE_LIBFFI
  13. #include <ffi.h>
  14. #endif
  15. #include <java-interp.h>
  16. // Set GC_DEBUG before including gc.h!
  17. #ifdef LIBGCJ_GC_DEBUG
  18. # define GC_DEBUG
  19. #endif
  20. #include <gc.h>
  21. #include <jvm.h>
  22. #include <gcj/cni.h>
  23. #include <string.h>
  24. #include <limits.h>
  25. #include <java-cpool.h>
  26. #include <execution.h>
  27. #ifdef INTERPRETER
  28. #include <jvmti.h>
  29. #include "jvmti-int.h"
  30. #endif
  31. #include <java/lang/Class.h>
  32. #include <java/lang/String.h>
  33. #include <java/lang/StringBuffer.h>
  34. #include <java/lang/Thread.h>
  35. #include <java/lang/InternalError.h>
  36. #include <java/lang/VirtualMachineError.h>
  37. #include <java/lang/VerifyError.h>
  38. #include <java/lang/NoSuchFieldError.h>
  39. #include <java/lang/NoSuchMethodError.h>
  40. #include <java/lang/ClassFormatError.h>
  41. #include <java/lang/IllegalAccessError.h>
  42. #include <java/lang/InternalError.h>
  43. #include <java/lang/AbstractMethodError.h>
  44. #include <java/lang/NoClassDefFoundError.h>
  45. #include <java/lang/IncompatibleClassChangeError.h>
  46. #include <java/lang/VerifyError.h>
  47. #include <java/lang/VMClassLoader.h>
  48. #include <java/lang/reflect/Modifier.h>
  49. #include <java/security/CodeSource.h>
  50. using namespace gcj;
  51. template<typename T>
  52. struct aligner
  53. {
  54. char c;
  55. T field;
  56. };
  57. #define ALIGNOF(TYPE) (offsetof (aligner<TYPE>, field))
  58. // This returns the alignment of a type as it would appear in a
  59. // structure. This can be different from the alignment of the type
  60. // itself. For instance on x86 double is 8-aligned but struct{double}
  61. // is 4-aligned.
  62. int
  63. _Jv_Linker::get_alignment_from_class (jclass klass)
  64. {
  65. if (klass == JvPrimClass (byte))
  66. return ALIGNOF (jbyte);
  67. else if (klass == JvPrimClass (short))
  68. return ALIGNOF (jshort);
  69. else if (klass == JvPrimClass (int))
  70. return ALIGNOF (jint);
  71. else if (klass == JvPrimClass (long))
  72. return ALIGNOF (jlong);
  73. else if (klass == JvPrimClass (boolean))
  74. return ALIGNOF (jboolean);
  75. else if (klass == JvPrimClass (char))
  76. return ALIGNOF (jchar);
  77. else if (klass == JvPrimClass (float))
  78. return ALIGNOF (jfloat);
  79. else if (klass == JvPrimClass (double))
  80. return ALIGNOF (jdouble);
  81. else
  82. return ALIGNOF (jobject);
  83. }
  84. void
  85. _Jv_Linker::resolve_field (_Jv_Field *field, java::lang::ClassLoader *loader)
  86. {
  87. if (! field->isResolved ())
  88. {
  89. _Jv_Utf8Const *sig = (_Jv_Utf8Const *) field->type;
  90. jclass type = _Jv_FindClassFromSignature (sig->chars(), loader);
  91. if (type == NULL)
  92. throw new java::lang::NoClassDefFoundError(field->name->toString());
  93. field->type = type;
  94. field->flags &= ~_Jv_FIELD_UNRESOLVED_FLAG;
  95. }
  96. }
  97. // A helper for find_field that knows how to recursively search
  98. // superclasses and interfaces.
  99. _Jv_Field *
  100. _Jv_Linker::find_field_helper (jclass search, _Jv_Utf8Const *name,
  101. _Jv_Utf8Const *type_name, jclass type,
  102. jclass *declarer)
  103. {
  104. while (search)
  105. {
  106. // From 5.4.3.2. First search class itself.
  107. for (int i = 0; i < search->field_count; ++i)
  108. {
  109. _Jv_Field *field = &search->fields[i];
  110. if (! _Jv_equalUtf8Consts (field->name, name))
  111. continue;
  112. // Checks for the odd situation where we were able to retrieve the
  113. // field's class from signature but the resolution of the field itself
  114. // failed which means a different class was resolved.
  115. if (type != NULL)
  116. {
  117. try
  118. {
  119. resolve_field (field, search->loader);
  120. }
  121. catch (java::lang::Throwable *exc)
  122. {
  123. java::lang::LinkageError *le = new java::lang::LinkageError
  124. (JvNewStringLatin1
  125. ("field type mismatch with different loaders"));
  126. le->initCause(exc);
  127. throw le;
  128. }
  129. }
  130. // Note that we compare type names and not types. This is
  131. // bizarre, but we do it because we want to find a field
  132. // (and terminate the search) if it has the correct
  133. // descriptor -- but then later reject it if the class
  134. // loader check results in different classes. We can't just
  135. // pass in the descriptor and check that way, because when
  136. // the field is already resolved there is no easy way to
  137. // find its descriptor again.
  138. if ((field->isResolved ()
  139. ? _Jv_equalUtf8Classnames (type_name, field->type->name)
  140. : _Jv_equalUtf8Classnames (type_name,
  141. (_Jv_Utf8Const *) field->type)))
  142. {
  143. *declarer = search;
  144. return field;
  145. }
  146. }
  147. // Next search direct interfaces.
  148. for (int i = 0; i < search->interface_count; ++i)
  149. {
  150. _Jv_Field *result = find_field_helper (search->interfaces[i], name,
  151. type_name, type, declarer);
  152. if (result)
  153. return result;
  154. }
  155. // Now search superclass.
  156. search = search->superclass;
  157. }
  158. return NULL;
  159. }
  160. bool
  161. _Jv_Linker::has_field_p (jclass search, _Jv_Utf8Const *field_name)
  162. {
  163. for (int i = 0; i < search->field_count; ++i)
  164. {
  165. _Jv_Field *field = &search->fields[i];
  166. if (_Jv_equalUtf8Consts (field->name, field_name))
  167. return true;
  168. }
  169. return false;
  170. }
  171. // Find a field.
  172. // KLASS is the class that is requesting the field.
  173. // OWNER is the class in which the field should be found.
  174. // FIELD_TYPE_NAME is the type descriptor for the field.
  175. // Fill FOUND_CLASS with the address of the class in which the field
  176. // is actually declared.
  177. // This function does the class loader type checks, and
  178. // also access checks. Returns the field, or throws an
  179. // exception on error.
  180. _Jv_Field *
  181. _Jv_Linker::find_field (jclass klass, jclass owner,
  182. jclass *found_class,
  183. _Jv_Utf8Const *field_name,
  184. _Jv_Utf8Const *field_type_name)
  185. {
  186. // FIXME: this allocates a _Jv_Utf8Const each time. We should make
  187. // it cheaper.
  188. // Note: This call will resolve the primitive type names ("Z", "B", ...) to
  189. // their Java counterparts ("boolean", "byte", ...) if accessed via
  190. // field_type->name later. Using these variants of the type name is in turn
  191. // important for the find_field_helper function. However if the class
  192. // resolution failed then we can only use the already given type name.
  193. jclass field_type
  194. = _Jv_FindClassFromSignatureNoException (field_type_name->chars(),
  195. klass->loader);
  196. _Jv_Field *the_field
  197. = find_field_helper (owner, field_name,
  198. (field_type
  199. ? field_type->name :
  200. field_type_name ),
  201. field_type, found_class);
  202. if (the_field == 0)
  203. {
  204. java::lang::StringBuffer *sb = new java::lang::StringBuffer();
  205. sb->append(JvNewStringLatin1("field "));
  206. sb->append(owner->getName());
  207. sb->append(JvNewStringLatin1("."));
  208. sb->append(_Jv_NewStringUTF(field_name->chars()));
  209. sb->append(JvNewStringLatin1(" was not found."));
  210. throw new java::lang::NoSuchFieldError (sb->toString());
  211. }
  212. // Accept it when the field's class could not be resolved.
  213. if (field_type == NULL)
  214. // Silently ignore that we were not able to retrieve the type to make it
  215. // possible to run code which does not access this field.
  216. return the_field;
  217. if (_Jv_CheckAccess (klass, *found_class, the_field->flags))
  218. {
  219. // Note that the field returned by find_field_helper is always
  220. // resolved. However, we still use the constraint mechanism
  221. // because this may affect other lookups.
  222. _Jv_CheckOrCreateLoadingConstraint (field_type, (*found_class)->loader);
  223. }
  224. else
  225. {
  226. java::lang::StringBuffer *sb
  227. = new java::lang::StringBuffer ();
  228. sb->append(klass->getName());
  229. sb->append(JvNewStringLatin1(": "));
  230. sb->append((*found_class)->getName());
  231. sb->append(JvNewStringLatin1("."));
  232. sb->append(_Jv_NewStringUtf8Const (field_name));
  233. throw new java::lang::IllegalAccessError(sb->toString());
  234. }
  235. return the_field;
  236. }
  237. // Check loading constraints for method.
  238. void
  239. _Jv_Linker::check_loading_constraints (_Jv_Method *method, jclass self_class,
  240. jclass other_class)
  241. {
  242. JArray<jclass> *klass_args;
  243. jclass klass_return;
  244. _Jv_GetTypesFromSignature (method, self_class, &klass_args, &klass_return);
  245. jclass *klass_arg = elements (klass_args);
  246. java::lang::ClassLoader *found_loader = other_class->loader;
  247. _Jv_CheckOrCreateLoadingConstraint (klass_return, found_loader);
  248. for (int i = 0; i < klass_args->length; i++)
  249. _Jv_CheckOrCreateLoadingConstraint (*(klass_arg++), found_loader);
  250. }
  251. _Jv_Method *
  252. _Jv_Linker::resolve_method_entry (jclass klass, jclass &found_class,
  253. int class_index, int name_and_type_index,
  254. bool init, bool is_iface)
  255. {
  256. _Jv_Constants *pool = &klass->constants;
  257. jclass owner = resolve_pool_entry (klass, class_index).clazz;
  258. if (init && owner != klass)
  259. _Jv_InitClass (owner);
  260. _Jv_ushort name_index, type_index;
  261. _Jv_loadIndexes (&pool->data[name_and_type_index],
  262. name_index,
  263. type_index);
  264. _Jv_Utf8Const *method_name = pool->data[name_index].utf8;
  265. _Jv_Utf8Const *method_signature = pool->data[type_index].utf8;
  266. _Jv_Method *the_method = 0;
  267. found_class = 0;
  268. // We're going to cache a pointer to the _Jv_Method object
  269. // when we find it. So, to ensure this doesn't get moved from
  270. // beneath us, we first put all the needed Miranda methods
  271. // into the target class.
  272. wait_for_state (klass, JV_STATE_LOADED);
  273. // First search the class itself.
  274. the_method = search_method_in_class (owner, klass,
  275. method_name, method_signature);
  276. if (the_method != 0)
  277. {
  278. found_class = owner;
  279. goto end_of_method_search;
  280. }
  281. // If we are resolving an interface method, search the
  282. // interface's superinterfaces (A superinterface is not an
  283. // interface's superclass - a superinterface is implemented by
  284. // the interface).
  285. if (is_iface)
  286. {
  287. _Jv_ifaces ifaces;
  288. ifaces.count = 0;
  289. ifaces.len = 4;
  290. ifaces.list = (jclass *) _Jv_Malloc (ifaces.len
  291. * sizeof (jclass *));
  292. get_interfaces (owner, &ifaces);
  293. for (int i = 0; i < ifaces.count; i++)
  294. {
  295. jclass cls = ifaces.list[i];
  296. the_method = search_method_in_class (cls, klass, method_name,
  297. method_signature);
  298. if (the_method != 0)
  299. {
  300. found_class = cls;
  301. break;
  302. }
  303. }
  304. _Jv_Free (ifaces.list);
  305. if (the_method != 0)
  306. goto end_of_method_search;
  307. }
  308. // Finally, search superclasses.
  309. the_method = (search_method_in_superclasses
  310. (owner->getSuperclass (), klass, method_name,
  311. method_signature, &found_class));
  312. end_of_method_search:
  313. if (the_method == 0)
  314. {
  315. java::lang::StringBuffer *sb = new java::lang::StringBuffer();
  316. sb->append(JvNewStringLatin1("method "));
  317. sb->append(owner->getName());
  318. sb->append(JvNewStringLatin1("."));
  319. sb->append(_Jv_NewStringUTF(method_name->chars()));
  320. sb->append(JvNewStringLatin1(" with signature "));
  321. sb->append(_Jv_NewStringUTF(method_signature->chars()));
  322. sb->append(JvNewStringLatin1(" was not found."));
  323. throw new java::lang::NoSuchMethodError (sb->toString());
  324. }
  325. // if (found_class->loader != klass->loader), then we must actually
  326. // check that the types of arguments correspond. JVMS 5.4.3.3.
  327. if (found_class->loader != klass->loader)
  328. check_loading_constraints (the_method, klass, found_class);
  329. return the_method;
  330. }
  331. _Jv_Mutex_t _Jv_Linker::resolve_mutex;
  332. void
  333. _Jv_Linker::init (void)
  334. {
  335. _Jv_MutexInit (&_Jv_Linker::resolve_mutex);
  336. }
  337. // Locking in resolve_pool_entry is somewhat subtle. Constant
  338. // resolution is idempotent, so it doesn't matter if two threads
  339. // resolve the same entry. However, it is important that we always
  340. // write the resolved flag and the data together, atomically. It is
  341. // also important that we read them atomically.
  342. _Jv_word
  343. _Jv_Linker::resolve_pool_entry (jclass klass, int index, bool lazy)
  344. {
  345. using namespace java::lang::reflect;
  346. if (GC_base (klass) && klass->constants.data
  347. && ! GC_base (klass->constants.data))
  348. // If a class is heap-allocated but the constant pool is not this
  349. // is a "new ABI" class, i.e. one where the initial constant pool
  350. // is in the read-only data section of an object file. Copy the
  351. // initial constant pool from there to a new heap-allocated pool.
  352. {
  353. jsize count = klass->constants.size;
  354. if (count)
  355. {
  356. _Jv_word* constants
  357. = (_Jv_word*) _Jv_AllocRawObj (count * sizeof (_Jv_word));
  358. memcpy ((void*)constants,
  359. (void*)klass->constants.data,
  360. count * sizeof (_Jv_word));
  361. klass->constants.data = constants;
  362. }
  363. }
  364. _Jv_Constants *pool = &klass->constants;
  365. jbyte tags;
  366. _Jv_word data;
  367. tags = read_cpool_entry (&data, pool, index);
  368. if ((tags & JV_CONSTANT_ResolvedFlag) != 0)
  369. return data;
  370. switch (tags & ~JV_CONSTANT_LazyFlag)
  371. {
  372. case JV_CONSTANT_Class:
  373. {
  374. _Jv_Utf8Const *name = data.utf8;
  375. jclass found;
  376. if (name->first() == '[')
  377. found = _Jv_FindClassFromSignatureNoException (name->chars(),
  378. klass->loader);
  379. else
  380. found = _Jv_FindClassNoException (name, klass->loader);
  381. // If the class could not be loaded a phantom class is created. Any
  382. // function that deals with such a class but cannot do something useful
  383. // with it should just throw a NoClassDefFoundError with the class'
  384. // name.
  385. if (! found)
  386. {
  387. if (lazy)
  388. {
  389. found = _Jv_NewClass(name, NULL, NULL);
  390. found->state = JV_STATE_PHANTOM;
  391. tags |= JV_CONSTANT_ResolvedFlag;
  392. data.clazz = found;
  393. break;
  394. }
  395. else
  396. throw new java::lang::NoClassDefFoundError (name->toString());
  397. }
  398. // Check accessibility, but first strip array types as
  399. // _Jv_ClassNameSamePackage can't handle arrays.
  400. jclass check;
  401. for (check = found;
  402. check && check->isArray();
  403. check = check->getComponentType())
  404. ;
  405. if ((found->accflags & Modifier::PUBLIC) == Modifier::PUBLIC
  406. || (_Jv_ClassNameSamePackage (check->name,
  407. klass->name)))
  408. {
  409. data.clazz = found;
  410. tags |= JV_CONSTANT_ResolvedFlag;
  411. }
  412. else
  413. {
  414. java::lang::StringBuffer *sb = new java::lang::StringBuffer ();
  415. sb->append(klass->getName());
  416. sb->append(JvNewStringLatin1(" can't access class "));
  417. sb->append(found->getName());
  418. throw new java::lang::IllegalAccessError(sb->toString());
  419. }
  420. }
  421. break;
  422. case JV_CONSTANT_String:
  423. {
  424. jstring str;
  425. str = _Jv_NewStringUtf8Const (data.utf8);
  426. data.o = str;
  427. tags |= JV_CONSTANT_ResolvedFlag;
  428. }
  429. break;
  430. case JV_CONSTANT_Fieldref:
  431. {
  432. _Jv_ushort class_index, name_and_type_index;
  433. _Jv_loadIndexes (&data,
  434. class_index,
  435. name_and_type_index);
  436. jclass owner = (resolve_pool_entry (klass, class_index, true)).clazz;
  437. // If a phantom class was resolved our field reference is
  438. // unusable because of the missing class.
  439. if (owner->state == JV_STATE_PHANTOM)
  440. throw new java::lang::NoClassDefFoundError(owner->getName());
  441. // We don't initialize 'owner', but we do make sure that its
  442. // fields exist.
  443. wait_for_state (owner, JV_STATE_PREPARED);
  444. _Jv_ushort name_index, type_index;
  445. _Jv_loadIndexes (&pool->data[name_and_type_index],
  446. name_index,
  447. type_index);
  448. _Jv_Utf8Const *field_name = pool->data[name_index].utf8;
  449. _Jv_Utf8Const *field_type_name = pool->data[type_index].utf8;
  450. jclass found_class = 0;
  451. _Jv_Field *the_field = find_field (klass, owner,
  452. &found_class,
  453. field_name,
  454. field_type_name);
  455. // Initialize the field's declaring class, not its qualifying
  456. // class.
  457. _Jv_InitClass (found_class);
  458. data.field = the_field;
  459. tags |= JV_CONSTANT_ResolvedFlag;
  460. }
  461. break;
  462. case JV_CONSTANT_Methodref:
  463. case JV_CONSTANT_InterfaceMethodref:
  464. {
  465. _Jv_ushort class_index, name_and_type_index;
  466. _Jv_loadIndexes (&data,
  467. class_index,
  468. name_and_type_index);
  469. _Jv_Method *the_method;
  470. jclass found_class;
  471. the_method = resolve_method_entry (klass, found_class,
  472. class_index, name_and_type_index,
  473. true,
  474. tags == JV_CONSTANT_InterfaceMethodref);
  475. data.rmethod
  476. = klass->engine->resolve_method(the_method,
  477. found_class,
  478. ((the_method->accflags
  479. & Modifier::STATIC) != 0));
  480. tags |= JV_CONSTANT_ResolvedFlag;
  481. }
  482. break;
  483. }
  484. write_cpool_entry (data, tags, pool, index);
  485. return data;
  486. }
  487. // This function is used to lazily locate superclasses and
  488. // superinterfaces. This must be called with the class lock held.
  489. void
  490. _Jv_Linker::resolve_class_ref (jclass klass, jclass *classref)
  491. {
  492. jclass ret = *classref;
  493. // If superclass looks like a constant pool entry, resolve it now.
  494. if (ret && (uaddr) ret < (uaddr) klass->constants.size)
  495. {
  496. if (klass->state < JV_STATE_LINKED)
  497. {
  498. _Jv_Utf8Const *name = klass->constants.data[(uaddr) *classref].utf8;
  499. ret = _Jv_FindClass (name, klass->loader);
  500. if (! ret)
  501. {
  502. throw new java::lang::NoClassDefFoundError (name->toString());
  503. }
  504. }
  505. else
  506. ret = klass->constants.data[(uaddr) classref].clazz;
  507. *classref = ret;
  508. }
  509. }
  510. // Find a method declared in the cls that is referenced from klass and
  511. // perform access checks if CHECK_PERMS is true.
  512. _Jv_Method *
  513. _Jv_Linker::search_method_in_class (jclass cls, jclass klass,
  514. _Jv_Utf8Const *method_name,
  515. _Jv_Utf8Const *method_signature,
  516. bool check_perms)
  517. {
  518. using namespace java::lang::reflect;
  519. for (int i = 0; i < cls->method_count; i++)
  520. {
  521. _Jv_Method *method = &cls->methods[i];
  522. if ( (!_Jv_equalUtf8Consts (method->name,
  523. method_name))
  524. || (!_Jv_equalUtf8Consts (method->signature,
  525. method_signature)))
  526. continue;
  527. if (!check_perms || _Jv_CheckAccess (klass, cls, method->accflags))
  528. return method;
  529. else
  530. {
  531. java::lang::StringBuffer *sb = new java::lang::StringBuffer();
  532. sb->append(klass->getName());
  533. sb->append(JvNewStringLatin1(": "));
  534. sb->append(cls->getName());
  535. sb->append(JvNewStringLatin1("."));
  536. sb->append(_Jv_NewStringUTF(method_name->chars()));
  537. sb->append(_Jv_NewStringUTF(method_signature->chars()));
  538. throw new java::lang::IllegalAccessError (sb->toString());
  539. }
  540. }
  541. return 0;
  542. }
  543. // Like search_method_in_class, but work our way up the superclass
  544. // chain.
  545. _Jv_Method *
  546. _Jv_Linker::search_method_in_superclasses (jclass cls, jclass klass,
  547. _Jv_Utf8Const *method_name,
  548. _Jv_Utf8Const *method_signature,
  549. jclass *found_class, bool check_perms)
  550. {
  551. _Jv_Method *the_method = NULL;
  552. for ( ; cls != 0; cls = cls->getSuperclass ())
  553. {
  554. the_method = search_method_in_class (cls, klass, method_name,
  555. method_signature, check_perms);
  556. if (the_method != 0)
  557. {
  558. if (found_class)
  559. *found_class = cls;
  560. break;
  561. }
  562. }
  563. return the_method;
  564. }
  565. #define INITIAL_IOFFSETS_LEN 4
  566. #define INITIAL_IFACES_LEN 4
  567. static _Jv_IDispatchTable null_idt = {SHRT_MAX, 0, {}};
  568. // Generate tables for constant-time assignment testing and interface
  569. // method lookup. This implements the technique described by Per Bothner
  570. // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
  571. // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
  572. void
  573. _Jv_Linker::prepare_constant_time_tables (jclass klass)
  574. {
  575. if (klass->isPrimitive () || klass->isInterface ())
  576. return;
  577. // Short-circuit in case we've been called already.
  578. if ((klass->idt != NULL) || klass->depth != 0)
  579. return;
  580. // Calculate the class depth and ancestor table. The depth of a class
  581. // is how many "extends" it is removed from Object. Thus the depth of
  582. // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
  583. // is 2. Depth is defined for all regular and array classes, but not
  584. // interfaces or primitive types.
  585. jclass klass0 = klass;
  586. jboolean has_interfaces = false;
  587. while (klass0 != &java::lang::Object::class$)
  588. {
  589. if (klass0->interface_count)
  590. has_interfaces = true;
  591. klass0 = klass0->superclass;
  592. klass->depth++;
  593. }
  594. // We do class member testing in constant time by using a small table
  595. // of all the ancestor classes within each class. The first element is
  596. // a pointer to the current class, and the rest are pointers to the
  597. // classes ancestors, ordered from the current class down by decreasing
  598. // depth. We do not include java.lang.Object in the table of ancestors,
  599. // since it is redundant. Note that the classes pointed to by
  600. // 'ancestors' will always be reachable by other paths.
  601. klass->ancestors = (jclass *) _Jv_AllocBytes (klass->depth
  602. * sizeof (jclass));
  603. klass0 = klass;
  604. for (int index = 0; index < klass->depth; index++)
  605. {
  606. klass->ancestors[index] = klass0;
  607. klass0 = klass0->superclass;
  608. }
  609. if ((klass->accflags & java::lang::reflect::Modifier::ABSTRACT) != 0)
  610. return;
  611. // Optimization: If class implements no interfaces, use a common
  612. // predefined interface table.
  613. if (!has_interfaces)
  614. {
  615. klass->idt = &null_idt;
  616. return;
  617. }
  618. _Jv_ifaces ifaces;
  619. ifaces.count = 0;
  620. ifaces.len = INITIAL_IFACES_LEN;
  621. ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
  622. int itable_size = get_interfaces (klass, &ifaces);
  623. if (ifaces.count > 0)
  624. {
  625. // The classes pointed to by the itable will always be reachable
  626. // via other paths.
  627. int idt_bytes = sizeof (_Jv_IDispatchTable) + (itable_size
  628. * sizeof (void *));
  629. klass->idt = (_Jv_IDispatchTable *) _Jv_AllocBytes (idt_bytes);
  630. klass->idt->itable_length = itable_size;
  631. jshort *itable_offsets =
  632. (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
  633. generate_itable (klass, &ifaces, itable_offsets);
  634. jshort cls_iindex = find_iindex (ifaces.list, itable_offsets,
  635. ifaces.count);
  636. for (int i = 0; i < ifaces.count; i++)
  637. {
  638. ifaces.list[i]->ioffsets[cls_iindex] = itable_offsets[i];
  639. }
  640. klass->idt->iindex = cls_iindex;
  641. _Jv_Free (ifaces.list);
  642. _Jv_Free (itable_offsets);
  643. }
  644. else
  645. {
  646. klass->idt->iindex = SHRT_MAX;
  647. }
  648. }
  649. // Return index of item in list, or -1 if item is not present.
  650. inline jshort
  651. _Jv_Linker::indexof (void *item, void **list, jshort list_len)
  652. {
  653. for (int i=0; i < list_len; i++)
  654. {
  655. if (list[i] == item)
  656. return i;
  657. }
  658. return -1;
  659. }
  660. // Find all unique interfaces directly or indirectly implemented by klass.
  661. // Returns the size of the interface dispatch table (itable) for klass, which
  662. // is the number of unique interfaces plus the total number of methods that
  663. // those interfaces declare. May extend ifaces if required.
  664. jshort
  665. _Jv_Linker::get_interfaces (jclass klass, _Jv_ifaces *ifaces)
  666. {
  667. jshort result = 0;
  668. for (int i = 0; i < klass->interface_count; i++)
  669. {
  670. jclass iface = klass->interfaces[i];
  671. /* Make sure interface is linked. */
  672. wait_for_state(iface, JV_STATE_LINKED);
  673. if (indexof (iface, (void **) ifaces->list, ifaces->count) == -1)
  674. {
  675. if (ifaces->count + 1 >= ifaces->len)
  676. {
  677. /* Resize ifaces list */
  678. ifaces->len = ifaces->len * 2;
  679. ifaces->list
  680. = (jclass *) _Jv_Realloc (ifaces->list,
  681. ifaces->len * sizeof(jclass));
  682. }
  683. ifaces->list[ifaces->count] = iface;
  684. ifaces->count++;
  685. result += get_interfaces (klass->interfaces[i], ifaces);
  686. }
  687. }
  688. if (klass->isInterface())
  689. {
  690. // We want to add 1 plus the number of interface methods here.
  691. // But, we take special care to skip <clinit>.
  692. ++result;
  693. for (int i = 0; i < klass->method_count; ++i)
  694. {
  695. if (klass->methods[i].name->first() != '<')
  696. ++result;
  697. }
  698. }
  699. else if (klass->superclass)
  700. result += get_interfaces (klass->superclass, ifaces);
  701. return result;
  702. }
  703. // Fill out itable in klass, resolving method declarations in each ifaces.
  704. // itable_offsets is filled out with the position of each iface in itable,
  705. // such that itable[itable_offsets[n]] == ifaces.list[n].
  706. void
  707. _Jv_Linker::generate_itable (jclass klass, _Jv_ifaces *ifaces,
  708. jshort *itable_offsets)
  709. {
  710. void **itable = klass->idt->itable;
  711. jshort itable_pos = 0;
  712. for (int i = 0; i < ifaces->count; i++)
  713. {
  714. jclass iface = ifaces->list[i];
  715. itable_offsets[i] = itable_pos;
  716. itable_pos = append_partial_itable (klass, iface, itable, itable_pos);
  717. /* Create ioffsets table for iface */
  718. if (iface->ioffsets == NULL)
  719. {
  720. // The first element of ioffsets is its length (itself included).
  721. jshort *ioffsets = (jshort *) _Jv_AllocBytes (INITIAL_IOFFSETS_LEN
  722. * sizeof (jshort));
  723. ioffsets[0] = INITIAL_IOFFSETS_LEN;
  724. for (int i = 1; i < INITIAL_IOFFSETS_LEN; i++)
  725. ioffsets[i] = -1;
  726. iface->ioffsets = ioffsets;
  727. }
  728. }
  729. }
  730. // Format method name for use in error messages.
  731. jstring
  732. _Jv_GetMethodString (jclass klass, _Jv_Method *meth,
  733. jclass derived)
  734. {
  735. using namespace java::lang;
  736. StringBuffer *buf = new StringBuffer (klass->name->toString());
  737. buf->append (jchar ('.'));
  738. buf->append (meth->name->toString());
  739. buf->append ((jchar) ' ');
  740. buf->append (meth->signature->toString());
  741. if (derived)
  742. {
  743. buf->append(JvNewStringLatin1(" in "));
  744. buf->append(derived->name->toString());
  745. }
  746. return buf->toString();
  747. }
  748. void
  749. _Jv_ThrowNoSuchMethodError ()
  750. {
  751. throw new java::lang::NoSuchMethodError;
  752. }
  753. #if defined USE_LIBFFI && FFI_CLOSURES && defined(INTERPRETER)
  754. // A function whose invocation is prepared using libffi. It gets called
  755. // whenever a static method of a missing class is invoked. The data argument
  756. // holds a reference to a String denoting the missing class.
  757. // The prepared function call is stored in a class' atable.
  758. void
  759. _Jv_ThrowNoClassDefFoundErrorTrampoline(ffi_cif *,
  760. void *,
  761. void **,
  762. void *data)
  763. {
  764. throw new java::lang::NoClassDefFoundError(
  765. _Jv_NewStringUtf8Const((_Jv_Utf8Const *) data));
  766. }
  767. #else
  768. // A variant of the NoClassDefFoundError throwing method that can
  769. // be used without libffi.
  770. void
  771. _Jv_ThrowNoClassDefFoundError()
  772. {
  773. throw new java::lang::NoClassDefFoundError();
  774. }
  775. #endif
  776. // Throw a NoSuchFieldError. Called by compiler-generated code when
  777. // an otable entry is zero. OTABLE_INDEX is the index in the caller's
  778. // otable that refers to the missing field. This index may be used to
  779. // print diagnostic information about the field.
  780. void
  781. _Jv_ThrowNoSuchFieldError (int /* otable_index */)
  782. {
  783. throw new java::lang::NoSuchFieldError;
  784. }
  785. // This is put in empty vtable slots.
  786. void
  787. _Jv_ThrowAbstractMethodError ()
  788. {
  789. throw new java::lang::AbstractMethodError();
  790. }
  791. // Each superinterface of a class (i.e. each interface that the class
  792. // directly or indirectly implements) has a corresponding "Partial
  793. // Interface Dispatch Table" whose size is (number of methods + 1) words.
  794. // The first word is a pointer to the interface (i.e. the java.lang.Class
  795. // instance for that interface). The remaining words are pointers to the
  796. // actual methods that implement the methods declared in the interface,
  797. // in order of declaration.
  798. //
  799. // Append partial interface dispatch table for "iface" to "itable", at
  800. // position itable_pos.
  801. // Returns the offset at which the next partial ITable should be appended.
  802. jshort
  803. _Jv_Linker::append_partial_itable (jclass klass, jclass iface,
  804. void **itable, jshort pos)
  805. {
  806. using namespace java::lang::reflect;
  807. itable[pos++] = (void *) iface;
  808. _Jv_Method *meth;
  809. for (int j=0; j < iface->method_count; j++)
  810. {
  811. // Skip '<clinit>' here.
  812. if (iface->methods[j].name->first() == '<')
  813. continue;
  814. meth = NULL;
  815. jclass cl;
  816. for (cl = klass; cl; cl = cl->getSuperclass())
  817. {
  818. meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
  819. iface->methods[j].signature);
  820. if (meth)
  821. break;
  822. }
  823. if (meth)
  824. {
  825. if ((meth->accflags & Modifier::STATIC) != 0)
  826. throw new java::lang::IncompatibleClassChangeError
  827. (_Jv_GetMethodString (klass, meth));
  828. if ((meth->accflags & Modifier::PUBLIC) == 0)
  829. throw new java::lang::IllegalAccessError
  830. (_Jv_GetMethodString (klass, meth));
  831. if ((meth->accflags & Modifier::ABSTRACT) != 0)
  832. itable[pos] = (void *) &_Jv_ThrowAbstractMethodError;
  833. else
  834. itable[pos] = meth->ncode;
  835. if (cl->loader != iface->loader)
  836. check_loading_constraints (meth, cl, iface);
  837. }
  838. else
  839. {
  840. // The method doesn't exist in klass. Binary compatibility rules
  841. // permit this, so we delay the error until runtime using a pointer
  842. // to a method which throws an exception.
  843. itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
  844. }
  845. pos++;
  846. }
  847. return pos;
  848. }
  849. static _Jv_Mutex_t iindex_mutex;
  850. static bool iindex_mutex_initialized = false;
  851. // We need to find the correct offset in the Class Interface Dispatch
  852. // Table for a given interface. Once we have that, invoking an interface
  853. // method just requires combining the Method's index in the interface
  854. // (known at compile time) to get the correct method. Doing a type test
  855. // (cast or instanceof) is the same problem: Once we have a possible Partial
  856. // Interface Dispatch Table, we just compare the first element to see if it
  857. // matches the desired interface. So how can we find the correct offset?
  858. // Our solution is to keep a vector of candiate offsets in each interface
  859. // (ioffsets), and in each class we have an index (idt->iindex) used to
  860. // select the correct offset from ioffsets.
  861. //
  862. // Calculate and return iindex for a new class.
  863. // ifaces is a vector of num interfaces that the class implements.
  864. // offsets[j] is the offset in the interface dispatch table for the
  865. // interface corresponding to ifaces[j].
  866. // May extend the interface ioffsets if required.
  867. jshort
  868. _Jv_Linker::find_iindex (jclass *ifaces, jshort *offsets, jshort num)
  869. {
  870. int i;
  871. int j;
  872. // Acquire a global lock to prevent itable corruption in case of multiple
  873. // classes that implement an intersecting set of interfaces being linked
  874. // simultaneously. We can assume that the mutex will be initialized
  875. // single-threaded.
  876. if (! iindex_mutex_initialized)
  877. {
  878. _Jv_MutexInit (&iindex_mutex);
  879. iindex_mutex_initialized = true;
  880. }
  881. _Jv_MutexLock (&iindex_mutex);
  882. for (i=1;; i++) /* each potential position in ioffsets */
  883. {
  884. for (j=0;; j++) /* each iface */
  885. {
  886. if (j >= num)
  887. goto found;
  888. if (i >= ifaces[j]->ioffsets[0])
  889. continue;
  890. int ioffset = ifaces[j]->ioffsets[i];
  891. /* We can potentially share this position with another class. */
  892. if (ioffset >= 0 && ioffset != offsets[j])
  893. break; /* Nope. Try next i. */
  894. }
  895. }
  896. found:
  897. for (j = 0; j < num; j++)
  898. {
  899. int len = ifaces[j]->ioffsets[0];
  900. if (i >= len)
  901. {
  902. // Resize ioffsets.
  903. int newlen = 2 * len;
  904. if (i >= newlen)
  905. newlen = i + 3;
  906. jshort *old_ioffsets = ifaces[j]->ioffsets;
  907. jshort *new_ioffsets = (jshort *) _Jv_AllocBytes (newlen
  908. * sizeof(jshort));
  909. memcpy (&new_ioffsets[1], &old_ioffsets[1],
  910. (len - 1) * sizeof (jshort));
  911. new_ioffsets[0] = newlen;
  912. while (len < newlen)
  913. new_ioffsets[len++] = -1;
  914. ifaces[j]->ioffsets = new_ioffsets;
  915. }
  916. ifaces[j]->ioffsets[i] = offsets[j];
  917. }
  918. _Jv_MutexUnlock (&iindex_mutex);
  919. return i;
  920. }
  921. #if defined USE_LIBFFI && FFI_CLOSURES && defined(INTERPRETER)
  922. // We use a structure of this type to store the closure that
  923. // represents a missing method.
  924. struct method_closure
  925. {
  926. // This field must come first, since the address of this field will
  927. // be the same as the address of the overall structure. This is due
  928. // to disabling interior pointers in the GC.
  929. ffi_closure closure;
  930. _Jv_ClosureList list;
  931. ffi_cif cif;
  932. ffi_type *arg_types[1];
  933. };
  934. void *
  935. _Jv_Linker::create_error_method (_Jv_Utf8Const *class_name, jclass klass)
  936. {
  937. void *code;
  938. method_closure *closure
  939. = (method_closure *)ffi_closure_alloc (sizeof (method_closure), &code);
  940. closure->arg_types[0] = &ffi_type_void;
  941. // Initializes the cif and the closure. If that worked the closure
  942. // is returned and can be used as a function pointer in a class'
  943. // atable.
  944. if ( ffi_prep_cif (&closure->cif,
  945. FFI_DEFAULT_ABI,
  946. 1,
  947. &ffi_type_void,
  948. closure->arg_types) == FFI_OK
  949. && ffi_prep_closure_loc (&closure->closure,
  950. &closure->cif,
  951. _Jv_ThrowNoClassDefFoundErrorTrampoline,
  952. class_name,
  953. code) == FFI_OK)
  954. {
  955. closure->list.registerClosure (klass, closure);
  956. return code;
  957. }
  958. else
  959. {
  960. ffi_closure_free (closure);
  961. java::lang::StringBuffer *buffer = new java::lang::StringBuffer();
  962. buffer->append(JvNewStringLatin1("Error setting up FFI closure"
  963. " for static method of"
  964. " missing class: "));
  965. buffer->append (_Jv_NewStringUtf8Const(class_name));
  966. throw new java::lang::InternalError(buffer->toString());
  967. }
  968. }
  969. #else
  970. void *
  971. _Jv_Linker::create_error_method (_Jv_Utf8Const *, jclass)
  972. {
  973. // Codepath for platforms which do not support (or want) libffi.
  974. // You have to accept that it is impossible to provide the name
  975. // of the missing class then.
  976. return (void *) _Jv_ThrowNoClassDefFoundError;
  977. }
  978. #endif // USE_LIBFFI && FFI_CLOSURES
  979. // Functions for indirect dispatch (symbolic virtual binding) support.
  980. // There are three tables, atable otable and itable. atable is an
  981. // array of addresses, and otable is an array of offsets, and these
  982. // are used for static and virtual members respectively. itable is an
  983. // array of pairs {address, index} where each address is a pointer to
  984. // an interface.
  985. // {a,o,i}table_syms is an array of _Jv_MethodSymbols. Each such
  986. // symbol is a tuple of {classname, member name, signature}.
  987. // Set this to true to enable debugging of indirect dispatch tables/linking.
  988. static bool debug_link = false;
  989. // link_symbol_table() scans these two arrays and fills in the
  990. // corresponding atable and otable with the addresses of static
  991. // members and the offsets of virtual members.
  992. // The offset (in bytes) for each resolved method or field is placed
  993. // at the corresponding position in the virtual method offset table
  994. // (klass->otable).
  995. // This must be called while holding the class lock.
  996. void
  997. _Jv_Linker::link_symbol_table (jclass klass)
  998. {
  999. int index = 0;
  1000. _Jv_MethodSymbol sym;
  1001. if (klass->otable == NULL
  1002. || klass->otable->state != 0)
  1003. goto atable;
  1004. klass->otable->state = 1;
  1005. if (debug_link)
  1006. fprintf (stderr, "Fixing up otable in %s:\n", klass->name->chars());
  1007. for (index = 0;
  1008. (sym = klass->otable_syms[index]).class_name != NULL;
  1009. ++index)
  1010. {
  1011. jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
  1012. _Jv_Method *meth = NULL;
  1013. _Jv_Utf8Const *signature = sym.signature;
  1014. uaddr special;
  1015. maybe_adjust_signature (signature, special);
  1016. if (target_class == NULL)
  1017. throw new java::lang::NoClassDefFoundError
  1018. (_Jv_NewStringUTF (sym.class_name->chars()));
  1019. // We're looking for a field or a method, and we can tell
  1020. // which is needed by looking at the signature.
  1021. if (signature->first() == '(' && signature->len() >= 2)
  1022. {
  1023. // Looks like someone is trying to invoke an interface method
  1024. if (target_class->isInterface())
  1025. {
  1026. using namespace java::lang;
  1027. StringBuffer *sb = new StringBuffer();
  1028. sb->append(JvNewStringLatin1("found interface "));
  1029. sb->append(target_class->getName());
  1030. sb->append(JvNewStringLatin1(" when searching for a class"));
  1031. throw new VerifyError(sb->toString());
  1032. }
  1033. // If the target class does not have a vtable_method_count yet,
  1034. // then we can't tell the offsets for its methods, so we must lay
  1035. // it out now.
  1036. wait_for_state(target_class, JV_STATE_PREPARED);
  1037. try
  1038. {
  1039. meth = (search_method_in_superclasses
  1040. (target_class, klass, sym.name, signature,
  1041. NULL, special == 0));
  1042. }
  1043. catch (::java::lang::IllegalAccessError *e)
  1044. {
  1045. }
  1046. // Every class has a throwNoSuchMethodErrorIndex method that
  1047. // it inherits from java.lang.Object. Find its vtable
  1048. // offset.
  1049. static int throwNoSuchMethodErrorIndex;
  1050. if (throwNoSuchMethodErrorIndex == 0)
  1051. {
  1052. Utf8Const* name
  1053. = _Jv_makeUtf8Const ("throwNoSuchMethodError",
  1054. strlen ("throwNoSuchMethodError"));
  1055. _Jv_Method* meth
  1056. = _Jv_LookupDeclaredMethod (&java::lang::Object::class$,
  1057. name, gcj::void_signature);
  1058. throwNoSuchMethodErrorIndex
  1059. = _Jv_VTable::idx_to_offset (meth->index);
  1060. }
  1061. // If we don't find a nonstatic method, insert the
  1062. // vtable index of Object.throwNoSuchMethodError().
  1063. // This defers the missing method error until an attempt
  1064. // is made to execute it.
  1065. {
  1066. int offset;
  1067. if (meth != NULL)
  1068. offset = _Jv_VTable::idx_to_offset (meth->index);
  1069. else
  1070. offset = throwNoSuchMethodErrorIndex;
  1071. if (offset == -1)
  1072. JvFail ("Bad method index");
  1073. JvAssert (meth->index < target_class->vtable_method_count);
  1074. klass->otable->offsets[index] = offset;
  1075. }
  1076. if (debug_link)
  1077. fprintf (stderr, " offsets[%d] = %d (class %s@%p : %s(%s))\n",
  1078. (int)index,
  1079. (int)klass->otable->offsets[index],
  1080. (const char*)target_class->name->chars(),
  1081. target_class,
  1082. (const char*)sym.name->chars(),
  1083. (const char*)signature->chars());
  1084. continue;
  1085. }
  1086. // Try fields.
  1087. {
  1088. wait_for_state(target_class, JV_STATE_PREPARED);
  1089. jclass found_class;
  1090. _Jv_Field *the_field = NULL;
  1091. try
  1092. {
  1093. the_field = find_field (klass, target_class, &found_class,
  1094. sym.name, signature);
  1095. if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
  1096. throw new java::lang::IncompatibleClassChangeError;
  1097. else
  1098. klass->otable->offsets[index] = the_field->u.boffset;
  1099. }
  1100. catch (java::lang::NoSuchFieldError *err)
  1101. {
  1102. klass->otable->offsets[index] = 0;
  1103. }
  1104. }
  1105. }
  1106. atable:
  1107. if (klass->atable == NULL || klass->atable->state != 0)
  1108. goto itable;
  1109. klass->atable->state = 1;
  1110. for (index = 0;
  1111. (sym = klass->atable_syms[index]).class_name != NULL;
  1112. ++index)
  1113. {
  1114. jclass target_class =
  1115. _Jv_FindClassNoException (sym.class_name, klass->loader);
  1116. _Jv_Method *meth = NULL;
  1117. _Jv_Utf8Const *signature = sym.signature;
  1118. uaddr special;
  1119. maybe_adjust_signature (signature, special);
  1120. // ??? Setting this pointer to null will at least get us a
  1121. // NullPointerException
  1122. klass->atable->addresses[index] = NULL;
  1123. bool use_error_method = false;
  1124. // If the target class is missing we prepare a function call
  1125. // that throws a NoClassDefFoundError and store the address of
  1126. // that newly prepared method in the atable. The user can run
  1127. // code in classes where the missing class is part of the
  1128. // execution environment as long as it is never referenced.
  1129. if (target_class == NULL)
  1130. use_error_method = true;
  1131. // We're looking for a static field or a static method, and we
  1132. // can tell which is needed by looking at the signature.
  1133. else if (signature->first() == '(' && signature->len() >= 2)
  1134. {
  1135. // If the target class does not have a vtable_method_count yet,
  1136. // then we can't tell the offsets for its methods, so we must lay
  1137. // it out now.
  1138. wait_for_state (target_class, JV_STATE_PREPARED);
  1139. // Interface methods cannot have bodies.
  1140. if (target_class->isInterface())
  1141. {
  1142. using namespace java::lang;
  1143. StringBuffer *sb = new StringBuffer();
  1144. sb->append(JvNewStringLatin1("class "));
  1145. sb->append(target_class->getName());
  1146. sb->append(JvNewStringLatin1(" is an interface: "
  1147. "class expected"));
  1148. throw new VerifyError(sb->toString());
  1149. }
  1150. try
  1151. {
  1152. meth = (search_method_in_superclasses
  1153. (target_class, klass, sym.name, signature,
  1154. NULL, special == 0));
  1155. }
  1156. catch (::java::lang::IllegalAccessError *e)
  1157. {
  1158. }
  1159. if (meth != NULL)
  1160. {
  1161. if (meth->ncode) // Maybe abstract?
  1162. {
  1163. klass->atable->addresses[index] = meth->ncode;
  1164. if (debug_link)
  1165. fprintf (stderr, " addresses[%d] = %p (class %s@%p : %s(%s))\n",
  1166. index,
  1167. &klass->atable->addresses[index],
  1168. (const char*)target_class->name->chars(),
  1169. klass,
  1170. (const char*)sym.name->chars(),
  1171. (const char*)signature->chars());
  1172. }
  1173. }
  1174. else
  1175. use_error_method = true;
  1176. if (use_error_method)
  1177. klass->atable->addresses[index]
  1178. = create_error_method(sym.class_name, klass);
  1179. continue;
  1180. }
  1181. // Try fields only if the target class exists.
  1182. if (target_class != NULL)
  1183. {
  1184. wait_for_state(target_class, JV_STATE_PREPARED);
  1185. jclass found_class;
  1186. _Jv_Field *the_field = find_field (klass, target_class, &found_class,
  1187. sym.name, signature);
  1188. if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
  1189. klass->atable->addresses[index] = the_field->u.addr;
  1190. else
  1191. throw new java::lang::IncompatibleClassChangeError;
  1192. }
  1193. }
  1194. itable:
  1195. if (klass->itable == NULL
  1196. || klass->itable->state != 0)
  1197. return;
  1198. klass->itable->state = 1;
  1199. for (index = 0;
  1200. (sym = klass->itable_syms[index]).class_name != NULL;
  1201. ++index)
  1202. {
  1203. jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
  1204. _Jv_Utf8Const *signature = sym.signature;
  1205. uaddr special;
  1206. maybe_adjust_signature (signature, special);
  1207. jclass cls;
  1208. int i;
  1209. wait_for_state(target_class, JV_STATE_LOADED);
  1210. bool found = _Jv_getInterfaceMethod (target_class, cls, i,
  1211. sym.name, signature);
  1212. if (found)
  1213. {
  1214. klass->itable->addresses[index * 2] = cls;
  1215. klass->itable->addresses[index * 2 + 1] = (void *)(unsigned long) i;
  1216. if (debug_link)
  1217. {
  1218. fprintf (stderr, " interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
  1219. index,
  1220. klass->itable->addresses[index * 2],
  1221. (const char*)cls->name->chars(),
  1222. cls,
  1223. (const char*)sym.name->chars(),
  1224. (const char*)signature->chars());
  1225. fprintf (stderr, " [%d] = offset %d\n",
  1226. index + 1,
  1227. (int)(unsigned long)klass->itable->addresses[index * 2 + 1]);
  1228. }
  1229. }
  1230. else
  1231. throw new java::lang::IncompatibleClassChangeError;
  1232. }
  1233. }
  1234. // For each catch_record in the list of caught classes, fill in the
  1235. // address field.
  1236. void
  1237. _Jv_Linker::link_exception_table (jclass self)
  1238. {
  1239. struct _Jv_CatchClass *catch_record = self->catch_classes;
  1240. if (!catch_record || catch_record->classname)
  1241. return;
  1242. catch_record++;
  1243. while (catch_record->classname)
  1244. {
  1245. try
  1246. {
  1247. jclass target_class
  1248. = _Jv_FindClass (catch_record->classname,
  1249. self->getClassLoaderInternal ());
  1250. *catch_record->address = target_class;
  1251. }
  1252. catch (::java::lang::Throwable *t)
  1253. {
  1254. // FIXME: We need to do something better here.
  1255. *catch_record->address = 0;
  1256. }
  1257. catch_record++;
  1258. }
  1259. self->catch_classes->classname = (_Jv_Utf8Const *)-1;
  1260. }
  1261. // Set itable method indexes for members of interface IFACE.
  1262. void
  1263. _Jv_Linker::layout_interface_methods (jclass iface)
  1264. {
  1265. if (! iface->isInterface())
  1266. return;
  1267. // itable indexes start at 1.
  1268. // FIXME: Static initalizers currently get a NULL placeholder entry in the
  1269. // itable so they are also assigned an index here.
  1270. for (int i = 0; i < iface->method_count; i++)
  1271. iface->methods[i].index = i + 1;
  1272. }
  1273. // Prepare virtual method declarations in KLASS, and any superclasses
  1274. // as required, by determining their vtable index, setting
  1275. // method->index, and finally setting the class's vtable_method_count.
  1276. // Must be called with the lock for KLASS held.
  1277. void
  1278. _Jv_Linker::layout_vtable_methods (jclass klass)
  1279. {
  1280. if (klass->vtable != NULL || klass->isInterface()
  1281. || klass->vtable_method_count != -1)
  1282. return;
  1283. jclass superclass = klass->getSuperclass();
  1284. if (superclass != NULL && superclass->vtable_method_count == -1)
  1285. {
  1286. JvSynchronize sync (superclass);
  1287. layout_vtable_methods (superclass);
  1288. }
  1289. int index = (superclass == NULL ? 0 : superclass->vtable_method_count);
  1290. for (int i = 0; i < klass->method_count; ++i)
  1291. {
  1292. _Jv_Method *meth = &klass->methods[i];
  1293. _Jv_Method *super_meth = NULL;
  1294. if (! _Jv_isVirtualMethod (meth))
  1295. continue;
  1296. if (superclass != NULL)
  1297. {
  1298. jclass declarer;
  1299. super_meth = _Jv_LookupDeclaredMethod (superclass, meth->name,
  1300. meth->signature, &declarer);
  1301. // See if this method actually overrides the other method
  1302. // we've found.
  1303. if (super_meth)
  1304. {
  1305. if (! _Jv_isVirtualMethod (super_meth)
  1306. || ! _Jv_CheckAccess (klass, declarer,
  1307. super_meth->accflags))
  1308. super_meth = NULL;
  1309. else if ((super_meth->accflags
  1310. & java::lang::reflect::Modifier::FINAL) != 0)
  1311. {
  1312. using namespace java::lang;
  1313. StringBuffer *sb = new StringBuffer();
  1314. sb->append(JvNewStringLatin1("method "));
  1315. sb->append(_Jv_GetMethodString(klass, meth));
  1316. sb->append(JvNewStringLatin1(" overrides final method "));
  1317. sb->append(_Jv_GetMethodString(declarer, super_meth));
  1318. throw new VerifyError(sb->toString());
  1319. }
  1320. else if (declarer->loader != klass->loader)
  1321. {
  1322. // JVMS 5.4.2.
  1323. check_loading_constraints (meth, klass, declarer);
  1324. }
  1325. }
  1326. }
  1327. if (super_meth)
  1328. meth->index = super_meth->index;
  1329. else
  1330. meth->index = index++;
  1331. }
  1332. klass->vtable_method_count = index;
  1333. }
  1334. // Set entries in VTABLE for virtual methods declared in KLASS.
  1335. void
  1336. _Jv_Linker::set_vtable_entries (jclass klass, _Jv_VTable *vtable)
  1337. {
  1338. for (int i = klass->method_count - 1; i >= 0; i--)
  1339. {
  1340. using namespace java::lang::reflect;
  1341. _Jv_Method *meth = &klass->methods[i];
  1342. if (meth->index == (_Jv_ushort) -1)
  1343. continue;
  1344. if ((meth->accflags & Modifier::ABSTRACT))
  1345. // FIXME: it might be nice to have a libffi trampoline here,
  1346. // so we could pass in the method name and other information.
  1347. vtable->set_method(meth->index,
  1348. (void *) &_Jv_ThrowAbstractMethodError);
  1349. else
  1350. vtable->set_method(meth->index, meth->ncode);
  1351. }
  1352. }
  1353. // Allocate and lay out the virtual method table for KLASS. This will
  1354. // also cause vtables to be generated for any non-abstract
  1355. // superclasses, and virtual method layout to occur for any abstract
  1356. // superclasses. Must be called with monitor lock for KLASS held.
  1357. void
  1358. _Jv_Linker::make_vtable (jclass klass)
  1359. {
  1360. using namespace java::lang::reflect;
  1361. // If the vtable exists, or for interface classes, do nothing. All
  1362. // other classes, including abstract classes, need a vtable.
  1363. if (klass->vtable != NULL || klass->isInterface())
  1364. return;
  1365. // Ensure all the `ncode' entries are set.
  1366. klass->engine->create_ncode(klass);
  1367. // Class must be laid out before we can create a vtable.
  1368. if (klass->vtable_method_count == -1)
  1369. layout_vtable_methods (klass);
  1370. // Allocate the new vtable.
  1371. _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
  1372. klass->vtable = vtable;
  1373. // Copy the vtable of the closest superclass.
  1374. jclass superclass = klass->superclass;
  1375. {
  1376. JvSynchronize sync (superclass);
  1377. make_vtable (superclass);
  1378. }
  1379. for (int i = 0; i < superclass->vtable_method_count; ++i)
  1380. vtable->set_method (i, superclass->vtable->get_method (i));
  1381. // Set the class pointer and GC descriptor.
  1382. vtable->clas = klass;
  1383. vtable->gc_descr = _Jv_BuildGCDescr (klass);
  1384. // For each virtual declared in klass, set new vtable entry or
  1385. // override an old one.
  1386. set_vtable_entries (klass, vtable);
  1387. // Note that we don't check for abstract methods here. We used to,
  1388. // but there is a JVMS clarification that indicates that a check
  1389. // here would be too eager. And, a simple test case confirms this.
  1390. }
  1391. // Lay out the class, allocating space for static fields and computing
  1392. // offsets of instance fields. The class lock must be held by the
  1393. // caller.
  1394. void
  1395. _Jv_Linker::ensure_fields_laid_out (jclass klass)
  1396. {
  1397. if (klass->size_in_bytes != -1)
  1398. return;
  1399. // Compute the alignment for this type by searching through the
  1400. // superclasses and finding the maximum required alignment. We
  1401. // could consider caching this in the Class.
  1402. int max_align = __alignof__ (java::lang::Object);
  1403. jclass super = klass->getSuperclass();
  1404. while (super != NULL)
  1405. {
  1406. // Ensure that our super has its super installed before
  1407. // recursing.
  1408. wait_for_state(super, JV_STATE_LOADING);
  1409. ensure_fields_laid_out(super);
  1410. int num = JvNumInstanceFields (super);
  1411. _Jv_Field *field = JvGetFirstInstanceField (super);
  1412. while (num > 0)
  1413. {
  1414. int field_align = get_alignment_from_class (field->type);
  1415. if (field_align > max_align)
  1416. max_align = field_align;
  1417. ++field;
  1418. --num;
  1419. }
  1420. super = super->getSuperclass();
  1421. }
  1422. int instance_size;
  1423. // This is the size of the 'static' non-reference fields.
  1424. int non_reference_size = 0;
  1425. // This is the size of the 'static' reference fields. We count
  1426. // these separately to make it simpler for the GC to scan them.
  1427. int reference_size = 0;
  1428. // Although java.lang.Object is never interpreted, an interface can
  1429. // have a null superclass. Note that we have to lay out an
  1430. // interface because it might have static fields.
  1431. if (klass->superclass)
  1432. instance_size = klass->superclass->size();
  1433. else
  1434. instance_size = java::lang::Object::class$.size();
  1435. klass->engine->allocate_field_initializers (klass);
  1436. for (int i = 0; i < klass->field_count; i++)
  1437. {
  1438. int field_size;
  1439. int field_align;
  1440. _Jv_Field *field = &klass->fields[i];
  1441. if (! field->isRef ())
  1442. {
  1443. // It is safe to resolve the field here, since it's a
  1444. // primitive class, which does not cause loading to happen.
  1445. resolve_field (field, klass->loader);
  1446. field_size = field->type->size ();
  1447. field_align = get_alignment_from_class (field->type);
  1448. }
  1449. else
  1450. {
  1451. field_size = sizeof (jobject);
  1452. field_align = __alignof__ (jobject);
  1453. }
  1454. field->bsize = field_size;
  1455. if ((field->flags & java::lang::reflect::Modifier::STATIC))
  1456. {
  1457. if (field->u.addr == NULL)
  1458. {
  1459. // This computes an offset into a region we'll allocate
  1460. // shortly, and then adds this offset to the start
  1461. // address.
  1462. if (field->isRef())
  1463. {
  1464. reference_size = ROUND (reference_size, field_align);
  1465. field->u.boffset = reference_size;
  1466. reference_size += field_size;
  1467. }
  1468. else
  1469. {
  1470. non_reference_size = ROUND (non_reference_size, field_align);
  1471. field->u.boffset = non_reference_size;
  1472. non_reference_size += field_size;
  1473. }
  1474. }
  1475. }
  1476. else
  1477. {
  1478. instance_size = ROUND (instance_size, field_align);
  1479. field->u.boffset = instance_size;
  1480. instance_size += field_size;
  1481. if (field_align > max_align)
  1482. max_align = field_align;
  1483. }
  1484. }
  1485. if (reference_size != 0 || non_reference_size != 0)
  1486. klass->engine->allocate_static_fields (klass, reference_size,
  1487. non_reference_size);
  1488. // Set the instance size for the class. Note that first we round it
  1489. // to the alignment required for this object; this keeps us in sync
  1490. // with our current ABI.
  1491. instance_size = ROUND (instance_size, max_align);
  1492. klass->size_in_bytes = instance_size;
  1493. }
  1494. // This takes the class to state JV_STATE_LINKED. The class lock must
  1495. // be held when calling this.
  1496. void
  1497. _Jv_Linker::ensure_class_linked (jclass klass)
  1498. {
  1499. if (klass->state >= JV_STATE_LINKED)
  1500. return;
  1501. int state = klass->state;
  1502. try
  1503. {
  1504. // Short-circuit, so that mutually dependent classes are ok.
  1505. klass->state = JV_STATE_LINKED;
  1506. _Jv_Constants *pool = &klass->constants;
  1507. // Compiled classes require that their class constants be
  1508. // resolved here. However, interpreted classes need their
  1509. // constants to be resolved lazily. If we resolve an
  1510. // interpreted class' constants eagerly, we can end up with
  1511. // spurious IllegalAccessErrors when the constant pool contains
  1512. // a reference to a class we can't access. This can validly
  1513. // occur in an obscure case involving the InnerClasses
  1514. // attribute.
  1515. if (! _Jv_IsInterpretedClass (klass))
  1516. {
  1517. // Resolve class constants first, since other constant pool
  1518. // entries may rely on these.
  1519. for (int index = 1; index < pool->size; ++index)
  1520. {
  1521. if (pool->tags[index] == JV_CONSTANT_Class)
  1522. // Lazily resolve the entries.
  1523. resolve_pool_entry (klass, index, true);
  1524. }
  1525. }
  1526. // Resolve the remaining constant pool entries.
  1527. for (int index = 1; index < pool->size; ++index)
  1528. {
  1529. jbyte tags;
  1530. _Jv_word data;
  1531. tags = read_cpool_entry (&data, pool, index);
  1532. if (tags == JV_CONSTANT_String)
  1533. {
  1534. data.o = _Jv_NewStringUtf8Const (data.utf8);
  1535. tags |= JV_CONSTANT_ResolvedFlag;
  1536. write_cpool_entry (data, tags, pool, index);
  1537. }
  1538. }
  1539. if (klass->engine->need_resolve_string_fields())
  1540. {
  1541. jfieldID f = JvGetFirstStaticField (klass);
  1542. for (int n = JvNumStaticFields (klass); n > 0; --n)
  1543. {
  1544. int mod = f->getModifiers ();
  1545. // If we have a static String field with a non-null initial
  1546. // value, we know it points to a Utf8Const.
  1547. // Finds out whether we have to initialize a String without the
  1548. // need to resolve the field.
  1549. if ((f->isResolved()
  1550. ? (f->type == &java::lang::String::class$)
  1551. : _Jv_equalUtf8Classnames((_Jv_Utf8Const *) f->type,
  1552. java::lang::String::class$.name))
  1553. && (mod & java::lang::reflect::Modifier::STATIC) != 0)
  1554. {
  1555. jstring *strp = (jstring *) f->u.addr;
  1556. if (*strp)
  1557. *strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
  1558. }
  1559. f = f->getNextField ();
  1560. }
  1561. }
  1562. klass->notifyAll ();
  1563. _Jv_PushClass (klass);
  1564. }
  1565. catch (java::lang::Throwable *t)
  1566. {
  1567. klass->state = state;
  1568. throw t;
  1569. }
  1570. }
  1571. // This ensures that symbolic superclass and superinterface references
  1572. // are resolved for the indicated class. This must be called with the
  1573. // class lock held.
  1574. void
  1575. _Jv_Linker::ensure_supers_installed (jclass klass)
  1576. {
  1577. resolve_class_ref (klass, &klass->superclass);
  1578. // An interface won't have a superclass.
  1579. if (klass->superclass)
  1580. wait_for_state (klass->superclass, JV_STATE_LOADING);
  1581. for (int i = 0; i < klass->interface_count; ++i)
  1582. {
  1583. resolve_class_ref (klass, &klass->interfaces[i]);
  1584. wait_for_state (klass->interfaces[i], JV_STATE_LOADING);
  1585. }
  1586. }
  1587. // This adds missing `Miranda methods' to a class.
  1588. void
  1589. _Jv_Linker::add_miranda_methods (jclass base, jclass iface_class)
  1590. {
  1591. // Note that at this point, all our supers, and the supers of all
  1592. // our superclasses and superinterfaces, will have been installed.
  1593. for (int i = 0; i < iface_class->interface_count; ++i)
  1594. {
  1595. jclass interface = iface_class->interfaces[i];
  1596. for (int j = 0; j < interface->method_count; ++j)
  1597. {
  1598. _Jv_Method *meth = &interface->methods[j];
  1599. // Don't bother with <clinit>.
  1600. if (meth->name->first() == '<')
  1601. continue;
  1602. _Jv_Method *new_meth = _Jv_LookupDeclaredMethod (base, meth->name,
  1603. meth->signature);
  1604. if (! new_meth)
  1605. {
  1606. // We assume that such methods are very unlikely, so we
  1607. // just reallocate the method array each time one is
  1608. // found. This greatly simplifies the searching --
  1609. // otherwise we have to make sure that each such method
  1610. // found is really unique among all superinterfaces.
  1611. int new_count = base->method_count + 1;
  1612. _Jv_Method *new_m
  1613. = (_Jv_Method *) _Jv_AllocRawObj (sizeof (_Jv_Method)
  1614. * new_count);
  1615. memcpy (new_m, base->methods,
  1616. sizeof (_Jv_Method) * base->method_count);
  1617. // Add new method.
  1618. new_m[base->method_count] = *meth;
  1619. new_m[base->method_count].index = (_Jv_ushort) -1;
  1620. new_m[base->method_count].accflags
  1621. |= java::lang::reflect::Modifier::INVISIBLE;
  1622. base->methods = new_m;
  1623. base->method_count = new_count;
  1624. }
  1625. }
  1626. wait_for_state (interface, JV_STATE_LOADED);
  1627. add_miranda_methods (base, interface);
  1628. }
  1629. }
  1630. // This ensures that the class' method table is "complete". This must
  1631. // be called with the class lock held.
  1632. void
  1633. _Jv_Linker::ensure_method_table_complete (jclass klass)
  1634. {
  1635. if (klass->vtable != NULL)
  1636. return;
  1637. // We need our superclass to have its own Miranda methods installed.
  1638. if (! klass->isInterface())
  1639. wait_for_state (klass->getSuperclass (), JV_STATE_LOADED);
  1640. // A class might have so-called "Miranda methods". This is a method
  1641. // that is declared in an interface and not re-declared in an
  1642. // abstract class. Some compilers don't emit declarations for such
  1643. // methods in the class; this will give us problems since we expect
  1644. // a declaration for any method requiring a vtable entry. We handle
  1645. // this here by searching for such methods and constructing new
  1646. // internal declarations for them. Note that we do this
  1647. // unconditionally, and not just for abstract classes, to correctly
  1648. // account for cases where a class is modified to be concrete and
  1649. // still incorrectly inherits an abstract method.
  1650. int pre_count = klass->method_count;
  1651. add_miranda_methods (klass, klass);
  1652. // Let the execution engine know that we've added methods.
  1653. if (klass->method_count != pre_count)
  1654. klass->engine->post_miranda_hook(klass);
  1655. }
  1656. // Verify a class. Must be called with class lock held.
  1657. void
  1658. _Jv_Linker::verify_class (jclass klass)
  1659. {
  1660. klass->engine->verify(klass);
  1661. }
  1662. // Check the assertions contained in the type assertion table for KLASS.
  1663. // This is the equivilent of bytecode verification for native, BC-ABI code.
  1664. void
  1665. _Jv_Linker::verify_type_assertions (jclass klass)
  1666. {
  1667. if (debug_link)
  1668. fprintf (stderr, "Evaluating type assertions for %s:\n",
  1669. klass->name->chars());
  1670. if (klass->assertion_table == NULL)
  1671. return;
  1672. for (int i = 0;; i++)
  1673. {
  1674. int assertion_code = klass->assertion_table[i].assertion_code;
  1675. _Jv_Utf8Const *op1 = klass->assertion_table[i].op1;
  1676. _Jv_Utf8Const *op2 = klass->assertion_table[i].op2;
  1677. if (assertion_code == JV_ASSERT_END_OF_TABLE)
  1678. return;
  1679. else if (assertion_code == JV_ASSERT_TYPES_COMPATIBLE)
  1680. {
  1681. if (debug_link)
  1682. {
  1683. fprintf (stderr, " code=%i, operand A=%s B=%s\n",
  1684. assertion_code, op1->chars(), op2->chars());
  1685. }
  1686. // The operands are class signatures. op1 is the source,
  1687. // op2 is the target.
  1688. jclass cl1 = _Jv_FindClassFromSignature (op1->chars(),
  1689. klass->getClassLoaderInternal());
  1690. jclass cl2 = _Jv_FindClassFromSignature (op2->chars(),
  1691. klass->getClassLoaderInternal());
  1692. // If the class doesn't exist, ignore the assertion. An exception
  1693. // will be thrown later if an attempt is made to actually
  1694. // instantiate the class.
  1695. if (cl1 == NULL || cl2 == NULL)
  1696. continue;
  1697. if (! _Jv_IsAssignableFromSlow (cl1, cl2))
  1698. {
  1699. jstring s = JvNewStringUTF ("Incompatible types: In class ");
  1700. s = s->concat (klass->getName());
  1701. s = s->concat (JvNewStringUTF (": "));
  1702. s = s->concat (cl1->getName());
  1703. s = s->concat (JvNewStringUTF (" is not assignable to "));
  1704. s = s->concat (cl2->getName());
  1705. throw new java::lang::VerifyError (s);
  1706. }
  1707. }
  1708. else if (assertion_code == JV_ASSERT_IS_INSTANTIABLE)
  1709. {
  1710. // TODO: Implement this.
  1711. }
  1712. // Unknown assertion codes are ignored, for forwards-compatibility.
  1713. }
  1714. }
  1715. void
  1716. _Jv_Linker::print_class_loaded (jclass klass)
  1717. {
  1718. char *codesource = NULL;
  1719. if (klass->protectionDomain != NULL)
  1720. {
  1721. java::security::CodeSource *cs
  1722. = klass->protectionDomain->getCodeSource();
  1723. if (cs != NULL)
  1724. {
  1725. jstring css = cs->toString();
  1726. int len = JvGetStringUTFLength(css);
  1727. codesource = (char *) _Jv_AllocBytes(len + 1);
  1728. JvGetStringUTFRegion(css, 0, css->length(), codesource);
  1729. codesource[len] = '\0';
  1730. }
  1731. }
  1732. if (codesource == NULL)
  1733. codesource = (char *) "<no code source>";
  1734. const char *abi;
  1735. if (_Jv_IsInterpretedClass (klass))
  1736. abi = "bytecode";
  1737. else if (_Jv_IsBinaryCompatibilityABI (klass))
  1738. abi = "BC-compiled";
  1739. else
  1740. abi = "pre-compiled";
  1741. fprintf (stderr, "[Loaded (%s) %s from %s]\n", abi, klass->name->chars(),
  1742. codesource);
  1743. }
  1744. // FIXME: mention invariants and stuff.
  1745. void
  1746. _Jv_Linker::wait_for_state (jclass klass, int state)
  1747. {
  1748. if (klass->state >= state)
  1749. return;
  1750. java::lang::Thread *self = java::lang::Thread::currentThread();
  1751. {
  1752. JvSynchronize sync (klass);
  1753. // This is similar to the strategy for class initialization. If we
  1754. // already hold the lock, just leave.
  1755. while (klass->state <= state
  1756. && klass->thread
  1757. && klass->thread != self)
  1758. klass->wait ();
  1759. java::lang::Thread *save = klass->thread;
  1760. klass->thread = self;
  1761. // Allocate memory for static fields and constants.
  1762. if (GC_base (klass) && klass->fields && ! GC_base (klass->fields))
  1763. {
  1764. jsize count = klass->field_count;
  1765. if (count)
  1766. {
  1767. _Jv_Field* fields
  1768. = (_Jv_Field*) _Jv_AllocRawObj (count * sizeof (_Jv_Field));
  1769. memcpy ((void*)fields,
  1770. (void*)klass->fields,
  1771. count * sizeof (_Jv_Field));
  1772. klass->fields = fields;
  1773. }
  1774. }
  1775. // Print some debugging info if requested. Interpreted classes are
  1776. // handled in defineclass, so we only need to handle the two
  1777. // pre-compiled cases here.
  1778. if ((klass->state == JV_STATE_COMPILED
  1779. || klass->state == JV_STATE_PRELOADING)
  1780. && ! _Jv_IsInterpretedClass (klass))
  1781. {
  1782. if (gcj::verbose_class_flag)
  1783. print_class_loaded (klass);
  1784. ++gcj::loadedClasses;
  1785. }
  1786. try
  1787. {
  1788. if (state >= JV_STATE_LOADING && klass->state < JV_STATE_LOADING)
  1789. {
  1790. ensure_supers_installed (klass);
  1791. klass->set_state(JV_STATE_LOADING);
  1792. }
  1793. if (state >= JV_STATE_LOADED && klass->state < JV_STATE_LOADED)
  1794. {
  1795. ensure_method_table_complete (klass);
  1796. klass->set_state(JV_STATE_LOADED);
  1797. }
  1798. if (state >= JV_STATE_PREPARED && klass->state < JV_STATE_PREPARED)
  1799. {
  1800. ensure_fields_laid_out (klass);
  1801. make_vtable (klass);
  1802. layout_interface_methods (klass);
  1803. prepare_constant_time_tables (klass);
  1804. klass->set_state(JV_STATE_PREPARED);
  1805. }
  1806. if (state >= JV_STATE_LINKED && klass->state < JV_STATE_LINKED)
  1807. {
  1808. if (gcj::verifyClasses)
  1809. verify_class (klass);
  1810. ensure_class_linked (klass);
  1811. link_exception_table (klass);
  1812. link_symbol_table (klass);
  1813. klass->set_state(JV_STATE_LINKED);
  1814. }
  1815. }
  1816. catch (java::lang::Throwable *exc)
  1817. {
  1818. klass->thread = save;
  1819. klass->set_state(JV_STATE_ERROR);
  1820. throw exc;
  1821. }
  1822. klass->thread = save;
  1823. if (klass->state == JV_STATE_ERROR)
  1824. throw new java::lang::LinkageError;
  1825. }
  1826. #ifdef INTERPRETER
  1827. if (__builtin_expect (klass->state == JV_STATE_LINKED, false)
  1828. && state >= JV_STATE_LINKED
  1829. && JVMTI_REQUESTED_EVENT (ClassPrepare))
  1830. {
  1831. JNIEnv *jni_env = _Jv_GetCurrentJNIEnv ();
  1832. _Jv_JVMTI_PostEvent (JVMTI_EVENT_CLASS_PREPARE, self, jni_env,
  1833. klass);
  1834. }
  1835. #endif
  1836. }