-
Notifications
You must be signed in to change notification settings - Fork 7.1k
/
MshObject.cs
2652 lines (2308 loc) · 104 KB
/
MshObject.cs
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) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using Microsoft.Management.Infrastructure;
#if !UNIX
using System.DirectoryServices;
using System.Management;
#endif
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
#pragma warning disable 56500
namespace System.Management.Automation
{
/// <summary>
/// Wraps an object providing alternate views of the available members
/// and ways to extend them. Members can be methods, properties,
/// parameterized properties, etc.
/// </summary>
/// <remarks>
/// It is permitted to subclass <see cref="PSObject"/>
/// but there is no established scenario for doing this, nor has it been tested.
/// </remarks>
[TypeDescriptionProvider(typeof(PSObjectTypeDescriptionProvider))]
[Serializable]
public class PSObject : IFormattable, IComparable, ISerializable, IDynamicMetaObjectProvider
{
#region constructors
#region private to the constructors
internal TypeTable GetTypeTable()
{
if (_typeTable != null && _typeTable.TryGetTarget(out TypeTable typeTable))
{
return typeTable;
}
ExecutionContext context = LocalPipeline.GetExecutionContextFromTLS();
return context?.TypeTable;
}
internal static T TypeTableGetMemberDelegate<T>(PSObject msjObj, string name) where T : PSMemberInfo
{
TypeTable table = msjObj.GetTypeTable();
return TypeTableGetMemberDelegate<T>(msjObj, table, name);
}
private static T TypeTableGetMemberDelegate<T>(PSObject msjObj, TypeTable typeTableToUse, string name) where T : PSMemberInfo
{
if (typeTableToUse == null)
{
return null;
}
PSMemberInfoInternalCollection<PSMemberInfo> allMembers = typeTableToUse.GetMembers<PSMemberInfo>(msjObj.InternalTypeNames);
PSMemberInfo member = allMembers[name];
if (member == null)
{
PSObject.MemberResolution.WriteLine("\"{0}\" NOT present in type table.", name);
return null;
}
if (member is T memberAsT)
{
PSObject.MemberResolution.WriteLine("\"{0}\" present in type table.", name);
return memberAsT;
}
PSObject.MemberResolution.WriteLine("\"{0}\" from types table ignored because it has type {1} instead of {2}.",
name, member.GetType(), typeof(T));
return null;
}
internal static PSMemberInfoInternalCollection<T> TypeTableGetMembersDelegate<T>(PSObject msjObj) where T : PSMemberInfo
{
TypeTable table = msjObj.GetTypeTable();
return TypeTableGetMembersDelegate<T>(msjObj, table);
}
internal static PSMemberInfoInternalCollection<T> TypeTableGetMembersDelegate<T>(PSObject msjObj, TypeTable typeTableToUse) where T : PSMemberInfo
{
if (typeTableToUse == null)
{
return new PSMemberInfoInternalCollection<T>();
}
PSMemberInfoInternalCollection<T> members = typeTableToUse.GetMembers<T>(msjObj.InternalTypeNames);
PSObject.MemberResolution.WriteLine("Type table members: {0}.", members.Count);
return members;
}
internal static T TypeTableGetFirstMemberOrDefaultDelegate<T>(PSObject msjObj, MemberNamePredicate predicate) where T : PSMemberInfo
{
TypeTable table = msjObj.GetTypeTable();
return TypeTableGetFirstOrDefaultMemberDelegate<T>(msjObj, table, predicate);
}
internal static T TypeTableGetFirstOrDefaultMemberDelegate<T>(PSObject msjObj, TypeTable typeTableToUse, MemberNamePredicate predicate) where T : PSMemberInfo
{
return typeTableToUse?.GetFirstMemberOrDefault<T>(msjObj.InternalTypeNames, predicate);
}
private static T AdapterGetMemberDelegate<T>(PSObject msjObj, string name) where T : PSMemberInfo
{
if (msjObj.IsDeserialized)
{
if (msjObj.AdaptedMembers == null)
{
return null;
}
T adaptedMember = msjObj.AdaptedMembers[name] as T;
PSObject.MemberResolution.WriteLine("Serialized adapted member: {0}.", adaptedMember == null ? "not found" : adaptedMember.Name);
return adaptedMember;
}
T retValue = msjObj.InternalAdapter.BaseGetMember<T>(msjObj.ImmediateBaseObject, name);
PSObject.MemberResolution.WriteLine("Adapted member: {0}.", retValue == null ? "not found" : retValue.Name);
return retValue;
}
private static T AdapterGetFirstMemberOrDefaultDelegate<T>(PSObject msjObj, MemberNamePredicate predicate) where T : PSMemberInfo
{
if (msjObj.IsDeserialized && typeof(T).IsAssignableFrom(typeof(PSPropertyInfo)))
{
if (msjObj.AdaptedMembers == null)
{
return null;
}
foreach (var adaptedMember in msjObj.AdaptedMembers)
{
if (predicate(adaptedMember.Name))
{
return adaptedMember as T;
}
}
}
T retValue = msjObj.InternalAdapter.BaseGetFirstMemberOrDefault<T>(msjObj._immediateBaseObject, predicate);
return retValue;
}
internal static PSMemberInfoInternalCollection<U> TransformMemberInfoCollection<T, U>(PSMemberInfoCollection<T> source) where T : PSMemberInfo where U : PSMemberInfo
{
if (typeof(T) == typeof(U))
{
// If the types are the same, don't make a copy, return the cached collection.
return source as PSMemberInfoInternalCollection<U>;
}
PSMemberInfoInternalCollection<U> returnValue = new PSMemberInfoInternalCollection<U>();
foreach (T member in source)
{
if (member is U tAsU)
{
returnValue.Add(tAsU);
}
}
return returnValue;
}
private static PSMemberInfoInternalCollection<T> AdapterGetMembersDelegate<T>(PSObject msjObj) where T : PSMemberInfo
{
if (msjObj.IsDeserialized)
{
if (msjObj.AdaptedMembers == null)
{
return new PSMemberInfoInternalCollection<T>();
}
PSObject.MemberResolution.WriteLine("Serialized adapted members: {0}.", msjObj.AdaptedMembers.Count);
return TransformMemberInfoCollection<PSPropertyInfo, T>(msjObj.AdaptedMembers);
}
PSMemberInfoInternalCollection<T> retValue = msjObj.InternalAdapter.BaseGetMembers<T>(msjObj._immediateBaseObject);
PSObject.MemberResolution.WriteLine("Adapted members: {0}.", retValue.VisibleCount);
return retValue;
}
private static PSMemberInfoInternalCollection<T> DotNetGetMembersDelegate<T>(PSObject msjObj) where T : PSMemberInfo
{
// Don't lookup dotnet members if the object doesn't insist.
if (msjObj.InternalBaseDotNetAdapter != null)
{
PSMemberInfoInternalCollection<T> retValue = msjObj.InternalBaseDotNetAdapter.BaseGetMembers<T>(msjObj._immediateBaseObject);
PSObject.MemberResolution.WriteLine("DotNet members: {0}.", retValue.VisibleCount);
return retValue;
}
return new PSMemberInfoInternalCollection<T>();
}
private static T DotNetGetMemberDelegate<T>(PSObject msjObj, string name) where T : PSMemberInfo
{
// Don't lookup dotnet member if the object doesn't insist.
if (msjObj.InternalBaseDotNetAdapter != null)
{
T retValue = msjObj.InternalBaseDotNetAdapter.BaseGetMember<T>(msjObj._immediateBaseObject, name);
PSObject.MemberResolution.WriteLine("DotNet member: {0}.", retValue == null ? "not found" : retValue.Name);
return retValue;
}
return null;
}
private static T DotNetGetFirstMemberOrDefaultDelegate<T>(PSObject msjObj, MemberNamePredicate predicate) where T : PSMemberInfo
{
// Don't lookup dotnet member if the object doesn't insist.
return msjObj.InternalBaseDotNetAdapter?.BaseGetFirstMemberOrDefault<T>(msjObj._immediateBaseObject, predicate);
}
/// <summary>
/// A collection of delegates to get Extended/Adapted/Dotnet members based on the
/// <paramref name="viewType"/>
/// </summary>
/// <param name="viewType">
/// A filter to select Extended/Adapted/Dotnet view of the object
/// </param>
/// <returns></returns>
internal static Collection<CollectionEntry<PSMemberInfo>> GetMemberCollection(PSMemberViewTypes viewType)
{
return GetMemberCollection(viewType, null);
}
/// <summary>
/// A collection of delegates to get Extended/Adapted/Dotnet members based on the
/// <paramref name="viewType"/>
/// </summary>
/// <param name="viewType">
/// A filter to select Extended/Adapted/Dotnet view of the object
/// </param>
/// <param name="backupTypeTable">
/// Backup type table to use if there is no execution context associated with the current thread
/// </param>
/// <returns></returns>
internal static Collection<CollectionEntry<PSMemberInfo>> GetMemberCollection(
PSMemberViewTypes viewType,
TypeTable backupTypeTable)
{
Collection<CollectionEntry<PSMemberInfo>> returnValue = new Collection<CollectionEntry<PSMemberInfo>>();
if ((viewType & PSMemberViewTypes.Extended) == PSMemberViewTypes.Extended)
{
if (backupTypeTable == null)
{
returnValue.Add(new CollectionEntry<PSMemberInfo>(
PSObject.TypeTableGetMembersDelegate<PSMemberInfo>,
PSObject.TypeTableGetMemberDelegate<PSMemberInfo>,
PSObject.TypeTableGetFirstMemberOrDefaultDelegate<PSMemberInfo>,
true, true, "type table members"));
}
else
{
returnValue.Add(new CollectionEntry<PSMemberInfo>(
msjObj => TypeTableGetMembersDelegate<PSMemberInfo>(msjObj, backupTypeTable),
(msjObj, name) => TypeTableGetMemberDelegate<PSMemberInfo>(msjObj, backupTypeTable, name),
(msjObj, predicate) => TypeTableGetFirstOrDefaultMemberDelegate<PSMemberInfo>(msjObj, backupTypeTable, predicate),
true, true, "type table members"));
}
}
if ((viewType & PSMemberViewTypes.Adapted) == PSMemberViewTypes.Adapted)
{
returnValue.Add(new CollectionEntry<PSMemberInfo>(
PSObject.AdapterGetMembersDelegate<PSMemberInfo>,
PSObject.AdapterGetMemberDelegate<PSMemberInfo>,
PSObject.AdapterGetFirstMemberOrDefaultDelegate<PSMemberInfo>,
shouldReplicateWhenReturning: false,
shouldCloneWhenReturning: false,
collectionNameForTracing: "adapted members"));
}
if ((viewType & PSMemberViewTypes.Base) == PSMemberViewTypes.Base)
{
returnValue.Add(new CollectionEntry<PSMemberInfo>(
PSObject.DotNetGetMembersDelegate<PSMemberInfo>,
PSObject.DotNetGetMemberDelegate<PSMemberInfo>,
PSObject.DotNetGetFirstMemberOrDefaultDelegate<PSMemberInfo>,
shouldReplicateWhenReturning: false,
shouldCloneWhenReturning: false,
collectionNameForTracing: "clr members"));
}
return returnValue;
}
private static Collection<CollectionEntry<PSMethodInfo>> GetMethodCollection()
{
Collection<CollectionEntry<PSMethodInfo>> returnValue = new Collection<CollectionEntry<PSMethodInfo>>
{
new CollectionEntry<PSMethodInfo>(
PSObject.TypeTableGetMembersDelegate<PSMethodInfo>,
PSObject.TypeTableGetMemberDelegate<PSMethodInfo>,
PSObject.TypeTableGetFirstMemberOrDefaultDelegate<PSMethodInfo>,
shouldReplicateWhenReturning: true,
shouldCloneWhenReturning: true,
collectionNameForTracing: "type table members"),
new CollectionEntry<PSMethodInfo>(
PSObject.AdapterGetMembersDelegate<PSMethodInfo>,
PSObject.AdapterGetMemberDelegate<PSMethodInfo>,
PSObject.AdapterGetFirstMemberOrDefaultDelegate<PSMethodInfo>,
shouldReplicateWhenReturning: false,
shouldCloneWhenReturning: false,
collectionNameForTracing: "adapted members"),
new CollectionEntry<PSMethodInfo>(
PSObject.DotNetGetMembersDelegate<PSMethodInfo>,
PSObject.DotNetGetMemberDelegate<PSMethodInfo>,
PSObject.DotNetGetFirstMemberOrDefaultDelegate<PSMethodInfo>,
shouldReplicateWhenReturning: false,
shouldCloneWhenReturning: false,
collectionNameForTracing: "clr members")
};
return returnValue;
}
/// <summary>
/// A collection of delegates to get Extended/Adapted/Dotnet properties based on the
/// <paramref name="viewType"/>
/// </summary>
/// <param name="viewType">
/// A filter to select Extended/Adapted/Dotnet view of the object
/// </param>
/// <returns></returns>
internal static Collection<CollectionEntry<PSPropertyInfo>> GetPropertyCollection(
PSMemberViewTypes viewType)
{
return GetPropertyCollection(viewType, null);
}
/// <summary>
/// A collection of delegates to get Extended/Adapted/Dotnet properties based on the
/// <paramref name="viewType"/>
/// </summary>
/// <param name="viewType">
/// A filter to select Extended/Adapted/Dotnet view of the object
/// </param>
/// <param name="backupTypeTable">
/// Backup type table to use if there is no execution context associated with the current thread
/// </param>
/// <returns></returns>
internal static Collection<CollectionEntry<PSPropertyInfo>> GetPropertyCollection(
PSMemberViewTypes viewType,
TypeTable backupTypeTable)
{
Collection<CollectionEntry<PSPropertyInfo>> returnValue = new Collection<CollectionEntry<PSPropertyInfo>>();
if ((viewType & PSMemberViewTypes.Extended) == PSMemberViewTypes.Extended)
{
if (backupTypeTable == null)
{
returnValue.Add(new CollectionEntry<PSPropertyInfo>(
PSObject.TypeTableGetMembersDelegate<PSPropertyInfo>,
PSObject.TypeTableGetMemberDelegate<PSPropertyInfo>,
PSObject.TypeTableGetFirstMemberOrDefaultDelegate<PSPropertyInfo>,
true, true, "type table members"));
}
else
{
returnValue.Add(new CollectionEntry<PSPropertyInfo>(
msjObj => TypeTableGetMembersDelegate<PSPropertyInfo>(msjObj, backupTypeTable),
(msjObj, name) => TypeTableGetMemberDelegate<PSPropertyInfo>(msjObj, backupTypeTable, name),
PSObject.TypeTableGetFirstMemberOrDefaultDelegate<PSPropertyInfo>,
true, true, "type table members"));
}
}
if ((viewType & PSMemberViewTypes.Adapted) == PSMemberViewTypes.Adapted)
{
returnValue.Add(new CollectionEntry<PSPropertyInfo>(
PSObject.AdapterGetMembersDelegate<PSPropertyInfo>,
PSObject.AdapterGetMemberDelegate<PSPropertyInfo>,
PSObject.AdapterGetFirstMemberOrDefaultDelegate<PSPropertyInfo>,
false, false, "adapted members"));
}
if ((viewType & PSMemberViewTypes.Base) == PSMemberViewTypes.Base)
{
returnValue.Add(new CollectionEntry<PSPropertyInfo>(
PSObject.DotNetGetMembersDelegate<PSPropertyInfo>,
PSObject.DotNetGetMemberDelegate<PSPropertyInfo>,
PSObject.DotNetGetFirstMemberOrDefaultDelegate<PSPropertyInfo>,
false, false, "clr members"));
}
return returnValue;
}
private void CommonInitialization(object obj)
{
Diagnostics.Assert(obj != null, "checked by callers");
if (obj is PSCustomObject)
{
this.ImmediateBaseObjectIsEmpty = true;
}
_immediateBaseObject = obj;
var context = LocalPipeline.GetExecutionContextFromTLS();
_typeTable = context?.TypeTableWeakReference;
}
#region Adapter Mappings
private static readonly ConcurrentDictionary<Type, AdapterSet> s_adapterMapping = new ConcurrentDictionary<Type, AdapterSet>();
private static readonly List<Func<object, AdapterSet>> s_adapterSetMappers = new List<Func<object, AdapterSet>>
{
MappedInternalAdapterSet
};
private static AdapterSet MappedInternalAdapterSet(object obj)
{
if (obj is PSMemberSet) { return PSObject.s_mshMemberSetAdapter; }
if (obj is PSObject) { return PSObject.s_mshObjectAdapter; }
if (obj is CimInstance) { return PSObject.s_cimInstanceAdapter; }
#if !UNIX
if (obj is ManagementClass) { return PSObject.s_managementClassAdapter; }
if (obj is ManagementBaseObject) { return PSObject.s_managementObjectAdapter; }
if (obj is DirectoryEntry) { return PSObject.s_directoryEntryAdapter; }
#endif
if (obj is DataRowView) { return PSObject.s_dataRowViewAdapter; }
if (obj is DataRow) { return PSObject.s_dataRowAdapter; }
if (obj is XmlNode) { return PSObject.s_xmlNodeAdapter; }
return null;
}
/// <summary>
/// Returns the adapter corresponding to obj.GetType()
/// </summary>
/// <returns>The adapter set corresponding to obj.GetType().</returns>
internal static AdapterSet GetMappedAdapter(object obj, TypeTable typeTable)
{
Type objectType = obj.GetType();
PSObject.AdapterSet adapter = typeTable?.GetTypeAdapter(objectType);
if (adapter != null)
{
// We don't cache results found via the type table because type tables may differ b/w runspaces,
// our cache is app domain wide, and the key is simply the type.
return adapter;
}
if (s_adapterMapping.TryGetValue(objectType, out AdapterSet result))
{
return result;
}
lock (s_adapterSetMappers)
{
foreach (var mapper in s_adapterSetMappers)
{
result = mapper(obj);
if (result != null)
{
break;
}
}
}
if (result == null)
{
if (objectType.IsCOMObject)
{
// All WinRT types are COM types.
// All WinRT types would contain the TypeAttributes flag being set to WindowsRunTime.
if (WinRTHelper.IsWinRTType(objectType))
{
result = PSObject.s_dotNetInstanceAdapterSet;
}
// We are not using IsAssignableFrom because we want to avoid
// using the COM adapters for Primary Interop Assembly types
// and they derive from System.__ComObject.
// We are not using Type.Equals because System.__ComObject is
// not public.
else if (objectType.FullName.Equals("System.__ComObject"))
{
// We don't cache the adapter set for COM objects because the adapter varies depending on the COM object, but often
// (typically), the runtime type is always the same. That's why this if statement is here and returns.
ComTypeInfo info = ComTypeInfo.GetDispatchTypeInfo(obj);
return info != null
? new AdapterSet(new ComAdapter(info), DotNetInstanceAdapter)
: PSObject.s_dotNetInstanceAdapterSet;
}
else
{
ComTypeInfo info = ComTypeInfo.GetDispatchTypeInfo(obj);
result = info != null
? new AdapterSet(new DotNetAdapterWithComTypeName(info), null)
: PSObject.s_dotNetInstanceAdapterSet;
}
}
else
{
result = PSObject.s_dotNetInstanceAdapterSet;
}
}
var existingOrNew = s_adapterMapping.GetOrAdd(objectType, result);
Diagnostics.Assert(existingOrNew == result, "There is a logic error in caching adapter sets.");
return result;
}
#endregion
internal static AdapterSet CreateThirdPartyAdapterSet(Type adaptedType, PSPropertyAdapter adapter)
{
return new AdapterSet(new ThirdPartyAdapter(adaptedType, adapter), s_baseAdapterForAdaptedObjects);
}
#endregion private to the constructors
/// <summary>
/// Initializes a new instance of PSObject with an PSCustomObject BaseObject.
/// </summary>
public PSObject()
{
CommonInitialization(PSCustomObject.SelfInstance);
}
/// <summary>
/// Initializes a new instance of PSObject with an PSCustomObject BaseObject
/// with an initial capacity for members.
/// </summary>
/// <param name="instanceMemberCapacity">The initial capacity for the instance member collection.</param>
public PSObject(int instanceMemberCapacity) : this()
{
_instanceMembers = new PSMemberInfoInternalCollection<PSMemberInfo>(instanceMemberCapacity);
}
/// <summary>
/// Initializes a new instance of PSObject wrapping obj (accessible through BaseObject).
/// </summary>
/// <param name="obj">Object we are wrapping.</param>
/// <exception cref="ArgumentNullException">If <paramref name="obj"/> is null.</exception>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj", Justification = "This is shipped as part of V1. Retaining this for backward compatibility.")]
public PSObject(object obj)
{
if (obj == null)
{
throw PSTraceSource.NewArgumentNullException("obj");
}
CommonInitialization(obj);
}
/// <summary>
/// Creates a PSObject from an ISerializable context.
/// </summary>
/// <param name="info">Serialization information for this instance.</param>
/// <param name="context">The streaming context for this instance.</param>
protected PSObject(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw PSTraceSource.NewArgumentNullException("info");
}
string serializedData = info.GetValue("CliXml", typeof(string)) as string;
if (serializedData == null)
{
throw PSTraceSource.NewArgumentNullException("info");
}
PSObject result = PSObject.AsPSObject(PSSerializer.Deserialize(serializedData));
CommonInitialization(result.ImmediateBaseObject);
CopyDeserializerFields(source: result, target: this);
}
internal static PSObject ConstructPSObjectFromSerializationInfo(SerializationInfo info, StreamingContext context)
{
return new PSObject(info, context);
}
#endregion constructors
#region fields
#region instance fields
private readonly object _lockObject = new object();
private ConsolidatedString _typeNames;
/// <summary>
/// This is the main field in the class representing
/// the System.Object we are encapsulating.
/// </summary>
private object _immediateBaseObject;
private WeakReference<TypeTable> _typeTable;
private AdapterSet _adapterSet;
private PSMemberInfoInternalCollection<PSMemberInfo> _instanceMembers;
private PSMemberInfoIntegratingCollection<PSMemberInfo> _members;
private PSMemberInfoIntegratingCollection<PSPropertyInfo> _properties;
private PSMemberInfoIntegratingCollection<PSMethodInfo> _methods;
private PSObjectFlags _flags;
#endregion instance fields
private static readonly PSTraceSource s_memberResolution = PSTraceSource.GetTracer("MemberResolution", "Traces the resolution from member name to the member. A member can be a property, method, etc.", false);
private static readonly ConditionalWeakTable<object, ConsolidatedString> s_typeNamesResurrectionTable = new ConditionalWeakTable<object, ConsolidatedString>();
private static readonly Collection<CollectionEntry<PSMemberInfo>> s_memberCollection = GetMemberCollection(PSMemberViewTypes.All);
private static readonly Collection<CollectionEntry<PSMethodInfo>> s_methodCollection = GetMethodCollection();
private static readonly Collection<CollectionEntry<PSPropertyInfo>> s_propertyCollection = GetPropertyCollection(PSMemberViewTypes.All);
private static readonly DotNetAdapter s_dotNetInstanceAdapter = new DotNetAdapter();
private static readonly DotNetAdapter s_baseAdapterForAdaptedObjects = new BaseDotNetAdapterForAdaptedObjects();
private static readonly DotNetAdapter s_dotNetStaticAdapter = new DotNetAdapter(true);
private static readonly AdapterSet s_dotNetInstanceAdapterSet = new AdapterSet(DotNetInstanceAdapter, null);
private static readonly AdapterSet s_mshMemberSetAdapter = new AdapterSet(new PSMemberSetAdapter(), null);
private static readonly AdapterSet s_mshObjectAdapter = new AdapterSet(new PSObjectAdapter(), null);
private static readonly PSObject.AdapterSet s_cimInstanceAdapter =
new PSObject.AdapterSet(new ThirdPartyAdapter(typeof(Microsoft.Management.Infrastructure.CimInstance),
new Microsoft.PowerShell.Cim.CimInstanceAdapter()),
PSObject.DotNetInstanceAdapter);
#if !UNIX
private static readonly AdapterSet s_managementObjectAdapter = new AdapterSet(new ManagementObjectAdapter(), DotNetInstanceAdapter);
private static readonly AdapterSet s_managementClassAdapter = new AdapterSet(new ManagementClassApdapter(), DotNetInstanceAdapter);
private static readonly AdapterSet s_directoryEntryAdapter = new AdapterSet(new DirectoryEntryAdapter(), DotNetInstanceAdapter);
#endif
private static readonly AdapterSet s_dataRowViewAdapter = new AdapterSet(new DataRowViewAdapter(), s_baseAdapterForAdaptedObjects);
private static readonly AdapterSet s_dataRowAdapter = new AdapterSet(new DataRowAdapter(), s_baseAdapterForAdaptedObjects);
private static readonly AdapterSet s_xmlNodeAdapter = new AdapterSet(new XmlNodeAdapter(), s_baseAdapterForAdaptedObjects);
#endregion fields
#region properties
internal PSMemberInfoInternalCollection<PSMemberInfo> InstanceMembers
{
get
{
if (_instanceMembers == null)
{
lock (_lockObject)
{
if (_instanceMembers == null)
{
_instanceMembers =
s_instanceMembersResurrectionTable.GetValue(
GetKeyForResurrectionTables(this),
_ => new PSMemberInfoInternalCollection<PSMemberInfo>());
}
}
}
return _instanceMembers;
}
set => _instanceMembers = value;
}
/// <summary>
/// This is the adapter that will depend on the type of baseObject.
/// </summary>
internal Adapter InternalAdapter => InternalAdapterSet.OriginalAdapter;
/// <summary>
/// This is the adapter that is used to resolve the base dotnet members for an
/// adapted object. If an object is not adapted, this will be null.
/// </summary>
/// <remarks>
/// If an object is not adapted, InternalAdapter will use the dotnet adapter.
/// So there is no point falling back to the same dotnet adapter.
///
/// If an object is adapted, this adapter will be used to resolve the dotnet
/// members.
/// </remarks>
internal Adapter InternalBaseDotNetAdapter => InternalAdapterSet.DotNetAdapter;
/// <summary>
/// This is the adapter set that will contain the adapter of the baseObject
/// and the ultimate .net member lookup adapter.
/// See <see cref="PSObject.AdapterSet"/> for explanation.
/// </summary>
private AdapterSet InternalAdapterSet
{
get
{
if (_adapterSet == null)
{
lock (_lockObject)
{
if (_adapterSet == null)
{
_adapterSet = GetMappedAdapter(_immediateBaseObject, GetTypeTable());
}
}
}
return _adapterSet;
}
}
/// <summary>
/// Gets the member collection.
/// </summary>
public PSMemberInfoCollection<PSMemberInfo> Members
{
get
{
if (_members == null)
{
lock (_lockObject)
{
if (_members == null)
{
_members = new PSMemberInfoIntegratingCollection<PSMemberInfo>(this, s_memberCollection);
}
}
}
return _members;
}
}
/// <summary>
/// Gets the Property collection, or the members that are actually properties.
/// </summary>
public PSMemberInfoCollection<PSPropertyInfo> Properties
{
get
{
if (_properties == null)
{
lock (_lockObject)
{
if (_properties == null)
{
_properties = new PSMemberInfoIntegratingCollection<PSPropertyInfo>(this, s_propertyCollection);
}
}
}
return _properties;
}
}
/// <summary>
/// Gets the Method collection, or the members that are actually methods.
/// </summary>
public PSMemberInfoCollection<PSMethodInfo> Methods
{
get
{
if (_methods == null)
{
lock (_lockObject)
{
if (_methods == null)
{
_methods = new PSMemberInfoIntegratingCollection<PSMethodInfo>(this, s_methodCollection);
}
}
}
return _methods;
}
}
/// <summary>
/// Gets the object we are directly wrapping.
/// </summary>
/// <remarks>If the ImmediateBaseObject is another PSObject,
/// that PSObject will be returned.</remarks>
public object ImmediateBaseObject => _immediateBaseObject;
/// <summary>
/// Gets the object we are wrapping.
/// </summary>
/// <remarks>If the ImmediateBaseObject is another PSObject, this property
/// will return its BaseObject.</remarks>
public object BaseObject
{
get
{
object returnValue;
PSObject mshObj = this;
do
{
returnValue = mshObj._immediateBaseObject;
mshObj = returnValue as PSObject;
} while (mshObj != null);
return returnValue;
}
}
/// <summary>
/// Gets the type names collection initially containing the object type hierarchy.
/// </summary>
public Collection<string> TypeNames
{
get
{
var result = InternalTypeNames;
if (result.IsReadOnly)
{
lock (_lockObject)
{
// Check again after acquiring the lock to ensure some other thread didn't make the copy.
if (result.IsReadOnly)
{
_typeNames = s_typeNamesResurrectionTable.GetValue(
GetKeyForResurrectionTables(this),
_ => new ConsolidatedString(_typeNames));
object baseObj = BaseObject;
// In most cases, the TypeNames will be modified after it's returned
if (baseObj != null) { PSVariableAssignmentBinder.NoteTypeHasInstanceMemberOrTypeName(baseObj.GetType()); }
return _typeNames;
}
}
}
return result;
}
}
internal ConsolidatedString InternalTypeNames
{
get
{
if (_typeNames == null)
{
lock (_lockObject)
{
if (_typeNames == null)
{
if (!s_typeNamesResurrectionTable.TryGetValue(GetKeyForResurrectionTables(this), out _typeNames))
{
// We don't cache this typename in the resurrection table because it's cached in the psobject,
// and the assumption is we'll usually get the value directly from the PSObject, so it's not
// needed in the resurrection table.
//
// If we hand out the typename to a client that could change it (through the public property
// TypeNames), then we'll need to store the copy in the resurrection table.
_typeNames = InternalAdapter.BaseGetTypeNameHierarchy(_immediateBaseObject);
}
}
}
}
return _typeNames;
}
set => _typeNames = value;
}
internal static ConsolidatedString GetTypeNames(object obj)
{
if (obj is PSObject psobj)
{
return psobj.InternalTypeNames;
}
if (HasInstanceTypeName(obj, out ConsolidatedString result))
{
return result;
}
return PSObject.GetMappedAdapter(obj, null).OriginalAdapter.BaseGetTypeNameHierarchy(obj);
}
internal static bool HasInstanceTypeName(object obj, out ConsolidatedString result)
{
return s_typeNamesResurrectionTable.TryGetValue(GetKeyForResurrectionTables(obj), out result);
}
#endregion properties
#region static methods
internal static bool HasInstanceMembers(object obj, out PSMemberInfoInternalCollection<PSMemberInfo> instanceMembers)
{
if (obj is PSObject psobj)
{
lock (psobj)
{
if (psobj._instanceMembers == null)
{
s_instanceMembersResurrectionTable.TryGetValue(GetKeyForResurrectionTables(psobj), out psobj._instanceMembers);
}
}
instanceMembers = psobj._instanceMembers;
}
else if (obj != null)
{
s_instanceMembersResurrectionTable.TryGetValue(GetKeyForResurrectionTables(obj), out instanceMembers);
}
else
{
instanceMembers = null;
}
return instanceMembers != null && instanceMembers.Count > 0;
}
private static readonly ConditionalWeakTable<object, PSMemberInfoInternalCollection<PSMemberInfo>> s_instanceMembersResurrectionTable =
new ConditionalWeakTable<object, PSMemberInfoInternalCollection<PSMemberInfo>>();
/// <summary>
/// </summary>
/// <param name="valueToConvert"></param>
/// <returns></returns>
public static implicit operator PSObject(int valueToConvert)
{
return PSObject.AsPSObject(valueToConvert);
}
/// <summary>
/// </summary>
/// <param name="valueToConvert"></param>
/// <returns></returns>
public static implicit operator PSObject(string valueToConvert)
{
return PSObject.AsPSObject(valueToConvert);
}
/// <summary>
/// </summary>
/// <param name="valueToConvert"></param>
/// <returns></returns>
public static implicit operator PSObject(Hashtable valueToConvert)
{
return PSObject.AsPSObject(valueToConvert);
}
/// <summary>
/// </summary>
/// <param name="valueToConvert"></param>
/// <returns></returns>
public static implicit operator PSObject(double valueToConvert)
{
return PSObject.AsPSObject(valueToConvert);
}
/// <summary>
/// </summary>
/// <param name="valueToConvert"></param>
/// <returns></returns>
public static implicit operator PSObject(bool valueToConvert)
{
return PSObject.AsPSObject(valueToConvert);
}
/// <summary>
/// If obj is not an PSObject, it is returned. Otherwise, retrieves
/// the first non PSObject or PSObject with CustomBaseObject
/// in the PSObject - BaseObject chain.
/// </summary>
internal static object Base(object obj)
{
PSObject mshObj = obj as PSObject;
if (mshObj == null)
{
return obj;
}
if (mshObj == AutomationNull.Value)
return null;
if (mshObj.ImmediateBaseObjectIsEmpty)
{
return obj;