-
Notifications
You must be signed in to change notification settings - Fork 143
/
ASURLClassLoader.java
1364 lines (1208 loc) · 49.6 KB
/
ASURLClassLoader.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2022, 2024 Contributors to the Eclipse Foundation
* Copyright (c) 2006, 2021 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.enterprise.loader;
import com.sun.appserv.server.util.PreprocessorUtil;
import com.sun.enterprise.security.integration.DDPermissionsLoader;
import com.sun.enterprise.security.integration.PermsHolder;
import com.sun.enterprise.util.CULoggerInfo;
import com.sun.enterprise.util.i18n.StringManager;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.PermissionCollection;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.ProtectionDomain;
import java.security.SecureClassLoader;
import java.security.cert.Certificate;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import org.glassfish.api.deployment.InstrumentableClassLoader;
import org.glassfish.common.util.GlassfishUrlClassLoader;
import org.glassfish.hk2.api.PreDestroy;
import static java.util.logging.Level.INFO;
/**
* Class loader used by the ejbs of an application or stand-alone module.
*
* <p>This class loader also keeps cache of not found classes and resources.
*
* @author Nazrul Islam
* @author Kenneth Saks
* @author Sivakumar Thyagarajan
* @since JDK 1.4
*/
public class ASURLClassLoader extends GlassfishUrlClassLoader
implements JasperAdapter, InstrumentableClassLoader, PreDestroy, DDPermissionsLoader {
/** logger for this class */
private static final Logger _logger = CULoggerInfo.getLogger();
/**
* list of url entries of this class loader. Using LinkedHashSet instead of original ArrayList
* for faster search.
*/
private final Set<URLEntry> urlSet = Collections.synchronizedSet(new LinkedHashSet<>());
/** cache of not found resources */
private final Map<String, String> notFoundResources = new ConcurrentHashMap<>();
/** cache of not found classes */
private final Map<String, String> notFoundClasses = new ConcurrentHashMap<>();
/**
* State flag to track whether this instance has been shut off.
* Note: 'volatile' *does not by itself eliminate a race condition* similar
* to null-check idiom bug.
*/
private volatile boolean doneCalled;
/**
* snapshot of classloader state at the time done was called.
* <p>
* Must be 'volatile'; not all access is within 'synchronized' eg it is used in toString().
*/
private volatile String doneSnapshot;
private final ArrayList<ClassFileTransformer> transformers = new ArrayList<>(1);
private final static StringManager sm = StringManager.getManager(ASURLClassLoader.class);
//holder for declared and ee permissions
private final PermsHolder permissionsHolder;
/**
* Constructor.
*/
public ASURLClassLoader() {
super(new URL[0]);
permissionsHolder = new PermsHolder();
_logger.log(Level.FINE, "ClassLoader: {0} is getting created.", this);
}
/**
* Constructor.
*
* @param parent parent class loader
*/
public ASURLClassLoader(ClassLoader parent) {
super(new URL[0], parent);
permissionsHolder = new PermsHolder();
}
public boolean isClosed() {
// method need not by 'synchronized' because 'doneCalled' is 'volatile'.
return doneCalled;
}
@Override
public void preDestroy() {
try {
close();
} catch(IOException ioe) {
_logger.log(INFO, CULoggerInfo.getString(CULoggerInfo.exceptionIO), ioe);
}
}
/**
* This method should be called to free up the resources.
* It helps garbage collection.
* Must be synchronized for:
* <ol>
* <li>visibility of variables
* <li>race condition while checking 'doneCalled'
* <li>only one caller should close the zip files,
* <li>done should occur only once and set the flag when done.
* <li>should not return 'true' when a previous thread might still
* be in the process of executing the method.
* </ol>
*/
@Override
public void close() throws IOException {
// This works because 'doneCalled' is 'volatile'
if (doneCalled) {
return;
}
// the above optimized check for 'doneCalled=true' is a race condition.
// The lock must now be acquired, and 'doneCalled' rechecked.
synchronized (this) {
if (doneCalled) {
return;
}
// Capture the fact that the classloader is now effectively disabled.
// First create a snapshot of our state. This should be called
// before setting doneCalled = true.
doneSnapshot = "ASURLClassLoader.done() called ON " + this
+ "\n AT " + Instant.now() +
" \n BY :" + Arrays.toString(Thread.currentThread().getStackTrace());
// Presumably OK to set this flag now while the rest of the cleanup proceeds,
// because we've taken the snapshot.
doneCalled = true;
// closes the jar handles and sets the url entries to null
for (URLEntry u : this.urlSet) {
if (u.zip != null) {
try {
u.zip.reallyClose();
} catch (IOException ioe) {
_logger.log(INFO, CULoggerInfo.getString(CULoggerInfo.exceptionClosingURLEntry, u.source), ioe);
}
}
if (u.table != null) {
u.table.clear();
u.table = null;
}
u = null;
}
// clears out the tables
// Clear all values. Because fields are 'final' (for thread safety), cannot null them
this.urlSet.clear();
this.notFoundResources.clear();
this.notFoundClasses.clear();
}
super.close();
}
/**
* Adds a URL to the search list, based on the specified File.
* <p>
* This variant of the method makes sure that the URL is valid, in particular
* encoding special characters (such as blanks) in the file path.
*
* @param file the File to use in creating the URL
* @throws IOException in case of errors converting the file to a URL
*/
public void appendURL(File file) throws IOException {
try {
appendURL(file.toURI().toURL());
} catch (MalformedURLException mue) {
_logger.log(Level.SEVERE, CULoggerInfo.getString(CULoggerInfo.badUrlEntry, file.toURI()), mue);
throw new IOException(mue);
}
}
/**
* Appends the specified URL to the list of URLs to search for
* classes and resources.
*
* @param url the URL to be added to the search path of URLs
*/
@Override
public void addURL(URL url) {
appendURL(url);
}
/**
* Add an url to the list of urls we search for a class's bytecodes.
*
* @param url url to be added
*/
public synchronized void appendURL(URL url) {
try {
if (url == null) {
_logger.log(INFO, CULoggerInfo.missingURLEntry);
return;
}
URLEntry entry = new URLEntry(url);
if (!urlSet.contains(entry)) {
// adds the url entry to the list
this.urlSet.add(entry);
if (entry.isJar) {
// checks the manifest if a jar
checkManifest(entry.zip, entry.file);
}
} else {
_logger.log(Level.FINE, "[ASURLClassLoader] Ignoring duplicate URL: {0}", url);
// Clean up the unused entry or it could hold open a jar file.
if (entry.zip != null) {
try {
entry.zip.reallyClose();
} catch (IOException ioe) {
_logger.log(INFO, CULoggerInfo.getString(CULoggerInfo.exceptionClosingDupUrlEntry, url), ioe);
}
}
}
// clears the "not found" cache since we are adding a new url
clearNotFoundCaches();
} catch (IOException ioe) {
_logger.log(Level.SEVERE, CULoggerInfo.getString(CULoggerInfo.badUrlEntry, url), ioe);
}
}
/**
* Returns the urls of this class loader.
*
* <p>Method is {@code synchronized} to avoid the thread-unsafe null-check idiom, also
* protects the caller from simultaneous changes while iterating,
* by returning a URL[] (copy) rather than the original. Also protects against
* changes to 'urlSet' while iterating over it.
*
* @return the urls of this class loader or an empty array
*/
@Override
public synchronized URL[] getURLs() {
return urlSet.stream().map(urlEntry -> urlEntry.source).toArray(URL[]::new);
}
/**
* Returns all the "file" protocol resources of this ASURLClassLoader,
* concatenated to a classpath string.
*
* <p>Notice that this method is called by the setClassPath() method of
* org.apache.catalina.loader.WebappLoader, since this ASURLClassLoader does
* not extend off of URLClassLoader.
*
* @return Classpath string containing all the "file" protocol resources
* of this ASURLClassLoader
*/
public String getClasspath() {
StringBuilder strBuf = null;
URL[] urls = getURLs();
if (urls != null) {
for (int i = 0; i < urls.length; i++) {
if (urls[i].getProtocol().equals("file")) {
if (strBuf == null) {
strBuf = new StringBuilder();
}
if (i > 0) {
strBuf.append(File.pathSeparator);
}
strBuf.append(urls[i].getFile());
}
}
}
return strBuf == null ? null : strBuf.toString();
}
/**
* Refreshes the memory of the class loader. This involves clearing the
* not-found caches and recreating the hash tables for the URLEntries that
* record the files accessible for each.
* <p>
* Code that creates an ASURLClassLoader and then adds files to a directory
* that is in the loader's classpath should invoke this method after the new
* file(s) have been added in order to update the class loader's data
* structures which optimize class and resource searches.
*
* @throws IOException in case of errors refreshing the cache
*/
public synchronized void refresh() throws IOException {
clearNotFoundCaches();
}
@Override
public void addTransformer(ClassFileTransformer transformer) {
transformers.add(transformer);
}
/**
* Create a new instance of a sibling classloader.
*
* @return a new instance of a class loader that has the same visibility
* as this class loader
*/
@Override
public ClassLoader copy() {
final ASURLClassLoader copyFrom = this;
PrivilegedAction<DelegatingClassLoader> privilegedAction = () -> new DelegatingClassLoader(copyFrom);
return AccessController.doPrivileged(privilegedAction);
}
/**
* Erases the memory of classes and resources that have been searched for
* but not found.
*/
private void clearNotFoundCaches() {
this.notFoundResources.clear();
this.notFoundClasses.clear();
}
/**
* Internal implementation of find resource.
*
* @param res url resource entry
* @param name name of the resource
*/
private URL findResource0(final URLEntry res, final String name) {
PrivilegedAction<URL> action = () -> {
if (res.isJar) {
try {
JarEntry jarEntry = res.zip.getJarEntry(name);
if (jarEntry == null) {
return null;
}
// Use a custom URL with a special stream handler to
// prevent the JDK's JarURLConnection caching from
// locking the jar file until JVM exit.
InternalURLStreamHandler handler = new InternalURLStreamHandler(res, name);
// Create a new sub URL from the resource URL (i.e. res.source). To avoid
// double encoding
// (see https://glassfish.dev.java.net/issues/show_bug.cgi?id=13045)
// use URL constructor instead of first creating a URI and then calling
// toURL().
// If the resource URL is not properly encoded, that's not our problem.
// Whoever has supplied the resource URL is at fault.
URL ret = new URL("jar", null /* host */, -1 /* port */, res.source + "!/" + name, handler);
handler.tieUrl(ret);
return ret;
} catch (Throwable thr) {
_logger.log(INFO, CULoggerInfo.exceptionInASURLClassLoader, thr);
}
} else { // directory
try {
File resourceFile = new File(res.file, name);
if (resourceFile.exists()) {
// If we make it this far,
// the resource is in the directory.
return resourceFile.toURI().toURL();
}
} catch (IOException e) {
_logger.log(INFO, CULoggerInfo.exceptionInASURLClassLoader, e);
}
}
return null;
};
return AccessController.doPrivileged(action);
}
@Override
public URL findResource(String name) {
// quick that relies on 'doneCalled' being 'volatile'
if (doneCalled) {
_logger.log(Level.WARNING, CULoggerInfo.getString(CULoggerInfo.findResourceAfterDone, name, this),
new Throwable());
return null;
}
// This code is dubious, because it iterates over items that could
// be changing via another thread. It appears that since 'urlSet' cannot shrink
// that the iteration at least won't go out of bounds. And it's probably OK
// if more than one thread adds the same resource to 'notFoundResources'.
//
// HOWEVER, there is still a race condition from the check for 'doneCalled' above.
// That's OK for 'notFoundResources', but it could lead to an ArrayIndexOutOfBounds
// exception for 'urlSet', should the set be cleared while looping.
// resource is in the not found list
String nf = notFoundResources.get(name);
if (nf != null && nf.equals(name) ) {
return null;
}
synchronized(this) {
for (final URLEntry u : this.urlSet) {
if (!u.hasItem(name)) {
continue;
}
final URL url = findResource0(u, name);
if (url != null) {
return url;
}
}
}
// add resource to the not found list
notFoundResources.put(name, name);
return null;
}
/**
* Returns an enumeration of java.net.URL objects
* representing all the resources with the given name.
* This method is synchronized to avoid
* <ol>
* <li>race condition checking 'doneCalled',
* <li>changes to contents or length of 'resourcesList' and/or 'notFoundResources' while
* iterating over them,
* <li>thread visibility to all of the above.
* </ol>
*/
@Override
public synchronized Enumeration<URL> findResources(String name) throws IOException {
if (doneCalled) {
_logger.log(Level.WARNING, CULoggerInfo.doneAlreadyCalled, new Object[] {name, doneSnapshot});
return Collections.emptyEnumeration();
}
List<URL> resourcesList = new ArrayList<>();
// resource is in the not found list
final String nf = notFoundResources.get(name);
if (nf != null && nf.equals(name) ) {
return Collections.emptyEnumeration();
}
for (URLEntry urlEntry : this.urlSet) {
final URL url = findResource0(urlEntry, name);
if (url != null) {
resourcesList.add(url);
}
}
if (resourcesList.isEmpty()) {
// add resource to the not found list
notFoundResources.put(name, name);
}
return Collections.enumeration(resourcesList);
}
/**
* Checks the manifest of the given jar file.
*
* @param jar the jar file that may contain manifest class path
* @param file file pointer to the jar
* @throws IOException if an i/o error
*/
private void checkManifest(JarFile jar, File file) throws IOException {
if (jar == null || file == null) {
return;
}
Manifest man = jar.getManifest();
if (man == null) {
return;
}
synchronized (this) {
String cp = man.getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
if (cp == null) {
return;
}
StringTokenizer st = new StringTokenizer(cp, " ");
while (st.hasMoreTokens()) {
final String entry = st.nextToken();
final File newFile = new File(file.getParentFile(), entry);
// add to class path of this class loader
try {
appendURL(newFile);
} catch (MalformedURLException ex) {
_logger.log(Level.SEVERE, CULoggerInfo.exceptionInASURLClassLoader, ex);
}
}
}
}
/**
* Internal implementation of load class.
*
* @param res url resource entry
* @param entryName name of the class
*/
private byte[] loadClassData0(final URLEntry res, final String entryName) {
PrivilegedAction<byte[]> action = () -> {
InputStream classStream = null;
try {
if (res.isJar) { // It is a jarfile.
JarFile zip = res.zip;
JarEntry entry = zip.getJarEntry(entryName);
if (entry != null) {
classStream = zip.getInputStream(entry);
byte[] classData1 = getClassData(classStream);
res.setProtectionDomain(ASURLClassLoader.this, entry.getCertificates());
return classData1;
}
} else { // Its a directory....
File classFile = new File (res.file, entryName.replace('/', File.separatorChar));
if (classFile.exists()) {
try {
classStream = new FileInputStream(classFile);
byte[] classData2 = getClassData(classStream);
res.setProtectionDomain(ASURLClassLoader.this, null);
return classData2;
} finally {
/*
* Close the stream only if this is a directory. The stream for
* a jar/zip file was opened elsewhere and should remain open after this
* method completes.
*/
if (classStream != null) {
try {
classStream.close();
} catch (IOException closeIOE) {
_logger.log(INFO, "loader.excep_in_asurlclassloader", closeIOE);
}
}
}
}
}
} catch (IOException ioe) {
_logger.log(INFO, CULoggerInfo.exceptionInASURLClassLoader, ioe);
}
return null;
};
return AccessController.doPrivileged(action);
}
@Override
public void addEEPermissions(PermissionCollection eePc) throws SecurityException {
// sm on
if (System.getSecurityManager() != null) {
System.getSecurityManager().checkSecurityAccess(DDPermissionsLoader.SET_EE_POLICY);
permissionsHolder.setEEPermissions(eePc);
}
}
@Override
public void addDeclaredPermissions(PermissionCollection declaredPc) throws SecurityException {
if (System.getSecurityManager() != null) {
System.getSecurityManager().checkSecurityAccess(DDPermissionsLoader.SET_EE_POLICY);
permissionsHolder.setDeclaredPermissions(declaredPc);
}
}
@Override
protected PermissionCollection getPermissions(CodeSource codeSource) {
PermissionCollection cachedPc = permissionsHolder.getCachedPerms(codeSource);
if (cachedPc != null) {
return cachedPc;
}
return permissionsHolder.getPermissions(codeSource, super.getPermissions(codeSource));
}
/**
* THREAD SAFETY: what happens when more than one thread requests the same class
* and thus works on the same classData? Or defines the same package? Maybe
* the same work just gets done twice, and that's all.
* <p>
* CAUTION: this method might be overridden, and subclasses must be cautious (also)
* about thread safety.
*/
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
ClassData classData = findClassData(name);
// Instruments the classes if the profiler's enabled
if (PreprocessorUtil.isPreprocessorEnabled()) {
// search through the JARs for a file of the form java/lang/Object.class
final String entryName = name.replace('.', '/') + ".class";
classData.setClassBytes(PreprocessorUtil.processClass(entryName, classData.getClassBytes()));
}
// Define package information if necessary
int lastPackageSep = name.lastIndexOf('.');
if (lastPackageSep != -1) {
String packageName = name.substring(0, lastPackageSep);
if (getDefinedPackage(packageName) == null) {
try {
// There's a small chance that one of our parents
// could define the same package after getPackage
// returns null but before we call definePackage,
// since the parent classloader instances
// are not locked. So, just catch the exception
// that is thrown in that case and ignore it.
//
// It's unclear where we would get the info to
// set all spec and impl data for the package,
// so just use null. This is consistent will the
// JDK code that does the same.
definePackage(packageName, null, null, null, null, null, null, null);
} catch (IllegalArgumentException iae) {
// duplicate attempt to define same package.
// safe to ignore.
_logger.log(Level.FINE, "duplicate package " + "definition attempt for " + packageName, iae);
}
}
}
// Loop though the transformers here!!
try {
@SuppressWarnings("unchecked")
final List<ClassFileTransformer> xformers = (ArrayList<ClassFileTransformer>) transformers.clone();
if (!xformers.isEmpty()) {
for (final ClassFileTransformer transformer : xformers) {
// see javadocs of transform().
// It expects class name as java/lang/Object
// as opposed to java.lang.Object
final String internalClassName = name.replace('.', '/');
final byte[] transformedBytes = transformer.transform(this, internalClassName, null,
classData.pd, classData.getClassBytes());
if (transformedBytes != null) { // null indicates no transformation
_logger.log(Level.FINE, CULoggerInfo.actuallyTransformed, name);
classData.setClassBytes(transformedBytes);
}
}
}
} catch (IllegalClassFormatException icfEx) {
throw new ClassNotFoundException(icfEx.toString(), icfEx);
}
try {
byte[] bytes = classData.getClassBytes();
return defineClass(name, bytes, 0, bytes.length, classData.pd);
} catch (UnsupportedClassVersionError ucve) {
throw new UnsupportedClassVersionError(
sm.getString("ejbClassLoader.unsupportedVersion", name, System.getProperty("java.version")));
}
}
/**
* This method is responsible for locating the url from the class bytes
* have to be read and reading the bytes. It does not actually define
* the Class object.
* <p>
* To preclude a race condition on checking 'doneCalled', as well as transient errors
* if done() is called while running, this method is 'synchronized'.
*
* @param name class name in java.lang.Object format
* @return class bytes as well protection domain information
* @throws ClassNotFoundException
*/
private synchronized ClassData findClassData(String name) throws ClassNotFoundException {
if (doneCalled) {
ClassNotFoundException exception = new ClassNotFoundException(name);
_logger.log(Level.WARNING, CULoggerInfo.getString(CULoggerInfo.findClassAfterDone, name, this), exception);
throw exception;
}
String nf = notFoundClasses.get(name);
if (nf != null && nf.equals(name) ) {
throw new ClassNotFoundException(name);
}
// search through the JARs for a file of the form java/lang/Object.class
String entryName = name.replace('.', '/') + ".class";
for (URLEntry u : this.urlSet) {
if (!u.hasItem(entryName)) {
continue;
}
byte[] result = loadClassData0(u, entryName);
if (result != null) {
if (System.getSecurityManager() == null) {
return new ClassData(result, u.pd);
}
//recreate the pd to include the declared permissions
CodeSource cs = u.pd.getCodeSource();
PermissionCollection pc = this.getPermissions(cs);
ProtectionDomain pdWithPemissions =
new ProtectionDomain(u.pd.getCodeSource(), pc, u.pd.getClassLoader(), u.pd.getPrincipals());
return new ClassData(result, pdWithPemissions);
}
}
// add to the not found classes list
notFoundClasses.put(name, name);
throw new ClassNotFoundException(name);
}
/**
* Returns the byte array from the given input stream.
*
* @param istream input stream to the class or resource
* @throws IOException if an i/o error
*/
private byte[] getClassData(InputStream istream) throws IOException {
int num;
byte[] buf = new byte[4096];
try(BufferedInputStream bstream = new BufferedInputStream(istream);
ByteArrayOutputStream bout = new ByteArrayOutputStream()) {
while( (num = bstream.read(buf)) != -1) {
bout.write(buf, 0, num);
}
return bout.toByteArray();
}
}
protected String getClassLoaderName() {
return "ASURLClassLoader";
}
/**
* Returns a string representation of this class loader
*/
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(getClassLoaderName()).append(" :\n");
if (doneCalled) {
buffer.append("doneCalled = true").append('\n');
buffer.append("doneSnapshot = ").append(doneSnapshot);
} else {
buffer.append("urlSet = ").append(this.urlSet).append('\n');
buffer.append("doneCalled = false").append('\n');
}
buffer.append(" Parent -> ").append(getParent()).append('\n');
return buffer.toString();
}
@Override
public Enumeration<URL> getResources(String name) throws IOException {
final ResourceLocator locator = new ResourceLocator(this, getParentClassLoader(), true);
return locator.getResources(name);
}
private ClassLoader getParentClassLoader() {
final ClassLoader parent = getParent();
if (parent == null) {
return getSystemClassLoader();
}
return parent;
}
/**
* The JarFile objects loaded in the classloader may get exposed to the
* application code (e.g. EJBs) through calls of
* ((JarURLConnection) getResource().openConnection()).getJarFile().
*
* This class protects the jar file from being closed by such an application.
*
* @author fkieviet
*/
private static final class ProtectedJarFile extends JarFile {
/**
* Constructor
*
* @param file File
* @throws IOException from parent
*/
public ProtectedJarFile(File file) throws IOException {
super(file, true, OPEN_READ, Runtime.version());
}
/**
* Do nothing
*
* @see java.util.zip.ZipFile#close()
*
* Byron sez: I wonder what's going on here?!? This looks quite weird.
* Why not just get rid of both reallyClose() and close() and finalize()
* -- and just rely on the superclass?
* At any rate I am not messing with it today, 1/9/2013. Mainly because
* maybe close() is called outside and we do NOT want it to really close?
* Here is what happens at finalize time:
* 1. ASURLClassLoader$ProtectedJarFile.finalize()
* 2. java.util.zip.ZipFile.finalize()
* 3. ASURLClassLoader$ProtectedJarFile.close()
* 4. dumps a WARNING log message
* 5. reallyClose()
* 6. java.util.zip.ZipFile.close()
* I
*/
@Override
public void close() {
// do nothing
}
/**
* Really close the jar file
*
* @throws IOException from parent
*/
public void reallyClose() throws IOException {
super.close();
}
/**
* @see java.lang.Object#finalize()
*/
@Override
@Deprecated(since = "6.1.0", forRemoval = true)
protected void finalize() throws IOException {
try {
super.finalize();
reallyClose();
} catch (Throwable t) {
throw new IOException(t);
}
}
}
/**
* URL entry - keeps track of the url resources.
*/
protected static final class URLEntry {
/** the url, ensure thread visibility by making it 'final' */
final URL source;
/**
* file of the url,
* ensure thread visibility by making it 'volatile'
*/
volatile File file = null;
/**
* jar file if url is a jar else null,
* ensure thread visibility by making it 'volatile'
*/
volatile ProtectedJarFile zip = null;
/**
* true if url is a jar,
* ensure thread visibility by making it 'volatile'
*/
volatile boolean isJar = false;
/** ensure thread visibility by making it 'volatile' */
volatile HashMap<String, String> table = null;
/**
* ProtectionDomain with signers if jar is signed,
* ensure thread visibility by making it 'volatile'
*/
volatile ProtectionDomain pd = null;
public URLEntry(URL url) throws IOException {
source = url;
init();
}
private void init() throws IOException {
try {
file = new File(source.toURI());
} catch (URISyntaxException use) {
throw new IOException(use);
}
isJar = file.isFile();
if (isJar) {
zip = new ProtectedJarFile(file);
}
table = new HashMap<>();
}
private void fillTable(File f, HashMap<String, String> t, String parent) throws IOException {
String localName = parent.isEmpty() ? "" : parent + "/";
File[] children = f.listFiles();
for (File child : children) {
processFile(child, t, localName);
}
}
/**
* Adds a file (or, if a directory, the directory's contents) to the table
* of files this loader knows about.
* <p>
* Invokes fillTable for subdirectories which in turn invokes processFile
* recursively.
* @param fileToProcess the File to be processed
* @param t the HashMap that holds the files the loader knows about
* @param parentLocalName prefix to be used for the full path; should be
* non-empty only for recursive invocations
* @throws IOException in case of errors working with the fileToProcess
*/
private void processFile(File fileToProcess, HashMap<String, String> t, String parentLocalName) throws IOException {
String key = parentLocalName + fileToProcess.getName();
if (fileToProcess.isFile()) {
t.put(key, key);
} else if (fileToProcess.isDirectory()) {
fillTable(fileToProcess, t, key);
}
}
private boolean hasItem(String item) {
// in the case of ejbc stub compilation, ASURLClassLoader is created before stubs
// gets generated, thus we need to return true for this case.
if (table.isEmpty()) {
return true;
}
/*
* Even with the previous special handling, a file could be created
* in a directory after the loader was created and its table of
* URLEntry names populated. So check the table first and, if
* the target item is not there and this URLEntry is for a directory, look for
* the file. If the file is now present but was not when the loader