blob: 14eb054baa568a97a57ba7e2fd535aee9c83023c [file] [log] [blame]
srs5694e7b4ff92009-08-18 13:16:10 -04001// support.cc
2// Non-class support functions for gdisk program.
3// Primarily by Rod Smith, February 2009, but with a few functions
4// copied from other sources (see attributions below).
5
Roderick W. Smithe3ee7332013-09-24 12:56:11 -04006/* This program is copyright (c) 2009-2013 by Roderick W. Smith. It is distributed
srs5694221e0872009-08-29 15:00:31 -04007 under the terms of the GNU GPL version 2, as detailed in the COPYING file. */
8
srs5694e7b4ff92009-08-18 13:16:10 -04009#define __STDC_LIMIT_MACROS
Aurimas Liutikasfcad0602016-05-10 19:16:10 -070010#ifndef __STDC_CONSTANT_MACROS
srs5694e7b4ff92009-08-18 13:16:10 -040011#define __STDC_CONSTANT_MACROS
Aurimas Liutikasfcad0602016-05-10 19:16:10 -070012#endif
srs5694e7b4ff92009-08-18 13:16:10 -040013
srs5694e7b4ff92009-08-18 13:16:10 -040014#include <stdio.h>
srs5694e7b4ff92009-08-18 13:16:10 -040015#include <stdint.h>
16#include <errno.h>
srs5694e4ac11e2009-08-31 10:13:04 -040017#include <fcntl.h>
srs5694fed16d02010-01-27 23:03:40 -050018#include <string.h>
srs5694e35eb1b2009-09-14 00:29:34 -040019#include <sys/stat.h>
srs5694fed16d02010-01-27 23:03:40 -050020#include <string>
21#include <iostream>
srs569408bb0da2010-02-19 17:19:55 -050022#include <sstream>
srs5694e7b4ff92009-08-18 13:16:10 -040023#include "support.h"
24
25#include <sys/types.h>
26
srs56945d58fe02010-01-03 20:57:08 -050027// As of 1/2010, BLKPBSZGET is very new, so I'm explicitly defining it if
28// it's not already defined. This should become unnecessary in the future.
29// Note that this is a Linux-only ioctl....
30#ifndef BLKPBSZGET
31#define BLKPBSZGET _IO(0x12,123)
32#endif
33
srs5694e7b4ff92009-08-18 13:16:10 -040034using namespace std;
35
srs56945a608532011-03-17 13:53:01 -040036// Reads a string from stdin, returning it as a C++-style string.
37// Note that the returned string will NOT include the carriage return
38// entered by the user.
39string ReadString(void) {
40 string inString;
41
42 getline(cin, inString);
srs5694a6297b82012-03-25 16:13:16 -040043 if (!cin.good())
44 exit(5);
srs56945a608532011-03-17 13:53:01 -040045 return inString;
46} // ReadString()
srs5694bf8950c2011-03-12 01:23:12 -050047
srs5694e7b4ff92009-08-18 13:16:10 -040048// Get a numeric value from the user, between low and high (inclusive).
49// Keeps looping until the user enters a value within that range.
50// If user provides no input, def (default value) is returned.
51// (If def is outside of the low-high range, an explicit response
52// is required.)
srs5694fed16d02010-01-27 23:03:40 -050053int GetNumber(int low, int high, int def, const string & prompt) {
srs5694e7b4ff92009-08-18 13:16:10 -040054 int response, num;
55 char line[255];
56
57 if (low != high) { // bother only if low and high differ...
srs56940873e9d2010-10-07 13:00:45 -040058 do {
srs5694fed16d02010-01-27 23:03:40 -050059 cout << prompt;
60 cin.getline(line, 255);
srs5694a6297b82012-03-25 16:13:16 -040061 if (!cin.good())
62 exit(5);
srs5694e7b4ff92009-08-18 13:16:10 -040063 num = sscanf(line, "%d", &response);
64 if (num == 1) { // user provided a response
65 if ((response < low) || (response > high))
srs5694fed16d02010-01-27 23:03:40 -050066 cout << "Value out of range\n";
srs5694e7b4ff92009-08-18 13:16:10 -040067 } else { // user hit enter; return default
68 response = def;
69 } // if/else
srs56940873e9d2010-10-07 13:00:45 -040070 } while ((response < low) || (response > high));
srs5694e7b4ff92009-08-18 13:16:10 -040071 } else { // low == high, so return this value
srs5694fed16d02010-01-27 23:03:40 -050072 cout << "Using " << low << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -040073 response = low;
74 } // else
75 return (response);
76} // GetNumber()
77
78// Gets a Y/N response (and converts lowercase to uppercase)
79char GetYN(void) {
srs56940873e9d2010-10-07 13:00:45 -040080 char response;
srs56945a608532011-03-17 13:53:01 -040081 string line;
Roderick W. Smith84aaff62014-02-17 16:17:11 -050082 bool again = 0 ;
srs5694e7b4ff92009-08-18 13:16:10 -040083
srs56940873e9d2010-10-07 13:00:45 -040084 do {
Roderick W. Smith84aaff62014-02-17 16:17:11 -050085 if ( again ) { cout << "Your option? " ; }
86 again = 1 ;
srs5694fed16d02010-01-27 23:03:40 -050087 cout << "(Y/N): ";
srs56945a608532011-03-17 13:53:01 -040088 line = ReadString();
srs569401f7f082011-03-15 23:53:31 -040089 response = toupper(line[0]);
srs56940873e9d2010-10-07 13:00:45 -040090 } while ((response != 'Y') && (response != 'N'));
srs5694e7b4ff92009-08-18 13:16:10 -040091 return response;
92} // GetYN(void)
93
srs5694e4ac11e2009-08-31 10:13:04 -040094// Obtains a sector number, between low and high, from the
srs5694e7b4ff92009-08-18 13:16:10 -040095// user, accepting values prefixed by "+" to add sectors to low,
srs56940873e9d2010-10-07 13:00:45 -040096// or the same with "K", "M", "G", "T", or "P" as suffixes to add
97// kilobytes, megabytes, gigabytes, terabytes, or petabytes,
98// respectively. If a "-" prefix is used, use the high value minus
99// the user-specified number of sectors (or KiB, MiB, etc.). Use the
100// def value as the default if the user just hits Enter. The sSize is
101// the sector size of the device.
srs5694df9d3632011-01-08 18:33:24 -0500102uint64_t GetSectorNum(uint64_t low, uint64_t high, uint64_t def, uint64_t sSize,
103 const string & prompt) {
104 uint64_t response;
105 char line[255];
srs56940873e9d2010-10-07 13:00:45 -0400106
107 do {
srs5694fed16d02010-01-27 23:03:40 -0500108 cout << prompt;
109 cin.getline(line, 255);
srs5694a6297b82012-03-25 16:13:16 -0400110 if (!cin.good())
111 exit(5);
srs569401f7f082011-03-15 23:53:31 -0400112 response = IeeeToInt(line, sSize, low, high, def);
srs56940873e9d2010-10-07 13:00:45 -0400113 } while ((response < low) || (response > high));
srs569455d92612010-03-07 22:16:07 -0500114 return response;
srs5694e4ac11e2009-08-31 10:13:04 -0400115} // GetSectorNum()
srs5694e7b4ff92009-08-18 13:16:10 -0400116
srs569401f7f082011-03-15 23:53:31 -0400117// Convert an IEEE-1541-2002 value (K, M, G, T, P, or E) to its equivalent in
srs5694df9d3632011-01-08 18:33:24 -0500118// number of sectors. If no units are appended, interprets as the number
119// of sectors; otherwise, interprets as number of specified units and
120// converts to sectors. For instance, with 512-byte sectors, "1K" converts
121// to 2. If value includes a "+", adds low and subtracts 1; if SIValue
srs569401f7f082011-03-15 23:53:31 -0400122// inclues a "-", subtracts from high. If IeeeValue is empty, returns def.
srs56946aae2a92011-06-10 01:16:51 -0400123// Returns final sector value. In case inValue is invalid, returns 0 (a
srs5694a17fe692011-09-10 20:30:20 -0400124// sector value that's always in use on GPT and therefore invalid); and if
srs56946aae2a92011-06-10 01:16:51 -0400125// inValue works out to something outside the range low-high, returns the
126// computed value; the calling function is responsible for checking the
127// validity of this value.
128// NOTE: There's a difference in how GCC and VC++ treat oversized values
129// (say, "999999999999999999999") read via the ">>" operator; GCC turns
130// them into the maximum value for the type, whereas VC++ turns them into
131// 0 values. The result is that IeeeToInt() returns UINT64_MAX when
132// compiled with GCC (and so the value is rejected), whereas when VC++
133// is used, the default value is returned.
srs569401f7f082011-03-15 23:53:31 -0400134uint64_t IeeeToInt(string inValue, uint64_t sSize, uint64_t low, uint64_t high, uint64_t def) {
135 uint64_t response = def, bytesPerUnit = 1, mult = 1, divide = 1;
136 size_t foundAt = 0;
Aurimas Liutikasbdbab022017-03-07 09:50:36 -0800137 char suffix, plusFlag = ' ';
srs569401f7f082011-03-15 23:53:31 -0400138 string suffixes = "KMGTPE";
srs56946aae2a92011-06-10 01:16:51 -0400139 int badInput = 0; // flag bad input; once this goes to 1, other values are irrelevant
srs5694df9d3632011-01-08 18:33:24 -0500140
141 if (sSize == 0) {
142 sSize = SECTOR_SIZE;
Roderick W. Smithf6948032014-03-29 00:27:33 -0400143 cerr << "Bug: Sector size invalid in IeeeToInt()!\n";
srs5694df9d3632011-01-08 18:33:24 -0500144 } // if
145
146 // Remove leading spaces, if present
srs569401f7f082011-03-15 23:53:31 -0400147 while (inValue[0] == ' ')
148 inValue.erase(0, 1);
srs5694df9d3632011-01-08 18:33:24 -0500149
srs569401f7f082011-03-15 23:53:31 -0400150 // If present, flag and remove leading plus or minus sign
151 if ((inValue[0] == '+') || (inValue[0] == '-')) {
152 plusFlag = inValue[0];
153 inValue.erase(0, 1);
srs5694df9d3632011-01-08 18:33:24 -0500154 } // if
155
156 // Extract numeric response and, if present, suffix
srs569401f7f082011-03-15 23:53:31 -0400157 istringstream inString(inValue);
srs56946aae2a92011-06-10 01:16:51 -0400158 if (((inString.peek() < '0') || (inString.peek() > '9')) && (inString.peek() != -1))
159 badInput = 1;
160 inString >> response >> suffix;
161 suffix = toupper(suffix);
162
163 // If no response, or if response == 0, use default (def)
164 if ((inValue.length() == 0) || (response == 0)) {
165 response = def;
166 suffix = ' ';
167 plusFlag = ' ';
168 } // if
169
170 // Find multiplication and division factors for the suffix
171 foundAt = suffixes.find(suffix);
172 if (foundAt != string::npos) {
173 bytesPerUnit = UINT64_C(1) << (10 * (foundAt + 1));
174 mult = bytesPerUnit / sSize;
175 divide = sSize / bytesPerUnit;
176 } // if
177
178 // Adjust response based on multiplier and plus flag, if present
179 if (mult > 1) {
180 if (response > (UINT64_MAX / mult))
181 badInput = 1;
182 else
srs569401f7f082011-03-15 23:53:31 -0400183 response *= mult;
srs56946aae2a92011-06-10 01:16:51 -0400184 } else if (divide > 1) {
srs569401f7f082011-03-15 23:53:31 -0400185 response /= divide;
srs56946aae2a92011-06-10 01:16:51 -0400186 } // if/elseif
187
188 if (plusFlag == '+') {
189 // Recompute response based on low part of range (if default == high
190 // value, which should be the case when prompting for the end of a
191 // range) or the defaut value (if default != high, which should be
192 // the case for the first sector of a partition).
193 if (def == high) {
194 if (response > 0)
195 response--;
196 if (response > (UINT64_MAX - low))
197 badInput = 1;
198 else
199 response = response + low;
200 } else {
201 if (response > (UINT64_MAX - def))
202 badInput = 1;
srs569401f7f082011-03-15 23:53:31 -0400203 else
204 response = response + def;
srs56946aae2a92011-06-10 01:16:51 -0400205 } // if/else
206 } else if (plusFlag == '-') {
207 if (response > high)
208 badInput = 1;
209 else
srs569401f7f082011-03-15 23:53:31 -0400210 response = high - response;
srs56946aae2a92011-06-10 01:16:51 -0400211 } // if
212
213 if (badInput)
214 response = UINT64_C(0);
srs5694df9d3632011-01-08 18:33:24 -0500215
216 return response;
srs569401f7f082011-03-15 23:53:31 -0400217} // IeeeToInt()
srs5694df9d3632011-01-08 18:33:24 -0500218
srs569401f7f082011-03-15 23:53:31 -0400219// Takes a size and converts this to a size in IEEE-1541-2002 units (KiB, MiB,
220// GiB, TiB, PiB, or EiB), returned in C++ string form. The size is either in
221// units of the sector size or, if that parameter is omitted, in bytes.
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400222// (sectorSize defaults to 1). Note that this function uses peculiar
223// manual computation of decimal value rather than simply setting
224// theValue.precision() because this isn't possible using the available
225// EFI library.
srs569401f7f082011-03-15 23:53:31 -0400226string BytesToIeee(uint64_t size, uint32_t sectorSize) {
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400227 uint64_t sizeInIeee;
228 uint64_t previousIeee;
229 float decimalIeee;
Aurimas Liutikasbdbab022017-03-07 09:50:36 -0800230 uint index = 0;
srs56946aae2a92011-06-10 01:16:51 -0400231 string units, prefixes = " KMGTPEZ";
srs569408bb0da2010-02-19 17:19:55 -0500232 ostringstream theValue;
srs5694e7b4ff92009-08-18 13:16:10 -0400233
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400234 sizeInIeee = previousIeee = size * (uint64_t) sectorSize;
235 while ((sizeInIeee > 1024) && (index < (prefixes.length() - 1))) {
srs569401f7f082011-03-15 23:53:31 -0400236 index++;
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400237 previousIeee = sizeInIeee;
238 sizeInIeee /= 1024;
srs569401f7f082011-03-15 23:53:31 -0400239 } // while
srs569401f7f082011-03-15 23:53:31 -0400240 if (prefixes[index] == ' ') {
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400241 theValue << sizeInIeee << " bytes";
srs5694fed16d02010-01-27 23:03:40 -0500242 } else {
srs569401f7f082011-03-15 23:53:31 -0400243 units = " iB";
244 units[1] = prefixes[index];
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400245 decimalIeee = ((float) previousIeee -
246 ((float) sizeInIeee * 1024.0) + 51.2) / 102.4;
247 if (decimalIeee >= 10.0) {
248 decimalIeee = 0.0;
249 sizeInIeee++;
250 }
251 theValue << sizeInIeee << "." << (uint32_t) decimalIeee << units;
srs5694fed16d02010-01-27 23:03:40 -0500252 } // if/else
srs569408bb0da2010-02-19 17:19:55 -0500253 return theValue.str();
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400254} // BytesToIeee()
srs5694e7b4ff92009-08-18 13:16:10 -0400255
srs56946699b012010-02-04 00:55:30 -0500256// Converts two consecutive characters in the input string into a
257// number, interpreting the string as a hexadecimal number, starting
258// at the specified position.
259unsigned char StrToHex(const string & input, unsigned int position) {
260 unsigned char retval = 0x00;
261 unsigned int temp;
srs5694e7b4ff92009-08-18 13:16:10 -0400262
srs56945a608532011-03-17 13:53:01 -0400263 if (input.length() > position) {
srs56946699b012010-02-04 00:55:30 -0500264 sscanf(input.substr(position, 2).c_str(), "%x", &temp);
265 retval = (unsigned char) temp;
srs5694e7b4ff92009-08-18 13:16:10 -0400266 } // if
srs56946699b012010-02-04 00:55:30 -0500267 return retval;
268} // StrToHex()
srs5694e7b4ff92009-08-18 13:16:10 -0400269
srs56940873e9d2010-10-07 13:00:45 -0400270// Returns 1 if input can be interpreted as a hexadecimal number --
271// all characters must be spaces, digits, or letters A-F (upper- or
srs56946aae2a92011-06-10 01:16:51 -0400272// lower-case), with at least one valid hexadecimal digit; with the
273// exception of the first two characters, which may be "0x"; otherwise
srs56940873e9d2010-10-07 13:00:45 -0400274// returns 0.
srs56946aae2a92011-06-10 01:16:51 -0400275int IsHex(string input) {
srs56940873e9d2010-10-07 13:00:45 -0400276 int isHex = 1, foundHex = 0, i;
277
srs56946aae2a92011-06-10 01:16:51 -0400278 if (input.substr(0, 2) == "0x")
279 input.erase(0, 2);
srs56940873e9d2010-10-07 13:00:45 -0400280 for (i = 0; i < (int) input.length(); i++) {
281 if ((input[i] < '0') || (input[i] > '9')) {
282 if ((input[i] < 'A') || (input[i] > 'F')) {
283 if ((input[i] < 'a') || (input[i] > 'f')) {
284 if ((input[i] != ' ') && (input[i] != '\n')) {
285 isHex = 0;
286 }
287 } else foundHex = 1;
288 } else foundHex = 1;
289 } else foundHex = 1;
290 } // for
291 if (!foundHex)
292 isHex = 0;
293 return isHex;
294} // IsHex()
295
srs56942a9f5da2009-08-26 00:48:01 -0400296// Return 1 if the CPU architecture is little endian, 0 if it's big endian....
297int IsLittleEndian(void) {
298 int littleE = 1; // assume little-endian (Intel-style)
299 union {
300 uint32_t num;
301 unsigned char uc[sizeof(uint32_t)];
302 } endian;
303
304 endian.num = 1;
305 if (endian.uc[0] != (unsigned char) 1) {
306 littleE = 0;
307 } // if
308 return (littleE);
309} // IsLittleEndian()
310
311// Reverse the byte order of theValue; numBytes is number of bytes
srs5694221e0872009-08-29 15:00:31 -0400312void ReverseBytes(void* theValue, int numBytes) {
srs5694fed16d02010-01-27 23:03:40 -0500313 char* tempValue = NULL;
srs56942a9f5da2009-08-26 00:48:01 -0400314 int i;
315
srs5694cb76c672010-02-11 22:22:22 -0500316 tempValue = new char [numBytes];
srs5694fed16d02010-01-27 23:03:40 -0500317 if (tempValue != NULL) {
318 memcpy(tempValue, theValue, numBytes);
319 for (i = 0; i < numBytes; i++)
320 ((char*) theValue)[i] = tempValue[numBytes - i - 1];
srs5694cb76c672010-02-11 22:22:22 -0500321 delete[] tempValue;
srs56946aae2a92011-06-10 01:16:51 -0400322 } else {
323 cerr << "Could not allocate memory in ReverseBytes()! Terminating\n";
324 exit(1);
325 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -0400326} // ReverseBytes()
srs5694a17fe692011-09-10 20:30:20 -0400327
328// On Windows, display a warning and ask whether to continue. If the user elects
329// not to continue, exit immediately.
330void WinWarning(void) {
331 #ifdef _WIN32
332 cout << "\a************************************************************************\n"
Roderick W. Smitha9203982014-03-29 00:45:59 -0400333 << "Most versions of Windows cannot boot from a GPT disk except on a UEFI-based\n"
334 << "computer, and most varieties prior to Vista cannot read GPT disks. Therefore,\n"
335 << "you should exit now unless you understand the implications of converting MBR\n"
336 << "to GPT or creating a new GPT disk layout!\n"
337 << "************************************************************************\n\n";
srs5694a17fe692011-09-10 20:30:20 -0400338 cout << "Are you SURE you want to continue? ";
339 if (GetYN() != 'Y')
340 exit(0);
341 #endif
342} // WinWarning()