/
Felix.java
5721 lines (5235 loc) · 209 KB
/
Felix.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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.felix.framework;
import org.apache.felix.framework.BundleWiringImpl.BundleClassLoader;
import org.apache.felix.framework.ServiceRegistry.ServiceRegistryCallbacks;
import org.apache.felix.framework.cache.BundleArchive;
import org.apache.felix.framework.cache.BundleCache;
import org.apache.felix.framework.capabilityset.CapabilitySet;
import org.apache.felix.framework.capabilityset.SimpleFilter;
import org.apache.felix.framework.ext.SecurityProvider;
import org.apache.felix.framework.util.FelixConstants;
import org.apache.felix.framework.util.ListenerInfo;
import org.apache.felix.framework.util.MapToDictionary;
import org.apache.felix.framework.util.SecureAction;
import org.apache.felix.framework.util.ShrinkableCollection;
import org.apache.felix.framework.util.StringMap;
import org.apache.felix.framework.util.ThreadGate;
import org.apache.felix.framework.util.Util;
import org.apache.felix.framework.util.manifestparser.NativeLibraryClause;
import org.apache.felix.framework.wiring.BundleRequirementImpl;
import org.osgi.framework.AdminPermission;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.BundleException;
import org.osgi.framework.BundleListener;
import org.osgi.framework.BundleReference;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkListener;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.PackagePermission;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceException;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServicePermission;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.Version;
import org.osgi.framework.launch.Framework;
import org.osgi.framework.namespace.HostNamespace;
import org.osgi.framework.startlevel.FrameworkStartLevel;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.framework.wiring.BundleRevisions;
import org.osgi.framework.wiring.BundleWire;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.framework.wiring.FrameworkWiring;
import org.osgi.resource.Requirement;
import org.osgi.service.packageadmin.ExportedPackage;
import org.osgi.service.resolver.ResolutionException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLStreamHandler;
import java.security.AccessControlException;
import java.security.Permission;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.WeakHashMap;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Felix extends BundleImpl implements Framework
{
// The secure action used to do privileged calls
static final SecureAction m_secureAction = new SecureAction();
// The extension manager to handle extension bundles
private final ExtensionManager m_extensionManager;
// Framework wiring object.
private final FrameworkWiringImpl m_fwkWiring;
private final FrameworkStartLevelImpl m_fwkStartLevel;
// Logging related member variables.
private final Logger m_logger;
// Immutable config properties.
private final Map<String, Object> m_configMap;
// Mutable configuration properties passed into constructor.
private final Map<String, Object> m_configMutableMap;
// Resolver and resolver state.
private final StatefulResolver m_resolver;
// Lock object used to determine if an individual bundle
// lock or the global lock can be acquired.
private final ReentrantLock m_bundleLock = new ReentrantLock(true);
private final Condition m_bundleLockCondition = m_bundleLock.newCondition();
// Keeps track of threads wanting to acquire the global lock.
private final List<Thread> m_globalLockWaitersList = new ArrayList<Thread>();
// The thread currently holding the global lock.
private Thread m_globalLockThread = null;
// How many times the global lock was acquired by the thread holding
// the global lock; if this value is zero, then it means the global
// lock is free.
private int m_globalLockCount = 0;
// Maps a bundle location to a bundle location;
// used to reserve a location when installing a bundle.
private final Map<String, String> m_installRequestMap = new HashMap<String, String>();
// This lock must be acquired to modify m_installRequestMap;
// to help avoid deadlock this lock as priority 1 and should
// be acquired before locks with lower priority.
private final Object[] m_installRequestLock_Priority1 = new Object[0];
// Contains two maps, one mapping a String bundle location to a bundle
// and the other mapping a Long bundle identifier to a bundle.
// CONCURRENCY: Access guarded by the global lock for writes,
// but no lock for reads since it is copy on write.
private volatile Map[] m_installedBundles;
private static final int LOCATION_MAP_IDX = 0;
private static final int IDENTIFIER_MAP_IDX = 1;
// An array of uninstalled bundles before a refresh occurs.
// CONCURRENCY: Access guarded by the global lock for writes,
// but no lock for reads since it is copy on write.
private volatile List<BundleImpl> m_uninstalledBundles;
// Object to keep track of dependencies among bundle revisions.
private final BundleRevisionDependencies m_dependencies =
new BundleRevisionDependencies();
// Framework's active start level.
private volatile int m_activeStartLevel = FelixConstants.FRAMEWORK_INACTIVE_STARTLEVEL;
// Framework's target start level.
// Normally the target start will equal the active start level, except
// when the start level is changing, in which case the target start level
// will report the new start level while the active start level will report
// the old start level. Once the start level change is complete, the two
// will become equal again.
private volatile int m_targetStartLevel = FelixConstants.FRAMEWORK_INACTIVE_STARTLEVEL;
// Keep track of bundles currently being processed by start level thread.
private final SortedSet<StartLevelTuple> m_startLevelBundles =
new TreeSet<StartLevelTuple>();
// Local bundle cache.
private BundleCache m_cache = null;
// System bundle activator list.
List m_activatorList = null;
// Next available bundle identifier.
private long m_nextId = 1L;
private final Object m_nextIdLock = new Object[0];
// Service registry.
private final ServiceRegistry m_registry;
// List of event listeners.
private final EventDispatcher m_dispatcher;
// Reusable bundle URL stream handler.
private final URLStreamHandler m_bundleStreamHandler;
// Boot package delegation.
private final String[] m_bootPkgs;
private final boolean[] m_bootPkgWildcards;
// Shutdown gate.
private volatile ThreadGate m_shutdownGate = null;
// Security Manager created by the framework
private SecurityManager m_securityManager = null;
// Do we need to consult the default java security policy if no security provider is present?
private volatile boolean m_securityDefaultPolicy;
/**
* <p>
* This constructor creates a framework instance with a specified <tt>Map</tt>
* of configuration properties. Configuration properties are used internally
* by the framework to alter its default behavior. The configuration properties
* should have a <tt>String</tt> key and an <tt>Object</tt> value. The passed
* in <tt>Map</tt> is copied by the framework and all keys are converted to
* <tt>String</tt>s.
* </p>
* <p>
* Configuration properties are generally the sole means to configure the
* framework's default behavior; the framework does not typically refer to
* any system properties for configuration information. If a <tt>Map</tt> is
* supplied to this method for configuration properties, then the framework
* will consult the <tt>Map</tt> instance for any and all configuration
* properties. It is possible to specify a <tt>null</tt> for the configuration
* property map, in which case the framework will use its default behavior
* in all cases.
* </p>
* <p>
* The following configuration properties can be specified (properties starting
* with "<tt>felix</tt>" are specific to Felix, while those starting with
* "<tt>org.osgi</tt>" are standard OSGi properties):
* </p>
* <ul>
* <li><tt>org.osgi.framework.storage</tt> - Sets the directory to use as
* the bundle cache; by default bundle cache directory is
* <tt>felix-cache</tt> in the current working directory. The value
* should be a valid directory name. The directory name can be either absolute
* or relative. Relative directory names are relative to the current working
* directory. The specified directory will be created if it does
* not exist.
* </li>
* <li><tt>org.osgi.framework.storage.clean</tt> - Determines whether the
* bundle cache is flushed. The value can either be "<tt>none</tt>"
* or "<tt>onFirstInit</tt>", where "<tt>none</tt>" does not flush
* the bundle cache and "<tt>onFirstInit</tt>" flushes the bundle
* cache when the framework instance is first initialized. The default
* value is "<tt>none</tt>".
* </li>
* <li><tt>felix.cache.rootdir</tt> - Sets the root directory to use to
* calculate the bundle cache directory for relative directory names. If
* <tt>org.osgi.framework.storage</tt> is set to a relative name, by
* default it is relative to the current working directory. If this
* property is set, then it will be calculated as being relative to
* the specified root directory.
* </li>
* <li><tt>felix.cache.filelimit</tt> - The integer value of this string
* sets an upper limit on how many files the cache will open. The default
* value is zero, which means there is no limit.
* </li>
* <li><tt>felix.cache.locking</tt> - Enables or disables bundle cache locking,
* which is used to prevent concurrent access to the bundle cache. This is
* enabled by default, but on older/smaller JVMs file channel locking is
* not available; set this property to <tt>false</tt> to disable it.
* </li>
* <li><tt>felix.cache.bufsize</tt> - Sets the buffer size to be used by
* the cache; the default value is 4096. The integer value of this
* string provides control over the size of the internal buffer of the
* disk cache for performance reasons.
* </li>
* <li><tt>org.osgi.framework.system.packages</tt> - Specifies a
* comma-delimited list of packages that should be exported via the
* System Bundle from the parent class loader. The framework will set
* this to a reasonable default. If the value is specified, it
* replaces any default value.
* </li>
* <li><tt>org.osgi.framework.system.packages.extra</tt> - Specifies a
* comma-delimited list of packages that should be exported via the
* System Bundle from the parent class loader in addition to the
* packages in <tt>org.osgi.framework.system.packages</tt>. The default
* value is empty. If a value is specified, it is appended to the list
* of default or specified packages in
* <tt>org.osgi.framework.system.packages</tt>.
* </li>
* <li><tt>org.osgi.framework.bootdelegation</tt> - Specifies a
* comma-delimited list of packages that should be made implicitly
* available to all bundles from the parent class loader. It is
* recommended not to use this property since it breaks modularity.
* The default value is empty.
* </li>
* <li><tt>felix.systembundle.activators</tt> - A <tt>List</tt> of
* <tt>BundleActivator</tt> instances that are started/stopped when
* the System Bundle is started/stopped. The specified instances will
* receive the System Bundle's <tt>BundleContext</tt> when invoked.
* </li>
* <li><tt>felix.log.logger</tt> - An instance of <tt>Logger</tt> that the
* framework uses as its default logger.
* </li>
* <li><tt>felix.log.level</tt> - An integer value indicating the degree
* of logging reported by the framework; the higher the value the more
* logging is reported. If zero ('0') is specified, then logging is
* turned off completely. The log levels match those specified in the
* OSGi Log Service (i.e., 1 = error, 2 = warning, 3 = information,
* and 4 = debug). The default value is 1.
* </li>
* <li><tt>org.osgi.framework.startlevel.beginning</tt> - The initial
* start level of the framework once it starts execution; the default
* value is 1.
* </li>
* <li><tt>felix.startlevel.bundle</tt> - The default start level for
* newly installed bundles; the default value is 1.
* </li>
* <li><tt>felix.service.urlhandlers</tt> - Flag to indicate whether
* to activate the URL Handlers service for the framework instance;
* the default value is "<tt>true</tt>". Activating the URL Handlers
* service will result in the <tt>URL.setURLStreamHandlerFactory()</tt>
* and <tt>URLConnection.setContentHandlerFactory()</tt> being called.
* </li>
* <li><tt>felix.fragment.validation</tt> - Determines if installing
* unsupported fragment bundles throws an exception or logs a warning.
* Possible values are "<tt>exception</tt>" or "<tt>warning</tt>". The
* default value is "<tt>exception</tt>".
* </li>
* <li><tt>felix.security.defaultpolicy</tt> - Flag to indicate whether
* to consult the default java securtiy policy if no security extension
* is present. The default value is "<tt>false</tt>".
* </li>
* </ul>
* <p>
* The <a href="Main.html"><tt>Main</tt></a> class implements some
* functionality for default property file handling, which makes it
* possible to specify configuration properties and framework properties
* in files that are automatically loaded when starting the framework. If you
* plan to create your own framework instance, you may be
* able to take advantage of the features it provides; refer to its
* class documentation for more information.
* </p>
* <p>
* The framework is not actually started until the <tt>start()</tt> method
* is called.
* </p>
*
* @param configMap A map for obtaining configuration properties,
* may be <tt>null</tt>.
**/
public Felix(Map configMap)
{
super();
// Copy the configuration properties; convert keys to strings.
m_configMutableMap = new StringMap();
if (configMap != null)
{
for (Iterator i = configMap.entrySet().iterator(); i.hasNext(); )
{
Map.Entry entry = (Map.Entry) i.next();
m_configMutableMap.put(entry.getKey().toString(), entry.getValue());
}
}
// Get any system bundle activators.
m_activatorList = (List) m_configMutableMap.remove(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP);
m_activatorList = (m_activatorList == null) ? new ArrayList() : new ArrayList(m_activatorList);
m_configMap = createUnmodifiableMap(m_configMutableMap);
// Create logger with appropriate log level. Even though the
// logger needs the system bundle's context for tracking log
// services, it is created now because it is needed before
// the system bundle is activated. The system bundle's context
// will be set in the init() method after the system bundle
// is activated.
if (m_configMutableMap.get(FelixConstants.LOG_LOGGER_PROP) != null)
{
m_logger = (Logger) m_configMutableMap.get(FelixConstants.LOG_LOGGER_PROP);
}
else
{
m_logger = new Logger();
}
try
{
m_logger.setLogLevel(
Integer.parseInt(
(String) m_configMutableMap.get(FelixConstants.LOG_LEVEL_PROP)));
}
catch (NumberFormatException ex)
{
// Ignore and just use the default logging level.
}
// Initialize framework properties.
initializeFrameworkProperties();
// Read the boot delegation property and parse it.
String s = (m_configMap == null)
? null
: (String) m_configMap.get(Constants.FRAMEWORK_BOOTDELEGATION);
s = (s == null) ? "java.*" : s + ",java.*";
StringTokenizer st = new StringTokenizer(s, " ,");
m_bootPkgs = new String[st.countTokens()];
m_bootPkgWildcards = new boolean[m_bootPkgs.length];
for (int i = 0; i < m_bootPkgs.length; i++)
{
s = st.nextToken();
if (s.equals("*") || s.endsWith(".*"))
{
m_bootPkgWildcards[i] = true;
s = s.substring(0, s.length() - 1);
}
m_bootPkgs[i] = s;
}
//Initialize Native Library Aliases
NativeLibraryClause.initializeNativeAliases(m_configMap);
// Read the security default policy property
m_securityDefaultPolicy = "true".equals(getProperty(FelixConstants.SECURITY_DEFAULT_POLICY));
// Create default bundle stream handler.
m_bundleStreamHandler = new URLHandlersBundleStreamHandler(this, m_secureAction);
// Create service registry.
m_registry = new ServiceRegistry(m_logger, new ServiceRegistryCallbacks() {
@Override
public void serviceChanged(ServiceEvent event, Dictionary oldProps)
{
fireServiceEvent(event, oldProps);
}
});
// Create a resolver and its state.
m_resolver = new StatefulResolver(this, m_registry);
// Create the extension manager, which we will use as the
// revision for the system bundle.
m_extensionManager = new ExtensionManager(m_logger, m_configMap, this);
try
{
addRevision(m_extensionManager.getRevision());
}
catch (Exception ex)
{
// This should not throw an exception, but if so, lets convert it to
// a runtime exception.
throw new RuntimeException("Exception creating system bundle revision", ex);
}
// Create event dispatcher.
m_dispatcher = new EventDispatcher(m_logger, m_registry);
// Create framework wiring object.
m_fwkWiring = new FrameworkWiringImpl(this, m_registry);
// Create framework start level object.
m_fwkStartLevel = new FrameworkStartLevelImpl(this, m_registry);
}
Logger getLogger()
{
return m_logger;
}
Map<String, Object> getConfig()
{
return m_configMap;
}
StatefulResolver getResolver()
{
return m_resolver;
}
BundleRevisionDependencies getDependencies()
{
return m_dependencies;
}
URLStreamHandler getBundleStreamHandler()
{
return m_bundleStreamHandler;
}
String[] getBootPackages()
{
return m_bootPkgs;
}
boolean[] getBootPackageWildcards()
{
return m_bootPkgWildcards;
}
private Map createUnmodifiableMap(Map mutableMap)
{
Map result = Collections.unmodifiableMap(mutableMap);
// Work around a bug in certain version of J9 where a call to
// Collections.unmodifiableMap().keySet().iterator() throws
// a NoClassDefFoundError. We try to detect this and return
// the given mutableMap instead.
try
{
result.keySet().iterator();
}
catch (NoClassDefFoundError ex)
{
return mutableMap;
}
return result;
}
// This overrides BundleImpl.close() which avoids removing the
// system bundle module from the resolver state.
@Override
void close()
{
}
// This overrides the default behavior of BundleImpl.getFramework()
// to return "this", since the system bundle is the framework.
@Override
Felix getFramework()
{
return this;
}
@Override
public <A> A adapt(Class<A> type)
{
checkAdapt(type);
if ((type == Framework.class)
|| (type == Felix.class))
{
return (A) this;
}
else if ((type == FrameworkWiring.class)
|| (type == FrameworkWiringImpl.class))
{
return (A) m_fwkWiring;
}
else if ((type == FrameworkStartLevel.class)
|| (type == FrameworkStartLevelImpl.class))
{
return (A) m_fwkStartLevel;
}
return super.adapt(type);
}
@Override
public long getBundleId()
{
return 0;
}
@Override
public long getLastModified()
{
return 0;
}
@Override
void setLastModified(long l)
{
// Ignore.
}
@Override
String _getLocation()
{
return Constants.SYSTEM_BUNDLE_LOCATION;
}
@Override
public int getPersistentState()
{
return Bundle.ACTIVE;
}
@Override
public void setPersistentStateInactive()
{
// Ignore.
}
@Override
public void setPersistentStateActive()
{
// Ignore.
}
@Override
public void setPersistentStateUninstalled()
{
// Ignore.
}
/**
* Overrides standard <tt>BundleImpl.getStartLevel()</tt> behavior to
* always return zero for the system bundle.
* @param defaultLevel This parameter is ignored by the system bundle.
* @return Always returns zero.
**/
@Override
int getStartLevel(int defaultLevel)
{
return 0;
}
/**
* Overrides standard <tt>BundleImpl.setStartLevel()</tt> behavior to
* always throw an exception since the system bundle's start level cannot
* be changed.
* @param level This parameter is ignored by the system bundle.
* @throws IllegalArgumentException Always throws exception since system
* bundle's start level cannot be changed.
**/
@Override
void setStartLevel(int level)
{
throw new IllegalArgumentException("Cannot set the system bundle's start level.");
}
@Override
public boolean hasPermission(Object obj)
{
return true;
}
@Override
public void init() throws BundleException
{
init((FrameworkListener[]) null);
}
/**
* @see org.osgi.framework.launch.Framework#init(org.osgi.framework.FrameworkListener[])
*/
@Override
public void init(final FrameworkListener... listeners) throws BundleException
{
// The system bundle can only be initialized if it currently isn't started.
acquireBundleLock(this,
Bundle.INSTALLED | Bundle.RESOLVED | Bundle.STARTING | Bundle.ACTIVE);
try
{
if ((getState() == Bundle.INSTALLED) || (getState() == Bundle.RESOLVED))
{
String security = (String) m_configMap.get(Constants.FRAMEWORK_SECURITY);
if (security != null)
{
if (System.getSecurityManager() != null)
{
throw new SecurityException("SecurityManager already installed");
}
security = security.trim();
if (Constants.FRAMEWORK_SECURITY_OSGI.equalsIgnoreCase(security) || (security.length() == 0))
{
System.setSecurityManager(m_securityManager = new SecurityManager());
}
else
{
try
{
System.setSecurityManager(m_securityManager =
(SecurityManager) Class.forName(security).newInstance());
}
catch (Throwable t)
{
SecurityException se =
new SecurityException(
"Unable to install custom SecurityManager: " + security);
se.initCause(t);
throw se;
}
}
}
// Generate a framework UUID.
// Spec says we get a new UUID for each invocation of init().
m_configMutableMap.put(
FelixConstants.FRAMEWORK_UUID,
Util.randomUUID("true".equalsIgnoreCase(_getProperty(FelixConstants.FRAMEWORK_UUID_SECURE))));
// Initialize event dispatcher.
m_dispatcher.startDispatching();
// Create the bundle cache, if necessary, so that we can reload any
// installed bundles.
m_cache = (BundleCache)
m_configMutableMap.get(FelixConstants.FRAMEWORK_BUNDLECACHE_IMPL);
if (m_cache == null)
{
try
{
m_cache = new BundleCache(m_logger, m_configMap);
}
catch (Exception ex)
{
m_logger.log(Logger.LOG_ERROR, "Error creating bundle cache.", ex);
throw new BundleException("Error creating bundle cache.", ex);
}
}
// If this is the first time init is called, check to see if
// we need to flush the bundle cache.
if (getState() == Bundle.INSTALLED)
{
String clean = (String) m_configMap.get(Constants.FRAMEWORK_STORAGE_CLEAN);
if ((clean != null)
&& clean.equalsIgnoreCase(Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT))
{
try
{
m_cache.delete();
}
catch (Exception ex)
{
throw new BundleException("Unable to flush bundle cache.", ex);
}
}
}
// Initialize installed bundle data structures.
Map[] maps = new Map[] {
new HashMap<String, BundleImpl>(1),
new TreeMap<Long, BundleImpl>()
};
m_uninstalledBundles = new ArrayList<BundleImpl>(0);
// Add the system bundle to the set of installed bundles.
maps[LOCATION_MAP_IDX].put(_getLocation(), this);
maps[IDENTIFIER_MAP_IDX].put(new Long(0), this);
m_installedBundles = maps;
try
{
getResolver().removeRevision(m_extensionManager.getRevision());
m_extensionManager.removeExtensionBundles();
m_extensionManager.updateRevision(this, m_configMap);
if (!m_configMutableMap.containsKey(Constants.FRAMEWORK_SYSTEMPACKAGES))
{
m_configMutableMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES, m_extensionManager.getRevision().getHeaders().get(Constants.EXPORT_PACKAGE));
}
getResolver().addRevision(m_extensionManager.getRevision());
}
catch (Exception ex)
{
// This should not throw an exception, but if so, lets convert it to
// a runtime exception.
throw new BundleException("Exception creating system bundle revision", ex);
}
// Manually resolve the system bundle, which will cause its
// state to be set to RESOLVED.
try
{
m_resolver.resolve(
Collections.singleton(adapt(BundleRevision.class)),
Collections.EMPTY_SET);
}
catch (ResolutionException ex)
{
// This should never happen.
throw new BundleException(
"Unresolved constraint in System Bundle:"
+ ex.getUnresolvedRequirements());
}
// Reload the cached bundles before creating and starting the
// system bundle, since we want all cached bundles to be reloaded
// when we activate the system bundle and any subsequent system
// bundle activators passed into the framework constructor.
BundleArchive[] archives = null;
// First get cached bundle identifiers.
try
{
archives = m_cache.getArchives();
}
catch (Exception ex)
{
m_logger.log(Logger.LOG_ERROR, "Unable to list saved bundles.", ex);
archives = null;
}
// Create system bundle activator and bundle context so we can activate it.
setActivator(new SystemBundleActivator());
setBundleContext(new BundleContextImpl(m_logger, this, this));
boolean javaVersionChanged = handleJavaVersionChange();
// Now load all cached bundles.
for (int i = 0; (archives != null) && (i < archives.length); i++)
{
try
{
// Keep track of the max bundle ID currently in use since we
// will need to use this as our next bundle ID value if the
// persisted value cannot be read.
m_nextId = Math.max(m_nextId, archives[i].getId() + 1);
// It is possible that a bundle in the cache was previously
// uninstalled, but not completely deleted (perhaps because
// of a crash or a locked file), so if we see an archive
// with an UNINSTALLED persistent state, then try to remove
// it now.
if (archives[i].getPersistentState() == Bundle.UNINSTALLED)
{
archives[i].closeAndDelete();
}
// Otherwise re-install the cached bundle.
else
{
// Install the cached bundle.
reloadBundle(archives[i], javaVersionChanged);
}
}
catch (Exception ex)
{
fireFrameworkEvent(FrameworkEvent.ERROR, this, ex);
try
{
m_logger.log(
Logger.LOG_ERROR,
"Unable to re-install " + archives[i].getLocation(),
ex);
}
catch (Exception ex2)
{
m_logger.log(
Logger.LOG_ERROR,
"Unable to re-install cached bundle.",
ex);
}
// TODO: FRAMEWORK - Perhaps we should remove the cached bundle?
}
}
for (Bundle extension : m_extensionManager.resolveExtensionBundles(this))
{
m_extensionManager.startExtensionBundle(this, (BundleImpl) extension);
}
// Now that we have loaded all cached bundles and have determined the
// max bundle ID of cached bundles, we need to try to load the next
// bundle ID from persistent storage. In case of failure, we should
// keep the max value.
m_nextId = Math.max(m_nextId, loadNextId());
// The framework is now in its startup sequence.
setBundleStateAndNotify(this, Bundle.STARTING);
// Now it is possible for threads to wait for the framework to stop,
// so create a gate for that purpose.
m_shutdownGate = new ThreadGate();
// add framework listeners
if ( listeners != null )
{
for(final FrameworkListener fl : listeners)
{
addFrameworkListener(this, fl);
}
}
// Start services
m_resolver.start();
m_fwkWiring.start();
m_fwkStartLevel.start();
try
{
Felix.m_secureAction.startActivator(
getActivator(), _getBundleContext());
}
catch (Throwable ex)
{
m_dispatcher.stopDispatching();
m_logger.log(Logger.LOG_ERROR, "Unable to start system bundle.", ex);
throw new RuntimeException("Unable to start system bundle.");
}
// We have to check with the security provider (if there is one).
// This is to avoid having bundles in the cache that have been tampered with
SecurityProvider sp = getFramework().getSecurityProvider();
if ((sp != null) && (System.getSecurityManager() != null))
{
boolean locked = acquireGlobalLock();
if (!locked)
{
throw new BundleException(
"Unable to acquire the global lock to check the bundle.");
}
try
{
for (Object bundle : m_installedBundles[IDENTIFIER_MAP_IDX].values())
{
try
{
if (bundle != this)
{
setBundleProtectionDomain(((BundleImpl) bundle).adapt(BundleRevisionImpl.class));
}
}
catch (Exception ex)
{
((BundleImpl) bundle).close();
maps = new Map[] {
new HashMap<String, BundleImpl>(m_installedBundles[LOCATION_MAP_IDX]),
new TreeMap<Long, BundleImpl>(m_installedBundles[IDENTIFIER_MAP_IDX])
};
maps[LOCATION_MAP_IDX].remove(((BundleImpl) bundle)._getLocation());
maps[IDENTIFIER_MAP_IDX].remove(new Long(((BundleImpl) bundle).getBundleId()));
m_installedBundles = maps;
m_logger.log(
Logger.LOG_ERROR,
"Bundle in cache doesn't pass security check anymore.",
ex);
}
}
}
finally
{
// Always release the global lock.
releaseGlobalLock();
}
}
m_extensionManager.startPendingExtensionBundles(Felix.this);
m_fwkWiring.refreshBundles(null);
// Clear the cache of classes coming from the system bundle.
// This is only used for Felix.getBundle(Class clazz) to speed
// up class lookup for the system bundle.
synchronized (m_systemBundleClassCache)
{
m_systemBundleClassCache.clear();
}
}
}
finally
{
releaseBundleLock(this);
if ( listeners != null )
{
for(final FrameworkListener fl : listeners)
{
removeFrameworkListener(this, fl);
}
}
}
}
private boolean handleJavaVersionChange()
{
File dataFile = getDataFile(this, "last.java.version");
int currentVersion = 8;
try
{
currentVersion = Version.parseVersion(_getProperty("java.specification.version")).getMajor();
}
catch (Exception ignore)
{
getLogger().log(this, Logger.LOG_WARNING, "Unable to parse current java version", ignore);
}
if (currentVersion < 8)
{
currentVersion = 8;
}
int lastVersion = 8;
if (dataFile.isFile())
{
BufferedReader input = null;
try
{
input = new BufferedReader(new InputStreamReader(new FileInputStream(dataFile), "UTF-8"));
lastVersion = Version.parseVersion(input.readLine()).getMajor();
}
catch (Exception ignore)
{
getLogger().log(this, Logger.LOG_WARNING, "Unable to parse last java version", ignore);
}
finally
{
if (input != null)
{