/
DynamicPlugins.kt
1394 lines (1234 loc) · 57.1 KB
/
DynamicPlugins.kt
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 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.plugins
import com.fasterxml.jackson.databind.type.TypeFactory
import com.intellij.configurationStore.jdomSerializer
import com.intellij.configurationStore.runInAutoSaveDisabledMode
import com.intellij.configurationStore.saveProjectsAndApp
import com.intellij.diagnostic.MessagePool
import com.intellij.diagnostic.PerformanceWatcher
import com.intellij.diagnostic.hprof.action.SystemTempFilenameSupplier
import com.intellij.diagnostic.hprof.analysis.AnalyzeClassloaderReferencesGraph
import com.intellij.diagnostic.hprof.analysis.HProfAnalysis
import com.intellij.ide.DataManager
import com.intellij.ide.IdeBundle
import com.intellij.ide.IdeEventQueue
import com.intellij.ide.actions.RevealFileAction
import com.intellij.ide.cancelAndJoinBlocking
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.plugins.cl.PluginAwareClassLoader
import com.intellij.ide.plugins.cl.PluginClassLoader
import com.intellij.ide.ui.TopHitCache
import com.intellij.ide.ui.UIThemeProvider
import com.intellij.ide.util.TipAndTrickManager
import com.intellij.idea.IdeaLogger
import com.intellij.lang.Language
import com.intellij.notification.NotificationType
import com.intellij.notification.NotificationsManager
import com.intellij.notification.impl.NotificationsManagerImpl
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.impl.ActionManagerImpl
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.actionSystem.impl.PresentationFactory
import com.intellij.openapi.actionSystem.impl.canUnloadActionGroup
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.application.impl.LaterInvocator
import com.intellij.openapi.components.ComponentManager
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionDescriptor
import com.intellij.openapi.extensions.ExtensionPointDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.keymap.impl.BundledKeymapBean
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ModalTaskOwner
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.runWithModalProgressBlocking
import com.intellij.openapi.progress.util.PotemkinProgress
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.impl.ProjectManagerImpl
import com.intellij.openapi.updateSettings.impl.UpdateChecker
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.objectTree.ThrowableInterner
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.registry.RegistryManager
import com.intellij.openapi.vfs.newvfs.FileAttribute
import com.intellij.openapi.wm.WindowManager
import com.intellij.openapi.wm.impl.IdeFrameImpl
import com.intellij.openapi.wm.impl.ProjectFrameHelper
import com.intellij.psi.util.CachedValuesManager
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.ui.IconDeferrer
import com.intellij.ui.mac.touchbar.TouchbarSupport
import com.intellij.util.CachedValuesManagerImpl
import com.intellij.util.MemoryDumpHelper
import com.intellij.util.ReflectionUtil
import com.intellij.util.SystemProperties
import com.intellij.util.containers.WeakList
import com.intellij.util.messages.impl.MessageBusEx
import com.intellij.util.ref.GCWatcher
import net.sf.cglib.core.ClassNameReader
import java.awt.KeyboardFocusManager
import java.awt.Window
import java.nio.channels.FileChannel
import java.nio.file.Paths
import java.nio.file.StandardOpenOption
import java.text.SimpleDateFormat
import java.util.*
import java.util.function.Predicate
import javax.swing.JComponent
import javax.swing.ToolTipManager
private val LOG = logger<DynamicPlugins>()
private val classloadersFromUnloadedPlugins = mutableMapOf<PluginId, WeakList<PluginClassLoader>>()
object DynamicPlugins {
@JvmStatic
@JvmOverloads
fun allowLoadUnloadWithoutRestart(descriptor: IdeaPluginDescriptorImpl,
baseDescriptor: IdeaPluginDescriptorImpl? = null,
context: List<IdeaPluginDescriptorImpl> = emptyList()): Boolean {
val reason = checkCanUnloadWithoutRestart(module = descriptor, parentModule = baseDescriptor, context = context)
if (reason != null) {
LOG.info(reason)
}
return reason == null
}
/**
* @return true if the requested enabled state was applied without restart, false if restart is required
*/
fun loadPlugins(descriptors: Collection<IdeaPluginDescriptorImpl>, project: Project?): Boolean {
return updateDescriptorsWithoutRestart(descriptors, load = true) {
loadPlugin(it, project)
}
}
/**
* @return true if the requested enabled state was applied without restart, false if restart is required
*/
fun unloadPlugins(
descriptors: Collection<IdeaPluginDescriptorImpl>,
project: Project? = null,
parentComponent: JComponent? = null,
options: UnloadPluginOptions = UnloadPluginOptions(disable = true),
): Boolean {
return updateDescriptorsWithoutRestart(descriptors, load = false) {
unloadPluginWithProgress(project, parentComponent, it, options)
}
}
private fun updateDescriptorsWithoutRestart(
plugins: Collection<IdeaPluginDescriptorImpl>,
load: Boolean,
executor: (IdeaPluginDescriptorImpl) -> Boolean,
): Boolean {
if (plugins.isEmpty()) {
return true
}
val pluginSet = PluginManagerCore.getPluginSet()
val descriptors = plugins
.asSequence()
.distinctBy { it.pluginId }
.filter { pluginSet.isPluginEnabled(it.pluginId) != load }
.toList()
val operationText = if (load) "load" else "unload"
val message = descriptors.joinToString(prefix = "Plugins to $operationText: [", postfix = "]")
LOG.info(message)
if (!descriptors.all { allowLoadUnloadWithoutRestart(it, context = descriptors) }) {
return false
}
// todo plugin installation should be done not in this method
var allPlugins = pluginSet.allPlugins
for (descriptor in descriptors) {
if (!allPlugins.contains(descriptor)) {
allPlugins = allPlugins + descriptor
}
}
// todo make internal:
// 1) ModuleGraphBase;
// 2) SortedModuleGraph;
// 3) SortedModuleGraph.topologicalComparator;
// 4) PluginSetBuilder.sortedModuleGraph.
var comparator = PluginSetBuilder(allPlugins)
.moduleGraph
.topologicalComparator
if (!load) {
comparator = comparator.reversed()
}
for (descriptor in descriptors.sortedWith(comparator)) {
descriptor.isEnabled = load
if (!executor.invoke(descriptor)) {
LOG.info("Failed to $operationText: $descriptor, restart required")
InstalledPluginsState.getInstance().isRestartRequired = true
return false
}
}
return true
}
fun checkCanUnloadWithoutRestart(module: IdeaPluginDescriptorImpl): String? {
return checkCanUnloadWithoutRestart(module, parentModule = null)
}
/**
* @param context Plugins which are being loaded at the same time as [module]
*/
private fun checkCanUnloadWithoutRestart(module: IdeaPluginDescriptorImpl,
parentModule: IdeaPluginDescriptorImpl?,
optionalDependencyPluginId: PluginId? = null,
context: List<IdeaPluginDescriptorImpl> = emptyList(),
checkImplementationDetailDependencies: Boolean = true): String? {
if (parentModule == null) {
if (module.isRequireRestart) {
return "Plugin ${module.pluginId} is explicitly marked as requiring restart"
}
if (module.productCode != null && !module.isBundled && !PluginManagerCore.isDevelopedByJetBrains(module)) {
return "Plugin ${module.pluginId} is a paid plugin"
}
if (InstalledPluginsState.getInstance().isRestartRequired) {
return InstalledPluginsState.RESTART_REQUIRED_MESSAGE
}
}
val pluginSet = PluginManagerCore.getPluginSet()
if (classloadersFromUnloadedPlugins[module.pluginId]?.isEmpty() == false) {
return "Not allowing load/unload of ${module.pluginId} because of incomplete previous unload operation for that plugin"
}
findMissingRequiredDependency(module, context, pluginSet)?.let { pluginDependency ->
return "Required dependency ${pluginDependency} of plugin ${module.pluginId} is not currently loaded"
}
val app = ApplicationManager.getApplication()
if (parentModule == null) {
if (!RegistryManager.getInstance().`is`("ide.plugins.allow.unload")) {
if (!allowLoadUnloadSynchronously(module)) {
return "ide.plugins.allow.unload is disabled and synchronous load/unload is not possible for ${module.pluginId}"
}
return null
}
try {
app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).checkUnloadPlugin(module)
}
catch (e: CannotUnloadPluginException) {
return e.cause?.localizedMessage ?: "checkUnloadPlugin listener blocked plugin unload"
}
}
if (!Registry.`is`("ide.plugins.allow.unload.from.sources")) {
if (pluginSet.findEnabledPlugin(module.pluginId) != null && module === parentModule && !module.isUseIdeaClassLoader) {
val pluginClassLoader = module.pluginClassLoader
if (pluginClassLoader != null && pluginClassLoader !is PluginClassLoader && !app.isUnitTestMode) {
return "Plugin ${module.pluginId} is not unload-safe because of use of ${pluginClassLoader.javaClass.name} as the default class loader. " +
"For example, the IDE is started from the sources with the plugin."
}
}
}
val epNameToExtensions = module.epNameToExtensions
if (epNameToExtensions != null) {
doCheckExtensionsCanUnloadWithoutRestart(
extensions = epNameToExtensions,
descriptor = module,
baseDescriptor = parentModule,
app = app,
optionalDependencyPluginId = optionalDependencyPluginId,
context = context,
pluginSet = pluginSet,
)?.let { return it }
}
checkNoComponentsOrServiceOverrides(module)?.let { return it }
checkUnloadActions(module)?.let { return it }
for (moduleRef in module.content.modules) {
if (pluginSet.isModuleEnabled(moduleRef.name)) {
val subModule = moduleRef.requireDescriptor()
checkCanUnloadWithoutRestart(module = subModule,
parentModule = module,
optionalDependencyPluginId = null,
context = context)?.let {
return "$it in optional dependency on ${subModule.pluginId}"
}
}
}
for (dependency in module.pluginDependencies) {
if (pluginSet.isPluginEnabled(dependency.pluginId)) {
checkCanUnloadWithoutRestart(dependency.subDescriptor ?: continue, parentModule ?: module, null, context)?.let {
return "$it in optional dependency on ${dependency.pluginId}"
}
}
}
// if not a sub plugin descriptor, then check that any dependent plugin also reloadable
if (parentModule != null && module !== parentModule) {
return null
}
var dependencyMessage: String? = null
processOptionalDependenciesOnPlugin(module, pluginSet, isLoaded = true) { mainDescriptor, subDescriptor ->
if (subDescriptor.packagePrefix == null
|| mainDescriptor.pluginId.idString == "org.jetbrains.kotlin" || mainDescriptor.pluginId == PluginManagerCore.JAVA_PLUGIN_ID) {
dependencyMessage = "Plugin ${subDescriptor.pluginId} that optionally depends on ${module.pluginId}" +
" does not have a separate classloader for the dependency"
return@processOptionalDependenciesOnPlugin false
}
dependencyMessage = checkCanUnloadWithoutRestart(subDescriptor, mainDescriptor, subDescriptor.pluginId, context)
if (dependencyMessage == null) {
true
}
else {
dependencyMessage = "Plugin ${subDescriptor.pluginId} that optionally depends on ${module.pluginId} requires restart: $dependencyMessage"
false
}
}
if (dependencyMessage == null && checkImplementationDetailDependencies) {
val contextWithImplementationDetails = context.toMutableList()
contextWithImplementationDetails.add(module)
processImplementationDetailDependenciesOnPlugin(module, pluginSet, contextWithImplementationDetails::add)
processImplementationDetailDependenciesOnPlugin(module, pluginSet) { dependentDescriptor ->
// don't check a plugin that is an implementation-detail dependency on the current plugin if it has other disabled dependencies
// and won't be loaded anyway
if (findMissingRequiredDependency(dependentDescriptor, contextWithImplementationDetails, pluginSet) == null) {
dependencyMessage = checkCanUnloadWithoutRestart(module = dependentDescriptor,
parentModule = null,
context = contextWithImplementationDetails,
checkImplementationDetailDependencies = false)
if (dependencyMessage != null) {
dependencyMessage = "implementation-detail plugin ${dependentDescriptor.pluginId} which depends on ${module.pluginId}" +
" requires restart: $dependencyMessage"
}
}
dependencyMessage == null
}
}
return dependencyMessage
}
private fun findMissingRequiredDependency(descriptor: IdeaPluginDescriptorImpl,
context: List<IdeaPluginDescriptorImpl>,
pluginSet: PluginSet): PluginId? {
for (dependency in descriptor.pluginDependencies) {
if (!dependency.isOptional &&
!PluginManagerCore.isModuleDependency(dependency.pluginId) &&
!pluginSet.isPluginEnabled(dependency.pluginId) &&
context.none { it.pluginId == dependency.pluginId }) {
return dependency.pluginId
}
}
return null
}
/**
* Checks if the plugin can be loaded/unloaded immediately when the corresponding action is invoked in the
* plugins settings, without pressing the Apply button.
*/
@JvmStatic
fun allowLoadUnloadSynchronously(module: IdeaPluginDescriptorImpl): Boolean {
val extensions = (module.unsortedEpNameToExtensionElements.takeIf { it.isNotEmpty() } ?: module.appContainerDescriptor.extensions)
if (extensions != null && !extensions.all {
it.key == UIThemeProvider.EP_NAME.name ||
it.key == BundledKeymapBean.EP_NAME.name
}) {
return false
}
return checkNoComponentsOrServiceOverrides(module) == null && module.actions.isEmpty()
}
private fun checkNoComponentsOrServiceOverrides(module: IdeaPluginDescriptorImpl): String? {
val id = module.pluginId
return checkNoComponentsOrServiceOverrides(id, module.appContainerDescriptor)
?: checkNoComponentsOrServiceOverrides(id, module.projectContainerDescriptor)
?: checkNoComponentsOrServiceOverrides(id, module.moduleContainerDescriptor)
}
private fun checkNoComponentsOrServiceOverrides(pluginId: PluginId?, containerDescriptor: ContainerDescriptor): String? {
if (!containerDescriptor.components.isNullOrEmpty()) {
return "Plugin $pluginId is not unload-safe because it declares components"
}
if (containerDescriptor.services.any { it.overrides }) {
return "Plugin $pluginId is not unload-safe because it overrides services"
}
return null
}
fun unloadPluginWithProgress(project: Project? = null,
parentComponent: JComponent?,
pluginDescriptor: IdeaPluginDescriptorImpl,
options: UnloadPluginOptions): Boolean {
var result = false
if (options.save) {
runInAutoSaveDisabledMode {
FileDocumentManager.getInstance().saveAllDocuments()
runWithModalProgressBlocking(project?.let { ModalTaskOwner.project(it) } ?: ModalTaskOwner.guess(), "") {
saveProjectsAndApp(true)
}
}
}
val indicator = PotemkinProgress(IdeBundle.message("plugins.progress.unloading.plugin.title", pluginDescriptor.name),
project,
parentComponent,
null)
indicator.runInSwingThread {
result = unloadPluginWithoutProgress(pluginDescriptor, options.withSave(false))
}
return result
}
data class UnloadPluginOptions(
var disable: Boolean = true,
var isUpdate: Boolean = false,
var save: Boolean = true,
var requireMemorySnapshot: Boolean = false,
var waitForClassloaderUnload: Boolean = false,
var checkImplementationDetailDependencies: Boolean = true,
var unloadWaitTimeout: Int? = null,
) {
fun withUpdate(isUpdate: Boolean): UnloadPluginOptions = also {
this.isUpdate = isUpdate
}
fun withWaitForClassloaderUnload(waitForClassloaderUnload: Boolean): UnloadPluginOptions = also {
this.waitForClassloaderUnload = waitForClassloaderUnload
}
fun withDisable(disable: Boolean): UnloadPluginOptions = also {
this.disable = disable
}
fun withRequireMemorySnapshot(requireMemorySnapshot: Boolean): UnloadPluginOptions = also {
this.requireMemorySnapshot = requireMemorySnapshot
}
fun withUnloadWaitTimeout(unloadWaitTimeout: Int): UnloadPluginOptions = also {
this.unloadWaitTimeout = unloadWaitTimeout
}
fun withSave(save: Boolean): UnloadPluginOptions = also {
this.save = save
}
fun withCheckImplementationDetailDependencies(checkImplementationDetailDependencies: Boolean): UnloadPluginOptions = also {
this.checkImplementationDetailDependencies = checkImplementationDetailDependencies
}
}
@JvmOverloads
fun unloadPlugin(pluginDescriptor: IdeaPluginDescriptorImpl,
options: UnloadPluginOptions = UnloadPluginOptions(disable = true)): Boolean {
return unloadPluginWithProgress(project = null, parentComponent = null, pluginDescriptor, options)
}
private fun unloadPluginWithoutProgress(pluginDescriptor: IdeaPluginDescriptorImpl,
options: UnloadPluginOptions = UnloadPluginOptions(disable = true)): Boolean {
val app = ApplicationManager.getApplication() as ApplicationImpl
val pluginId = pluginDescriptor.pluginId
val pluginSet = PluginManagerCore.getPluginSet()
if (options.checkImplementationDetailDependencies) {
processImplementationDetailDependenciesOnPlugin(pluginDescriptor, pluginSet) { dependentDescriptor ->
dependentDescriptor.isEnabled = false
unloadPluginWithoutProgress(dependentDescriptor, UnloadPluginOptions(waitForClassloaderUnload = false,
checkImplementationDetailDependencies = false))
true
}
}
try {
TipAndTrickManager.getInstance().closeTipDialog()
app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).beforePluginUnload(pluginDescriptor, options.isUpdate)
IdeEventQueue.getInstance().flushQueue()
}
catch (e: Exception) {
logger<DynamicPlugins>().error(e)
DynamicPluginsUsagesCollector.logDescriptorUnload(pluginDescriptor, success = false)
return false
}
var classLoaderUnloaded: Boolean
val classLoaders = WeakList<PluginClassLoader>()
try {
app.runWriteAction {
// must be after flushQueue (e.g. https://youtrack.jetbrains.com/issue/IDEA-252010)
val forbidGettingServicesToken = app.forbidGettingServices("Plugin $pluginId being unloaded.")
try {
(pluginDescriptor.pluginClassLoader as? PluginClassLoader)?.let {
classLoaders.add(it)
}
// https://youtrack.jetbrains.com/issue/IDEA-245031
// mark plugin classloaders as being unloaded to ensure that new extension instances will be not created during unload
setClassLoaderState(pluginDescriptor, PluginAwareClassLoader.UNLOAD_IN_PROGRESS)
unloadLoadedOptionalDependenciesOnPlugin(pluginDescriptor, pluginSet = pluginSet, classLoaders = classLoaders)
unloadDependencyDescriptors(pluginDescriptor, pluginSet, classLoaders)
unloadModuleDescriptorNotRecursively(pluginDescriptor)
clearPluginClassLoaderParentListCache(pluginSet)
app.extensionArea.clearUserCache()
for (project in ProjectUtil.getOpenProjects()) {
(project.extensionArea as ExtensionsAreaImpl).clearUserCache()
}
clearCachedValues()
jdomSerializer.clearSerializationCaches()
TypeFactory.defaultInstance().clearCache()
app.getServiceIfCreated(TopHitCache::class.java)?.clear()
ActionToolbarImpl.resetAllToolbars()
PresentationFactory.clearPresentationCaches()
TouchbarSupport.reloadAllActions()
(serviceIfCreated<NotificationsManager>() as? NotificationsManagerImpl)?.expireAll()
MessagePool.getInstance().clearErrors()
LaterInvocator.purgeExpiredItems()
FileAttribute.resetRegisteredIds()
resetFocusCycleRoot()
clearNewFocusOwner()
hideTooltip()
PerformanceWatcher.getInstance().clearFreezeStacktraces()
for (classLoader in classLoaders) {
IconLoader.detachClassLoader(classLoader)
Language.unregisterAllLanguagesIn(classLoader, pluginDescriptor)
}
serviceIfCreated<IconDeferrer>()?.clearCache()
(ApplicationManager.getApplication().messageBus as MessageBusEx).clearPublisherCache()
@Suppress("TestOnlyProblems")
(ProjectManager.getInstanceIfCreated() as? ProjectManagerImpl)?.disposeDefaultProjectAndCleanupComponentsForDynamicPluginTests()
val newPluginSet = pluginSet.withoutModule(
module = pluginDescriptor,
disable = options.disable,
).createPluginSetWithEnabledModulesMap()
PluginManagerCore.setPluginSet(newPluginSet)
}
finally {
try {
forbidGettingServicesToken.finish()
}
finally {
app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).pluginUnloaded(pluginDescriptor, options.isUpdate)
}
}
}
}
catch (e: Exception) {
logger<DynamicPlugins>().error(e)
}
finally {
IdeEventQueue.getInstance().flushQueue()
cancelAndJoinPluginScopes(classLoaders)
// do it after IdeEventQueue.flushQueue() to ensure that Disposer.isDisposed(...) works as expected in flushed tasks.
Disposer.clearDisposalTraces() // ensure we don't have references to plugin classes in disposal backtraces
ThrowableInterner.clearInternedBacktraces()
IdeaLogger.ourErrorsOccurred = null // ensure we don't have references to plugin classes in exception stacktraces
clearTemporaryLostComponent()
clearCglibStopBacktrace()
if (app.isUnitTestMode && pluginDescriptor.pluginClassLoader !is PluginClassLoader) {
classLoaderUnloaded = true
}
else {
classloadersFromUnloadedPlugins[pluginId] = classLoaders
ClassLoaderTreeChecker(pluginDescriptor, classLoaders).checkThatClassLoaderNotReferencedByPluginClassLoader()
val checkClassLoaderUnload = options.waitForClassloaderUnload ||
options.requireMemorySnapshot ||
Registry.`is`("ide.plugins.snapshot.on.unload.fail")
val timeout = if (checkClassLoaderUnload) {
options.unloadWaitTimeout ?: Registry.intValue("ide.plugins.unload.timeout", 5000)
}
else {
0
}
classLoaderUnloaded = unloadClassLoader(pluginDescriptor, timeout)
if (classLoaderUnloaded) {
LOG.info("Successfully unloaded plugin $pluginId (classloader unload checked=$checkClassLoaderUnload)")
classloadersFromUnloadedPlugins.remove(pluginId)
}
else {
if ((options.requireMemorySnapshot || (Registry.`is`("ide.plugins.snapshot.on.unload.fail") && !app.isUnitTestMode)) &&
MemoryDumpHelper.memoryDumpAvailable()) {
classLoaderUnloaded = saveMemorySnapshot(pluginId)
}
else {
LOG.info("Plugin $pluginId is not unload-safe because class loader cannot be unloaded")
}
}
if (!classLoaderUnloaded) {
InstalledPluginsState.getInstance().isRestartRequired = true
}
DynamicPluginsUsagesCollector.logDescriptorUnload(pluginDescriptor, success = classLoaderUnloaded)
}
}
if (!classLoaderUnloaded) {
setClassLoaderState(pluginDescriptor, PluginAwareClassLoader.ACTIVE)
}
ActionToolbarImpl.updateAllToolbarsImmediately(true)
return classLoaderUnloaded
}
private fun resetFocusCycleRoot() {
val focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager()
var focusCycleRoot = focusManager.currentFocusCycleRoot
if (focusCycleRoot != null) {
while (focusCycleRoot != null && focusCycleRoot !is IdeFrameImpl) {
focusCycleRoot = focusCycleRoot.parent
}
if (focusCycleRoot is IdeFrameImpl) {
focusManager.setGlobalCurrentFocusCycleRoot(focusCycleRoot)
}
else {
focusCycleRoot = focusManager.currentFocusCycleRoot
val dataContext = DataManager.getInstance().getDataContext(focusCycleRoot)
val project = CommonDataKeys.PROJECT.getData(dataContext)
if (project != null) {
val projectFrame = WindowManager.getInstance().getFrame(project)
if (projectFrame != null) {
focusManager.setGlobalCurrentFocusCycleRoot(projectFrame)
}
}
}
}
}
private fun unloadLoadedOptionalDependenciesOnPlugin(dependencyPlugin: IdeaPluginDescriptorImpl,
pluginSet: PluginSet,
classLoaders: WeakList<PluginClassLoader>) {
val dependencyClassloader = dependencyPlugin.classLoader
processOptionalDependenciesOnPlugin(dependencyPlugin, pluginSet, isLoaded = true) { mainDescriptor, subDescriptor ->
val classLoader = subDescriptor.classLoader
unloadModuleDescriptorNotRecursively(subDescriptor)
// this additional code is required because in unit tests PluginClassLoader is not used
if (mainDescriptor !== subDescriptor) {
subDescriptor.pluginClassLoader = null
}
if (dependencyClassloader is PluginClassLoader && classLoader is PluginClassLoader) {
LOG.info("Detach classloader $dependencyClassloader from $classLoader")
if (mainDescriptor !== subDescriptor && classLoader.pluginDescriptor === subDescriptor) {
classLoaders.add(classLoader)
classLoader.state = PluginAwareClassLoader.UNLOAD_IN_PROGRESS
}
}
true
}
}
private fun unloadDependencyDescriptors(plugin: IdeaPluginDescriptorImpl,
pluginSet: PluginSet,
classLoaders: WeakList<PluginClassLoader>) {
for (dependency in plugin.pluginDependencies) {
val subDescriptor = dependency.subDescriptor ?: continue
val classLoader = subDescriptor.pluginClassLoader
if (!pluginSet.isPluginEnabled(dependency.pluginId)) {
LOG.assertTrue(classLoader == null,
"Expected not to have any sub descriptor classloader when dependency ${dependency.pluginId} is not loaded")
continue
}
if (classLoader is PluginClassLoader && classLoader.pluginDescriptor === subDescriptor) {
classLoaders.add(classLoader)
classLoader.state = PluginAwareClassLoader.UNLOAD_IN_PROGRESS
}
unloadDependencyDescriptors(subDescriptor, pluginSet, classLoaders)
unloadModuleDescriptorNotRecursively(subDescriptor)
subDescriptor.pluginClassLoader = null
}
for (module in plugin.content.modules) {
val subDescriptor = module.requireDescriptor()
val classLoader = subDescriptor.pluginClassLoader ?: continue
if (classLoader is PluginClassLoader && classLoader.pluginDescriptor === subDescriptor) {
classLoaders.add(classLoader)
classLoader.state = PluginAwareClassLoader.UNLOAD_IN_PROGRESS
}
unloadModuleDescriptorNotRecursively(subDescriptor)
subDescriptor.pluginClassLoader = null
}
}
internal fun notify(@NlsContexts.NotificationContent text: String, notificationType: NotificationType, vararg actions: AnAction) {
val notification = UpdateChecker.getNotificationGroupForPluginUpdateResults().createNotification(text, notificationType)
for (action in actions) {
notification.addAction(action)
}
notification.notify(null)
}
// PluginId cannot be used to unload related resources because one plugin descriptor may consist of several sub descriptors,
// each of them depends on presense of another plugin, here not the whole plugin is unloaded, but only one part.
private fun unloadModuleDescriptorNotRecursively(module: IdeaPluginDescriptorImpl) {
val app = ApplicationManager.getApplication() as ApplicationImpl
(ActionManager.getInstance() as ActionManagerImpl).unloadActions(module)
val openedProjects = ProjectUtil.getOpenProjects().asList()
val appExtensionArea = app.extensionArea
val priorityUnloadListeners = mutableListOf<Runnable>()
val unloadListeners = mutableListOf<Runnable>()
unregisterUnknownLevelExtensions(module.unsortedEpNameToExtensionElements, module, appExtensionArea, openedProjects,
priorityUnloadListeners, unloadListeners)
for (epName in (module.appContainerDescriptor.extensions?.keys ?: emptySet())) {
appExtensionArea.unregisterExtensions(epName, module, priorityUnloadListeners, unloadListeners)
}
for (epName in (module.projectContainerDescriptor.extensions?.keys ?: emptySet())) {
for (project in openedProjects) {
(project.extensionArea as ExtensionsAreaImpl).unregisterExtensions(epName, module, priorityUnloadListeners,
unloadListeners)
}
}
// not an error - unsorted goes to module level, see registerExtensions
unregisterUnknownLevelExtensions(module.moduleContainerDescriptor.extensions, module, appExtensionArea, openedProjects,
priorityUnloadListeners, unloadListeners)
for (priorityUnloadListener in priorityUnloadListeners) {
priorityUnloadListener.run()
}
for (unloadListener in unloadListeners) {
unloadListener.run()
}
// first, reset all plugin extension points before unregistering, so that listeners don't see plugin in semi-torn-down state
processExtensionPoints(module, openedProjects) { points, area ->
area.resetExtensionPoints(points, module)
}
// unregister plugin extension points
processExtensionPoints(module, openedProjects) { points, area ->
area.unregisterExtensionPoints(points, module)
}
val pluginId = module.pluginId
app.unloadServices(module.appContainerDescriptor.services, pluginId)
val appMessageBus = app.messageBus as MessageBusEx
module.appContainerDescriptor.listeners?.let { appMessageBus.unsubscribeLazyListeners(module, it) }
for (project in openedProjects) {
(project as ComponentManagerImpl).unloadServices(module.projectContainerDescriptor.services, pluginId)
module.projectContainerDescriptor.listeners?.let {
((project as ComponentManagerImpl).messageBus as MessageBusEx).unsubscribeLazyListeners(module, it)
}
val moduleServices = module.moduleContainerDescriptor.services
for (ideaModule in ModuleManager.getInstance(project).modules) {
(ideaModule as ComponentManagerImpl).unloadServices(moduleServices, pluginId)
createDisposeTreePredicate(module)?.let { Disposer.disposeChildren(ideaModule, it) }
}
createDisposeTreePredicate(module)?.let { Disposer.disposeChildren(project, it) }
}
appMessageBus.disconnectPluginConnections(Predicate { aClass ->
(aClass.classLoader as? PluginClassLoader)?.pluginDescriptor === module
})
createDisposeTreePredicate(module)?.let { Disposer.disposeChildren(ApplicationManager.getApplication(), it) }
}
private fun unregisterUnknownLevelExtensions(extensionMap: Map<String, List<ExtensionDescriptor>>?,
pluginDescriptor: IdeaPluginDescriptorImpl,
appExtensionArea: ExtensionsAreaImpl,
openedProjects: List<Project>,
priorityUnloadListeners: MutableList<Runnable>,
unloadListeners: MutableList<Runnable>) {
for (epName in (extensionMap?.keys ?: return)) {
val isAppLevelEp = appExtensionArea.unregisterExtensions(epName, pluginDescriptor, priorityUnloadListeners,
unloadListeners)
if (isAppLevelEp) {
continue
}
for (project in openedProjects) {
val isProjectLevelEp = (project.extensionArea as ExtensionsAreaImpl)
.unregisterExtensions(epName, pluginDescriptor, priorityUnloadListeners, unloadListeners)
if (!isProjectLevelEp) {
for (module in ModuleManager.getInstance(project).modules) {
(module.extensionArea as ExtensionsAreaImpl)
.unregisterExtensions(epName, pluginDescriptor, priorityUnloadListeners, unloadListeners)
}
}
}
}
}
private inline fun processExtensionPoints(pluginDescriptor: IdeaPluginDescriptorImpl,
projects: List<Project>,
processor: (points: List<ExtensionPointDescriptor>, area: ExtensionsAreaImpl) -> Unit) {
pluginDescriptor.appContainerDescriptor.extensionPoints?.let {
processor(it, ApplicationManager.getApplication().extensionArea as ExtensionsAreaImpl)
}
pluginDescriptor.projectContainerDescriptor.extensionPoints?.let { extensionPoints ->
for (project in projects) {
processor(extensionPoints, project.extensionArea as ExtensionsAreaImpl)
}
}
pluginDescriptor.moduleContainerDescriptor.extensionPoints?.let { extensionPoints ->
for (project in projects) {
for (module in ModuleManager.getInstance(project).modules) {
processor(extensionPoints, module.extensionArea as ExtensionsAreaImpl)
}
}
}
}
@JvmOverloads
fun loadPlugin(pluginDescriptor: IdeaPluginDescriptorImpl, project: Project? = null): Boolean {
var result = false
val indicator = PotemkinProgress(IdeBundle.message("plugins.progress.loading.plugin.title", pluginDescriptor.name),
project,
null,
null)
indicator.runInSwingThread {
result = loadPluginWithoutProgress(pluginDescriptor, checkImplementationDetailDependencies = true)
}
return result
}
private fun loadPluginWithoutProgress(pluginDescriptor: IdeaPluginDescriptorImpl, checkImplementationDetailDependencies: Boolean = true): Boolean {
if (classloadersFromUnloadedPlugins[pluginDescriptor.pluginId]?.isEmpty() == false) {
LOG.info("Requiring restart for loading plugin ${pluginDescriptor.pluginId}" +
" because previous version of the plugin wasn't fully unloaded")
return false
}
val loadStartTime = System.currentTimeMillis()
val pluginSet = PluginManagerCore.getPluginSet()
.withModule(pluginDescriptor)
.createPluginSetWithEnabledModulesMap()
val classLoaderConfigurator = ClassLoaderConfigurator(pluginSet)
// todo loadPluginWithoutProgress should be called per each module, temporary solution
val pluginWithContentModules = pluginSet.getEnabledModules()
.filter { it.pluginId == pluginDescriptor.pluginId }
.filter(classLoaderConfigurator::configureModule)
.toList()
val app = ApplicationManager.getApplication() as ApplicationImpl
app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).beforePluginLoaded(pluginDescriptor)
app.runWriteAction {
try {
PluginManagerCore.setPluginSet(pluginSet)
val listenerCallbacks = mutableListOf<Runnable>()
// 4. load into service container
loadModules(pluginWithContentModules, app, listenerCallbacks)
loadModules(
optionalDependenciesOnPlugin(pluginDescriptor, classLoaderConfigurator, pluginSet),
app,
listenerCallbacks,
)
clearPluginClassLoaderParentListCache(pluginSet)
clearCachedValues()
listenerCallbacks.forEach(Runnable::run)
DynamicPluginsUsagesCollector.logDescriptorLoad(pluginDescriptor)
LOG.info("Plugin ${pluginDescriptor.pluginId} loaded without restart in ${System.currentTimeMillis() - loadStartTime} ms")
}
finally {
app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).pluginLoaded(pluginDescriptor)
}
}
if (checkImplementationDetailDependencies) {
var implementationDetailsLoadedWithoutRestart = true
processImplementationDetailDependenciesOnPlugin(pluginDescriptor, pluginSet) { dependentDescriptor ->
val dependencies = dependentDescriptor.pluginDependencies
if (dependencies.all { it.isOptional || PluginManagerCore.getPlugin(it.pluginId) != null }) {
if (!loadPluginWithoutProgress(dependentDescriptor, checkImplementationDetailDependencies = false)) {
implementationDetailsLoadedWithoutRestart = false
}
}
implementationDetailsLoadedWithoutRestart
}
return implementationDetailsLoadedWithoutRestart
}
return true
}
fun onPluginUnload(parentDisposable: Disposable, callback: Runnable) {
ApplicationManager.getApplication().messageBus.connect(parentDisposable)
.subscribe(DynamicPluginListener.TOPIC, object : DynamicPluginListener {
override fun beforePluginUnload(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean) {
callback.run()
}
})
}
}
private fun clearTemporaryLostComponent() {
try {
val clearMethod = Window::class.java.declaredMethods.find { it.name == "setTemporaryLostComponent" }
if (clearMethod == null) {
LOG.info("setTemporaryLostComponent method not found")
return
}
clearMethod.isAccessible = true
loop@ for (frame in WindowManager.getInstance().allProjectFrames) {
val window = when (frame) {
is ProjectFrameHelper -> frame.frame
is Window -> frame
else -> continue@loop
}
clearMethod.invoke(window, null)
}
}
catch (e: Throwable) {
LOG.info("Failed to clear Window.temporaryLostComponent", e)
}
}
private fun hideTooltip() {
try {
val showMethod = ToolTipManager::class.java.declaredMethods.find { it.name == "show" }
if (showMethod == null) {
LOG.info("ToolTipManager.show method not found")
return
}
showMethod.isAccessible = true
showMethod.invoke(ToolTipManager.sharedInstance(), null)
}
catch (e: Throwable) {
LOG.info("Failed to hide tooltip", e)
}
}
private fun clearCglibStopBacktrace() {
val field = ReflectionUtil.getDeclaredField(ClassNameReader::class.java, "EARLY_EXIT")
if (field != null) {
try {
ThrowableInterner.clearBacktrace((field[null] as Throwable))
}
catch (e: Throwable) {
LOG.info(e)
}
}
}
private fun clearNewFocusOwner() {
val field = ReflectionUtil.getDeclaredField(KeyboardFocusManager::class.java, "newFocusOwner")
if (field != null) {
try {
field.set(null, null)
}
catch (e: Throwable) {
LOG.info(e)
}
}
}
private fun cancelAndJoinPluginScopes(classLoaders: WeakList<PluginClassLoader>) {
if (!Registry.`is`("ide.await.scope.completion")) {
return
}
for (classLoader in classLoaders) {
cancelAndJoinBlocking(classLoader.pluginCoroutineScope, "Plugin ${classLoader.pluginId}") { job, _ ->
while (job.isActive) {
ProgressManager.checkCanceled()
IdeEventQueue.getInstance().flushQueue()
}
}
}
}
private fun saveMemorySnapshot(pluginId: PluginId): Boolean {
val snapshotDate = SimpleDateFormat("dd.MM.yyyy_HH.mm.ss").format(Date())
val snapshotFileName = "unload-$pluginId-$snapshotDate.hprof"
val snapshotPath = System.getProperty("memory.snapshots.path", SystemProperties.getUserHome()) + "/" + snapshotFileName
MemoryDumpHelper.captureMemoryDump(snapshotPath)
if (classloadersFromUnloadedPlugins[pluginId]?.isEmpty() != false) {
LOG.info("Successfully unloaded plugin $pluginId (classloader collected during memory snapshot generation)")
return true
}
if (Registry.`is`("ide.plugins.analyze.snapshot")) {
val analysisResult = analyzeSnapshot(snapshotPath, pluginId)
@Suppress("ReplaceSizeZeroCheckWithIsEmpty")
if (analysisResult.length == 0) {
LOG.info("Successfully unloaded plugin $pluginId (no strong references to classloader in .hprof file)")
classloadersFromUnloadedPlugins.remove(pluginId)
return true
}
else {
LOG.info("Snapshot analysis result: $analysisResult")
}