aboutsummaryrefslogtreecommitdiff
path: root/src/WixToolset.Core.WindowsInstaller/PatchAPI/PatchInterop.cs
blob: fcd749d2484acf86f9ceaa3891472b8aa196e16e (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
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
// Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information.

namespace WixToolset.PatchAPI
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.Runtime.InteropServices;
    using WixToolset.Core;

    /// <summary>
    /// Interop class for the mspatchc.dll.
    /// </summary>
    internal static class PatchInterop
    {
        // From WinError.h in the Platform SDK
        internal const ushort FACILITY_WIN32 = 7;

        /// <summary>
        /// Parse a number from text in either hex or decimal.
        /// </summary>
        /// <param name="source">Source value. Treated as hex if it starts 0x (or 0X), decimal otherwise.</param>
        /// <returns>Numeric value that source represents.</returns>
        static internal UInt32 ParseHexOrDecimal(string source)
        {
            string value = source.Trim();
            if (String.Equals(value.Substring(0,2), "0x", StringComparison.OrdinalIgnoreCase))
            {
                return UInt32.Parse(value.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture.NumberFormat);
            }
            else
            {
                return UInt32.Parse(value, CultureInfo.InvariantCulture.NumberFormat);
            }
        }

        /// <summary>
        /// Create a binary delta file.
        /// </summary>
        /// <param name="deltaFile">Name of the delta file to create.</param>
        /// <param name="targetFile">Name of updated file.</param>
        /// <param name="targetSymbolPath">Optional paths to updated file's symbols.</param>
        /// <param name="targetRetainOffsets">Optional offsets to the delta retain sections in the updated file.</param>
        /// <param name="basisFiles">Optional array of target files.</param>
        /// <param name="basisSymbolPaths">Optional array of target files' symbol paths (must match basisFiles array).</param>
        /// <param name="basisIgnoreLengths">Optional array of target files' delta ignore section lengths (must match basisFiles array)(each entry must match basisIgnoreOffsets entries).</param>
        /// <param name="basisIgnoreOffsets">Optional array of target files' delta ignore section offsets (must match basisFiles array)(each entry must match basisIgnoreLengths entries).</param>
        /// <param name="basisRetainLengths">Optional array of target files' delta protect section lengths (must match basisFiles array)(each entry must match basisRetainOffsets and targetRetainOffsets entries).</param>
        /// <param name="basisRetainOffsets">Optional array of target files' delta protect section offsets (must match basisFiles array)(each entry must match basisRetainLengths and targetRetainOffsets entries).</param>
        /// <param name="apiPatchingSymbolFlags">ApiPatchingSymbolFlags value.</param>
        /// <param name="optimizePatchSizeForLargeFiles">OptimizePatchSizeForLargeFiles value.</param>
        /// <param name="retainRangesIgnored">Flag to indicate retain ranges were ignored due to mismatch.</param>
        /// <returns>true if delta file was created, false if whole file should be used instead.</returns>
        static public bool CreateDelta(
                string deltaFile,
                string targetFile,
                string targetSymbolPath,
                string targetRetainOffsets,
                string[] basisFiles,
                string[] basisSymbolPaths,
                string[] basisIgnoreLengths,
                string[] basisIgnoreOffsets,
                string[] basisRetainLengths,
                string[] basisRetainOffsets,
                PatchSymbolFlagsType apiPatchingSymbolFlags,
                bool optimizePatchSizeForLargeFiles,
                out bool retainRangesIgnored
                )
        {
            retainRangesIgnored = false;
            if (0 != (apiPatchingSymbolFlags & ~(PatchSymbolFlagsType.PATCH_SYMBOL_NO_IMAGEHLP | PatchSymbolFlagsType.PATCH_SYMBOL_NO_FAILURES | PatchSymbolFlagsType.PATCH_SYMBOL_UNDECORATED_TOO)))
            {
                throw new ArgumentOutOfRangeException("apiPatchingSymbolFlags");
            }

            if (null == deltaFile || 0 == deltaFile.Length)
            {
                throw new ArgumentNullException("deltaFile");
            }

            if (null == targetFile || 0 == targetFile.Length)
            {
                throw new ArgumentNullException("targetFile");
            }

            if (null == basisFiles || 0 == basisFiles.Length)
            {
                return false;
            }
            uint countOldFiles = (uint) basisFiles.Length;

            if (null != basisSymbolPaths)
            {
                if (0 != basisSymbolPaths.Length)
                {
                    if ((uint) basisSymbolPaths.Length != countOldFiles)
                    {
                        throw new ArgumentOutOfRangeException("basisSymbolPaths");
                    }
                }
            }
            // a null basisSymbolPaths is allowed.

            if (null != basisIgnoreLengths)
            {
                if (0 != basisIgnoreLengths.Length)
                {
                    if ((uint) basisIgnoreLengths.Length != countOldFiles)
                    {
                        throw new ArgumentOutOfRangeException("basisIgnoreLengths");
                    }
                }
            }
            else
            {
                basisIgnoreLengths = new string[countOldFiles];
            }

            if (null != basisIgnoreOffsets)
            {
                if (0 != basisIgnoreOffsets.Length)
                {
                    if ((uint) basisIgnoreOffsets.Length != countOldFiles)
                    {
                        throw new ArgumentOutOfRangeException("basisIgnoreOffsets");
                    }
                }
            }
            else
            {
                basisIgnoreOffsets = new string[countOldFiles];
            }

            if (null != basisRetainLengths)
            {
                if (0 != basisRetainLengths.Length)
                {
                    if ((uint) basisRetainLengths.Length != countOldFiles)
                    {
                        throw new ArgumentOutOfRangeException("basisRetainLengths");
                    }
                }
            }
            else
            {
                basisRetainLengths = new string[countOldFiles];
            }

            if (null != basisRetainOffsets)
            {
                if (0 != basisRetainOffsets.Length)
                {
                    if ((uint) basisRetainOffsets.Length != countOldFiles)
                    {
                        throw new ArgumentOutOfRangeException("basisRetainOffsets");
                    }
                }
            }
            else
            {
                basisRetainOffsets = new string[countOldFiles];
            }

            PatchOptionData pod = new PatchOptionData();
            pod.symbolOptionFlags = apiPatchingSymbolFlags;
            pod.newFileSymbolPath = targetSymbolPath;
            pod.oldFileSymbolPathArray = basisSymbolPaths;
            pod.extendedOptionFlags = 0;
            PatchOldFileInfoW[] oldFileInfoArray = new PatchOldFileInfoW[countOldFiles];
            string[] newRetainOffsetArray = ((null == targetRetainOffsets) ? new string[0] : targetRetainOffsets.Split(','));
            for (uint i = 0; i < countOldFiles; ++i)
            {
                PatchOldFileInfoW ofi = new PatchOldFileInfoW();
                ofi.oldFileName = basisFiles[i];
                string[] ignoreLengthArray = ((null == basisIgnoreLengths[i]) ? new string[0] : basisIgnoreLengths[i].Split(','));
                string[] ignoreOffsetArray = ((null == basisIgnoreOffsets[i]) ? new string[0] : basisIgnoreOffsets[i].Split(','));
                string[] retainLengthArray = ((null == basisRetainLengths[i]) ? new string[0] : basisRetainLengths[i].Split(','));
                string[] retainOffsetArray = ((null == basisRetainOffsets[i]) ? new string[0] : basisRetainOffsets[i].Split(','));
                // Validate inputs
                if (ignoreLengthArray.Length != ignoreOffsetArray.Length)
                {
                    throw new ArgumentOutOfRangeException("basisIgnoreLengths");
                }

                if (retainLengthArray.Length != retainOffsetArray.Length)
                {
                    throw new ArgumentOutOfRangeException("basisRetainLengths");
                }

                if (newRetainOffsetArray.Length != retainOffsetArray.Length)
                {
                    // remove all retain range information
                    retainRangesIgnored = true;
                    for (uint j = 0; j < countOldFiles; ++j)
                    {
                        basisRetainLengths[j] = null;
                        basisRetainOffsets[j] = null;
                    }
                    retainLengthArray = new string[0];
                    retainOffsetArray = new string[0];
                    newRetainOffsetArray = new string[0];
                    for (uint j = 0; j < oldFileInfoArray.Length; ++j)
                    {
                        oldFileInfoArray[j].retainRange = null;
                    }
                }

                // Populate IgnoreRange structure
                PatchIgnoreRange[] ignoreArray = null;
                if (0 != ignoreLengthArray.Length)
                {
                    ignoreArray = new PatchIgnoreRange[ignoreLengthArray.Length];
                    for (int j = 0; j < ignoreLengthArray.Length; ++j)
                    {
                        PatchIgnoreRange ignoreRange = new PatchIgnoreRange();
                        ignoreRange.offsetInOldFile = ParseHexOrDecimal(ignoreOffsetArray[j]);
                        ignoreRange.lengthInBytes = ParseHexOrDecimal(ignoreLengthArray[j]);
                        ignoreArray[j] = ignoreRange;
                    }
                    ofi.ignoreRange = ignoreArray;
                }

                PatchRetainRange[] retainArray = null;
                if (0 != newRetainOffsetArray.Length)
                {
                    retainArray = new PatchRetainRange[retainLengthArray.Length];
                    for (int j = 0; j < newRetainOffsetArray.Length; ++j)
                    {
                        PatchRetainRange retainRange = new PatchRetainRange();
                        retainRange.offsetInOldFile = ParseHexOrDecimal(retainOffsetArray[j]);
                        retainRange.lengthInBytes = ParseHexOrDecimal(retainLengthArray[j]);
                        retainRange.offsetInNewFile = ParseHexOrDecimal(newRetainOffsetArray[j]);
                        retainArray[j] = retainRange;
                    }
                    ofi.retainRange = retainArray;
                }
                oldFileInfoArray[i] = ofi;
            }

            if (CreatePatchFileExW(
                    countOldFiles,
                    oldFileInfoArray,
                    targetFile,
                    deltaFile,
                    PatchOptionFlags(optimizePatchSizeForLargeFiles),
                    pod,
                    null,
                    IntPtr.Zero))
            {
                return true;
            }

            // determine if this is an error or a need to use whole file.
            int err = Marshal.GetLastWin32Error();
            switch(err)
            {
            case unchecked((int) ERROR_PATCH_BIGGER_THAN_COMPRESSED):
                break;

            // too late to exclude this file -- should have been caught before
            case unchecked((int) ERROR_PATCH_SAME_FILE):
            default:
                throw new System.ComponentModel.Win32Exception(err);
            }
            return false;
        }

        /// <summary>
        /// Extract the delta header.
        /// </summary>
        /// <param name="delta">Name of delta file.</param>
        /// <param name="deltaHeader">Name of file to create with the delta's header.</param>
        static public void ExtractDeltaHeader(string delta, string deltaHeader)
        {
            if (!ExtractPatchHeaderToFileW(delta, deltaHeader))
            {
                throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
            }
        }

        /// <summary>
        /// Returns the PatchOptionFlags to use.
        /// </summary>
        /// <param name="optimizeForLargeFiles">True if optimizing for large files.</param>
        /// <returns>PATCH_OPTION_FLAG values</returns>
        static private UInt32 PatchOptionFlags(bool optimizeForLargeFiles)
        {
            UInt32 flags = PATCH_OPTION_FAIL_IF_SAME_FILE | PATCH_OPTION_FAIL_IF_BIGGER | PATCH_OPTION_USE_LZX_BEST;
            if (optimizeForLargeFiles)
            {
                flags |= PATCH_OPTION_USE_LZX_LARGE;
            }
            return flags;
        }

        //---------------------------------------------------------------------
        // From PatchApi.h
        //---------------------------------------------------------------------

        //
        // The following contants can be combined and used as the OptionFlags
        // parameter in the patch creation apis.

        internal const uint PATCH_OPTION_USE_BEST          = 0x00000000; // auto choose best (slower)

        internal const uint PATCH_OPTION_USE_LZX_BEST      = 0x00000003; // auto choose best of LXZ A/B (but not large)
        internal const uint PATCH_OPTION_USE_LZX_A         = 0x00000001; // normal
        internal const uint PATCH_OPTION_USE_LXZ_B         = 0x00000002; // better on some x86 binaries
        internal const uint PATCH_OPTION_USE_LZX_LARGE     = 0x00000004; // better support for large files (requires 5.1 or higher applyer)

        internal const uint PATCH_OPTION_NO_BINDFIX        = 0x00010000; // PE bound imports
        internal const uint PATCH_OPTION_NO_LOCKFIX        = 0x00020000; // PE smashed locks
        internal const uint PATCH_OPTION_NO_REBASE         = 0x00040000; // PE rebased image
        internal const uint PATCH_OPTION_FAIL_IF_SAME_FILE = 0x00080000; // don't create if same
        internal const uint PATCH_OPTION_FAIL_IF_BIGGER    = 0x00100000; // fail if patch is larger than simply compressing new file (slower)
        internal const uint PATCH_OPTION_NO_CHECKSUM       = 0x00200000; // PE checksum zero
        internal const uint PATCH_OPTION_NO_RESTIMEFIX     = 0x00400000; // PE resource timestamps
        internal const uint PATCH_OPTION_NO_TIMESTAMP      = 0x00800000; // don't store new file timestamp in patch
        internal const uint PATCH_OPTION_SIGNATURE_MD5     = 0x01000000; // use MD5 instead of CRC (reserved for future support)
        internal const uint PATCH_OPTION_INTERLEAVE_FILES  = 0x40000000; // better support for large files (requires 5.2 or higher applyer)
        internal const uint PATCH_OPTION_RESERVED1         = 0x80000000; // (used internally)

        internal const uint PATCH_OPTION_VALID_FLAGS       = 0xC0FF0007;

        //
        // The following flags are used with PATCH_OPTION_DATA ExtendedOptionFlags:
        //

        internal const uint PATCH_TRANSFORM_PE_RESOURCE_2  = 0x00000100; // better handling of PE resources (requires 5.2 or higher applyer)
        internal const uint PATCH_TRANSFORM_PE_IRELOC_2    = 0x00000200; // better handling of PE stripped relocs (requires 5.2 or higher applyer)

        //
        // In addition to the standard Win32 error codes, the following error codes may
        // be returned via GetLastError() when one of the patch APIs fails.

        internal const uint ERROR_PATCH_ENCODE_FAILURE         = 0xC00E3101; // create
        internal const uint ERROR_PATCH_INVALID_OPTIONS        = 0xC00E3102; // create
        internal const uint ERROR_PATCH_SAME_FILE              = 0xC00E3103; // create
        internal const uint ERROR_PATCH_RETAIN_RANGES_DIFFER   = 0xC00E3104; // create
        internal const uint ERROR_PATCH_BIGGER_THAN_COMPRESSED = 0xC00E3105; // create
        internal const uint ERROR_PATCH_IMAGEHLP_FALURE        = 0xC00E3106; // create

        /// <summary>
        /// Delegate type that the PatchAPI calls for progress notification.
        /// </summary>
        /// <param name="context">.</param>
        /// <param name="currentPosition">.</param>
        /// <param name="maxPosition">.</param>
        /// <returns>True for success</returns>
        public delegate bool PatchProgressCallback(
                IntPtr context,
                uint currentPosition,
                uint maxPosition
                );

        /// <summary>
        /// Delegate type that the PatchAPI calls for patch symbol load information.
        /// </summary>
        /// <param name="whichFile">.</param>
        /// <param name="symbolFileName">.</param>
        /// <param name="symType">.</param>
        /// <param name="symbolFileCheckSum">.</param>
        /// <param name="symbolFileTimeDate">.</param>
        /// <param name="imageFileCheckSum">.</param>
        /// <param name="imageFileTimeDate">.</param>
        /// <param name="context">.</param>
        /// <returns>???</returns>
        public delegate bool PatchSymloadCallback(
                                                 uint whichFile, // 0 for new file, 1 for first old file, etc
                [MarshalAs(UnmanagedType.LPStr)] string symbolFileName,
                                                 uint symType,   // see SYM_TYPE in imagehlp.h
                                                 uint symbolFileCheckSum,
                                                 uint symbolFileTimeDate,
                                                 uint imageFileCheckSum,
                                                 uint imageFileTimeDate,
                                                 IntPtr context
                                                 );

        /// <summary>
        /// Wraps PATCH_IGNORE_RANGE
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        internal class PatchIgnoreRange
        {
            public uint offsetInOldFile;
            public uint lengthInBytes;
        }

        /// <summary>
        /// Wraps PATCH_RETAIN_RANGE
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        internal class PatchRetainRange
        {
            public uint offsetInOldFile;
            public uint lengthInBytes;
            public uint offsetInNewFile;
        }

        /// <summary>
        /// Wraps PATCH_OLD_FILE_INFO (except for the OldFile~ portion)
        /// </summary>
        internal class PatchOldFileInfo
        {
            public PatchIgnoreRange[] ignoreRange;
            public PatchRetainRange[] retainRange;
        }

        /// <summary>
        /// Wraps PATCH_OLD_FILE_INFO_W
        /// </summary>
        internal class PatchOldFileInfoW : PatchOldFileInfo
        {
            public string oldFileName;
        }

        /// <summary>
        /// Wraps each PATCH_INTERLEAVE_MAP Range
        /// </summary>
        [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses"), StructLayout(LayoutKind.Sequential)]
        internal class PatchInterleaveMapRange
        {
            public uint oldOffset;
            public uint oldLength;
            public uint newLength;
        }

        /// <summary>
        /// Wraps PATCH_INTERLEAVE_MAP
        /// </summary>
        internal class PatchInterleaveMap
        {
            public PatchInterleaveMapRange[] ranges = null;
        }


        /// <summary>
        /// Wraps PATCH_OPTION_DATA
        /// </summary>
        [BestFitMapping(false, ThrowOnUnmappableChar = true)]
        internal class PatchOptionData
        {
            public PatchSymbolFlagsType symbolOptionFlags;          // PATCH_SYMBOL_xxx flags
            [MarshalAs(UnmanagedType.LPStr)] public string               newFileSymbolPath;          // always ANSI, never Unicode
            [MarshalAs(UnmanagedType.LPStr)] public string[]             oldFileSymbolPathArray;     // array[ OldFileCount ]
            public uint                 extendedOptionFlags;
            public PatchSymloadCallback symLoadCallback = null;
            public IntPtr symLoadContext = IntPtr.Zero;
            public PatchInterleaveMap[] interleaveMapArray = null;  // array[ OldFileCount ] (requires 5.2 or higher applyer)
            public uint maxLzxWindowSize = 0;       // limit memory requirements (requires 5.2 or higher applyer)
        }

        //
        // Note that PATCH_OPTION_DATA contains LPCSTR paths, and no LPCWSTR (Unicode)
        // path argument is available, even when used with one of the Unicode APIs
        // such as CreatePatchFileW. This is because the unlerlying system services
        // for symbol file handling (IMAGEHLP.DLL) only support ANSI file/path names.
        //

        //
        // A note about PATCH_RETAIN_RANGE specifiers with multiple old files:
        //
        // Each old version file must have the same RetainRangeCount, and the same
        // retain range LengthInBytes and OffsetInNewFile values in the same order.
        // Only the OffsetInOldFile values can differ between old foles for retain
        // ranges.
        //

        //
        // The following prototypes are (some of the) interfaces for creating patches from files.
        //

        /// <summary>
        /// Creates a new delta.
        /// </summary>
        /// <param name="oldFileCount">Size of oldFileInfoArray.</param>
        /// <param name="oldFileInfoArray">Target file information.</param>
        /// <param name="newFileName">Name of updated file.</param>
        /// <param name="patchFileName">Name of delta to create.</param>
        /// <param name="optionFlags">PATCH_OPTION_xxx.</param>
        /// <param name="optionData">Optional PATCH_OPTION_DATA structure.</param>
        /// <param name="progressCallback">Delegate for progress callbacks.</param>
        /// <param name="context">Context for progress callback delegate.</param>
        /// <returns>true if successfull, sets Marshal.GetLastWin32Error() if not.</returns>
        [DllImport("mspatchc.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool CreatePatchFileExW(
                uint oldFileCount,      // maximum 255
                [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(PatchAPIMarshaler), MarshalCookie="PATCH_OLD_FILE_INFO_W")]
                PatchOldFileInfoW[] oldFileInfoArray,
                string newFileName,     // input file  (required)
                string patchFileName,   // output file (required)
                uint optionFlags,
                [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(PatchAPIMarshaler), MarshalCookie="PATCH_OPTION_DATA")]
                PatchOptionData optionData,
                [MarshalAs (UnmanagedType.FunctionPtr)]
                PatchProgressCallback progressCallback,
                IntPtr context
                );

        /// <summary>
        /// Extracts delta header from delta.
        /// </summary>
        /// <param name="patchFileName">Name of delta file.</param>
        /// <param name="patchHeaderFileName">Name of file to create with delta header.</param>
        /// <returns>true if successfull, sets Marshal.GetLastWin32Error() if not.</returns>
        [DllImport("mspatchc.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool ExtractPatchHeaderToFileW(
                string patchFileName,      // input file
                string patchHeaderFileName // output file
                );

        // TODO: Add rest of APIs to enable custom binders to perform more exhaustive checks

        /// <summary>
        /// Marshals arguments for the CreatePatch~ APIs
        /// </summary>
        [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")]
        internal class PatchAPIMarshaler : ICustomMarshaler
        {
            internal static ICustomMarshaler GetInstance(string cookie)
            {
                return new PatchAPIMarshaler(cookie);
            }

            private enum MarshalType
            {
                PATCH_OPTION_DATA,
                PATCH_OLD_FILE_INFO_W
            };
            private PatchAPIMarshaler.MarshalType marshalType;

            private PatchAPIMarshaler(string cookie)
            {
                this.marshalType = (PatchAPIMarshaler.MarshalType) Enum.Parse(typeof(PatchAPIMarshaler.MarshalType), cookie);
            }

            //
            // Summary:
            //     Returns the size of the native data to be marshaled.
            //
            // Returns:
            //     The size in bytes of the native data.
            public int GetNativeDataSize()
            {
                return Marshal.SizeOf(typeof(IntPtr));
            }

            //
            // Summary:
            //     Performs necessary cleanup of the managed data when it is no longer needed.
            //
            // Parameters:
            //     ManagedObj:
            //       The managed object to be destroyed.
            public void CleanUpManagedData(object ManagedObj)
            {
            }

            //
            // Summary:
            //     Performs necessary cleanup of the unmanaged data when it is no longer needed.
            //
            // Parameters:
            //     pNativeData:
            //       A pointer to the unmanaged data to be destroyed.
            public void CleanUpNativeData(IntPtr pNativeData)
            {
                if (IntPtr.Zero == pNativeData)
                {
                    return;
                }

                switch (this.marshalType)
                {
                case PatchAPIMarshaler.MarshalType.PATCH_OPTION_DATA:
                    this.CleanUpPOD(pNativeData);
                    break;
                default:
                    this.CleanUpPOFI_A(pNativeData);
                    break;
                }
            }

            //
            // Summary:
            //     Converts the managed data to unmanaged data.
            //
            // Parameters:
            //     ManagedObj:
            //       The managed object to be converted.
            //
            // Returns:
            //     Returns the COM view of the managed object.
            public IntPtr MarshalManagedToNative(object ManagedObj)
            {
                if (null == ManagedObj)
                {
                    return IntPtr.Zero;
                }

                switch(this.marshalType)
                {
                case PatchAPIMarshaler.MarshalType.PATCH_OPTION_DATA:
                    return this.MarshalPOD(ManagedObj as PatchOptionData);
                case PatchAPIMarshaler.MarshalType.PATCH_OLD_FILE_INFO_W:
                    return this.MarshalPOFIW_A(ManagedObj as PatchOldFileInfoW[]);
                default:
                    throw new InvalidOperationException();
                }
            }


            //
            // Summary:
            //     Converts the unmanaged data to managed data.
            //
            // Parameters:
            //     pNativeData:
            //       A pointer to the unmanaged data to be wrapped.
            //
            // Returns:
            //     Returns the managed view of the COM data.
            public object MarshalNativeToManaged(IntPtr pNativeData)
            {
                return null;
            }

            // Implementation *************************************************

            // PATCH_OPTION_DATA offsets
            private static readonly int symbolOptionFlagsOffset      =   Marshal.SizeOf(typeof(Int32));
            private static readonly int newFileSymbolPathOffset      = 2*Marshal.SizeOf(typeof(Int32));
            private static readonly int oldFileSymbolPathArrayOffset = 2*Marshal.SizeOf(typeof(Int32)) + Marshal.SizeOf(typeof(IntPtr));
            private static readonly int extendedOptionFlagsOffset    = 2*Marshal.SizeOf(typeof(Int32)) + 2*Marshal.SizeOf(typeof(IntPtr));
            private static readonly int symLoadCallbackOffset        = 3*Marshal.SizeOf(typeof(Int32)) + 2*Marshal.SizeOf(typeof(IntPtr));
            private static readonly int symLoadContextOffset         = 3*Marshal.SizeOf(typeof(Int32)) + 3*Marshal.SizeOf(typeof(IntPtr));
            private static readonly int interleaveMapArrayOffset     = 3*Marshal.SizeOf(typeof(Int32)) + 4*Marshal.SizeOf(typeof(IntPtr));
            private static readonly int maxLzxWindowSizeOffset       = 3*Marshal.SizeOf(typeof(Int32)) + 5*Marshal.SizeOf(typeof(IntPtr));
            private static readonly int patchOptionDataSize          = 4*Marshal.SizeOf(typeof(Int32)) + 5*Marshal.SizeOf(typeof(IntPtr));

            // PATCH_OLD_FILE_INFO offsets
            private static readonly int oldFileOffset          =   Marshal.SizeOf(typeof(Int32));
            private static readonly int ignoreRangeCountOffset =   Marshal.SizeOf(typeof(Int32)) + Marshal.SizeOf(typeof(IntPtr));
            private static readonly int ignoreRangeArrayOffset = 2*Marshal.SizeOf(typeof(Int32)) + Marshal.SizeOf(typeof(IntPtr));
            private static readonly int retainRangeCountOffset = 2*Marshal.SizeOf(typeof(Int32)) + 2*Marshal.SizeOf(typeof(IntPtr));
            private static readonly int retainRangeArrayOffset = 3*Marshal.SizeOf(typeof(Int32)) + 2*Marshal.SizeOf(typeof(IntPtr));
            private static readonly int patchOldFileInfoSize   = 3*Marshal.SizeOf(typeof(Int32)) + 3*Marshal.SizeOf(typeof(IntPtr));

            // Methods and data used to preserve data needed for cleanup

            // This dictionary holds the quantity of items internal to each native structure that will need to be freed (the OldFileCount)
            private static readonly Dictionary<IntPtr, int> OldFileCounts = new Dictionary<IntPtr, int>();
            private static readonly object OldFileCountsLock = new object();

            private IntPtr CreateMainStruct(int oldFileCount)
            {
                int nativeSize;
                switch(this.marshalType)
                {
                case PatchAPIMarshaler.MarshalType.PATCH_OPTION_DATA:
                    nativeSize = patchOptionDataSize;
                    break;
                case PatchAPIMarshaler.MarshalType.PATCH_OLD_FILE_INFO_W:
                    nativeSize = oldFileCount*patchOldFileInfoSize;
                    break;
                default:
                    throw new InvalidOperationException();
                }

                IntPtr native = Marshal.AllocCoTaskMem(nativeSize);

                lock (PatchAPIMarshaler.OldFileCountsLock)
                {
                    PatchAPIMarshaler.OldFileCounts.Add(native, oldFileCount);
                }

                return native;
            }

            private static void ReleaseMainStruct(IntPtr native)
            {
                lock (PatchAPIMarshaler.OldFileCountsLock)
                {
                    PatchAPIMarshaler.OldFileCounts.Remove(native);
                }
                Marshal.FreeCoTaskMem(native);
            }

            private static int GetOldFileCount(IntPtr native)
            {
                lock (PatchAPIMarshaler.OldFileCountsLock)
                {
                    return PatchAPIMarshaler.OldFileCounts[native];
                }
            }

            // Helper methods

            private static IntPtr OptionalAnsiString(string managed)
            {
                return (null == managed) ? IntPtr.Zero : Marshal.StringToCoTaskMemAnsi(managed);
            }

            private static IntPtr OptionalUnicodeString(string managed)
            {
                return (null == managed) ? IntPtr.Zero : Marshal.StringToCoTaskMemUni(managed);
            }

            // string array must be of the same length as the number of old files
            private static IntPtr CreateArrayOfStringA(string[] managed)
            {
                if (null == managed)
                {
                    return IntPtr.Zero;
                }

                int size = managed.Length * Marshal.SizeOf(typeof(IntPtr));
                IntPtr native = Marshal.AllocCoTaskMem(size);

                for (int i = 0; i < managed.Length; ++i)
                {
                    Marshal.WriteIntPtr(native, i*Marshal.SizeOf(typeof(IntPtr)), OptionalAnsiString(managed[i]));
                }

                return native;
            }

            // string array must be of the same length as the number of old files
            private static IntPtr CreateArrayOfStringW(string[] managed)
            {
                if (null == managed)
                {
                    return IntPtr.Zero;
                }

                int size = managed.Length * Marshal.SizeOf(typeof(IntPtr));
                IntPtr native = Marshal.AllocCoTaskMem(size);

                for (int i = 0; i < managed.Length; ++i)
                {
                    Marshal.WriteIntPtr(native, i*Marshal.SizeOf(typeof(IntPtr)), OptionalUnicodeString(managed[i]));
                }

                return native;
            }

            private static IntPtr CreateInterleaveMapRange(PatchInterleaveMap managed)
            {
                if (null == managed)
                {
                    return IntPtr.Zero;
                }

                if (null == managed.ranges)
                {
                    return IntPtr.Zero;
                }

                if (0 == managed.ranges.Length)
                {
                    return IntPtr.Zero;
                }

                IntPtr native = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(UInt32))
                                        + managed.ranges.Length*(Marshal.SizeOf(typeof(PatchInterleaveMap))));
                WriteUInt32(native, (uint) managed.ranges.Length);

                for (int i = 0; i < managed.ranges.Length; ++i)
                {
                    Marshal.StructureToPtr(managed.ranges[i], (IntPtr)((Int64)native + i*Marshal.SizeOf(typeof(PatchInterleaveMap))), false);
                }
                return native;
            }

            private static IntPtr CreateInterleaveMap(PatchInterleaveMap[] managed)
            {
                if (null == managed)
                {
                    return IntPtr.Zero;
                }

                IntPtr native = Marshal.AllocCoTaskMem(managed.Length * Marshal.SizeOf(typeof(IntPtr)));

                for (int i = 0; i < managed.Length; ++i)
                {
                    Marshal.WriteIntPtr(native, i*Marshal.SizeOf(typeof(IntPtr)), CreateInterleaveMapRange(managed[i]));
                }

                return native;
            }

            private static void WriteUInt32(IntPtr native, uint data)
            {
                Marshal.WriteInt32(native, unchecked((int) data));
            }

            private static void WriteUInt32(IntPtr native, int offset, uint data)
            {
                Marshal.WriteInt32(native, offset, unchecked((int) data));
            }

            // Marshal operations

            private IntPtr MarshalPOD(PatchOptionData managed)
            {
                if (null == managed)
                {
                    throw new ArgumentNullException("managed");
                }

                IntPtr native = this.CreateMainStruct(managed.oldFileSymbolPathArray.Length);
                Marshal.WriteInt32(native, patchOptionDataSize); // SizeOfThisStruct
                WriteUInt32(native, symbolOptionFlagsOffset, (uint) managed.symbolOptionFlags);
                Marshal.WriteIntPtr(native, newFileSymbolPathOffset, PatchAPIMarshaler.OptionalAnsiString(managed.newFileSymbolPath));
                Marshal.WriteIntPtr(native, oldFileSymbolPathArrayOffset, PatchAPIMarshaler.CreateArrayOfStringA(managed.oldFileSymbolPathArray));
                WriteUInt32(native, extendedOptionFlagsOffset, managed.extendedOptionFlags);

                // GetFunctionPointerForDelegate() throws an ArgumentNullException if the delegate is null.
                if (null == managed.symLoadCallback)
                {
                    Marshal.WriteIntPtr(native, symLoadCallbackOffset, IntPtr.Zero);
                }
                else
                {
                    Marshal.WriteIntPtr(native, symLoadCallbackOffset, Marshal.GetFunctionPointerForDelegate(managed.symLoadCallback));
                }

                Marshal.WriteIntPtr(native, symLoadContextOffset, managed.symLoadContext);
                Marshal.WriteIntPtr(native, interleaveMapArrayOffset, PatchAPIMarshaler.CreateInterleaveMap(managed.interleaveMapArray));
                WriteUInt32(native, maxLzxWindowSizeOffset, managed.maxLzxWindowSize);
                return native;
            }

            private IntPtr MarshalPOFIW_A(PatchOldFileInfoW[] managed)
            {
                if (null == managed)
                {
                    throw new ArgumentNullException("managed");
                }

                if (0 == managed.Length)
                {
                    return IntPtr.Zero;
                }

                IntPtr native = this.CreateMainStruct(managed.Length);

                for (int i = 0; i < managed.Length; ++i)
                {
                    PatchAPIMarshaler.MarshalPOFIW(managed[i], (IntPtr)((Int64)native + i * patchOldFileInfoSize));
                }

                return native;
            }

            private static void MarshalPOFIW(PatchOldFileInfoW managed, IntPtr native)
            {
                PatchAPIMarshaler.MarshalPOFI(managed, native);
                Marshal.WriteIntPtr(native, oldFileOffset, PatchAPIMarshaler.OptionalUnicodeString(managed.oldFileName)); // OldFileName
            }

            private static void MarshalPOFI(PatchOldFileInfo managed, IntPtr native)
            {
                Marshal.WriteInt32(native, patchOldFileInfoSize); // SizeOfThisStruct
                WriteUInt32(native, ignoreRangeCountOffset,
                                    (null == managed.ignoreRange) ? 0 : (uint) managed.ignoreRange.Length); // IgnoreRangeCount // maximum 255
                Marshal.WriteIntPtr(native, ignoreRangeArrayOffset, MarshalPIRArray(managed.ignoreRange));  // IgnoreRangeArray
                WriteUInt32(native, retainRangeCountOffset,
                                    (null == managed.retainRange) ? 0 : (uint) managed.retainRange.Length); // RetainRangeCount // maximum 255
                Marshal.WriteIntPtr(native, retainRangeArrayOffset, MarshalPRRArray(managed.retainRange));  // RetainRangeArray
            }

            private static IntPtr MarshalPIRArray(PatchIgnoreRange[] array)
            {
                if (null == array)
                {
                    return IntPtr.Zero;
                }

                if (0 == array.Length)
                {
                    return IntPtr.Zero;
                }

                IntPtr native = Marshal.AllocCoTaskMem(array.Length*Marshal.SizeOf(typeof(PatchIgnoreRange)));

                for (int i = 0; i < array.Length; ++i)
                {
                    Marshal.StructureToPtr(array[i], (IntPtr)((Int64)native + (i*Marshal.SizeOf(typeof(PatchIgnoreRange)))), false);
                }

                return native;
            }

            private static IntPtr MarshalPRRArray(PatchRetainRange[] array)
            {
                if (null == array)
                {
                    return IntPtr.Zero;
                }

                if (0 == array.Length)
                {
                    return IntPtr.Zero;
                }

                IntPtr native = Marshal.AllocCoTaskMem(array.Length*Marshal.SizeOf(typeof(PatchRetainRange)));

                for (int i = 0; i < array.Length; ++i)
                {
                    Marshal.StructureToPtr(array[i], (IntPtr)((Int64)native + (i*Marshal.SizeOf(typeof(PatchRetainRange)))), false);
                }

                return native;
            }

            // CleanUp operations

            private void CleanUpPOD(IntPtr native)
            {
                Marshal.FreeCoTaskMem(Marshal.ReadIntPtr(native, newFileSymbolPathOffset));

                if (IntPtr.Zero != Marshal.ReadIntPtr(native, oldFileSymbolPathArrayOffset))
                {
                    for (int i = 0; i < GetOldFileCount(native); ++i)
                    {
                        Marshal.FreeCoTaskMem(
                                Marshal.ReadIntPtr(
                                        Marshal.ReadIntPtr(native, oldFileSymbolPathArrayOffset),
                                        i*Marshal.SizeOf(typeof(IntPtr))));
                    }

                    Marshal.FreeCoTaskMem(Marshal.ReadIntPtr(native, oldFileSymbolPathArrayOffset));
                }

                if (IntPtr.Zero != Marshal.ReadIntPtr(native, interleaveMapArrayOffset))
                {
                    for (int i = 0; i < GetOldFileCount(native); ++i)
                    {
                        Marshal.FreeCoTaskMem(
                                Marshal.ReadIntPtr(
                                        Marshal.ReadIntPtr(native, interleaveMapArrayOffset),
                                        i*Marshal.SizeOf(typeof(IntPtr))));
                    }

                    Marshal.FreeCoTaskMem(Marshal.ReadIntPtr(native, interleaveMapArrayOffset));
                }

                PatchAPIMarshaler.ReleaseMainStruct(native);
            }

            private void CleanUpPOFI_A(IntPtr native)
            {
                for (int i = 0; i < GetOldFileCount(native); ++i)
                {
                    PatchAPIMarshaler.CleanUpPOFI((IntPtr)((Int64)native + i*patchOldFileInfoSize));
                }

                PatchAPIMarshaler.ReleaseMainStruct(native);
            }

            private static void CleanUpPOFI(IntPtr native)
            {
                if (IntPtr.Zero != Marshal.ReadIntPtr(native, oldFileOffset))
                {
                    Marshal.FreeCoTaskMem(Marshal.ReadIntPtr(native, oldFileOffset));
                }

                PatchAPIMarshaler.CleanUpPOFIH(native);
            }

            private static void CleanUpPOFIH(IntPtr native)
            {
                if (IntPtr.Zero != Marshal.ReadIntPtr(native, ignoreRangeArrayOffset))
                {
                    Marshal.FreeCoTaskMem(Marshal.ReadIntPtr(native, ignoreRangeArrayOffset));
                }

                if (IntPtr.Zero != Marshal.ReadIntPtr(native, retainRangeArrayOffset))
                {
                    Marshal.FreeCoTaskMem(Marshal.ReadIntPtr(native, retainRangeArrayOffset));
                }
            }
        }
    }
}