blob: ea344444e78e63d7f6372855ecffb6614df58ddb [file] [log] [blame]
srs5694fad06422010-02-19 17:19:17 -05001/*
Rod Smith44cda472018-07-05 09:07:58 -04002 Copyright (C) 2010-2018 <Roderick W. Smith>
srs5694fad06422010-02-19 17:19:17 -05003
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, write to the Free Software Foundation, Inc.,
16 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17
18*/
19
20/* This class implements an interactive text-mode interface atop the
21 GPTData class */
22
23#include <string.h>
24#include <errno.h>
srs569455d92612010-03-07 22:16:07 -050025#include <stdint.h>
srs569461768bc2010-07-04 01:54:00 -040026#include <limits.h>
srs5694fad06422010-02-19 17:19:17 -050027#include <iostream>
srs5694a6297b82012-03-25 16:13:16 -040028#include <fstream>
srs5694fad06422010-02-19 17:19:17 -050029#include <sstream>
srs56941c6f8b02010-02-21 11:09:20 -050030#include <cstdio>
srs5694fad06422010-02-19 17:19:17 -050031#include "attributes.h"
32#include "gpttext.h"
srs569455d92612010-03-07 22:16:07 -050033#include "support.h"
srs5694fad06422010-02-19 17:19:17 -050034
35using namespace std;
36
srs5694a17fe692011-09-10 20:30:20 -040037/********************************************
38 * *
39 * GPTDataText class and related structures *
40 * *
41 ********************************************/
srs5694fad06422010-02-19 17:19:17 -050042
43GPTDataTextUI::GPTDataTextUI(void) : GPTData() {
44} // default constructor
45
46GPTDataTextUI::GPTDataTextUI(string filename) : GPTData(filename) {
47} // constructor passing filename
48
49GPTDataTextUI::~GPTDataTextUI(void) {
50} // default destructor
51
52/*********************************************************************
53 * *
54 * The following functions are extended (interactive) versions of *
55 * simpler functions in the base class.... *
56 * *
57 *********************************************************************/
58
59// Overridden function; calls base-class function and then makes
60// additional queries of the user, if the base-class function can't
61// decide what to do.
62WhichToUse GPTDataTextUI::UseWhichPartitions(void) {
63 WhichToUse which;
64 MBRValidity mbrState;
65 int answer;
66
67 which = GPTData::UseWhichPartitions();
68 if ((which != use_abort) || beQuiet)
69 return which;
70
71 // If we get past here, it means that the non-interactive tests were
72 // inconclusive, so we must ask the user which table to use....
73 mbrState = protectiveMBR.GetValidity();
74
75 if ((state == gpt_valid) && (mbrState == mbr)) {
76 cout << "Found valid MBR and GPT. Which do you want to use?\n";
77 answer = GetNumber(1, 3, 2, " 1 - MBR\n 2 - GPT\n 3 - Create blank GPT\n\nYour answer: ");
78 if (answer == 1) {
79 which = use_mbr;
80 } else if (answer == 2) {
81 which = use_gpt;
82 cout << "Using GPT and creating fresh protective MBR.\n";
83 } else which = use_new;
84 } // if
85
86 // Nasty decisions here -- GPT is present, but corrupt (bad CRCs or other
87 // problems)
88 if (state == gpt_corrupt) {
89 if ((mbrState == mbr) || (mbrState == hybrid)) {
90 cout << "Found valid MBR and corrupt GPT. Which do you want to use? (Using the\n"
91 << "GPT MAY permit recovery of GPT data.)\n";
92 answer = GetNumber(1, 3, 2, " 1 - MBR\n 2 - GPT\n 3 - Create blank GPT\n\nYour answer: ");
93 if (answer == 1) {
94 which = use_mbr;
95 } else if (answer == 2) {
96 which = use_gpt;
97 } else which = use_new;
98 } else if (mbrState == invalid) {
99 cout << "Found invalid MBR and corrupt GPT. What do you want to do? (Using the\n"
100 << "GPT MAY permit recovery of GPT data.)\n";
srs56940283dae2010-04-28 16:44:34 -0400101 answer = GetNumber(1, 2, 1, " 1 - Use current GPT\n 2 - Create blank GPT\n\nYour answer: ");
srs5694fad06422010-02-19 17:19:17 -0500102 if (answer == 1) {
103 which = use_gpt;
104 } else which = use_new;
105 } // if/else/else
106 } // if (corrupt GPT)
107
108 return which;
109} // UseWhichPartitions()
110
111// Ask the user for a partition number; and prompt for verification
112// if the requested partition isn't of a known BSD type.
113// Lets the base-class function do the work, and returns its value (the
114// number of converted partitions).
115int GPTDataTextUI::XFormDisklabel(void) {
116 uint32_t partNum;
117 uint16_t hexCode;
118 int goOn = 1, numDone = 0;
119 BSDData disklabel;
120
121 partNum = GetPartNum();
122
123 // Now see if the specified partition has a BSD type code....
124 hexCode = partitions[partNum].GetHexType();
125 if ((hexCode != 0xa500) && (hexCode != 0xa900)) {
126 cout << "Specified partition doesn't have a disklabel partition type "
127 << "code.\nContinue anyway? ";
128 goOn = (GetYN() == 'Y');
129 } // if
130
131 if (goOn)
132 numDone = GPTData::XFormDisklabel(partNum);
133
134 return numDone;
Rod Smith503e9ad2017-07-21 21:48:13 -0400135} // GPTDataTextUI::XFormDisklabel(void)
srs5694fad06422010-02-19 17:19:17 -0500136
srs569455d92612010-03-07 22:16:07 -0500137
srs5694fad06422010-02-19 17:19:17 -0500138/*********************************************************************
139 * *
140 * Begin functions that obtain information from the users, and often *
141 * do something with that information (call other functions) *
142 * *
143 *********************************************************************/
144
srs5694a17fe692011-09-10 20:30:20 -0400145// Prompts user for partition number and returns the result. Returns "0"
146// (the first partition) if none are currently defined.
srs5694fad06422010-02-19 17:19:17 -0500147uint32_t GPTDataTextUI::GetPartNum(void) {
148 uint32_t partNum;
149 uint32_t low, high;
150 ostringstream prompt;
151
152 if (GetPartRange(&low, &high) > 0) {
153 prompt << "Partition number (" << low + 1 << "-" << high + 1 << "): ";
154 partNum = GetNumber(low + 1, high + 1, low, prompt.str());
155 } else partNum = 1;
156 return (partNum - 1);
157} // GPTDataTextUI::GetPartNum()
158
159// What it says: Resize the partition table. (Default is 128 entries.)
160void GPTDataTextUI::ResizePartitionTable(void) {
161 int newSize;
162 ostringstream prompt;
163 uint32_t curLow, curHigh;
164
srs56940283dae2010-04-28 16:44:34 -0400165 cout << "Current partition table size is " << numParts << ".\n";
srs5694fad06422010-02-19 17:19:17 -0500166 GetPartRange(&curLow, &curHigh);
167 curHigh++; // since GetPartRange() returns numbers starting from 0...
168 // There's no point in having fewer than four partitions....
169 if (curHigh < (blockSize / GPT_SIZE))
170 curHigh = blockSize / GPT_SIZE;
171 prompt << "Enter new size (" << curHigh << " up, default " << NUM_GPT_ENTRIES << "): ";
172 newSize = GetNumber(4, 65535, 128, prompt.str());
173 if (newSize < 128) {
174 cout << "Caution: The partition table size should officially be 16KB or larger,\n"
175 << "which works out to 128 entries. In practice, smaller tables seem to\n"
176 << "work with most OSes, but this practice is risky. I'm proceeding with\n"
177 << "the resize, but you may want to reconsider this action and undo it.\n\n";
178 } // if
179 SetGPTSize(newSize);
180} // GPTDataTextUI::ResizePartitionTable()
181
Rod Smith503e9ad2017-07-21 21:48:13 -0400182// Move the main partition table (to enable some SoC boot loaders to place
183// code at sector 2, for instance).
184void GPTDataTextUI::MoveMainTable(void) {
185 uint64_t newStart, pteSize = GetTableSizeInSectors();
186 uint64_t maxValue = FindFirstUsedLBA() - pteSize;
187 ostringstream prompt;
188
189 cout << "Currently, main partition table begins at sector " << mainHeader.partitionEntriesLBA
190 << " and ends at sector " << mainHeader.partitionEntriesLBA + pteSize - 1 << "\n";
191 prompt << "Enter new starting location (2 to " << maxValue << "; default is 2; 1 to abort): ";
192 newStart = GetNumber(1, maxValue, 2, prompt.str());
193 if (newStart != 1) {
194 GPTData::MoveMainTable(newStart);
195 } else {
196 cout << "Aborting change!\n";
197 } // if
198} // GPTDataTextUI::MoveMainTable()
199
srs5694fad06422010-02-19 17:19:17 -0500200// Interactively create a partition
201void GPTDataTextUI::CreatePartition(void) {
srs56945a081752010-09-24 20:39:41 -0400202 uint64_t firstBlock, firstInLargest, lastBlock, sector, origSector;
srs5694fad06422010-02-19 17:19:17 -0500203 uint32_t firstFreePart = 0;
204 ostringstream prompt1, prompt2, prompt3;
205 int partNum;
206
207 // Find first free partition...
208 while (partitions[firstFreePart].GetFirstLBA() != 0) {
209 firstFreePart++;
210 } // while
211
212 if (((firstBlock = FindFirstAvailable()) != 0) &&
srs56940283dae2010-04-28 16:44:34 -0400213 (firstFreePart < numParts)) {
srs5694fad06422010-02-19 17:19:17 -0500214 lastBlock = FindLastAvailable();
srs569455d92612010-03-07 22:16:07 -0500215 firstInLargest = FindFirstInLargest();
srs56940541b562011-12-18 16:35:25 -0500216 Align(&firstInLargest);
srs569455d92612010-03-07 22:16:07 -0500217
218 // Get partition number....
Roderick W. Smithf6948032014-03-29 00:27:33 -0400219 prompt1 << "Partition number (" << firstFreePart + 1 << "-" << numParts
220 << ", default " << firstFreePart + 1 << "): ";
srs569455d92612010-03-07 22:16:07 -0500221 do {
srs56940283dae2010-04-28 16:44:34 -0400222 partNum = GetNumber(firstFreePart + 1, numParts,
srs569455d92612010-03-07 22:16:07 -0500223 firstFreePart + 1, prompt1.str()) - 1;
224 if (partitions[partNum].GetFirstLBA() != 0)
225 cout << "partition " << partNum + 1 << " is in use.\n";
226 } while (partitions[partNum].GetFirstLBA() != 0);
227
228 // Get first block for new partition...
229 prompt2 << "First sector (" << firstBlock << "-" << lastBlock << ", default = "
srs56940873e9d2010-10-07 13:00:45 -0400230 << firstInLargest << ") or {+-}size{KMGTP}: ";
srs569455d92612010-03-07 22:16:07 -0500231 do {
srs56940873e9d2010-10-07 13:00:45 -0400232 sector = GetSectorNum(firstBlock, lastBlock, firstInLargest, blockSize, prompt2.str());
srs569455d92612010-03-07 22:16:07 -0500233 } while (IsFree(sector) == 0);
srs56945a081752010-09-24 20:39:41 -0400234 origSector = sector;
235 if (Align(&sector)) {
236 cout << "Information: Moved requested sector from " << origSector << " to "
237 << sector << " in\norder to align on " << sectorAlignment
238 << "-sector boundaries.\n";
239 if (!beQuiet)
240 cout << "Use 'l' on the experts' menu to adjust alignment\n";
241 } // if
242 // Align(&sector); // Align sector to correct multiple
srs569455d92612010-03-07 22:16:07 -0500243 firstBlock = sector;
244
245 // Get last block for new partitions...
246 lastBlock = FindLastInFree(firstBlock);
247 prompt3 << "Last sector (" << firstBlock << "-" << lastBlock << ", default = "
srs56940873e9d2010-10-07 13:00:45 -0400248 << lastBlock << ") or {+-}size{KMGTP}: ";
srs569455d92612010-03-07 22:16:07 -0500249 do {
srs56940873e9d2010-10-07 13:00:45 -0400250 sector = GetSectorNum(firstBlock, lastBlock, lastBlock, blockSize, prompt3.str());
srs569455d92612010-03-07 22:16:07 -0500251 } while (IsFree(sector) == 0);
252 lastBlock = sector;
253
254 firstFreePart = GPTData::CreatePartition(partNum, firstBlock, lastBlock);
255 partitions[partNum].ChangeType();
256 partitions[partNum].SetDefaultDescription();
srs5694fad06422010-02-19 17:19:17 -0500257 } else {
srs5694bf8950c2011-03-12 01:23:12 -0500258 if (firstFreePart >= numParts)
259 cout << "No table partition entries left\n";
260 else
261 cout << "No free sectors available\n";
srs5694fad06422010-02-19 17:19:17 -0500262 } // if/else
263} // GPTDataTextUI::CreatePartition()
264
265// Interactively delete a partition (duh!)
266void GPTDataTextUI::DeletePartition(void) {
267 int partNum;
268 uint32_t low, high;
269 ostringstream prompt;
270
271 if (GetPartRange(&low, &high) > 0) {
272 prompt << "Partition number (" << low + 1 << "-" << high + 1 << "): ";
273 partNum = GetNumber(low + 1, high + 1, low, prompt.str());
274 GPTData::DeletePartition(partNum - 1);
275 } else {
276 cout << "No partitions\n";
277 } // if/else
278} // GPTDataTextUI::DeletePartition()
279
280// Prompt user for a partition number, then change its type code
srs5694fad06422010-02-19 17:19:17 -0500281void GPTDataTextUI::ChangePartType(void) {
282 int partNum;
283 uint32_t low, high;
srs569455d92612010-03-07 22:16:07 -0500284
srs5694fad06422010-02-19 17:19:17 -0500285 if (GetPartRange(&low, &high) > 0) {
286 partNum = GetPartNum();
287 partitions[partNum].ChangeType();
288 } else {
289 cout << "No partitions\n";
290 } // if/else
291} // GPTDataTextUI::ChangePartType()
292
srs5694815fb652011-03-18 12:35:56 -0400293// Prompt user for a partition number, then change its unique
294// GUID.
295void GPTDataTextUI::ChangeUniqueGuid(void) {
296 int partNum;
297 uint32_t low, high;
298 string guidStr;
299
300 if (GetPartRange(&low, &high) > 0) {
301 partNum = GetPartNum();
302 cout << "Enter the partition's new unique GUID ('R' to randomize): ";
303 guidStr = ReadString();
304 if ((guidStr.length() >= 32) || (guidStr[0] == 'R') || (guidStr[0] == 'r')) {
305 SetPartitionGUID(partNum, (GUIDData) guidStr);
306 cout << "New GUID is " << partitions[partNum].GetUniqueGUID() << "\n";
307 } else {
308 cout << "GUID is too short!\n";
309 } // if/else
310 } else
311 cout << "No partitions\n";
312} // GPTDataTextUI::ChangeUniqueGuid()
313
srs5694fad06422010-02-19 17:19:17 -0500314// Partition attributes seem to be rarely used, but I want a way to
315// adjust them for completeness....
316void GPTDataTextUI::SetAttributes(uint32_t partNum) {
srs56940873e9d2010-10-07 13:00:45 -0400317 partitions[partNum].SetAttributes();
srs5694fad06422010-02-19 17:19:17 -0500318} // GPTDataTextUI::SetAttributes()
319
srs5694699941e2011-03-21 21:33:57 -0400320// Prompts the user for a partition name and sets the partition's
321// name. Returns 1 on success, 0 on failure (invalid partition
322// number). (Note that the function skips prompting when an
323// invalid partition number is detected.)
324int GPTDataTextUI::SetName(uint32_t partNum) {
325 UnicodeString theName = "";
326 int retval = 1;
327
328 if (IsUsedPartNum(partNum)) {
329 cout << "Enter name: ";
Roderick W. Smith84aaff62014-02-17 16:17:11 -0500330#ifdef USE_UTF16
srs5694699941e2011-03-21 21:33:57 -0400331 theName = ReadUString();
Roderick W. Smith84aaff62014-02-17 16:17:11 -0500332#else
333 theName = ReadString();
334#endif
srs5694699941e2011-03-21 21:33:57 -0400335 partitions[partNum].SetName(theName);
336 } else {
337 cerr << "Invalid partition number (" << partNum << ")\n";
338 retval = 0;
339 } // if/else
340
341 return retval;
342} // GPTDataTextUI::SetName()
343
srs5694fad06422010-02-19 17:19:17 -0500344// Ask user for two partition numbers and swap them in the table. Note that
345// this just reorders table entries; it doesn't adjust partition layout on
346// the disk.
347// Returns 1 if successful, 0 if not. (If user enters identical numbers, it
348// counts as successful.)
349int GPTDataTextUI::SwapPartitions(void) {
350 int partNum1, partNum2, didIt = 0;
351 uint32_t low, high;
352 ostringstream prompt;
353 GPTPart temp;
354
355 if (GetPartRange(&low, &high) > 0) {
356 partNum1 = GetPartNum();
srs56940283dae2010-04-28 16:44:34 -0400357 if (high >= numParts - 1)
srs5694fad06422010-02-19 17:19:17 -0500358 high = 0;
srs56940283dae2010-04-28 16:44:34 -0400359 prompt << "New partition number (1-" << numParts
srs569455d92612010-03-07 22:16:07 -0500360 << ", default " << high + 2 << "): ";
srs56940283dae2010-04-28 16:44:34 -0400361 partNum2 = GetNumber(1, numParts, high + 2, prompt.str()) - 1;
srs5694fad06422010-02-19 17:19:17 -0500362 didIt = GPTData::SwapPartitions(partNum1, partNum2);
363 } else {
364 cout << "No partitions\n";
365 } // if/else
366 return didIt;
367} // GPTDataTextUI::SwapPartitionNumbers()
368
369// This function destroys the on-disk GPT structures. Returns 1 if the user
370// confirms destruction, 0 if the user aborts or if there's a disk error.
371int GPTDataTextUI::DestroyGPTwPrompt(void) {
372 int allOK = 1;
373
374 if ((apmFound) || (bsdFound)) {
375 cout << "WARNING: APM or BSD disklabel structures detected! This operation could\n"
376 << "damage any APM or BSD partitions on this disk!\n";
377 } // if APM or BSD
378 cout << "\a\aAbout to wipe out GPT on " << device << ". Proceed? ";
379 if (GetYN() == 'Y') {
380 if (DestroyGPT()) {
381 // Note on below: Touch the MBR only if the user wants it completely
382 // blanked out. Version 0.4.2 deleted the 0xEE partition and re-wrote
383 // the MBR, but this could wipe out a valid MBR that the program
384 // had subsequently discarded (say, if it conflicted with older GPT
385 // structures).
386 cout << "Blank out MBR? ";
387 if (GetYN() == 'Y') {
388 DestroyMBR();
389 } else {
390 cout << "MBR is unchanged. You may need to delete an EFI GPT (0xEE) partition\n"
391 << "with fdisk or another tool.\n";
392 } // if/else
393 } else allOK = 0; // if GPT structures destroyed
394 } else allOK = 0; // if user confirms destruction
395 return (allOK);
396} // GPTDataTextUI::DestroyGPTwPrompt()
397
398// Get partition number from user and then call ShowPartDetails(partNum)
399// to show its detailed information
400void GPTDataTextUI::ShowDetails(void) {
401 int partNum;
402 uint32_t low, high;
srs569455d92612010-03-07 22:16:07 -0500403
srs5694fad06422010-02-19 17:19:17 -0500404 if (GetPartRange(&low, &high) > 0) {
405 partNum = GetPartNum();
406 ShowPartDetails(partNum);
407 } else {
408 cout << "No partitions\n";
409 } // if/else
410} // GPTDataTextUI::ShowDetails()
411
412// Create a hybrid MBR -- an ugly, funky thing that helps GPT work with
413// OSes that don't understand GPT.
414void GPTDataTextUI::MakeHybrid(void) {
Roderick W. Smitha345a922014-02-22 12:12:32 -0500415 uint32_t partNums[3] = {0, 0, 0};
srs56945a608532011-03-17 13:53:01 -0400416 string line;
Roderick W. Smitha345a922014-02-22 12:12:32 -0500417 int numPartsToCvt = 0, numConverted = 0, i, j, mbrNum = 0;
srs569455d92612010-03-07 22:16:07 -0500418 unsigned int hexCode = 0;
srs5694bf8950c2011-03-12 01:23:12 -0500419 MBRPart hybridPart;
420 MBRData hybridMBR;
srs5694fad06422010-02-19 17:19:17 -0500421 char eeFirst = 'Y'; // Whether EFI GPT (0xEE) partition comes first in table
422
srs5694058d4a52010-10-12 12:42:47 -0400423 cout << "\nWARNING! Hybrid MBRs are flaky and dangerous! If you decide not to use one,\n"
424 << "just hit the Enter key at the below prompt and your MBR partition table will\n"
425 << "be untouched.\n\n\a";
srs5694fad06422010-02-19 17:19:17 -0500426
srs56946aae2a92011-06-10 01:16:51 -0400427 // Use a local MBR structure, copying from protectiveMBR to keep its
428 // boot loader code intact....
429 hybridMBR = protectiveMBR;
430 hybridMBR.EmptyMBR(0);
431
srs5694fad06422010-02-19 17:19:17 -0500432 // Now get the numbers of up to three partitions to add to the
433 // hybrid MBR....
434 cout << "Type from one to three GPT partition numbers, separated by spaces, to be\n"
435 << "added to the hybrid MBR, in sequence: ";
srs56945a608532011-03-17 13:53:01 -0400436 line = ReadString();
Roderick W. Smith9b338c52014-02-20 11:13:36 -0500437 istringstream inLine(line);
438 do {
Roderick W. Smitha345a922014-02-22 12:12:32 -0500439 inLine >> partNums[numPartsToCvt];
440 if (partNums[numPartsToCvt] > 0)
441 numPartsToCvt++;
Roderick W. Smith9b338c52014-02-20 11:13:36 -0500442 } while (!inLine.eof() && (numPartsToCvt < 3));
srs5694fad06422010-02-19 17:19:17 -0500443
srs56940283dae2010-04-28 16:44:34 -0400444 if (numPartsToCvt > 0) {
srs5694fad06422010-02-19 17:19:17 -0500445 cout << "Place EFI GPT (0xEE) partition first in MBR (good for GRUB)? ";
446 eeFirst = GetYN();
447 } // if
448
srs56940283dae2010-04-28 16:44:34 -0400449 for (i = 0; i < numPartsToCvt; i++) {
srs5694bf8950c2011-03-12 01:23:12 -0500450 j = partNums[i] - 1;
Roderick W. Smitha345a922014-02-22 12:12:32 -0500451 if (partitions[j].IsUsed() && (partitions[j].IsSizedForMBR() != MBR_SIZED_BAD)) {
srs5694058d4a52010-10-12 12:42:47 -0400452 mbrNum = i + (eeFirst == 'Y');
453 cout << "\nCreating entry for GPT partition #" << j + 1
454 << " (MBR partition #" << mbrNum + 1 << ")\n";
srs5694bf8950c2011-03-12 01:23:12 -0500455 hybridPart.SetType(GetMBRTypeCode(partitions[j].GetHexType() / 256));
456 hybridPart.SetLocation(partitions[j].GetFirstLBA(), partitions[j].GetLengthLBA());
457 hybridPart.SetInclusion(PRIMARY);
srs5694058d4a52010-10-12 12:42:47 -0400458 cout << "Set the bootable flag? ";
459 if (GetYN() == 'Y')
srs56946aae2a92011-06-10 01:16:51 -0400460 hybridPart.SetStatus(0x80);
srs5694058d4a52010-10-12 12:42:47 -0400461 else
srs56946aae2a92011-06-10 01:16:51 -0400462 hybridPart.SetStatus(0x00);
srs5694bf8950c2011-03-12 01:23:12 -0500463 hybridPart.SetInclusion(PRIMARY);
Roderick W. Smitha345a922014-02-22 12:12:32 -0500464 if (partitions[j].IsSizedForMBR() == MBR_SIZED_IFFY)
465 WarnAboutIffyMBRPart(j + 1);
466 numConverted++;
srs5694058d4a52010-10-12 12:42:47 -0400467 } else {
Roderick W. Smith9b338c52014-02-20 11:13:36 -0500468 cerr << "\nGPT partition #" << j + 1 << " does not exist or is too big; skipping.\n";
srs5694058d4a52010-10-12 12:42:47 -0400469 } // if/else
srs5694bf8950c2011-03-12 01:23:12 -0500470 hybridMBR.AddPart(mbrNum, hybridPart);
srs5694fad06422010-02-19 17:19:17 -0500471 } // for
472
Roderick W. Smitha345a922014-02-22 12:12:32 -0500473 if (numConverted > 0) { // User opted to create a hybrid MBR....
srs5694fad06422010-02-19 17:19:17 -0500474 // Create EFI protective partition that covers the start of the disk.
475 // If this location (covering the main GPT data structures) is omitted,
476 // Linux won't find any partitions on the disk.
srs5694bf8950c2011-03-12 01:23:12 -0500477 hybridPart.SetLocation(1, hybridMBR.FindLastInFree(1));
478 hybridPart.SetStatus(0);
479 hybridPart.SetType(0xEE);
480 hybridPart.SetInclusion(PRIMARY);
srs569455d92612010-03-07 22:16:07 -0500481 // newNote firstLBA and lastLBA are computed later...
482 if (eeFirst == 'Y') {
srs5694bf8950c2011-03-12 01:23:12 -0500483 hybridMBR.AddPart(0, hybridPart);
srs569455d92612010-03-07 22:16:07 -0500484 } else {
Roderick W. Smitha345a922014-02-22 12:12:32 -0500485 hybridMBR.AddPart(numConverted, hybridPart);
srs569455d92612010-03-07 22:16:07 -0500486 } // else
srs5694bf8950c2011-03-12 01:23:12 -0500487 hybridMBR.SetHybrid();
srs5694fad06422010-02-19 17:19:17 -0500488
489 // ... and for good measure, if there are any partition spaces left,
490 // optionally create another protective EFI partition to cover as much
491 // space as possible....
srs5694bf8950c2011-03-12 01:23:12 -0500492 if (hybridMBR.CountParts() < 4) { // unused entry....
srs569455d92612010-03-07 22:16:07 -0500493 cout << "\nUnused partition space(s) found. Use one to protect more partitions? ";
494 if (GetYN() == 'Y') {
srs56945a608532011-03-17 13:53:01 -0400495 cout << "Note: Default is 0xEE, but this may confuse Mac OS X.\n";
496 // Comment on above: Mac OS treats disks with more than one
497 // 0xEE MBR partition as MBR disks, not as GPT disks.
498 hexCode = GetMBRTypeCode(0xEE);
499 hybridMBR.MakeBiggestPart(3, hexCode);
srs569455d92612010-03-07 22:16:07 -0500500 } // if (GetYN() == 'Y')
501 } // if unused entry
srs5694bf8950c2011-03-12 01:23:12 -0500502 protectiveMBR = hybridMBR;
Roderick W. Smitha345a922014-02-22 12:12:32 -0500503 } else {
504 cout << "\nNo partitions converted; original protective/hybrid MBR is unmodified!\n";
505 } // if/else (numConverted > 0)
srs5694fad06422010-02-19 17:19:17 -0500506} // GPTDataTextUI::MakeHybrid()
507
srs569455d92612010-03-07 22:16:07 -0500508// Convert the GPT to MBR form, storing partitions in the protectiveMBR
509// variable. This function is necessarily limited; it may not be able to
510// convert all partitions, depending on the disk size and available space
511// before each partition (one free sector is required to create a logical
512// partition, which are necessary to convert more than four partitions).
513// Returns the number of converted partitions; if this value
srs5694fad06422010-02-19 17:19:17 -0500514// is over 0, the calling function should call DestroyGPT() to destroy
srs569455d92612010-03-07 22:16:07 -0500515// the GPT data, call SaveMBR() to save the MBR, and then exit.
srs5694fad06422010-02-19 17:19:17 -0500516int GPTDataTextUI::XFormToMBR(void) {
srs569455d92612010-03-07 22:16:07 -0500517 uint32_t i;
srs5694fad06422010-02-19 17:19:17 -0500518
srs56946aae2a92011-06-10 01:16:51 -0400519 protectiveMBR.EmptyMBR(0);
srs5694bf8950c2011-03-12 01:23:12 -0500520 for (i = 0; i < numParts; i++) {
521 if (partitions[i].IsUsed()) {
Roderick W. Smitha345a922014-02-22 12:12:32 -0500522 if (partitions[i].IsSizedForMBR() == MBR_SIZED_IFFY)
523 WarnAboutIffyMBRPart(i + 1);
524 // Note: MakePart() checks for oversized partitions, so don't
525 // bother checking other IsSizedForMBR() return values....
srs5694bf8950c2011-03-12 01:23:12 -0500526 protectiveMBR.MakePart(i, partitions[i].GetFirstLBA(),
527 partitions[i].GetLengthLBA(),
528 partitions[i].GetHexType() / 0x0100, 0);
529 } // if
530 } // for
531 protectiveMBR.MakeItLegal();
532 return protectiveMBR.DoMenu();
srs5694fad06422010-02-19 17:19:17 -0500533} // GPTDataTextUI::XFormToMBR()
534
Roderick W. Smitha345a922014-02-22 12:12:32 -0500535/******************************************************
536 * *
537 * Display informational messages for the user.... *
538 * *
539 ******************************************************/
540
541// Although an MBR partition that begins below sector 2^32 and is less than 2^32 sectors in
542// length is technically legal even if it ends above the 2^32-sector mark, such a partition
543// tends to confuse a lot of OSes, so warn the user about such partitions. This function is
544// called by XFormToMBR() and MakeHybrid(); it's a separate function just to consolidate the
545// lengthy message in one place.
546void GPTDataTextUI::WarnAboutIffyMBRPart(int partNum) {
547 cout << "\a\nWarning! GPT partition " << partNum << " ends after the 2^32 sector mark! The partition\n"
548 << "begins before this point, and is smaller than 2^32 sectors. This is technically\n"
549 << "legal, but will confuse some OSes. The partition IS being added to the MBR, but\n"
550 << "if your OS misbehaves or can't see the partition, the partition may simply be\n"
551 << "unusable in that OS and may need to be resized or omitted from the MBR.\n\n";
552} // GPTDataTextUI::WarnAboutIffyMBRPart()
srs5694a17fe692011-09-10 20:30:20 -0400553
554/*********************************************************************
555 * *
556 * The following functions provide the main menus for the gdisk *
557 * program.... *
558 * *
559 *********************************************************************/
560
561// Accept a command and execute it. Returns only when the user
562// wants to exit (such as after a 'w' or 'q' command).
563void GPTDataTextUI::MainMenu(string filename) {
564 int goOn = 1;
565 PartType typeHelper;
566 uint32_t temp1, temp2;
srs5694a6297b82012-03-25 16:13:16 -0400567
srs5694a17fe692011-09-10 20:30:20 -0400568 do {
569 cout << "\nCommand (? for help): ";
570 switch (ReadString()[0]) {
571 case '\0':
srs5694a6297b82012-03-25 16:13:16 -0400572 goOn = cin.good();
srs5694a17fe692011-09-10 20:30:20 -0400573 break;
574 case 'b': case 'B':
575 cout << "Enter backup filename to save: ";
576 SaveGPTBackup(ReadString());
577 break;
578 case 'c': case 'C':
579 if (GetPartRange(&temp1, &temp2) > 0)
580 SetName(GetPartNum());
581 else
582 cout << "No partitions\n";
583 break;
584 case 'd': case 'D':
585 DeletePartition();
586 break;
587 case 'i': case 'I':
588 ShowDetails();
589 break;
590 case 'l': case 'L':
591 typeHelper.ShowAllTypes();
592 break;
593 case 'n': case 'N':
594 CreatePartition();
595 break;
596 case 'o': case 'O':
597 cout << "This option deletes all partitions and creates a new protective MBR.\n"
598 << "Proceed? ";
599 if (GetYN() == 'Y') {
600 ClearGPTData();
601 MakeProtectiveMBR();
602 } // if
603 break;
604 case 'p': case 'P':
605 DisplayGPTData();
606 break;
607 case 'q': case 'Q':
608 goOn = 0;
609 break;
610 case 'r': case 'R':
611 RecoveryMenu(filename);
612 goOn = 0;
613 break;
614 case 's': case 'S':
615 SortGPT();
616 cout << "You may need to edit /etc/fstab and/or your boot loader configuration!\n";
617 break;
618 case 't': case 'T':
619 ChangePartType();
620 break;
621 case 'v': case 'V':
622 Verify();
623 break;
624 case 'w': case 'W':
625 if (SaveGPTData() == 1)
626 goOn = 0;
627 break;
628 case 'x': case 'X':
629 ExpertsMenu(filename);
630 goOn = 0;
631 break;
632 default:
633 ShowCommands();
634 break;
635 } // switch
636 } while (goOn);
637} // GPTDataTextUI::MainMenu()
638
639void GPTDataTextUI::ShowCommands(void) {
640 cout << "b\tback up GPT data to a file\n";
641 cout << "c\tchange a partition's name\n";
642 cout << "d\tdelete a partition\n";
643 cout << "i\tshow detailed information on a partition\n";
644 cout << "l\tlist known partition types\n";
645 cout << "n\tadd a new partition\n";
646 cout << "o\tcreate a new empty GUID partition table (GPT)\n";
647 cout << "p\tprint the partition table\n";
648 cout << "q\tquit without saving changes\n";
649 cout << "r\trecovery and transformation options (experts only)\n";
650 cout << "s\tsort partitions\n";
651 cout << "t\tchange a partition's type code\n";
652 cout << "v\tverify disk\n";
653 cout << "w\twrite table to disk and exit\n";
654 cout << "x\textra functionality (experts only)\n";
655 cout << "?\tprint this menu\n";
656} // GPTDataTextUI::ShowCommands()
657
658// Accept a recovery & transformation menu command. Returns only when the user
659// issues an exit command, such as 'w' or 'q'.
660void GPTDataTextUI::RecoveryMenu(string filename) {
661 uint32_t numParts;
662 int goOn = 1, temp1;
663
664 do {
665 cout << "\nRecovery/transformation command (? for help): ";
666 switch (ReadString()[0]) {
667 case '\0':
srs5694a6297b82012-03-25 16:13:16 -0400668 goOn = cin.good();
srs5694a17fe692011-09-10 20:30:20 -0400669 break;
670 case 'b': case 'B':
671 RebuildMainHeader();
672 break;
673 case 'c': case 'C':
674 cout << "Warning! This will probably do weird things if you've converted an MBR to\n"
675 << "GPT form and haven't yet saved the GPT! Proceed? ";
676 if (GetYN() == 'Y')
677 LoadSecondTableAsMain();
678 break;
679 case 'd': case 'D':
680 RebuildSecondHeader();
681 break;
682 case 'e': case 'E':
683 cout << "Warning! This will probably do weird things if you've converted an MBR to\n"
684 << "GPT form and haven't yet saved the GPT! Proceed? ";
685 if (GetYN() == 'Y')
686 LoadMainTable();
687 break;
688 case 'f': case 'F':
689 cout << "Warning! This will destroy the currently defined partitions! Proceed? ";
690 if (GetYN() == 'Y') {
691 if (LoadMBR(filename) == 1) { // successful load
692 XFormPartitions();
693 } else {
694 cout << "Problem loading MBR! GPT is untouched; regenerating protective MBR!\n";
695 MakeProtectiveMBR();
696 } // if/else
697 } // if
698 break;
699 case 'g': case 'G':
700 numParts = GetNumParts();
701 temp1 = XFormToMBR();
702 if (temp1 > 0)
703 cout << "\nConverted " << temp1 << " partitions. Finalize and exit? ";
704 if ((temp1 > 0) && (GetYN() == 'Y')) {
705 if ((DestroyGPT() > 0) && (SaveMBR())) {
706 goOn = 0;
707 } // if
708 } else {
709 MakeProtectiveMBR();
srs5694706e5122012-01-21 13:47:24 -0500710 SetGPTSize(numParts, 0);
srs5694a17fe692011-09-10 20:30:20 -0400711 cout << "Note: New protective MBR created\n\n";
712 } // if/else
713 break;
714 case 'h': case 'H':
715 MakeHybrid();
716 break;
717 case 'i': case 'I':
718 ShowDetails();
719 break;
720 case 'l': case 'L':
721 cout << "Enter backup filename to load: ";
722 LoadGPTBackup(ReadString());
723 break;
724 case 'm': case 'M':
725 MainMenu(filename);
726 goOn = 0;
727 break;
728 case 'o': case 'O':
729 DisplayMBRData();
730 break;
731 case 'p': case 'P':
732 DisplayGPTData();
733 break;
734 case 'q': case 'Q':
735 goOn = 0;
736 break;
737 case 't': case 'T':
738 XFormDisklabel();
739 break;
740 case 'v': case 'V':
741 Verify();
742 break;
743 case 'w': case 'W':
744 if (SaveGPTData() == 1) {
745 goOn = 0;
746 } // if
747 break;
748 case 'x': case 'X':
749 ExpertsMenu(filename);
750 goOn = 0;
751 break;
752 default:
753 ShowRecoveryCommands();
754 break;
755 } // switch
756 } while (goOn);
757} // GPTDataTextUI::RecoveryMenu()
758
759void GPTDataTextUI::ShowRecoveryCommands(void) {
760 cout << "b\tuse backup GPT header (rebuilding main)\n";
761 cout << "c\tload backup partition table from disk (rebuilding main)\n";
762 cout << "d\tuse main GPT header (rebuilding backup)\n";
763 cout << "e\tload main partition table from disk (rebuilding backup)\n";
764 cout << "f\tload MBR and build fresh GPT from it\n";
765 cout << "g\tconvert GPT into MBR and exit\n";
766 cout << "h\tmake hybrid MBR\n";
767 cout << "i\tshow detailed information on a partition\n";
768 cout << "l\tload partition data from a backup file\n";
769 cout << "m\treturn to main menu\n";
770 cout << "o\tprint protective MBR data\n";
771 cout << "p\tprint the partition table\n";
772 cout << "q\tquit without saving changes\n";
773 cout << "t\ttransform BSD disklabel partition\n";
774 cout << "v\tverify disk\n";
775 cout << "w\twrite table to disk and exit\n";
776 cout << "x\textra functionality (experts only)\n";
777 cout << "?\tprint this menu\n";
778} // GPTDataTextUI::ShowRecoveryCommands()
779
780// Accept an experts' menu command. Returns only after the user
781// selects an exit command, such as 'w' or 'q'.
782void GPTDataTextUI::ExpertsMenu(string filename) {
783 GPTData secondDevice;
784 uint32_t temp1, temp2;
785 int goOn = 1;
786 string guidStr, device;
787 GUIDData aGUID;
788 ostringstream prompt;
789
790 do {
791 cout << "\nExpert command (? for help): ";
792 switch (ReadString()[0]) {
793 case '\0':
srs5694a6297b82012-03-25 16:13:16 -0400794 goOn = cin.good();
srs5694a17fe692011-09-10 20:30:20 -0400795 break;
796 case 'a': case 'A':
797 if (GetPartRange(&temp1, &temp2) > 0)
798 SetAttributes(GetPartNum());
799 else
800 cout << "No partitions\n";
801 break;
802 case 'c': case 'C':
803 ChangeUniqueGuid();
804 break;
805 case 'd': case 'D':
806 cout << "Partitions will begin on " << GetAlignment()
807 << "-sector boundaries.\n";
808 break;
809 case 'e': case 'E':
810 cout << "Relocating backup data structures to the end of the disk\n";
811 MoveSecondHeaderToEnd();
812 break;
813 case 'f': case 'F':
814 RandomizeGUIDs();
815 break;
816 case 'g': case 'G':
817 cout << "Enter the disk's unique GUID ('R' to randomize): ";
818 guidStr = ReadString();
819 if ((guidStr.length() >= 32) || (guidStr[0] == 'R') || (guidStr[0] == 'r')) {
820 SetDiskGUID((GUIDData) guidStr);
821 cout << "The new disk GUID is " << GetDiskGUID() << "\n";
822 } else {
823 cout << "GUID is too short!\n";
824 } // if/else
825 break;
826 case 'h': case 'H':
827 RecomputeCHS();
828 break;
829 case 'i': case 'I':
830 ShowDetails();
831 break;
Rod Smith503e9ad2017-07-21 21:48:13 -0400832 case 'j': case 'J':
833 MoveMainTable();
834 break;
srs5694a17fe692011-09-10 20:30:20 -0400835 case 'l': case 'L':
836 prompt.seekp(0);
837 prompt << "Enter the sector alignment value (1-" << MAX_ALIGNMENT << ", default = "
838 << DEFAULT_ALIGNMENT << "): ";
839 temp1 = GetNumber(1, MAX_ALIGNMENT, DEFAULT_ALIGNMENT, prompt.str());
840 SetAlignment(temp1);
841 break;
842 case 'm': case 'M':
843 MainMenu(filename);
844 goOn = 0;
845 break;
846 case 'n': case 'N':
847 MakeProtectiveMBR();
848 break;
849 case 'o': case 'O':
850 DisplayMBRData();
851 break;
852 case 'p': case 'P':
853 DisplayGPTData();
854 break;
855 case 'q': case 'Q':
856 goOn = 0;
857 break;
858 case 'r': case 'R':
859 RecoveryMenu(filename);
860 goOn = 0;
861 break;
862 case 's': case 'S':
863 ResizePartitionTable();
864 break;
865 case 't': case 'T':
866 SwapPartitions();
867 break;
868 case 'u': case 'U':
869 cout << "Type device filename, or press <Enter> to exit: ";
870 device = ReadString();
871 if (device.length() > 0) {
872 secondDevice = *this;
873 secondDevice.SetDisk(device);
874 secondDevice.SaveGPTData(0);
875 } // if
876 break;
877 case 'v': case 'V':
878 Verify();
879 break;
880 case 'w': case 'W':
881 if (SaveGPTData() == 1) {
882 goOn = 0;
883 } // if
884 break;
885 case 'z': case 'Z':
886 if (DestroyGPTwPrompt() == 1) {
887 goOn = 0;
888 }
889 break;
890 default:
891 ShowExpertCommands();
892 break;
893 } // switch
894 } while (goOn);
895} // GPTDataTextUI::ExpertsMenu()
896
897void GPTDataTextUI::ShowExpertCommands(void) {
898 cout << "a\tset attributes\n";
899 cout << "c\tchange partition GUID\n";
900 cout << "d\tdisplay the sector alignment value\n";
901 cout << "e\trelocate backup data structures to the end of the disk\n";
Rod Smith503e9ad2017-07-21 21:48:13 -0400902 cout << "f\trandomize disk and partition unique GUIDs\n";
srs5694a17fe692011-09-10 20:30:20 -0400903 cout << "g\tchange disk GUID\n";
904 cout << "h\trecompute CHS values in protective/hybrid MBR\n";
905 cout << "i\tshow detailed information on a partition\n";
Rod Smith503e9ad2017-07-21 21:48:13 -0400906 cout << "j\tmove the main partition table\n";
srs5694a17fe692011-09-10 20:30:20 -0400907 cout << "l\tset the sector alignment value\n";
908 cout << "m\treturn to main menu\n";
909 cout << "n\tcreate a new protective MBR\n";
910 cout << "o\tprint protective MBR data\n";
911 cout << "p\tprint the partition table\n";
912 cout << "q\tquit without saving changes\n";
913 cout << "r\trecovery and transformation options (experts only)\n";
914 cout << "s\tresize partition table\n";
915 cout << "t\ttranspose two partition table entries\n";
Roderick W. Smith84aaff62014-02-17 16:17:11 -0500916 cout << "u\treplicate partition table on new device\n";
srs5694a17fe692011-09-10 20:30:20 -0400917 cout << "v\tverify disk\n";
918 cout << "w\twrite table to disk and exit\n";
919 cout << "z\tzap (destroy) GPT data structures and exit\n";
920 cout << "?\tprint this menu\n";
921} // GPTDataTextUI::ShowExpertCommands()
922
923
924
srs5694699941e2011-03-21 21:33:57 -0400925/********************************
926 * *
927 * Non-class support functions. *
928 * *
929 ********************************/
930
931// GetMBRTypeCode() doesn't really belong in the class, since it's MBR-
932// specific, but it's also user I/O-related, so I want to keep it in
933// this file....
srs5694fad06422010-02-19 17:19:17 -0500934
935// Get an MBR type code from the user and return it
936int GetMBRTypeCode(int defType) {
srs56945a608532011-03-17 13:53:01 -0400937 string line;
srs5694fad06422010-02-19 17:19:17 -0500938 int typeCode;
939
940 cout.setf(ios::uppercase);
941 cout.fill('0');
942 do {
943 cout << "Enter an MBR hex code (default " << hex;
944 cout.width(2);
945 cout << defType << "): " << dec;
srs56945a608532011-03-17 13:53:01 -0400946 line = ReadString();
947 if (line[0] == '\0')
srs5694fad06422010-02-19 17:19:17 -0500948 typeCode = defType;
949 else
srs56945a608532011-03-17 13:53:01 -0400950 typeCode = StrToHex(line, 0);
srs5694fad06422010-02-19 17:19:17 -0500951 } while ((typeCode <= 0) || (typeCode > 255));
952 cout.fill(' ');
953 return typeCode;
srs56941c6f8b02010-02-21 11:09:20 -0500954} // GetMBRTypeCode
srs5694699941e2011-03-21 21:33:57 -0400955
Roderick W. Smith84aaff62014-02-17 16:17:11 -0500956#ifdef USE_UTF16
srs5694699941e2011-03-21 21:33:57 -0400957// Note: ReadUString() is here rather than in support.cc so that the ICU
958// libraries need not be linked to fixparts.
959
960// Reads a Unicode string from stdin, returning it as an ICU-style string.
961// Note that the returned string will NOT include the carriage return
962// entered by the user. Relies on the ICU constructor from a string
963// encoded in the current codepage to work.
964UnicodeString ReadUString(void) {
965 return ReadString().c_str();
966} // ReadUString()
Roderick W. Smith84aaff62014-02-17 16:17:11 -0500967#endif
srs5694699941e2011-03-21 21:33:57 -0400968