blob: cd1c07abdf6a4b7690b5ad11cb4015b009a60c41 [file] [log] [blame]
srs5694fad06422010-02-19 17:19:17 -05001/*
srs5694699941e2011-03-21 21:33:57 -04002 Copyright (C) 2010-2011 <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>
28#include <sstream>
srs56941c6f8b02010-02-21 11:09:20 -050029#include <cstdio>
srs5694fad06422010-02-19 17:19:17 -050030#include "attributes.h"
31#include "gpttext.h"
srs569455d92612010-03-07 22:16:07 -050032#include "support.h"
srs5694fad06422010-02-19 17:19:17 -050033
34using namespace std;
35
srs5694a17fe692011-09-10 20:30:20 -040036/********************************************
37 * *
38 * GPTDataText class and related structures *
39 * *
40 ********************************************/
srs5694fad06422010-02-19 17:19:17 -050041
42GPTDataTextUI::GPTDataTextUI(void) : GPTData() {
43} // default constructor
44
45GPTDataTextUI::GPTDataTextUI(string filename) : GPTData(filename) {
46} // constructor passing filename
47
48GPTDataTextUI::~GPTDataTextUI(void) {
49} // default destructor
50
51/*********************************************************************
52 * *
53 * The following functions are extended (interactive) versions of *
54 * simpler functions in the base class.... *
55 * *
56 *********************************************************************/
57
58// Overridden function; calls base-class function and then makes
59// additional queries of the user, if the base-class function can't
60// decide what to do.
61WhichToUse GPTDataTextUI::UseWhichPartitions(void) {
62 WhichToUse which;
63 MBRValidity mbrState;
64 int answer;
65
66 which = GPTData::UseWhichPartitions();
67 if ((which != use_abort) || beQuiet)
68 return which;
69
70 // If we get past here, it means that the non-interactive tests were
71 // inconclusive, so we must ask the user which table to use....
72 mbrState = protectiveMBR.GetValidity();
73
74 if ((state == gpt_valid) && (mbrState == mbr)) {
75 cout << "Found valid MBR and GPT. Which do you want to use?\n";
76 answer = GetNumber(1, 3, 2, " 1 - MBR\n 2 - GPT\n 3 - Create blank GPT\n\nYour answer: ");
77 if (answer == 1) {
78 which = use_mbr;
79 } else if (answer == 2) {
80 which = use_gpt;
81 cout << "Using GPT and creating fresh protective MBR.\n";
82 } else which = use_new;
83 } // if
84
85 // Nasty decisions here -- GPT is present, but corrupt (bad CRCs or other
86 // problems)
87 if (state == gpt_corrupt) {
88 if ((mbrState == mbr) || (mbrState == hybrid)) {
89 cout << "Found valid MBR and corrupt GPT. Which do you want to use? (Using the\n"
90 << "GPT MAY permit recovery of GPT data.)\n";
91 answer = GetNumber(1, 3, 2, " 1 - MBR\n 2 - GPT\n 3 - Create blank GPT\n\nYour answer: ");
92 if (answer == 1) {
93 which = use_mbr;
94 } else if (answer == 2) {
95 which = use_gpt;
96 } else which = use_new;
97 } else if (mbrState == invalid) {
98 cout << "Found invalid MBR and corrupt GPT. What do you want to do? (Using the\n"
99 << "GPT MAY permit recovery of GPT data.)\n";
srs56940283dae2010-04-28 16:44:34 -0400100 answer = GetNumber(1, 2, 1, " 1 - Use current GPT\n 2 - Create blank GPT\n\nYour answer: ");
srs5694fad06422010-02-19 17:19:17 -0500101 if (answer == 1) {
102 which = use_gpt;
103 } else which = use_new;
104 } // if/else/else
105 } // if (corrupt GPT)
106
107 return which;
108} // UseWhichPartitions()
109
110// Ask the user for a partition number; and prompt for verification
111// if the requested partition isn't of a known BSD type.
112// Lets the base-class function do the work, and returns its value (the
113// number of converted partitions).
114int GPTDataTextUI::XFormDisklabel(void) {
115 uint32_t partNum;
116 uint16_t hexCode;
117 int goOn = 1, numDone = 0;
118 BSDData disklabel;
119
120 partNum = GetPartNum();
121
122 // Now see if the specified partition has a BSD type code....
123 hexCode = partitions[partNum].GetHexType();
124 if ((hexCode != 0xa500) && (hexCode != 0xa900)) {
125 cout << "Specified partition doesn't have a disklabel partition type "
126 << "code.\nContinue anyway? ";
127 goOn = (GetYN() == 'Y');
128 } // if
129
130 if (goOn)
131 numDone = GPTData::XFormDisklabel(partNum);
132
133 return numDone;
134} // GPTData::XFormDisklabel(int i)
135
srs569455d92612010-03-07 22:16:07 -0500136
srs5694fad06422010-02-19 17:19:17 -0500137/*********************************************************************
138 * *
139 * Begin functions that obtain information from the users, and often *
140 * do something with that information (call other functions) *
141 * *
142 *********************************************************************/
143
srs5694a17fe692011-09-10 20:30:20 -0400144// Prompts user for partition number and returns the result. Returns "0"
145// (the first partition) if none are currently defined.
srs5694fad06422010-02-19 17:19:17 -0500146uint32_t GPTDataTextUI::GetPartNum(void) {
147 uint32_t partNum;
148 uint32_t low, high;
149 ostringstream prompt;
150
151 if (GetPartRange(&low, &high) > 0) {
152 prompt << "Partition number (" << low + 1 << "-" << high + 1 << "): ";
153 partNum = GetNumber(low + 1, high + 1, low, prompt.str());
154 } else partNum = 1;
155 return (partNum - 1);
156} // GPTDataTextUI::GetPartNum()
157
158// What it says: Resize the partition table. (Default is 128 entries.)
159void GPTDataTextUI::ResizePartitionTable(void) {
160 int newSize;
161 ostringstream prompt;
162 uint32_t curLow, curHigh;
163
srs56940283dae2010-04-28 16:44:34 -0400164 cout << "Current partition table size is " << numParts << ".\n";
srs5694fad06422010-02-19 17:19:17 -0500165 GetPartRange(&curLow, &curHigh);
166 curHigh++; // since GetPartRange() returns numbers starting from 0...
167 // There's no point in having fewer than four partitions....
168 if (curHigh < (blockSize / GPT_SIZE))
169 curHigh = blockSize / GPT_SIZE;
170 prompt << "Enter new size (" << curHigh << " up, default " << NUM_GPT_ENTRIES << "): ";
171 newSize = GetNumber(4, 65535, 128, prompt.str());
172 if (newSize < 128) {
173 cout << "Caution: The partition table size should officially be 16KB or larger,\n"
174 << "which works out to 128 entries. In practice, smaller tables seem to\n"
175 << "work with most OSes, but this practice is risky. I'm proceeding with\n"
176 << "the resize, but you may want to reconsider this action and undo it.\n\n";
177 } // if
178 SetGPTSize(newSize);
179} // GPTDataTextUI::ResizePartitionTable()
180
181// Interactively create a partition
182void GPTDataTextUI::CreatePartition(void) {
srs56945a081752010-09-24 20:39:41 -0400183 uint64_t firstBlock, firstInLargest, lastBlock, sector, origSector;
srs5694fad06422010-02-19 17:19:17 -0500184 uint32_t firstFreePart = 0;
185 ostringstream prompt1, prompt2, prompt3;
186 int partNum;
187
188 // Find first free partition...
189 while (partitions[firstFreePart].GetFirstLBA() != 0) {
190 firstFreePart++;
191 } // while
192
193 if (((firstBlock = FindFirstAvailable()) != 0) &&
srs56940283dae2010-04-28 16:44:34 -0400194 (firstFreePart < numParts)) {
srs5694fad06422010-02-19 17:19:17 -0500195 lastBlock = FindLastAvailable();
srs569455d92612010-03-07 22:16:07 -0500196 firstInLargest = FindFirstInLargest();
197
198 // Get partition number....
199 do {
srs56940283dae2010-04-28 16:44:34 -0400200 prompt1 << "Partition number (" << firstFreePart + 1 << "-" << numParts
srs569455d92612010-03-07 22:16:07 -0500201 << ", default " << firstFreePart + 1 << "): ";
srs56940283dae2010-04-28 16:44:34 -0400202 partNum = GetNumber(firstFreePart + 1, numParts,
srs569455d92612010-03-07 22:16:07 -0500203 firstFreePart + 1, prompt1.str()) - 1;
204 if (partitions[partNum].GetFirstLBA() != 0)
205 cout << "partition " << partNum + 1 << " is in use.\n";
206 } while (partitions[partNum].GetFirstLBA() != 0);
207
208 // Get first block for new partition...
209 prompt2 << "First sector (" << firstBlock << "-" << lastBlock << ", default = "
srs56940873e9d2010-10-07 13:00:45 -0400210 << firstInLargest << ") or {+-}size{KMGTP}: ";
srs569455d92612010-03-07 22:16:07 -0500211 do {
srs56940873e9d2010-10-07 13:00:45 -0400212 sector = GetSectorNum(firstBlock, lastBlock, firstInLargest, blockSize, prompt2.str());
srs569455d92612010-03-07 22:16:07 -0500213 } while (IsFree(sector) == 0);
srs56945a081752010-09-24 20:39:41 -0400214 origSector = sector;
215 if (Align(&sector)) {
216 cout << "Information: Moved requested sector from " << origSector << " to "
217 << sector << " in\norder to align on " << sectorAlignment
218 << "-sector boundaries.\n";
219 if (!beQuiet)
220 cout << "Use 'l' on the experts' menu to adjust alignment\n";
221 } // if
222 // Align(&sector); // Align sector to correct multiple
srs569455d92612010-03-07 22:16:07 -0500223 firstBlock = sector;
224
225 // Get last block for new partitions...
226 lastBlock = FindLastInFree(firstBlock);
227 prompt3 << "Last sector (" << firstBlock << "-" << lastBlock << ", default = "
srs56940873e9d2010-10-07 13:00:45 -0400228 << lastBlock << ") or {+-}size{KMGTP}: ";
srs569455d92612010-03-07 22:16:07 -0500229 do {
srs56940873e9d2010-10-07 13:00:45 -0400230 sector = GetSectorNum(firstBlock, lastBlock, lastBlock, blockSize, prompt3.str());
srs569455d92612010-03-07 22:16:07 -0500231 } while (IsFree(sector) == 0);
232 lastBlock = sector;
233
234 firstFreePart = GPTData::CreatePartition(partNum, firstBlock, lastBlock);
235 partitions[partNum].ChangeType();
236 partitions[partNum].SetDefaultDescription();
srs5694fad06422010-02-19 17:19:17 -0500237 } else {
srs5694bf8950c2011-03-12 01:23:12 -0500238 if (firstFreePart >= numParts)
239 cout << "No table partition entries left\n";
240 else
241 cout << "No free sectors available\n";
srs5694fad06422010-02-19 17:19:17 -0500242 } // if/else
243} // GPTDataTextUI::CreatePartition()
244
245// Interactively delete a partition (duh!)
246void GPTDataTextUI::DeletePartition(void) {
247 int partNum;
248 uint32_t low, high;
249 ostringstream prompt;
250
251 if (GetPartRange(&low, &high) > 0) {
252 prompt << "Partition number (" << low + 1 << "-" << high + 1 << "): ";
253 partNum = GetNumber(low + 1, high + 1, low, prompt.str());
254 GPTData::DeletePartition(partNum - 1);
255 } else {
256 cout << "No partitions\n";
257 } // if/else
258} // GPTDataTextUI::DeletePartition()
259
260// Prompt user for a partition number, then change its type code
srs5694fad06422010-02-19 17:19:17 -0500261void GPTDataTextUI::ChangePartType(void) {
262 int partNum;
263 uint32_t low, high;
srs569455d92612010-03-07 22:16:07 -0500264
srs5694fad06422010-02-19 17:19:17 -0500265 if (GetPartRange(&low, &high) > 0) {
266 partNum = GetPartNum();
267 partitions[partNum].ChangeType();
268 } else {
269 cout << "No partitions\n";
270 } // if/else
271} // GPTDataTextUI::ChangePartType()
272
srs5694815fb652011-03-18 12:35:56 -0400273// Prompt user for a partition number, then change its unique
274// GUID.
275void GPTDataTextUI::ChangeUniqueGuid(void) {
276 int partNum;
277 uint32_t low, high;
278 string guidStr;
279
280 if (GetPartRange(&low, &high) > 0) {
281 partNum = GetPartNum();
282 cout << "Enter the partition's new unique GUID ('R' to randomize): ";
283 guidStr = ReadString();
284 if ((guidStr.length() >= 32) || (guidStr[0] == 'R') || (guidStr[0] == 'r')) {
285 SetPartitionGUID(partNum, (GUIDData) guidStr);
286 cout << "New GUID is " << partitions[partNum].GetUniqueGUID() << "\n";
287 } else {
288 cout << "GUID is too short!\n";
289 } // if/else
290 } else
291 cout << "No partitions\n";
292} // GPTDataTextUI::ChangeUniqueGuid()
293
srs5694fad06422010-02-19 17:19:17 -0500294// Partition attributes seem to be rarely used, but I want a way to
295// adjust them for completeness....
296void GPTDataTextUI::SetAttributes(uint32_t partNum) {
srs56940873e9d2010-10-07 13:00:45 -0400297 partitions[partNum].SetAttributes();
srs5694fad06422010-02-19 17:19:17 -0500298} // GPTDataTextUI::SetAttributes()
299
srs5694699941e2011-03-21 21:33:57 -0400300// Prompts the user for a partition name and sets the partition's
301// name. Returns 1 on success, 0 on failure (invalid partition
302// number). (Note that the function skips prompting when an
303// invalid partition number is detected.)
304int GPTDataTextUI::SetName(uint32_t partNum) {
305 UnicodeString theName = "";
306 int retval = 1;
307
308 if (IsUsedPartNum(partNum)) {
309 cout << "Enter name: ";
310 theName = ReadUString();
311 partitions[partNum].SetName(theName);
312 } else {
313 cerr << "Invalid partition number (" << partNum << ")\n";
314 retval = 0;
315 } // if/else
316
317 return retval;
318} // GPTDataTextUI::SetName()
319
srs5694fad06422010-02-19 17:19:17 -0500320// Ask user for two partition numbers and swap them in the table. Note that
321// this just reorders table entries; it doesn't adjust partition layout on
322// the disk.
323// Returns 1 if successful, 0 if not. (If user enters identical numbers, it
324// counts as successful.)
325int GPTDataTextUI::SwapPartitions(void) {
326 int partNum1, partNum2, didIt = 0;
327 uint32_t low, high;
328 ostringstream prompt;
329 GPTPart temp;
330
331 if (GetPartRange(&low, &high) > 0) {
332 partNum1 = GetPartNum();
srs56940283dae2010-04-28 16:44:34 -0400333 if (high >= numParts - 1)
srs5694fad06422010-02-19 17:19:17 -0500334 high = 0;
srs56940283dae2010-04-28 16:44:34 -0400335 prompt << "New partition number (1-" << numParts
srs569455d92612010-03-07 22:16:07 -0500336 << ", default " << high + 2 << "): ";
srs56940283dae2010-04-28 16:44:34 -0400337 partNum2 = GetNumber(1, numParts, high + 2, prompt.str()) - 1;
srs5694fad06422010-02-19 17:19:17 -0500338 didIt = GPTData::SwapPartitions(partNum1, partNum2);
339 } else {
340 cout << "No partitions\n";
341 } // if/else
342 return didIt;
343} // GPTDataTextUI::SwapPartitionNumbers()
344
345// This function destroys the on-disk GPT structures. Returns 1 if the user
346// confirms destruction, 0 if the user aborts or if there's a disk error.
347int GPTDataTextUI::DestroyGPTwPrompt(void) {
348 int allOK = 1;
349
350 if ((apmFound) || (bsdFound)) {
351 cout << "WARNING: APM or BSD disklabel structures detected! This operation could\n"
352 << "damage any APM or BSD partitions on this disk!\n";
353 } // if APM or BSD
354 cout << "\a\aAbout to wipe out GPT on " << device << ". Proceed? ";
355 if (GetYN() == 'Y') {
356 if (DestroyGPT()) {
357 // Note on below: Touch the MBR only if the user wants it completely
358 // blanked out. Version 0.4.2 deleted the 0xEE partition and re-wrote
359 // the MBR, but this could wipe out a valid MBR that the program
360 // had subsequently discarded (say, if it conflicted with older GPT
361 // structures).
362 cout << "Blank out MBR? ";
363 if (GetYN() == 'Y') {
364 DestroyMBR();
365 } else {
366 cout << "MBR is unchanged. You may need to delete an EFI GPT (0xEE) partition\n"
367 << "with fdisk or another tool.\n";
368 } // if/else
369 } else allOK = 0; // if GPT structures destroyed
370 } else allOK = 0; // if user confirms destruction
371 return (allOK);
372} // GPTDataTextUI::DestroyGPTwPrompt()
373
374// Get partition number from user and then call ShowPartDetails(partNum)
375// to show its detailed information
376void GPTDataTextUI::ShowDetails(void) {
377 int partNum;
378 uint32_t low, high;
srs569455d92612010-03-07 22:16:07 -0500379
srs5694fad06422010-02-19 17:19:17 -0500380 if (GetPartRange(&low, &high) > 0) {
381 partNum = GetPartNum();
382 ShowPartDetails(partNum);
383 } else {
384 cout << "No partitions\n";
385 } // if/else
386} // GPTDataTextUI::ShowDetails()
387
388// Create a hybrid MBR -- an ugly, funky thing that helps GPT work with
389// OSes that don't understand GPT.
390void GPTDataTextUI::MakeHybrid(void) {
391 uint32_t partNums[3];
srs56945a608532011-03-17 13:53:01 -0400392 string line;
srs5694bf8950c2011-03-12 01:23:12 -0500393 int numPartsToCvt, i, j, mbrNum = 0;
srs569455d92612010-03-07 22:16:07 -0500394 unsigned int hexCode = 0;
srs5694bf8950c2011-03-12 01:23:12 -0500395 MBRPart hybridPart;
396 MBRData hybridMBR;
srs5694fad06422010-02-19 17:19:17 -0500397 char eeFirst = 'Y'; // Whether EFI GPT (0xEE) partition comes first in table
398
srs5694058d4a52010-10-12 12:42:47 -0400399 cout << "\nWARNING! Hybrid MBRs are flaky and dangerous! If you decide not to use one,\n"
400 << "just hit the Enter key at the below prompt and your MBR partition table will\n"
401 << "be untouched.\n\n\a";
srs5694fad06422010-02-19 17:19:17 -0500402
srs56946aae2a92011-06-10 01:16:51 -0400403 // Use a local MBR structure, copying from protectiveMBR to keep its
404 // boot loader code intact....
405 hybridMBR = protectiveMBR;
406 hybridMBR.EmptyMBR(0);
407
srs5694fad06422010-02-19 17:19:17 -0500408 // Now get the numbers of up to three partitions to add to the
409 // hybrid MBR....
410 cout << "Type from one to three GPT partition numbers, separated by spaces, to be\n"
411 << "added to the hybrid MBR, in sequence: ";
srs56945a608532011-03-17 13:53:01 -0400412 line = ReadString();
413 numPartsToCvt = sscanf(line.c_str(), "%d %d %d", &partNums[0], &partNums[1], &partNums[2]);
srs5694fad06422010-02-19 17:19:17 -0500414
srs56940283dae2010-04-28 16:44:34 -0400415 if (numPartsToCvt > 0) {
srs5694fad06422010-02-19 17:19:17 -0500416 cout << "Place EFI GPT (0xEE) partition first in MBR (good for GRUB)? ";
417 eeFirst = GetYN();
418 } // if
419
srs56940283dae2010-04-28 16:44:34 -0400420 for (i = 0; i < numPartsToCvt; i++) {
srs5694bf8950c2011-03-12 01:23:12 -0500421 j = partNums[i] - 1;
srs5694058d4a52010-10-12 12:42:47 -0400422 if (partitions[j].IsUsed()) {
423 mbrNum = i + (eeFirst == 'Y');
424 cout << "\nCreating entry for GPT partition #" << j + 1
425 << " (MBR partition #" << mbrNum + 1 << ")\n";
srs5694bf8950c2011-03-12 01:23:12 -0500426 hybridPart.SetType(GetMBRTypeCode(partitions[j].GetHexType() / 256));
427 hybridPart.SetLocation(partitions[j].GetFirstLBA(), partitions[j].GetLengthLBA());
428 hybridPart.SetInclusion(PRIMARY);
srs5694058d4a52010-10-12 12:42:47 -0400429 cout << "Set the bootable flag? ";
430 if (GetYN() == 'Y')
srs56946aae2a92011-06-10 01:16:51 -0400431 hybridPart.SetStatus(0x80);
srs5694058d4a52010-10-12 12:42:47 -0400432 else
srs56946aae2a92011-06-10 01:16:51 -0400433 hybridPart.SetStatus(0x00);
srs5694bf8950c2011-03-12 01:23:12 -0500434 hybridPart.SetInclusion(PRIMARY);
srs5694058d4a52010-10-12 12:42:47 -0400435 } else {
srs5694058d4a52010-10-12 12:42:47 -0400436 cerr << "\nGPT partition #" << j + 1 << " does not exist; skipping.\n";
437 } // if/else
srs5694bf8950c2011-03-12 01:23:12 -0500438 hybridMBR.AddPart(mbrNum, hybridPart);
srs5694fad06422010-02-19 17:19:17 -0500439 } // for
440
srs56940283dae2010-04-28 16:44:34 -0400441 if (numPartsToCvt > 0) { // User opted to create a hybrid MBR....
srs5694fad06422010-02-19 17:19:17 -0500442 // Create EFI protective partition that covers the start of the disk.
443 // If this location (covering the main GPT data structures) is omitted,
444 // Linux won't find any partitions on the disk.
srs5694bf8950c2011-03-12 01:23:12 -0500445 hybridPart.SetLocation(1, hybridMBR.FindLastInFree(1));
446 hybridPart.SetStatus(0);
447 hybridPart.SetType(0xEE);
448 hybridPart.SetInclusion(PRIMARY);
srs569455d92612010-03-07 22:16:07 -0500449 // newNote firstLBA and lastLBA are computed later...
450 if (eeFirst == 'Y') {
srs5694bf8950c2011-03-12 01:23:12 -0500451 hybridMBR.AddPart(0, hybridPart);
srs569455d92612010-03-07 22:16:07 -0500452 } else {
srs5694bf8950c2011-03-12 01:23:12 -0500453 hybridMBR.AddPart(3, hybridPart);
srs569455d92612010-03-07 22:16:07 -0500454 } // else
srs5694bf8950c2011-03-12 01:23:12 -0500455 hybridMBR.SetHybrid();
srs5694fad06422010-02-19 17:19:17 -0500456
457 // ... and for good measure, if there are any partition spaces left,
458 // optionally create another protective EFI partition to cover as much
459 // space as possible....
srs5694bf8950c2011-03-12 01:23:12 -0500460 if (hybridMBR.CountParts() < 4) { // unused entry....
srs569455d92612010-03-07 22:16:07 -0500461 cout << "\nUnused partition space(s) found. Use one to protect more partitions? ";
462 if (GetYN() == 'Y') {
srs56945a608532011-03-17 13:53:01 -0400463 cout << "Note: Default is 0xEE, but this may confuse Mac OS X.\n";
464 // Comment on above: Mac OS treats disks with more than one
465 // 0xEE MBR partition as MBR disks, not as GPT disks.
466 hexCode = GetMBRTypeCode(0xEE);
467 hybridMBR.MakeBiggestPart(3, hexCode);
srs569455d92612010-03-07 22:16:07 -0500468 } // if (GetYN() == 'Y')
469 } // if unused entry
srs5694bf8950c2011-03-12 01:23:12 -0500470 protectiveMBR = hybridMBR;
srs56940283dae2010-04-28 16:44:34 -0400471 } // if (numPartsToCvt > 0)
srs5694fad06422010-02-19 17:19:17 -0500472} // GPTDataTextUI::MakeHybrid()
473
srs569455d92612010-03-07 22:16:07 -0500474// Convert the GPT to MBR form, storing partitions in the protectiveMBR
475// variable. This function is necessarily limited; it may not be able to
476// convert all partitions, depending on the disk size and available space
477// before each partition (one free sector is required to create a logical
478// partition, which are necessary to convert more than four partitions).
479// Returns the number of converted partitions; if this value
srs5694fad06422010-02-19 17:19:17 -0500480// is over 0, the calling function should call DestroyGPT() to destroy
srs569455d92612010-03-07 22:16:07 -0500481// the GPT data, call SaveMBR() to save the MBR, and then exit.
srs5694fad06422010-02-19 17:19:17 -0500482int GPTDataTextUI::XFormToMBR(void) {
srs569455d92612010-03-07 22:16:07 -0500483 uint32_t i;
srs5694fad06422010-02-19 17:19:17 -0500484
srs56946aae2a92011-06-10 01:16:51 -0400485 protectiveMBR.EmptyMBR(0);
srs5694bf8950c2011-03-12 01:23:12 -0500486 for (i = 0; i < numParts; i++) {
487 if (partitions[i].IsUsed()) {
488 protectiveMBR.MakePart(i, partitions[i].GetFirstLBA(),
489 partitions[i].GetLengthLBA(),
490 partitions[i].GetHexType() / 0x0100, 0);
491 } // if
492 } // for
493 protectiveMBR.MakeItLegal();
494 return protectiveMBR.DoMenu();
srs5694fad06422010-02-19 17:19:17 -0500495} // GPTDataTextUI::XFormToMBR()
496
srs5694a17fe692011-09-10 20:30:20 -0400497
498/*********************************************************************
499 * *
500 * The following functions provide the main menus for the gdisk *
501 * program.... *
502 * *
503 *********************************************************************/
504
505// Accept a command and execute it. Returns only when the user
506// wants to exit (such as after a 'w' or 'q' command).
507void GPTDataTextUI::MainMenu(string filename) {
508 int goOn = 1;
509 PartType typeHelper;
510 uint32_t temp1, temp2;
511
512 do {
513 cout << "\nCommand (? for help): ";
514 switch (ReadString()[0]) {
515 case '\0':
516 break;
517 case 'b': case 'B':
518 cout << "Enter backup filename to save: ";
519 SaveGPTBackup(ReadString());
520 break;
521 case 'c': case 'C':
522 if (GetPartRange(&temp1, &temp2) > 0)
523 SetName(GetPartNum());
524 else
525 cout << "No partitions\n";
526 break;
527 case 'd': case 'D':
528 DeletePartition();
529 break;
530 case 'i': case 'I':
531 ShowDetails();
532 break;
533 case 'l': case 'L':
534 typeHelper.ShowAllTypes();
535 break;
536 case 'n': case 'N':
537 CreatePartition();
538 break;
539 case 'o': case 'O':
540 cout << "This option deletes all partitions and creates a new protective MBR.\n"
541 << "Proceed? ";
542 if (GetYN() == 'Y') {
543 ClearGPTData();
544 MakeProtectiveMBR();
545 } // if
546 break;
547 case 'p': case 'P':
548 DisplayGPTData();
549 break;
550 case 'q': case 'Q':
551 goOn = 0;
552 break;
553 case 'r': case 'R':
554 RecoveryMenu(filename);
555 goOn = 0;
556 break;
557 case 's': case 'S':
558 SortGPT();
559 cout << "You may need to edit /etc/fstab and/or your boot loader configuration!\n";
560 break;
561 case 't': case 'T':
562 ChangePartType();
563 break;
564 case 'v': case 'V':
565 Verify();
566 break;
567 case 'w': case 'W':
568 if (SaveGPTData() == 1)
569 goOn = 0;
570 break;
571 case 'x': case 'X':
572 ExpertsMenu(filename);
573 goOn = 0;
574 break;
575 default:
576 ShowCommands();
577 break;
578 } // switch
579 } while (goOn);
580} // GPTDataTextUI::MainMenu()
581
582void GPTDataTextUI::ShowCommands(void) {
583 cout << "b\tback up GPT data to a file\n";
584 cout << "c\tchange a partition's name\n";
585 cout << "d\tdelete a partition\n";
586 cout << "i\tshow detailed information on a partition\n";
587 cout << "l\tlist known partition types\n";
588 cout << "n\tadd a new partition\n";
589 cout << "o\tcreate a new empty GUID partition table (GPT)\n";
590 cout << "p\tprint the partition table\n";
591 cout << "q\tquit without saving changes\n";
592 cout << "r\trecovery and transformation options (experts only)\n";
593 cout << "s\tsort partitions\n";
594 cout << "t\tchange a partition's type code\n";
595 cout << "v\tverify disk\n";
596 cout << "w\twrite table to disk and exit\n";
597 cout << "x\textra functionality (experts only)\n";
598 cout << "?\tprint this menu\n";
599} // GPTDataTextUI::ShowCommands()
600
601// Accept a recovery & transformation menu command. Returns only when the user
602// issues an exit command, such as 'w' or 'q'.
603void GPTDataTextUI::RecoveryMenu(string filename) {
604 uint32_t numParts;
605 int goOn = 1, temp1;
606
607 do {
608 cout << "\nRecovery/transformation command (? for help): ";
609 switch (ReadString()[0]) {
610 case '\0':
611 break;
612 case 'b': case 'B':
613 RebuildMainHeader();
614 break;
615 case 'c': case 'C':
616 cout << "Warning! This will probably do weird things if you've converted an MBR to\n"
617 << "GPT form and haven't yet saved the GPT! Proceed? ";
618 if (GetYN() == 'Y')
619 LoadSecondTableAsMain();
620 break;
621 case 'd': case 'D':
622 RebuildSecondHeader();
623 break;
624 case 'e': case 'E':
625 cout << "Warning! This will probably do weird things if you've converted an MBR to\n"
626 << "GPT form and haven't yet saved the GPT! Proceed? ";
627 if (GetYN() == 'Y')
628 LoadMainTable();
629 break;
630 case 'f': case 'F':
631 cout << "Warning! This will destroy the currently defined partitions! Proceed? ";
632 if (GetYN() == 'Y') {
633 if (LoadMBR(filename) == 1) { // successful load
634 XFormPartitions();
635 } else {
636 cout << "Problem loading MBR! GPT is untouched; regenerating protective MBR!\n";
637 MakeProtectiveMBR();
638 } // if/else
639 } // if
640 break;
641 case 'g': case 'G':
642 numParts = GetNumParts();
643 temp1 = XFormToMBR();
644 if (temp1 > 0)
645 cout << "\nConverted " << temp1 << " partitions. Finalize and exit? ";
646 if ((temp1 > 0) && (GetYN() == 'Y')) {
647 if ((DestroyGPT() > 0) && (SaveMBR())) {
648 goOn = 0;
649 } // if
650 } else {
651 MakeProtectiveMBR();
652 SetGPTSize(numParts);
653 cout << "Note: New protective MBR created\n\n";
654 } // if/else
655 break;
656 case 'h': case 'H':
657 MakeHybrid();
658 break;
659 case 'i': case 'I':
660 ShowDetails();
661 break;
662 case 'l': case 'L':
663 cout << "Enter backup filename to load: ";
664 LoadGPTBackup(ReadString());
665 break;
666 case 'm': case 'M':
667 MainMenu(filename);
668 goOn = 0;
669 break;
670 case 'o': case 'O':
671 DisplayMBRData();
672 break;
673 case 'p': case 'P':
674 DisplayGPTData();
675 break;
676 case 'q': case 'Q':
677 goOn = 0;
678 break;
679 case 't': case 'T':
680 XFormDisklabel();
681 break;
682 case 'v': case 'V':
683 Verify();
684 break;
685 case 'w': case 'W':
686 if (SaveGPTData() == 1) {
687 goOn = 0;
688 } // if
689 break;
690 case 'x': case 'X':
691 ExpertsMenu(filename);
692 goOn = 0;
693 break;
694 default:
695 ShowRecoveryCommands();
696 break;
697 } // switch
698 } while (goOn);
699} // GPTDataTextUI::RecoveryMenu()
700
701void GPTDataTextUI::ShowRecoveryCommands(void) {
702 cout << "b\tuse backup GPT header (rebuilding main)\n";
703 cout << "c\tload backup partition table from disk (rebuilding main)\n";
704 cout << "d\tuse main GPT header (rebuilding backup)\n";
705 cout << "e\tload main partition table from disk (rebuilding backup)\n";
706 cout << "f\tload MBR and build fresh GPT from it\n";
707 cout << "g\tconvert GPT into MBR and exit\n";
708 cout << "h\tmake hybrid MBR\n";
709 cout << "i\tshow detailed information on a partition\n";
710 cout << "l\tload partition data from a backup file\n";
711 cout << "m\treturn to main menu\n";
712 cout << "o\tprint protective MBR data\n";
713 cout << "p\tprint the partition table\n";
714 cout << "q\tquit without saving changes\n";
715 cout << "t\ttransform BSD disklabel partition\n";
716 cout << "v\tverify disk\n";
717 cout << "w\twrite table to disk and exit\n";
718 cout << "x\textra functionality (experts only)\n";
719 cout << "?\tprint this menu\n";
720} // GPTDataTextUI::ShowRecoveryCommands()
721
722// Accept an experts' menu command. Returns only after the user
723// selects an exit command, such as 'w' or 'q'.
724void GPTDataTextUI::ExpertsMenu(string filename) {
725 GPTData secondDevice;
726 uint32_t temp1, temp2;
727 int goOn = 1;
728 string guidStr, device;
729 GUIDData aGUID;
730 ostringstream prompt;
731
732 do {
733 cout << "\nExpert command (? for help): ";
734 switch (ReadString()[0]) {
735 case '\0':
736 break;
737 case 'a': case 'A':
738 if (GetPartRange(&temp1, &temp2) > 0)
739 SetAttributes(GetPartNum());
740 else
741 cout << "No partitions\n";
742 break;
743 case 'c': case 'C':
744 ChangeUniqueGuid();
745 break;
746 case 'd': case 'D':
747 cout << "Partitions will begin on " << GetAlignment()
748 << "-sector boundaries.\n";
749 break;
750 case 'e': case 'E':
751 cout << "Relocating backup data structures to the end of the disk\n";
752 MoveSecondHeaderToEnd();
753 break;
754 case 'f': case 'F':
755 RandomizeGUIDs();
756 break;
757 case 'g': case 'G':
758 cout << "Enter the disk's unique GUID ('R' to randomize): ";
759 guidStr = ReadString();
760 if ((guidStr.length() >= 32) || (guidStr[0] == 'R') || (guidStr[0] == 'r')) {
761 SetDiskGUID((GUIDData) guidStr);
762 cout << "The new disk GUID is " << GetDiskGUID() << "\n";
763 } else {
764 cout << "GUID is too short!\n";
765 } // if/else
766 break;
767 case 'h': case 'H':
768 RecomputeCHS();
769 break;
770 case 'i': case 'I':
771 ShowDetails();
772 break;
773 case 'l': case 'L':
774 prompt.seekp(0);
775 prompt << "Enter the sector alignment value (1-" << MAX_ALIGNMENT << ", default = "
776 << DEFAULT_ALIGNMENT << "): ";
777 temp1 = GetNumber(1, MAX_ALIGNMENT, DEFAULT_ALIGNMENT, prompt.str());
778 SetAlignment(temp1);
779 break;
780 case 'm': case 'M':
781 MainMenu(filename);
782 goOn = 0;
783 break;
784 case 'n': case 'N':
785 MakeProtectiveMBR();
786 break;
787 case 'o': case 'O':
788 DisplayMBRData();
789 break;
790 case 'p': case 'P':
791 DisplayGPTData();
792 break;
793 case 'q': case 'Q':
794 goOn = 0;
795 break;
796 case 'r': case 'R':
797 RecoveryMenu(filename);
798 goOn = 0;
799 break;
800 case 's': case 'S':
801 ResizePartitionTable();
802 break;
803 case 't': case 'T':
804 SwapPartitions();
805 break;
806 case 'u': case 'U':
807 cout << "Type device filename, or press <Enter> to exit: ";
808 device = ReadString();
809 if (device.length() > 0) {
810 secondDevice = *this;
811 secondDevice.SetDisk(device);
812 secondDevice.SaveGPTData(0);
813 } // if
814 break;
815 case 'v': case 'V':
816 Verify();
817 break;
818 case 'w': case 'W':
819 if (SaveGPTData() == 1) {
820 goOn = 0;
821 } // if
822 break;
823 case 'z': case 'Z':
824 if (DestroyGPTwPrompt() == 1) {
825 goOn = 0;
826 }
827 break;
828 default:
829 ShowExpertCommands();
830 break;
831 } // switch
832 } while (goOn);
833} // GPTDataTextUI::ExpertsMenu()
834
835void GPTDataTextUI::ShowExpertCommands(void) {
836 cout << "a\tset attributes\n";
837 cout << "c\tchange partition GUID\n";
838 cout << "d\tdisplay the sector alignment value\n";
839 cout << "e\trelocate backup data structures to the end of the disk\n";
840 cout << "g\tchange disk GUID\n";
841 cout << "h\trecompute CHS values in protective/hybrid MBR\n";
842 cout << "i\tshow detailed information on a partition\n";
843 cout << "l\tset the sector alignment value\n";
844 cout << "m\treturn to main menu\n";
845 cout << "n\tcreate a new protective MBR\n";
846 cout << "o\tprint protective MBR data\n";
847 cout << "p\tprint the partition table\n";
848 cout << "q\tquit without saving changes\n";
849 cout << "r\trecovery and transformation options (experts only)\n";
850 cout << "s\tresize partition table\n";
851 cout << "t\ttranspose two partition table entries\n";
852 cout << "u\tReplicate partition table on new device\n";
853 cout << "v\tverify disk\n";
854 cout << "w\twrite table to disk and exit\n";
855 cout << "z\tzap (destroy) GPT data structures and exit\n";
856 cout << "?\tprint this menu\n";
857} // GPTDataTextUI::ShowExpertCommands()
858
859
860
srs5694699941e2011-03-21 21:33:57 -0400861/********************************
862 * *
863 * Non-class support functions. *
864 * *
865 ********************************/
866
867// GetMBRTypeCode() doesn't really belong in the class, since it's MBR-
868// specific, but it's also user I/O-related, so I want to keep it in
869// this file....
srs5694fad06422010-02-19 17:19:17 -0500870
871// Get an MBR type code from the user and return it
872int GetMBRTypeCode(int defType) {
srs56945a608532011-03-17 13:53:01 -0400873 string line;
srs5694fad06422010-02-19 17:19:17 -0500874 int typeCode;
875
876 cout.setf(ios::uppercase);
877 cout.fill('0');
878 do {
879 cout << "Enter an MBR hex code (default " << hex;
880 cout.width(2);
881 cout << defType << "): " << dec;
srs56945a608532011-03-17 13:53:01 -0400882 line = ReadString();
883 if (line[0] == '\0')
srs5694fad06422010-02-19 17:19:17 -0500884 typeCode = defType;
885 else
srs56945a608532011-03-17 13:53:01 -0400886 typeCode = StrToHex(line, 0);
srs5694fad06422010-02-19 17:19:17 -0500887 } while ((typeCode <= 0) || (typeCode > 255));
888 cout.fill(' ');
889 return typeCode;
srs56941c6f8b02010-02-21 11:09:20 -0500890} // GetMBRTypeCode
srs5694699941e2011-03-21 21:33:57 -0400891
892// Note: ReadUString() is here rather than in support.cc so that the ICU
893// libraries need not be linked to fixparts.
894
895// Reads a Unicode string from stdin, returning it as an ICU-style string.
896// Note that the returned string will NOT include the carriage return
897// entered by the user. Relies on the ICU constructor from a string
898// encoded in the current codepage to work.
899UnicodeString ReadUString(void) {
900 return ReadString().c_str();
901} // ReadUString()
902