summaryrefslogtreecommitdiff
path: root/src/mscorlib/src/System/Runtime/InteropServices/TCEAdapterGen/EventProviderWriter.cs
blob: 160a0ab4918b86a07615f79286cc0e79cc8d59fc (plain)
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace System.Runtime.InteropServices.TCEAdapterGen {
    using System.Runtime.InteropServices.ComTypes;
    using ubyte = System.Byte;
    using System;
    using System.Reflection;
    using System.Reflection.Emit;
    using System.Collections;
    using System.Threading;
    using System.Diagnostics;
    using System.Diagnostics.Contracts;
    
    internal class EventProviderWriter
    {
        private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;

        private readonly Type[] MonitorEnterParamTypes = new Type[] { typeof(Object), Type.GetType("System.Boolean&") };
        
        public EventProviderWriter( ModuleBuilder OutputModule, String strDestTypeName, Type EventItfType, Type SrcItfType, Type SinkHelperType )
        {
            m_OutputModule = OutputModule;  
            m_strDestTypeName = strDestTypeName;
            m_EventItfType = EventItfType;
            m_SrcItfType = SrcItfType;
            m_SinkHelperType = SinkHelperType;
        }
        
        public Type Perform()
        {       
            // Create the event provider class.
            TypeBuilder OutputTypeBuilder = m_OutputModule.DefineType(
                m_strDestTypeName,
                TypeAttributes.Sealed | TypeAttributes.NotPublic, 
                typeof(Object),
                new Type[]{m_EventItfType, typeof(IDisposable)}
                );

            // Create the event source field.
            FieldBuilder fbCPC = OutputTypeBuilder.DefineField( 
                "m_ConnectionPointContainer", 
                typeof(IConnectionPointContainer), 
                FieldAttributes.Private
                );
            
            // Create array of event sink helpers.
            FieldBuilder fbSinkHelper = OutputTypeBuilder.DefineField( 
                "m_aEventSinkHelpers", 
                typeof(ArrayList), 
                FieldAttributes.Private
                );
            
            // Define the connection point field.
            FieldBuilder fbEventCP = OutputTypeBuilder.DefineField( 
                "m_ConnectionPoint", 
                typeof(IConnectionPoint),
                FieldAttributes.Private
                );
            
            // Define the InitXXX method.
            MethodBuilder InitSrcItfMethodBuilder = 
                DefineInitSrcItfMethod( OutputTypeBuilder, m_SrcItfType, fbSinkHelper, fbEventCP, fbCPC );

            // Process all the methods in the event interface.
            MethodInfo[] aMethods = TCEAdapterGenerator.GetNonPropertyMethods(m_SrcItfType);
            for ( int cMethods = 0; cMethods < aMethods.Length; cMethods++ )
            {
                if ( m_SrcItfType == aMethods[cMethods].DeclaringType )
                {
                    // Define the add_XXX method.
                    MethodBuilder AddEventMethodBuilder = DefineAddEventMethod( 
                        OutputTypeBuilder, aMethods[cMethods], m_SinkHelperType, fbSinkHelper, fbEventCP, InitSrcItfMethodBuilder );
                    
                    // Define the remove_XXX method.
                    MethodBuilder RemoveEventMethodBuilder = DefineRemoveEventMethod( 
                        OutputTypeBuilder, aMethods[cMethods], m_SinkHelperType, fbSinkHelper, fbEventCP );
                }
            }
            
            // Define the constructor.
            DefineConstructor( OutputTypeBuilder, fbCPC );
            
            // Define the finalize method.
            MethodBuilder FinalizeMethod = DefineFinalizeMethod( OutputTypeBuilder, m_SinkHelperType, fbSinkHelper, fbEventCP );
            
            // Define the Dispose method.
            DefineDisposeMethod( OutputTypeBuilder, FinalizeMethod);

            return OutputTypeBuilder.CreateType();
        }
        
        private MethodBuilder DefineAddEventMethod( TypeBuilder OutputTypeBuilder, MethodInfo SrcItfMethod, Type SinkHelperClass, FieldBuilder fbSinkHelperArray, FieldBuilder fbEventCP, MethodBuilder mbInitSrcItf )
        {
            Type[] aParamTypes;
            
            // Find the delegate on the event sink helper.
            FieldInfo DelegateField = SinkHelperClass.GetField( "m_" + SrcItfMethod.Name + "Delegate" );
            Debug.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper");
            
            // Find the cookie on the event sink helper.
            FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" );
            Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
            
            // Retrieve the sink helper's constructor.
            ConstructorInfo SinkHelperCons = SinkHelperClass.GetConstructor(EventProviderWriter.DefaultLookup | BindingFlags.NonPublic, null, Array.Empty<Type>(), null );    
            Debug.Assert(SinkHelperCons != null, "Unable to find the constructor for the sink helper");
            
            // Retrieve the IConnectionPoint.Advise method.
            MethodInfo CPAdviseMethod = typeof(IConnectionPoint).GetMethod( "Advise" );
            Debug.Assert(CPAdviseMethod != null, "Unable to find the method ConnectionPoint.Advise");
           
            // Retrieve the ArrayList.Add method.
            aParamTypes = new Type[1];
            aParamTypes[0] = typeof(Object);
            MethodInfo ArrayListAddMethod = typeof(ArrayList).GetMethod( "Add", aParamTypes, null );
            Debug.Assert(ArrayListAddMethod != null, "Unable to find the method ArrayList.Add");

            // Retrieve the Monitor.Enter() method.
            MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod( "Enter", MonitorEnterParamTypes, null );
            Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
            
            // Retrieve the Monitor.Exit() method.
            aParamTypes[0] = typeof(Object);
            MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null );
            Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
            
            // Define the add_XXX method.
            Type[] parameterTypes;
            parameterTypes = new Type[1];
            parameterTypes[0] = DelegateField.FieldType;
            MethodBuilder Meth = OutputTypeBuilder.DefineMethod(
                "add_" + SrcItfMethod.Name,
                MethodAttributes.Public | MethodAttributes.Virtual,
                null,
                parameterTypes );
            
            ILGenerator il = Meth.GetILGenerator();
            
            // Define a label for the m_IFooEventsCP comparision.
            Label EventCPNonNullLabel = il.DefineLabel();
            
            // Declare the local variables.
            LocalBuilder ltSinkHelper = il.DeclareLocal( SinkHelperClass );
            LocalBuilder ltCookie = il.DeclareLocal( typeof(Int32) );
            LocalBuilder ltLockTaken = il.DeclareLocal( typeof(bool) );

            // Generate the following code:
            //   try {
            il.BeginExceptionBlock();

            // Generate the following code:
            //   Monitor.Enter(this, ref lockTaken);
            il.Emit(OpCodes.Ldarg, (short)0);
            il.Emit(OpCodes.Ldloca_S, ltLockTaken);
            il.Emit(OpCodes.Call, MonitorEnterMethod);

            // Generate the following code:
            //   if ( m_IFooEventsCP != null ) goto EventCPNonNullLabel;
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Ldfld, fbEventCP );
            il.Emit( OpCodes.Brtrue, EventCPNonNullLabel );
            
            // Generate the following code:
            //   InitIFooEvents();
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Call, mbInitSrcItf );
            
            // Mark this as label to jump to if the CP is not null.
            il.MarkLabel( EventCPNonNullLabel );
            
            // Generate the following code:
            //   IFooEvents_SinkHelper SinkHelper = new IFooEvents_SinkHelper;  
            il.Emit( OpCodes.Newobj, SinkHelperCons );
            il.Emit( OpCodes.Stloc, ltSinkHelper );
            
            // Generate the following code:
            //   dwCookie = 0;
            il.Emit( OpCodes.Ldc_I4_0 );
            il.Emit( OpCodes.Stloc, ltCookie );
            
            // Generate the following code:
            //   m_IFooEventsCP.Advise( SinkHelper, dwCookie );
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Ldfld, fbEventCP );
            il.Emit( OpCodes.Ldloc, ltSinkHelper );
            il.Emit( OpCodes.Castclass, typeof(Object) );
            il.Emit( OpCodes.Ldloca, ltCookie );
            il.Emit( OpCodes.Callvirt, CPAdviseMethod );
            
            // Generate the following code:
            //   SinkHelper.m_dwCookie = dwCookie;
            il.Emit( OpCodes.Ldloc, ltSinkHelper );
            il.Emit( OpCodes.Ldloc, ltCookie );
            il.Emit( OpCodes.Stfld, CookieField );
            
            // Generate the following code:
            //   SinkHelper.m_FooDelegate = d;
            il.Emit( OpCodes.Ldloc, ltSinkHelper );
            il.Emit( OpCodes.Ldarg, (short)1 );
            il.Emit( OpCodes.Stfld, DelegateField );
            
            // Generate the following code:
            //   m_aIFooEventsHelpers.Add( SinkHelper );
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Ldfld, fbSinkHelperArray );
            il.Emit( OpCodes.Ldloc, ltSinkHelper );
            il.Emit( OpCodes.Castclass, typeof(Object) );
            il.Emit( OpCodes.Callvirt, ArrayListAddMethod );
            il.Emit( OpCodes.Pop );
            
            // Generate the following code:
            //   } finally {
            il.BeginFinallyBlock();

            // Generate the following code:
            //   if (lockTaken)
            //      Monitor.Exit(this);
            Label skipExit = il.DefineLabel();
            il.Emit( OpCodes.Ldloc, ltLockTaken );
            il.Emit( OpCodes.Brfalse_S, skipExit );
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Call, MonitorExitMethod );
            il.MarkLabel(skipExit);

            // Generate the following code:
            //   }
            il.EndExceptionBlock();            

            // Generate the return opcode.
            il.Emit( OpCodes.Ret );
            
            return Meth;
        }
        
        private MethodBuilder DefineRemoveEventMethod( TypeBuilder OutputTypeBuilder, MethodInfo SrcItfMethod, Type SinkHelperClass, FieldBuilder fbSinkHelperArray, FieldBuilder fbEventCP )
        {
            Type[] aParamTypes;
            
            // Find the delegate on the event sink helper.
            FieldInfo DelegateField = SinkHelperClass.GetField( "m_" + SrcItfMethod.Name + "Delegate" );
            Debug.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper");
            
            // Find the cookie on the event sink helper.
            FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" );
            Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
            
            // Retrieve the ArrayList.RemoveAt method.
            aParamTypes = new Type[1];
            aParamTypes[0] = typeof(Int32);
            MethodInfo ArrayListRemoveMethod = typeof(ArrayList).GetMethod( "RemoveAt", aParamTypes, null );
            Debug.Assert(ArrayListRemoveMethod != null, "Unable to find the method ArrayList.RemoveAt()");
            
            // Retrieve the ArrayList.Item property get method.
            PropertyInfo ArrayListItemProperty = typeof(ArrayList).GetProperty( "Item" );
            Debug.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item");
            MethodInfo ArrayListItemGetMethod = ArrayListItemProperty.GetGetMethod();
            Debug.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item");
            
            // Retrieve the ArrayList.Count property get method.
            PropertyInfo ArrayListSizeProperty = typeof(ArrayList).GetProperty( "Count" );
            Debug.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count");
            MethodInfo ArrayListSizeGetMethod = ArrayListSizeProperty.GetGetMethod();
            Debug.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count");
            
            // Retrieve the Delegate.Equals() method.
            aParamTypes[0] = typeof(Delegate);
            MethodInfo DelegateEqualsMethod = typeof(Delegate).GetMethod( "Equals", aParamTypes, null );
            Debug.Assert(DelegateEqualsMethod != null, "Unable to find the method Delegate.Equlals()");

            // Retrieve the Monitor.Enter() method.
            MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod("Enter", MonitorEnterParamTypes, null);
            Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
            
            // Retrieve the Monitor.Exit() method.
            aParamTypes[0] = typeof(Object);
            MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null );
            Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
            
            // Retrieve the ConnectionPoint.Unadvise() method.
            MethodInfo CPUnadviseMethod = typeof(IConnectionPoint).GetMethod( "Unadvise" );
            Debug.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()");
            
            // Retrieve the Marshal.ReleaseComObject() method.
            MethodInfo ReleaseComObjectMethod = typeof(Marshal).GetMethod( "ReleaseComObject" );
            Debug.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()");
            
            // Define the remove_XXX method.
            Type[] parameterTypes;
            parameterTypes = new Type[1];
            parameterTypes[0] = DelegateField.FieldType;
            MethodBuilder Meth = OutputTypeBuilder.DefineMethod(
                "remove_" + SrcItfMethod.Name,
                MethodAttributes.Public | MethodAttributes.Virtual,
                null,
                parameterTypes );
            
            ILGenerator il = Meth.GetILGenerator();
            
            // Declare the local variables.
            LocalBuilder ltNumSinkHelpers = il.DeclareLocal( typeof(Int32) );
            LocalBuilder ltSinkHelperCounter = il.DeclareLocal( typeof(Int32) );
            LocalBuilder ltCurrSinkHelper = il.DeclareLocal( SinkHelperClass );
            LocalBuilder ltLockTaken = il.DeclareLocal(typeof(bool));
            
            // Generate the labels for the for loop.
            Label ForBeginLabel = il.DefineLabel();
            Label ForEndLabel = il.DefineLabel();
            Label FalseIfLabel = il.DefineLabel();
            Label MonitorExitLabel = il.DefineLabel();
            
            // Generate the following code:
            //   try {
            il.BeginExceptionBlock();

            // Generate the following code:
            //   Monitor.Enter(this, ref lockTaken);
            il.Emit(OpCodes.Ldarg, (short)0);
            il.Emit(OpCodes.Ldloca_S, ltLockTaken);
            il.Emit(OpCodes.Call, MonitorEnterMethod);

            // Generate the following code:
            //   if ( m_aIFooEventsHelpers == null ) goto ForEndLabel;        
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Ldfld, fbSinkHelperArray );
            il.Emit( OpCodes.Brfalse, ForEndLabel );

            // Generate the following code:
            //   int NumEventHelpers = m_aIFooEventsHelpers.Count;
            //   int cEventHelpers = 0;
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Ldfld, fbSinkHelperArray );
            il.Emit( OpCodes.Callvirt, ArrayListSizeGetMethod );
            il.Emit( OpCodes.Stloc, ltNumSinkHelpers );
            il.Emit( OpCodes.Ldc_I4, 0 );
            il.Emit( OpCodes.Stloc, ltSinkHelperCounter );
            
            // Generate the following code:
            //   if ( 0 >= NumEventHelpers ) goto ForEndLabel;        
            il.Emit( OpCodes.Ldc_I4, 0 );
            il.Emit( OpCodes.Ldloc, ltNumSinkHelpers );
            il.Emit( OpCodes.Bge, ForEndLabel );
            
            // Mark this as the beginning of the for loop's body.
            il.MarkLabel( ForBeginLabel );
            
            // Generate the following code:
            //   CurrentHelper = (IFooEvents_SinkHelper)m_aIFooEventsHelpers.Get( cEventHelpers );
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Ldfld, fbSinkHelperArray );
            il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
            il.Emit( OpCodes.Callvirt, ArrayListItemGetMethod );
            il.Emit( OpCodes.Castclass, SinkHelperClass );
            il.Emit( OpCodes.Stloc, ltCurrSinkHelper );
            
            // Generate the following code:
            //   if ( CurrentHelper.m_FooDelegate )
            il.Emit( OpCodes.Ldloc, ltCurrSinkHelper );
            il.Emit( OpCodes.Ldfld, DelegateField );
            il.Emit( OpCodes.Ldnull );
            il.Emit( OpCodes.Beq, FalseIfLabel );
            
            // Generate the following code:
            //   if ( CurrentHelper.m_FooDelegate.Equals( d ) )
            il.Emit( OpCodes.Ldloc, ltCurrSinkHelper );
            il.Emit( OpCodes.Ldfld, DelegateField );
            il.Emit( OpCodes.Ldarg, (short)1 );
            il.Emit( OpCodes.Castclass, typeof(Object) );
            il.Emit( OpCodes.Callvirt, DelegateEqualsMethod );
            il.Emit( OpCodes.Ldc_I4, 0xff );
            il.Emit( OpCodes.And );
            il.Emit( OpCodes.Ldc_I4, 0 );
            il.Emit( OpCodes.Beq, FalseIfLabel );
            
            // Generate the following code:
            //   m_aIFooEventsHelpers.RemoveAt( cEventHelpers );
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Ldfld, fbSinkHelperArray );
            il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
            il.Emit( OpCodes.Callvirt, ArrayListRemoveMethod );
            
            // Generate the following code:
            //   m_IFooEventsCP.Unadvise( CurrentHelper.m_dwCookie );
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Ldfld, fbEventCP );
            il.Emit( OpCodes.Ldloc, ltCurrSinkHelper );
            il.Emit( OpCodes.Ldfld, CookieField );
            il.Emit( OpCodes.Callvirt, CPUnadviseMethod );
            
            // Generate the following code:
            //   if ( NumEventHelpers > 1) break;
            il.Emit( OpCodes.Ldloc, ltNumSinkHelpers );
            il.Emit( OpCodes.Ldc_I4, 1 );
            il.Emit( OpCodes.Bgt, ForEndLabel );
                       
            // Generate the following code:
            //   Marshal.ReleaseComObject(m_IFooEventsCP);
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Ldfld, fbEventCP );
            il.Emit( OpCodes.Call, ReleaseComObjectMethod );            
            il.Emit( OpCodes.Pop );

            // Generate the following code:
            //   m_IFooEventsCP = null;
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Ldnull );
            il.Emit( OpCodes.Stfld, fbEventCP );
            
            // Generate the following code:
            //   m_aIFooEventsHelpers = null;      
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Ldnull );
            il.Emit( OpCodes.Stfld, fbSinkHelperArray );
            
            // Generate the following code:
            //   break;
            il.Emit( OpCodes.Br, ForEndLabel );
            
            // Mark this as the label to jump to when the if statement is false.
            il.MarkLabel( FalseIfLabel );       
            
            // Generate the following code:
            //   cEventHelpers++;
            il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
            il.Emit( OpCodes.Ldc_I4, 1 );
            il.Emit( OpCodes.Add );
            il.Emit( OpCodes.Stloc, ltSinkHelperCounter );
            
            // Generate the following code:
            //   if ( cEventHelpers < NumEventHelpers ) goto ForBeginLabel;
            il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
            il.Emit( OpCodes.Ldloc, ltNumSinkHelpers );
            il.Emit( OpCodes.Blt, ForBeginLabel );
            
            // Mark this as the end of the for loop's body.
            il.MarkLabel( ForEndLabel );

            // Generate the following code:
            //   } finally {
            il.BeginFinallyBlock();

            // Generate the following code:
            //   if (lockTaken)
            //      Monitor.Exit(this);
            Label skipExit = il.DefineLabel();
            il.Emit(OpCodes.Ldloc, ltLockTaken);
            il.Emit(OpCodes.Brfalse_S, skipExit);
            il.Emit(OpCodes.Ldarg, (short)0);
            il.Emit(OpCodes.Call, MonitorExitMethod);
            il.MarkLabel(skipExit);

            // Generate the following code:
            //   }
            il.EndExceptionBlock();            

            // Generate the return opcode.
            il.Emit( OpCodes.Ret );
            
            return Meth;
        }

        private MethodBuilder DefineInitSrcItfMethod( TypeBuilder OutputTypeBuilder, Type SourceInterface, FieldBuilder fbSinkHelperArray, FieldBuilder fbEventCP, FieldBuilder fbCPC )
        {
            // Retrieve the constructor info for the array list's default constructor.
            ConstructorInfo DefaultArrayListCons = typeof(ArrayList).GetConstructor(EventProviderWriter.DefaultLookup, null, Array.Empty<Type>(), null );
            Debug.Assert(DefaultArrayListCons != null, "Unable to find the constructor for class ArrayList");    
            
            // Temp byte array for Guid
            ubyte[] rgByteGuid = new ubyte[16];
            
            // Retrieve the constructor info for the Guid constructor.
            Type[] aParamTypes = new Type[1];
            aParamTypes[0] = typeof(Byte[]);
            ConstructorInfo ByteArrayGUIDCons = typeof(Guid).GetConstructor(EventProviderWriter.DefaultLookup, null, aParamTypes, null );
            Debug.Assert(ByteArrayGUIDCons != null, "Unable to find the constructor for GUID that accepts a string as argument");    
            
            // Retrieve the IConnectionPointContainer.FindConnectionPoint() method.
            MethodInfo CPCFindCPMethod = typeof(IConnectionPointContainer).GetMethod( "FindConnectionPoint" );
            Debug.Assert(CPCFindCPMethod != null, "Unable to find the method ConnectionPointContainer.FindConnectionPoint()");    
            
            // Define the Init method itself.
            MethodBuilder Meth = OutputTypeBuilder.DefineMethod(
                "Init", 
                MethodAttributes.Private, 
                null, 
                null );
            
            ILGenerator il = Meth.GetILGenerator();
            
            // Declare the local variables.
            LocalBuilder ltCP = il.DeclareLocal( typeof(IConnectionPoint) );
            LocalBuilder ltEvGuid = il.DeclareLocal( typeof(Guid) );
            LocalBuilder ltByteArrayGuid = il.DeclareLocal( typeof(Byte[]) );
            
            // Generate the following code:
            //   IConnectionPoint CP = NULL;
            il.Emit( OpCodes.Ldnull );
            il.Emit( OpCodes.Stloc, ltCP );
            
            // Get unsigned byte array for the GUID of the event interface.
            rgByteGuid = SourceInterface.GUID.ToByteArray();
            
            // Generate the following code:
            //  ubyte rgByteArray[] = new ubyte [16];
            il.Emit( OpCodes.Ldc_I4, 0x10 );
            il.Emit( OpCodes.Newarr, typeof(Byte) ); 
            il.Emit( OpCodes.Stloc, ltByteArrayGuid );
            
            // Generate the following code:
            //  rgByteArray[i] = rgByteGuid[i];
            for (int i = 0; i < 16; i++ )
            {
                il.Emit( OpCodes.Ldloc, ltByteArrayGuid );
                il.Emit( OpCodes.Ldc_I4, i );
                il.Emit( OpCodes.Ldc_I4, (int) (rgByteGuid[i]) );
                il.Emit( OpCodes.Stelem_I1);
            }
            
            // Generate the following code:
            //   EventItfGuid = Guid( ubyte b[] );          
            il.Emit( OpCodes.Ldloca, ltEvGuid );
            il.Emit( OpCodes.Ldloc, ltByteArrayGuid );
            il.Emit( OpCodes.Call, ByteArrayGUIDCons );
            
            // Generate the following code:
            //   m_ConnectionPointContainer.FindConnectionPoint( EventItfGuid, CP );
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Ldfld, fbCPC );
            il.Emit( OpCodes.Ldloca, ltEvGuid );
            il.Emit( OpCodes.Ldloca, ltCP );
            il.Emit( OpCodes.Callvirt, CPCFindCPMethod );
            
            // Generate the following code:
            //   m_ConnectionPoint = (IConnectionPoint)CP;
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Ldloc, ltCP );
            il.Emit( OpCodes.Castclass, typeof(IConnectionPoint) );
            il.Emit( OpCodes.Stfld, fbEventCP );
            
            // Generate the following code:
            //   m_aEventSinkHelpers = new ArrayList;      
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Newobj, DefaultArrayListCons );
            il.Emit( OpCodes.Stfld, fbSinkHelperArray );   
            
            // Generate the return opcode.
            il.Emit( OpCodes.Ret );
            
            return Meth;
        }
        
        private void DefineConstructor( TypeBuilder OutputTypeBuilder, FieldBuilder fbCPC )
        {
            // Retrieve the constructor info for the base class's constructor.
            ConstructorInfo DefaultBaseClsCons = typeof(Object).GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, Array.Empty<Type>(), null );
            Debug.Assert(DefaultBaseClsCons != null, "Unable to find the object's public default constructor");
            
            // Define the default constructor.
            MethodAttributes ctorAttributes = MethodAttributes.SpecialName | (DefaultBaseClsCons.Attributes & MethodAttributes.MemberAccessMask);
            MethodBuilder Cons = OutputTypeBuilder.DefineMethod( 
                ".ctor", 
                ctorAttributes, 
                null, 
                new Type[]{typeof(Object)} );
            
            ILGenerator il = Cons.GetILGenerator();
            
            // Generate the call to the base class constructor.
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Call, DefaultBaseClsCons );
            
            // Generate the following code:
            //   m_ConnectionPointContainer = (IConnectionPointContainer)EventSource;
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Ldarg, (short)1 );
            il.Emit( OpCodes.Castclass, typeof(IConnectionPointContainer) );
            il.Emit( OpCodes.Stfld, fbCPC );

            // Generate the return opcode.
            il.Emit( OpCodes.Ret );
        }
               
        private MethodBuilder DefineFinalizeMethod( TypeBuilder OutputTypeBuilder, Type SinkHelperClass, FieldBuilder fbSinkHelper, FieldBuilder fbEventCP )
        {
            // Find the cookie on the event sink helper.
            FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" );
            Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");    

            // Retrieve the ArrayList.Item property get method.
            PropertyInfo ArrayListItemProperty = typeof(ArrayList).GetProperty( "Item" );
            Debug.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item");    
            MethodInfo ArrayListItemGetMethod = ArrayListItemProperty.GetGetMethod();
            Debug.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item");    
            
            // Retrieve the ArrayList.Count property get method.
            PropertyInfo ArrayListSizeProperty = typeof(ArrayList).GetProperty( "Count" );
            Debug.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count");    
            MethodInfo ArrayListSizeGetMethod = ArrayListSizeProperty.GetGetMethod();
            Debug.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count");    
            
            // Retrieve the ConnectionPoint.Unadvise() method.
            MethodInfo CPUnadviseMethod = typeof(IConnectionPoint).GetMethod( "Unadvise" );
            Debug.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()");    

            // Retrieve the Marshal.ReleaseComObject() method.
            MethodInfo ReleaseComObjectMethod = typeof(Marshal).GetMethod( "ReleaseComObject" );
            Debug.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()");

            // Retrieve the Monitor.Enter() method.
            MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod("Enter", MonitorEnterParamTypes, null);
            Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
            
            // Retrieve the Monitor.Exit() method.
            Type[] aParamTypes = new Type[1];
            aParamTypes[0] = typeof(Object);
            MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null );
            Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
                        
            // Define the Finalize method itself.
            MethodBuilder Meth = OutputTypeBuilder.DefineMethod( "Finalize", MethodAttributes.Public | MethodAttributes.Virtual, null, null );
            
            ILGenerator il = Meth.GetILGenerator();
            
            // Declare the local variables.
            LocalBuilder ltNumSinkHelpers = il.DeclareLocal( typeof(Int32) );
            LocalBuilder ltSinkHelperCounter = il.DeclareLocal( typeof(Int32) );
            LocalBuilder ltCurrSinkHelper = il.DeclareLocal( SinkHelperClass );
            LocalBuilder ltLockTaken = il.DeclareLocal(typeof(bool));
                        
            // Generate the following code:
            //   try {
            il.BeginExceptionBlock();

            // Generate the following code:
            //   Monitor.Enter(this, ref lockTaken);
            il.Emit(OpCodes.Ldarg, (short)0);
            il.Emit(OpCodes.Ldloca_S, ltLockTaken);
            il.Emit(OpCodes.Call, MonitorEnterMethod);

            // Generate the labels.
            Label ForBeginLabel = il.DefineLabel();
            Label ReleaseComObjectLabel = il.DefineLabel();
            Label AfterReleaseComObjectLabel = il.DefineLabel();

            // Generate the following code:
            //   if ( m_IFooEventsCP == null ) goto AfterReleaseComObjectLabel;        
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Ldfld, fbEventCP );
            il.Emit( OpCodes.Brfalse, AfterReleaseComObjectLabel );

            // Generate the following code:
            //   int NumEventHelpers = m_aIFooEventsHelpers.Count;
            //   int cEventHelpers = 0;
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Ldfld, fbSinkHelper );
            il.Emit( OpCodes.Callvirt, ArrayListSizeGetMethod );
            il.Emit( OpCodes.Stloc, ltNumSinkHelpers );
            il.Emit( OpCodes.Ldc_I4, 0 );
            il.Emit( OpCodes.Stloc, ltSinkHelperCounter );
            
            // Generate the following code:
            //   if ( 0 >= NumEventHelpers ) goto ReleaseComObjectLabel;        
            il.Emit( OpCodes.Ldc_I4, 0 );
            il.Emit( OpCodes.Ldloc, ltNumSinkHelpers );
            il.Emit( OpCodes.Bge, ReleaseComObjectLabel );
            
            // Mark this as the beginning of the for loop's body.
            il.MarkLabel( ForBeginLabel );
            
            // Generate the following code:
            //   CurrentHelper = (IFooEvents_SinkHelper)m_aIFooEventsHelpers.Get( cEventHelpers );
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Ldfld, fbSinkHelper );
            il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
            il.Emit( OpCodes.Callvirt, ArrayListItemGetMethod );
            il.Emit( OpCodes.Castclass, SinkHelperClass );
            il.Emit( OpCodes.Stloc, ltCurrSinkHelper );
            
            // Generate the following code:
            //   m_IFooEventsCP.Unadvise( CurrentHelper.m_dwCookie );
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Ldfld, fbEventCP );
            il.Emit( OpCodes.Ldloc, ltCurrSinkHelper );
            il.Emit( OpCodes.Ldfld, CookieField );
            il.Emit( OpCodes.Callvirt, CPUnadviseMethod );
            
            // Generate the following code:
            //   cEventHelpers++;
            il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
            il.Emit( OpCodes.Ldc_I4, 1 );
            il.Emit( OpCodes.Add );
            il.Emit( OpCodes.Stloc, ltSinkHelperCounter );
            
            // Generate the following code:
            //   if ( cEventHelpers < NumEventHelpers ) goto ForBeginLabel;
            il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
            il.Emit( OpCodes.Ldloc, ltNumSinkHelpers );
            il.Emit( OpCodes.Blt, ForBeginLabel );
            
            // Mark this as the end of the for loop's body.
            il.MarkLabel( ReleaseComObjectLabel );           

            // Generate the following code:
            //   Marshal.ReleaseComObject(m_IFooEventsCP);
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Ldfld, fbEventCP );
            il.Emit( OpCodes.Call, ReleaseComObjectMethod );            
            il.Emit( OpCodes.Pop );

            // Mark this as the end of the for loop's body.
            il.MarkLabel( AfterReleaseComObjectLabel );           
            
            // Generate the following code:
            //   } catch {
            il.BeginCatchBlock(typeof(System.Exception));
            il.Emit( OpCodes.Pop );

            // Generate the following code:
            //   } finally {
            il.BeginFinallyBlock();

            // Generate the following code:
            //   if (lockTaken)
            //      Monitor.Exit(this);
            Label skipExit = il.DefineLabel();
            il.Emit(OpCodes.Ldloc, ltLockTaken);
            il.Emit(OpCodes.Brfalse_S, skipExit);
            il.Emit(OpCodes.Ldarg, (short)0);
            il.Emit(OpCodes.Call, MonitorExitMethod);
            il.MarkLabel(skipExit);

            // Generate the following code:
            //   }
            il.EndExceptionBlock();            
            
            // Generate the return opcode.
            il.Emit( OpCodes.Ret );
            
            return Meth;
        }   
        
        private void DefineDisposeMethod( TypeBuilder OutputTypeBuilder, MethodBuilder FinalizeMethod )
        {
            // Retrieve the method info for GC.SuppressFinalize().
            MethodInfo SuppressFinalizeMethod = typeof(GC).GetMethod("SuppressFinalize");
            Debug.Assert(SuppressFinalizeMethod != null, "Unable to find the GC.SuppressFinalize");    
            
            // Define the Finalize method itself.
            MethodBuilder Meth = OutputTypeBuilder.DefineMethod( "Dispose", MethodAttributes.Public | MethodAttributes.Virtual, null, null );
            
            ILGenerator il = Meth.GetILGenerator();
            
            // Generate the following code:
            //   Finalize()
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Callvirt, FinalizeMethod );
            
            // Generate the following code:
            //   GC.SuppressFinalize()
            il.Emit( OpCodes.Ldarg, (short)0 );
            il.Emit( OpCodes.Call, SuppressFinalizeMethod );    
            
            // Generate the return opcode.
            il.Emit( OpCodes.Ret );   
        }      

        private ModuleBuilder m_OutputModule;
        private String m_strDestTypeName;
        private Type m_EventItfType;
        private Type m_SrcItfType;
        private Type m_SinkHelperType;
    }
}