-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRawrite32Dlg.cpp
1658 lines (1494 loc) · 53.2 KB
/
Rawrite32Dlg.cpp
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) 2000-2003,2010-2020 The NetBSD Foundation, Inc.
* All rights reserved.
*
* Copyright (c) 2000-2003,2010-2020 Martin Husemann <[email protected]>.
* All rights reserved.
*
* This code was developed by Martin Husemann for the benefit of
* all NetBSD users and The NetBSD Foundation.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. The name of the author may not be used to endorse or promote products
* derived from this software withough specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "stdafx.h"
#include "Rawrite32.h"
#include "Rawrite32Dlg.h"
#include "Hash.h"
#include "Decompress.h"
#include <winioctl.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// single threaded hash calculation with timing
// #define HASH_BENCHMARK
// log total hash time
// #define HASH_TOTAL_TIME
// do not write output, similar to writing to /dev/null on unix
// #define NULL_OUTPUT
// XXX - just blindly assume we write to a 512-bye sectored medium if using old (win9x) systems.
#define SECTOR_SIZE 512 // this value is not used on WinNT based systems
// size of the important data at the start of a disk carrying partition info
#define PARTITION_INFO_SIZE (16*1024)
// size of the view into the input image
#define MAP_VIEW_SIZE (16*1024*1024)
// size of the decompression buffer
#define OUTPUT_BUF_SIZE (128*1024*1024)
// decompression output has to be a multiple of this before swapping buffers
#define OUTPUT_BUF_CHUNK_SIZE (1*1024*1024)
// maximum size of a single write request to the raw output device
#define MAX_WRITE_CHUNK (1*1024*1024)
#ifdef _M_IX86
// only needed on arch=i386, otherwise assume NT anyway
static bool RunningOnDOS()
{
OSVERSIONINFO osVers;
memset(&osVers, 0, sizeof osVers);
osVers.dwOSVersionInfoSize = sizeof osVers;
GetVersionEx(&osVers);
return osVers.dwPlatformId != VER_PLATFORM_WIN32_NT;
}
#endif
/////////////////////////////////////////////////////////////////////////////
static void DoSurfHome()
{
CString url;
url.LoadString(IDS_HOME_URL);
ShellExecute(NULL, _T("open"), url, NULL, NULL, SW_SHOWNORMAL);
}
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg() : CDialog(IDD) {}
private:
enum { IDD = IDD_ABOUTBOX };
protected:
afx_msg void OnSurfHome();
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
ON_BN_CLICKED(IDC_SURF_HOME, OnSurfHome)
END_MESSAGE_MAP()
void CAboutDlg::OnSurfHome()
{
OnOK();
DoSurfHome();
}
/////////////////////////////////////////////////////////////////////////////
// CSecSkipOptionsDlg dialog used for App About
class CSecSkipOptionsDlg : public CDialog
{
public:
CSecSkipOptionsDlg() : CDialog(IDD) {}
private:
enum { IDD = IDD_SEC_SKIP_OPTIONS };
protected:
virtual void DoDataExchange(CDataExchange*pDX);
public:
long m_sekCount;
};
void CSecSkipOptionsDlg::DoDataExchange(CDataExchange*pDX)
{
DDX_Text(pDX, IDC_SECTOR_SKIP, m_sekCount);
}
/////////////////////////////////////////////////////////////////////////////
// CHashOptionsDlg
class CHashOptionsDlg : public CDialog
{
protected:
enum { IDD = IDD_HASH_OPTIONS };
BOOL OnInitDialog();
public:
CHashOptionsDlg() : CDialog(IDD), m_initDone(false) { }
protected:
afx_msg void OnHashSelect(NMHDR*,LRESULT*);
DECLARE_MESSAGE_MAP();
virtual void OnOK();
protected:
map<CString,bool> m_modified;
bool m_initDone;
};
BEGIN_MESSAGE_MAP(CHashOptionsDlg, CDialog)
ON_NOTIFY(LVN_ITEMCHANGED, IDC_HASH_TYPE_LIST, OnHashSelect)
END_MESSAGE_MAP()
BOOL CHashOptionsDlg::OnInitDialog()
{
BOOL res = CDialog::OnInitDialog();
CListCtrl lc; lc.Attach(*GetDlgItem(IDC_HASH_TYPE_LIST));
CRect r;
vector<CString> hashNames;
GetAllHashNames(hashNames);
lc.GetClientRect(&r);
lc.InsertColumn(1, _T(""), 0, r.Width()-GetSystemMetrics(SM_CXVSCROLL)-1);
lc.SetExtendedStyle(lc.GetExtendedStyle()|LVS_EX_CHECKBOXES);
for (size_t i = 0; i < hashNames.size(); i++) {
int ndx = lc.InsertItem(i, hashNames[i]);
if (HashIsSelected(hashNames[i]))
lc.SetCheck(ndx, 1);
}
lc.Detach();
m_initDone = true;
return res;
}
void CHashOptionsDlg::OnHashSelect(NMHDR*pHDR,LRESULT*)
{
if (!m_initDone) return;
NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pHDR;
if ((pNMListView->uChanged & LVIF_STATE) == 0) return;
if (((pNMListView->uNewState ^ pNMListView->uOldState) & LVIS_STATEIMAGEMASK) == 0) return;
CListCtrl *pList = (CListCtrl*)GetDlgItem(IDC_HASH_TYPE_LIST);
int ndx = pNMListView->iItem;
bool activate = !!pList->GetCheck(ndx);
CString name(pList->GetItemText(ndx, 0));
m_modified[name] = activate;
}
void CHashOptionsDlg::OnOK()
{
CDialog::OnOK();
if (m_modified.empty()) return;
for (map<CString,bool>::const_iterator i = m_modified.begin(); i != m_modified.end(); i++)
SelectHash(i->first, i->second);
}
/////////////////////////////////////////////////////////////////////////////
class CMenuIcon : public CButton
{
public:
CMenuIcon(CMenu *popup, UINT icon) : m_menu(popup) { m_icon = AfxGetApp()->LoadIcon(icon); }
protected:
virtual void PostNcDestroy() { delete this; }
virtual void DrawItem(LPDRAWITEMSTRUCT);
afx_msg void OnLButtonDown(UINT flags, CPoint point);
DECLARE_MESSAGE_MAP()
protected:
HICON m_icon;
CMenu *m_menu;
};
BEGIN_MESSAGE_MAP(CMenuIcon, CButton)
ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()
void CMenuIcon::DrawItem(LPDRAWITEMSTRUCT lpdi)
{
DrawIcon(lpdi->hDC, lpdi->rcItem.left, lpdi->rcItem.top, m_icon);
}
void CMenuIcon::OnLButtonDown(UINT /*flags*/, CPoint point)
{
((CRawrite32Dlg*)GetParent())->UpdateMenu(m_menu);
CRect r;
GetWindowRect(&r);
ClientToScreen(&point);
m_menu->TrackPopupMenu(TPM_RIGHTALIGN, r.right, point.y, GetParent());
}
/////////////////////////////////////////////////////////////////////////////
// CRawrite32Dlg dialog
CRawrite32Dlg::CRawrite32Dlg(LPCTSTR imageFileName)
: CDialog(CRawrite32Dlg::IDD, NULL), m_fsImage(NULL), m_fsImageSize(0), m_sectorSkip(0),
m_inputFile(INVALID_HANDLE_VALUE), m_inputMapping(NULL),
m_curInput(NULL), m_sizeRemaining(0), m_sizeWritten(0),
m_inputFileSize(0), m_fileOffset(0),m_outputDevice(INVALID_HANDLE_VALUE),
m_decompOutputSpaceAvailable(INVALID_HANDLE_VALUE),
m_decompOutputAvailable(INVALID_HANDLE_VALUE),
m_decomp(NULL),
m_decompOutputLen(0), m_curDecompTarget(0), m_decompForcedExit(0), m_writerIdle(0),
m_outputBuffer(new BYTE[OUTPUT_BUF_SIZE]), m_writeTargetLogicalVolume(false),
m_startBuf(NULL)
#ifdef _M_IX86
, m_usingVXD(RunningOnDOS()), m_sectorOut(0)
#endif
{
m_hIcon = (HICON)::LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_ICON, 32, 32, LR_DEFAULTCOLOR);
m_hSmallIcon = (HICON)::LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
EnableAutomation();
m_imageName = imageFileName;
m_output.LoadString(IDS_START_HINT);
if (m_usingVXD) m_writeTargetLogicalVolume = true; // can only access DOS drives
m_mainMenu.LoadMenu(IDR_MAINFRAME);
UpdateMenu(&m_mainMenu);
}
CRawrite32Dlg::~CRawrite32Dlg()
{
CloseInputFile();
delete [] m_startBuf;
delete [] m_outputBuffer;
}
void CRawrite32Dlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CRawrite32Dlg)
DDX_Control(pDX, IDC_PROGRESS, m_progress);
DDX_Control(pDX, IDC_DRIVES, m_drives);
DDX_Text(pDX, IDC_OUTPUT, m_output);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CRawrite32Dlg, CDialog)
//{{AFX_MSG_MAP(CRawrite32Dlg)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_DESTROY()
ON_WM_EXITMENULOOP()
ON_BN_CLICKED(IDC_BROWSE, OnBrowse)
ON_EN_CHANGE(IDC_IMAGE_NAME, OnNewImage)
ON_BN_CLICKED(IDC_WRITE_DISK, OnWriteImage)
ON_COMMAND(IDD_ABOUTBOX, OnAboutDlg)
ON_COMMAND(IDC_SURF_HOME, OnSurfHome)
ON_COMMAND(IDD_HASH_OPTIONS, OnHashOptions)
ON_COMMAND(IDD_SEC_SKIP_OPTIONS, OnSecSkipOptions)
ON_COMMAND(IDM_USE_VOLUMES, OnUseVolumes)
ON_COMMAND(IDM_USE_PHYSDISKS, OnUsePhysDisks)
ON_COMMAND(IDM_COLLECT_DEBUG_INFO, (AFX_PMSG)CollectDebugInfo)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
BEGIN_INTERFACE_MAP(CRawrite32Dlg, CDialog)
INTERFACE_PART(CRawrite32Dlg, IID_IDropTarget, Drop)
END_INTERFACE_MAP()
DWORD CRawrite32Dlg::XDrop::AddRef()
{
METHOD_PROLOGUE(CRawrite32Dlg, Drop)
return pThis->ExternalAddRef();
}
DWORD CRawrite32Dlg::XDrop::Release()
{
METHOD_PROLOGUE(CRawrite32Dlg, Drop)
return pThis->ExternalRelease();
}
STDMETHODIMP CRawrite32Dlg::XDrop::QueryInterface(REFIID iid, void **ppv)
{
METHOD_PROLOGUE(CRawrite32Dlg, Drop)
return pThis->ExternalQueryInterface(&iid, ppv);
}
STDMETHODIMP CRawrite32Dlg::XDrop::DragEnter(IDataObject * pDataObject, DWORD /*grfKeyState*/, POINTL /*pt*/, DWORD * pdwEffect)
{
FORMATETC fmt;
STGMEDIUM stg;
memset(&stg, 0, sizeof stg);
memset(&fmt, 0, sizeof fmt);
fmt.cfFormat = CF_HDROP;
fmt.lindex = -1;
fmt.tymed = TYMED_HGLOBAL;
fmt.dwAspect = DVASPECT_CONTENT;
*pdwEffect = DROPEFFECT_NONE;
HRESULT res = pDataObject->GetData(&fmt, &stg);
if (FAILED(res)) {
return S_OK;
}
HDROP dropData = (HDROP)stg.hGlobal;
TCHAR fileName[_MAX_PATH];
UINT numFiles = DragQueryFile(dropData, 0xFFFFFFFF, fileName, _MAX_PATH);
if (numFiles == 1) {
*pdwEffect = DROPEFFECT_COPY;
}
return S_OK;
}
STDMETHODIMP CRawrite32Dlg::XDrop::DragOver(DWORD /*grfKeyState*/, POINTL /*pt*/, DWORD * pdwEffect)
{
*pdwEffect = DROPEFFECT_COPY;
return S_OK;
}
STDMETHODIMP CRawrite32Dlg::XDrop::DragLeave()
{
return S_OK;
}
STDMETHODIMP CRawrite32Dlg::XDrop::Drop(IDataObject * pDataObject, DWORD /*grfKeyState*/, POINTL /*pt*/, DWORD * pdwEffect)
{
METHOD_PROLOGUE(CRawrite32Dlg, Drop)
FORMATETC fmt;
STGMEDIUM stg;
memset(&stg, 0, sizeof stg);
memset(&fmt, 0, sizeof fmt);
fmt.cfFormat = CF_HDROP;
fmt.lindex = -1;
fmt.tymed = TYMED_HGLOBAL;
fmt.dwAspect = DVASPECT_CONTENT;
*pdwEffect = DROPEFFECT_NONE;
HRESULT res = pDataObject->GetData(&fmt, &stg);
if (FAILED(res)) {
return S_OK;
}
HDROP dropData = (HDROP)stg.hGlobal;
TCHAR fileName[_MAX_PATH];
UINT numFiles = DragQueryFile(dropData, 0xFFFFFFFF, fileName, _MAX_PATH);
if (numFiles == 1) {
DragQueryFile(dropData, 0, fileName, _MAX_PATH);
*pdwEffect = DROPEFFECT_COPY;
pThis->GetDlgItem(IDC_IMAGE_NAME)->SetWindowText(fileName);
}
return S_OK;
}
#if _MSC_VER < 1600
extern "C" {
// avoid DDK includes, just paste some stuff here
enum STORAGE_PROPERTY_ID {
StorageDeviceProperty = 0,
StorageAdapterProperty = 1,
StorageDeviceIdProperty = 2,
StorageDeviceUniqueIdProperty = 3,
StorageDeviceWriteCacheProperty = 4,
StorageMiniportProperty = 5,
StorageAccessAlignmentProperty = 6,
StorageDeviceSeekPenaltyProperty = 7,
StorageDeviceTrimProperty = 8,
StorageDeviceWriteAggregationProperty = 9
};
enum STORAGE_QUERY_TYPE {
PropertyStandardQuery = 0,
PropertyExistsQuery = 1,
PropertyMaskQuery = 2,
PropertyQueryMaxDefined = 3
};
struct STORAGE_PROPERTY_QUERY {
STORAGE_PROPERTY_ID PropertyId;
STORAGE_QUERY_TYPE QueryType;
UCHAR AdditionalParameters[1];
};
struct STORAGE_DEVICE_DESCRIPTOR {
ULONG Version;
ULONG Size;
UCHAR DeviceType;
UCHAR DeviceTypeModifier;
BOOLEAN RemovableMedia;
BOOLEAN CommandQueueing;
ULONG VendorIdOffset;
ULONG ProductIdOffset;
ULONG ProductRevisionOffset;
ULONG SerialNumberOffset;
STORAGE_BUS_TYPE BusType;
ULONG RawPropertiesLength;
UCHAR RawDeviceProperties[1];
};
#define IOCTL_STORAGE_QUERY_PROPERTY CTL_CODE(IOCTL_STORAGE_BASE, 0x0500, METHOD_BUFFERED, FILE_ANY_ACCESS)
}
#endif
/////////////////////////////////////////////////////////////////////////////
// CRawrite32Dlg message handlers
void CRawrite32Dlg::CollectDebugInfo() const
{
CString diag;
// search by DOS drive letter
TCHAR allDrives[32*4 + 10];
GetLogicalDriveStrings(sizeof allDrives/sizeof allDrives[0], allDrives);
LPCTSTR drive;
for (drive = allDrives; *drive; drive += _tcslen(drive)+1) {
CString volName(drive, 2), logName, fsName;
if (!GetVolumeInformation(drive, logName.GetBuffer(200), 200, NULL, NULL, NULL, fsName.GetBuffer(200), 200)) continue;
if (diag.IsEmpty()) diag = "Logical drives:\r\n";
logName.ReleaseBuffer(); fsName.ReleaseBuffer();
if (logName.IsEmpty())
volName += " " + fsName;
else
volName += " " + logName + ", " + fsName;
auto t = GetDriveType(drive);
switch (t) {
case DRIVE_UNKNOWN: volName += " {DRIVE_UNKNOWN}"; break;
case DRIVE_NO_ROOT_DIR: volName += " {DRIVE_NO_ROOT_DIR}"; break;
case DRIVE_REMOVABLE: volName += " {DRIVE_REMOVABLE}"; break;
case DRIVE_FIXED: volName += " {DRIVE_FIXED}"; break;
case DRIVE_REMOTE: volName += " {DRIVE_REMOTE}"; break;
case DRIVE_CDROM: volName += " {DRIVE_CDROM}"; break;
case DRIVE_RAMDISK: volName += " {DRIVE_RAMDISK}"; break;
default: { CString type; type.Format(_T(" {%u}"), t); volName += type; break; }
}
diag += volName + "\r\n";
}
// search physical drives
size_t errCnt = 0, physFound = 0;
for (DWORD i = 0; ; i++) {
CString internalFileName, line;
internalFileName.Format(_T("\\\\.\\PhysicalDrive%u"), i);
HANDLE outputDevice = CreateFile(internalFileName, 0, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (outputDevice == INVALID_HANDLE_VALUE) {
errCnt++;
if (errCnt > 48) break;
continue;
}
if (physFound == 0) {
if (!diag.IsEmpty()) diag += "\r\n";
diag += "Physical drives:\r\n";
}
physFound++;
line.Format(_T("drive #%u: "), i);
errCnt = 0;
DWORD bytes = 0;
union {
STORAGE_DEVICE_DESCRIPTOR header;
TCHAR buf[1024];
} desc;
STORAGE_PROPERTY_QUERY qry;
memset(&qry, 0, sizeof qry);
qry.PropertyId = StorageDeviceProperty;
qry.QueryType = PropertyStandardQuery;
if (DeviceIoControl(outputDevice, IOCTL_STORAGE_QUERY_PROPERTY, &qry, sizeof qry, &desc.header, sizeof desc, &bytes, NULL)
&& bytes >= sizeof(STORAGE_DEVICE_DESCRIPTOR)) {
const char *strings = (const char *)&desc;
CString info;
if (desc.header.VendorIdOffset || desc.header.ProductIdOffset) {
if (desc.header.VendorIdOffset) {
CString t(strings + desc.header.VendorIdOffset);
t.Trim();
info = t;
}
if (desc.header.ProductIdOffset) {
CString t(strings + desc.header.ProductIdOffset);
t.Trim();
if (!info.IsEmpty()) info += " ";
info += t;
}
line += info;
}
}
DISK_GEOMETRY geom;
if (DeviceIoControl(outputDevice, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &geom, sizeof geom, &bytes, NULL)) {
DWORD64 size = (DWORD64)geom.Cylinders.QuadPart * geom.SectorsPerTrack * geom.TracksPerCylinder;
CString s;
FormatSize(size, s, geom.BytesPerSector);
line += " [" + s + "]";
}
CloseHandle(outputDevice);
diag += line + "\r\n";
}
// find logical volumes on the physical drives
bool firstLogOnPhys = true;
for (drive = allDrives; *drive; drive += _tcslen(drive)+1) {
CString internalFileName, vol(drive,2);
internalFileName.Format(_T("\\\\.\\%s"), (LPCTSTR)vol);
HANDLE outputDevice = CreateFile(internalFileName, 0, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (outputDevice != INVALID_HANDLE_VALUE) {
if (firstLogOnPhys) {
if (!diag.IsEmpty()) diag += "\r\n";
diag += "Location of logical drives:\r\n";
firstLogOnPhys = false;
}
STORAGE_DEVICE_NUMBER sdn;
DWORD bytes = 0;
if (DeviceIoControl(outputDevice, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, &sdn, sizeof sdn, &bytes, NULL)) {
CString line, typeStr, partStr;
if (sdn.PartitionNumber != ~0U)
partStr.Format(_T(" partition %u"), sdn.PartitionNumber);
switch (sdn.DeviceType) {
case FILE_DEVICE_CD_ROM: typeStr = "CD-ROM"; break;
case FILE_DEVICE_CD_ROM_FILE_SYSTEM: typeStr = "CD-ROM file system"; break;
case FILE_DEVICE_DISK: typeStr = "DISK"; break;
case FILE_DEVICE_DISK_FILE_SYSTEM: typeStr = "DISK file system"; break;
case FILE_DEVICE_FILE_SYSTEM: typeStr = "file system"; break;
case FILE_DEVICE_NETWORK: typeStr = "NETWORK"; break;
case FILE_DEVICE_NETWORK_FILE_SYSTEM: typeStr = "NETWORK file system"; break;
case FILE_DEVICE_TAPE: typeStr = "TAPE"; break;
case FILE_DEVICE_VIRTUAL_DISK: typeStr = "VIRTUAL DISK"; break;
case FILE_DEVICE_MASS_STORAGE: typeStr = "MASS STORAGE"; break;
default: typeStr.Format(_T("FILE_DEVICE_#%08x"), sdn.DeviceType); break;
}
line.Format(_T("%s on %u ("), (LPCTSTR)vol, sdn.DeviceNumber);
diag += line + typeStr + partStr + ")\r\n";
}
CloseHandle(outputDevice);
}
}
if (diag.IsEmpty()) return;
if (::OpenClipboard(m_hWnd)) {
::EmptyClipboard();
HANDLE hMem = GlobalAlloc(GMEM_MOVEABLE, (diag.GetLength()+1)*sizeof(TCHAR));
LPTSTR t = (LPTSTR)GlobalLock(hMem);
_tcscpy(t, diag);
GlobalUnlock(hMem);
::SetClipboardData(CF_UNICODETEXT, hMem);
::CloseClipboard();
AfxMessageBox(IDP_DEBUG_INFO_COPIED);
}
}
void CRawrite32Dlg::EnumPhysicalDrives()
{
ASSERT(!m_usingVXD);
// find all "floppy" devices first...
TCHAR allDrives[32*4 + 10];
GetLogicalDriveStrings(sizeof allDrives/sizeof allDrives[0], allDrives);
LPCTSTR drive;
for (drive = allDrives; *drive; drive += _tcslen(drive)+1) {
DWORD type = GetDriveType(drive);
if (type != DRIVE_REMOVABLE) continue;
CString volName(drive, 2);
DriveSelectionEntry driveDesc;
driveDesc.volumes.push_back(volName);
driveDesc.driveNumber = ~0U;
driveDesc.internalFileName.Format(_T("\\\\.\\%s"), (LPCTSTR)volName);
CString logName, fsName;
GetVolumeInformation(drive, logName.GetBuffer(200), 200, NULL, NULL, NULL, fsName.GetBuffer(200), 200);
logName.ReleaseBuffer(); fsName.ReleaseBuffer();
if (logName.IsEmpty())
driveDesc.deviceName = fsName;
else
driveDesc.deviceName = logName + ", " + fsName;
m_driveData.push_back(driveDesc);
}
size_t errCnt = 0;
for (DWORD i = 0; ; i++) {
CString internalFileName;
internalFileName.Format(_T("\\\\.\\PhysicalDrive%u"), i);
HANDLE outputDevice = CreateFile(internalFileName, 0, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (outputDevice == INVALID_HANDLE_VALUE) {
errCnt++;
if (errCnt > 48) break;
continue;
}
errCnt = 0;
DriveSelectionEntry driveDesc;
driveDesc.driveNumber = i;
driveDesc.internalFileName = internalFileName;
DWORD bytes = 0;
union {
STORAGE_DEVICE_DESCRIPTOR header;
TCHAR buf[1024];
} desc;
STORAGE_PROPERTY_QUERY qry;
memset(&qry, 0, sizeof qry);
qry.PropertyId = StorageDeviceProperty;
qry.QueryType = PropertyStandardQuery;
if (DeviceIoControl(outputDevice, IOCTL_STORAGE_QUERY_PROPERTY, &qry, sizeof qry, &desc.header, sizeof desc, &bytes, NULL)
&& bytes >= sizeof(STORAGE_DEVICE_DESCRIPTOR)) {
const char *strings = (const char *)&desc;
CString info;
if (desc.header.VendorIdOffset || desc.header.ProductIdOffset) {
if (desc.header.VendorIdOffset) {
CString t(strings + desc.header.VendorIdOffset);
t.Trim();
info = t;
}
if (desc.header.ProductIdOffset) {
CString t(strings + desc.header.ProductIdOffset);
t.Trim();
if (!info.IsEmpty()) info += " ";
info += t;
}
driveDesc.deviceName = info;
}
}
DISK_GEOMETRY geom;
if (DeviceIoControl(outputDevice, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &geom, sizeof geom, &bytes, NULL)) {
DWORD64 size = (DWORD64)geom.Cylinders.QuadPart * geom.SectorsPerTrack * geom.TracksPerCylinder;
FormatSize(size, driveDesc.size,geom.BytesPerSector);
}
CloseHandle(outputDevice);
m_driveData.push_back(driveDesc);
}
// find logical volumes on the physical drives
for (drive = allDrives; *drive; drive += _tcslen(drive)+1) {
CString internalFileName, vol(drive,2);
DWORD type = GetDriveType(drive);
if (type == DRIVE_CDROM || type == DRIVE_REMOTE || type == DRIVE_RAMDISK) continue;
internalFileName.Format(_T("\\\\.\\%s"), (LPCTSTR)vol);
HANDLE outputDevice = CreateFile(internalFileName, 0, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (outputDevice != INVALID_HANDLE_VALUE) {
STORAGE_DEVICE_NUMBER sdn;
DWORD bytes = 0;
if (DeviceIoControl(outputDevice, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, &sdn, sizeof sdn, &bytes, NULL)) {
for (size_t i = 0; i < m_driveData.size(); i++) {
if (m_driveData[i].driveNumber == sdn.DeviceNumber) {
m_driveData[i].volumes.push_back(vol);
// check if this volume has already been enumerated before (unpartitioned removable disks)
for (size_t j = 0; j < m_driveData.size(); j++) {
if (m_driveData[j].driveNumber != ~0U) continue;
if (i == j) continue;
if (m_driveData[j].volumes.size() == 1 && m_driveData[j].volumes[0].CompareNoCase(vol) == 0) {
m_driveData.erase(m_driveData.begin()+j);
break;
}
}
}
}
}
CloseHandle(outputDevice);
}
}
}
void CRawrite32Dlg::EnumLogicalVolumes()
{
TCHAR allDrives[32*4 + 10];
GetLogicalDriveStrings(sizeof allDrives/sizeof allDrives[0], allDrives);
LPCTSTR drive;
for (drive = allDrives; *drive; drive += _tcslen(drive)+1) {
DWORD type = GetDriveType(drive);
if (type != DRIVE_CDROM && type != DRIVE_REMOTE && type != DRIVE_RAMDISK) {
CString volName(drive, 2);
DriveSelectionEntry driveDesc;
driveDesc.volumes.push_back(volName);
driveDesc.driveNumber = drive[0] - 'A';
driveDesc.internalFileName.Format(_T("\\\\.\\%s"), (LPCTSTR)volName);
CString logName, fsName;
GetVolumeInformation(drive, logName.GetBuffer(200), 200, NULL, NULL, NULL, fsName.GetBuffer(200), 200);
logName.ReleaseBuffer(); fsName.ReleaseBuffer();
if (logName.IsEmpty())
driveDesc.deviceName = fsName;
else
driveDesc.deviceName = logName + ", " + fsName;
m_driveData.push_back(driveDesc);
}
}
}
void CRawrite32Dlg::FillDriveCombo()
{
CWaitCursor hourglass;
m_driveData.clear();
if (m_writeTargetLogicalVolume)
EnumLogicalVolumes();
else
EnumPhysicalDrives();
CString winDir, sysDir;
GetWindowsDirectory(winDir.GetBuffer(MAX_PATH), MAX_PATH); winDir.ReleaseBuffer(); winDir.MakeUpper();
GetSystemDirectory(sysDir.GetBuffer(MAX_PATH), MAX_PATH); sysDir.ReleaseBuffer(); sysDir.MakeUpper();
for (size_t i = 0; i < m_driveData.size(); i++) {
for (size_t j = 0; j < m_driveData[i].volumes.size(); j++) {
CString drive = m_driveData[i].volumes[j];
drive.MakeUpper();
// exclude the main disk from our list to avoid catastrophic disasters
if (winDir[1] == ':' && winDir[0] == drive[0]) m_driveData[i].hidden = true;;
if (sysDir[1] == ':' && sysDir[0] == drive[0]) m_driveData[i].hidden = true;;
}
}
m_drives.ResetContent();
for (size_t i = 0; i < m_driveData.size(); i++) {
if (m_driveData[i].hidden) continue;
CString display;
if (m_driveData[i].volumes.empty()) {
if (m_driveData[i].deviceName.IsEmpty()) {
CString physString; physString.LoadString(IDS_UNKNOWN_PHYSDEV);
display.Format(_T("%s %u"), (LPCTSTR)physString, m_driveData[i].driveNumber);
}
} else {
for (size_t j = 0; j < m_driveData[i].volumes.size(); j++) {
if (!display.IsEmpty()) display += " ";
display += m_driveData[i].volumes[j];
}
}
if (!m_driveData[i].deviceName.IsEmpty()) {
if (!display.IsEmpty()) display += " ";
display += m_driveData[i].deviceName;
}
if (!m_driveData[i].size.IsEmpty())
display += " [" + m_driveData[i].size + "]";
m_drives.SetItemData(m_drives.AddString(display), i);
}
if (m_drives.GetCount() > 0)
m_drives.SetCurSel(m_drives.GetCount()-1);
}
void CRawrite32Dlg::UpdateMenu(CMenu *menu)
{
if (menu) {
menu->CheckMenuItem(IDM_USE_VOLUMES, MF_BYCOMMAND | (m_writeTargetLogicalVolume ? MF_CHECKED : MF_UNCHECKED));
menu->CheckMenuItem(IDM_USE_PHYSDISKS, MF_BYCOMMAND | (m_writeTargetLogicalVolume ? MF_UNCHECKED : MF_CHECKED));
}
}
BOOL CRawrite32Dlg::OnInitDialog()
{
CDialog::OnInitDialog();
CRect r;
GetWindowRect(&r);
m_origHeight = r.Height();
m_outWinFont.CreateFont(-12, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
FIXED_PITCH|FF_DONTCARE, NULL);
GetDlgItem(IDC_OUTPUT)->SetFont(&m_outWinFont);
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hSmallIcon, FALSE); // Set small icon
// two image buttons for drop down context menus
(new CMenuIcon(m_mainMenu.GetSubMenu(1), IDI_OPTIONS))->SubclassDlgItem(IDC_OPTIONS_ICON, this);
(new CMenuIcon(m_mainMenu.GetSubMenu(2), IDI_HELP))->SubclassDlgItem(IDC_HELP_ICON, this);
// register the dialog as file drop target
IDropTarget *dt;
GetIDispatch(FALSE)->QueryInterface(IID_IDropTarget, (void**)&dt);
RegisterDragDrop(m_hWnd, dt);
dt->Release();
FillDriveCombo();
if (m_imageName)
GetDlgItem(IDC_IMAGE_NAME)->SetWindowText(m_imageName);
return TRUE; // return TRUE unless you set the focus to a control
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CRawrite32Dlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
void CRawrite32Dlg::ShowMainMenu(bool showIt)
{
int dy = GetSystemMetrics(SM_CYMENU);
CRect r;
GetWindowRect(&r);
int w = r.Width();
int h = r.Height();
if (showIt) {
SetMenu(&m_mainMenu);
h += dy;
} else {
SetMenu(NULL);
h = m_origHeight;
}
SetWindowPos(NULL, 0, 0, w, h, SWP_NOMOVE|SWP_NOZORDER);
}
BOOL CRawrite32Dlg::PreTranslateMessage(MSG *pMsg)
{
// check for the UP transition of the ALT key as syskey (i.e. not after use as an accelerator)
// or F10 to popup the menu
if ((pMsg->message == WM_SYSKEYUP && (pMsg->wParam & 0x0ffff) == VK_MENU) ||
(pMsg->message == WM_SYSKEYDOWN && (pMsg->wParam & 0x0ffff) == VK_F10)) {
// only if currently there is no menu...
if (GetMenu() == NULL) {
ShowMainMenu(true);
return FALSE; // process this message further, this will make the app enter the menu loop
}
}
return CDialog::PreTranslateMessage(pMsg);
}
void CRawrite32Dlg::OnExitMenuLoop(BOOL isPopup)
{
// if the main menu loop was terminated, hide the menu again
if (!isPopup) ShowMainMenu(false);
CDialog::OnExitMenuLoop(isPopup);
}
HCURSOR CRawrite32Dlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CRawrite32Dlg::OnDestroy()
{
RevokeDragDrop(m_hWnd);
CDialog::OnDestroy();
}
void CRawrite32Dlg::OnBrowse()
{
CString filter;
CString title;
filter.LoadString(IDS_OPEN_IMAGE_FILTER);
title.LoadString(IDS_OPEN_IMAGE_TITLE);
CFileDialog dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY, filter, this);
dlg.m_ofn.lpstrTitle = title;
if (dlg.DoModal() == IDOK)
GetDlgItem(IDC_IMAGE_NAME)->SetWindowText(dlg.GetPathName());
}
void CRawrite32Dlg::OnNewImage()
{
CString name;
GetDlgItem(IDC_IMAGE_NAME)->GetWindowText(name);
HANDLE hFile = CreateFile(name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
m_output.Empty();
UpdateData(FALSE);
return;
}
m_imageName = name;
OpenInputFile(hFile);
VerifyInput();
}
void CRawrite32Dlg::ShowError(DWORD err, UINT id, LPCTSTR arg)
{
CString msg;
if (arg)
msg.Format(id, arg);
else
msg.LoadString(id);
LPTSTR errStr = NULL;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_IGNORE_INSERTS,NULL,err,0,(LPTSTR)&errStr,1,NULL);
CString t; t.Format(_T("%s\r\n[#%u] %s"), (LPCTSTR)msg, err, errStr);
LocalFree(errStr);
m_output += t;
ShowOutput();
AfxMessageBox(msg, MB_OK|MB_ICONERROR, id);
}
void CRawrite32Dlg::ShowOutput()
{
UpdateData(FALSE);
CEdit* edit = (CEdit*)GetDlgItem(IDC_OUTPUT);
int n = m_output.GetLength();
edit->SetSel(n,n);
}
UINT CRawrite32Dlg::dcompressionStarter(void *token)
{
return ((CRawrite32Dlg*)token)->BackgroundDecompressor();
}
UINT CRawrite32Dlg::BackgroundDecompressor()
{
for (;;) {
if (m_decompForcedExit)
break;
WaitForSingleObject(m_decompOutputSpaceAvailable, INFINITE);
if (m_decompForcedExit || m_decomp->allDone())
break;
DWORD outBufSize = OUTPUT_BUF_SIZE/2;
m_decomp->SetOutputSpace(m_outputBuffer + m_curDecompTarget*(OUTPUT_BUF_SIZE/2), outBufSize);
decompMore:
if (m_decompForcedExit)
break;
if (m_writerIdle) {
size_t space = m_decomp->outputSpace();
size_t newSpace = space & (OUTPUT_BUF_CHUNK_SIZE-1);
outBufSize -= space-newSpace;
m_decomp->LimitOutputSpace(newSpace);
}
if (m_decomp->isError())
break;
if (!m_decomp->allDone() && m_decomp->needInputData()) {
UnmapViewOfFile(m_fsImage);
if (AdvanceMapOffset() && MapInputView()) {
m_decomp->AddInputData(m_fsImage, m_fsImageSize);
if (m_decomp->outputSpace() > 0 && m_decomp->needInputData())
goto decompMore;
}
}
if (m_decomp->outputSpace() == outBufSize) {
if (m_decomp->allDone())
break;
goto decompMore;
}
m_decompOutputLen = outBufSize - m_decomp->outputSpace();
SetEvent(m_decompOutputAvailable);
}
m_decompOutputLen = 0;
SetEvent(m_decompOutputAvailable);
return 0;
}
void CRawrite32Dlg::OnWriteImage()
{
if (!VerifyInput())
return;
CString drive, msg, internalFileName;
DWORD ddIndex = 0;
DWORD driveIndex = 0;
bool didSkipStartBuf = false;
int ndx = m_drives.GetCurSel();
if (ndx == CB_ERR) return;
ddIndex = m_drives.GetItemData(ndx);
if (ddIndex >= m_driveData.size()) return;
m_drives.GetLBText(ndx, drive);
internalFileName = m_driveData[ddIndex].internalFileName;