2 * Copyright 2012 Aleksas Pantechovskis, <alexp.frl@gmail.com>
3 * All rights reserved. Distributed under the terms of the MIT License.
13 #include <DiskDevice.h>
14 #include <DiskDeviceRoster.h>
17 #include <VolumeRoster.h>
24 const char* kUsageMessage
= \
25 "Usage: writembr [ device ] \n"
26 "#\tRewrites the MBR for the specified device.\n"
27 "#\tIf no device is specified, the boot device is used.\n"
28 "#\t--help shows this usage message\n";
32 main(int argc
, char** argv
)
34 if ((argc
== 2 && strcmp(argv
[1], "--help") == 0) || argc
> 2) {
35 cerr
<< kUsageMessage
;
42 // user specified device for rewriting
43 device
.SetTo(argv
[1]);
46 // no parameters specified, rewrite boot device
47 BVolumeRoster volumeRoster
;
49 if (volumeRoster
.GetBootVolume(&bootVolume
) != B_OK
) {
50 cerr
<< "Can not find boot device" << endl
;
54 BDiskDeviceRoster roster
;
55 BDiskDevice bootDevice
;
56 if(roster
.FindPartitionByVolume(bootVolume
, &bootDevice
, NULL
) != B_OK
) {
57 cerr
<< "Can not find boot device" << endl
;
61 bootDevice
.GetPath(&device
);
65 if (strcmp(device
.Leaf(), "raw") != 0) {
66 cerr
<< device
.Path() << " is not a raw device" << endl
;
71 fs
.open(device
.Path(), fstream::in
| fstream::out
| fstream::binary
);
73 cerr
<< "Can't open " << device
.Path() << endl
;
77 STATIC_ASSERT(kMBRSize
== 512);
79 unsigned char MBR
[kMBRSize
];
80 fs
.read((char*)MBR
, kMBRSize
);
81 if (fs
.fail() || fs
.gcount() < kMBRSize
) {
82 cerr
<< "Cannot read " << kMBRSize
83 << " bytes from " << device
.Path() << endl
;
88 // update only the code area and the MBR signature
89 memcpy(MBR
, kMBR
, 0x1be);
90 MBR
[0x1FE] = kMBR
[0x1FE];
91 MBR
[0x1FF] = kMBR
[0x1FF];
93 cerr
<< "About to overwrite the MBR boot code on " << device
.Path()
94 << "\nThis may disable any partition managers you have installed.\n"
95 << "Are you sure you want to continue?\nyes/[no]: ";
98 getline(cin
, choice
, '\n');
99 if (choice
== "no" || choice
== "" || choice
!= "yes") {
100 cerr
<< "MBR was NOT written" << endl
;
105 cerr
<< "Rewriting MBR for " << device
.Path() << endl
;
107 fs
.seekg(0, ios::beg
);
108 fs
.write((char*)MBR
, kMBRSize
);
110 cerr
<< "Cannot write " << kMBRSize
111 << " bytes to " << device
.Path() << endl
;
118 cerr
<< "MBR was written OK" << endl
;