blob: a7242f68df155eb5c0f435196d21a84dbfbb0aef [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.
Aurimas Liutikas74b74902016-05-10 18:53:54 -070039#ifdef EFI
40extern int __sscanf( const char * str , const char * format , ... ) ;
41string ReadString(void) {
42 string inString;
43 char efiString[256];
44 int stringLength;
45
46 if (fgets(efiString, 255, stdin) != NULL) {
47 stringLength = strlen(efiString);
48 if ((stringLength > 0) && (efiString[stringLength - 1] == '\n'))
49 efiString[stringLength - 1] = '\0';
50 inString = efiString;
51 } else {
52 inString = "";
53 }
54 return inString;
55} // ReadString()
56#else
srs56945a608532011-03-17 13:53:01 -040057string ReadString(void) {
58 string inString;
59
60 getline(cin, inString);
srs5694a6297b82012-03-25 16:13:16 -040061 if (!cin.good())
62 exit(5);
srs56945a608532011-03-17 13:53:01 -040063 return inString;
64} // ReadString()
Aurimas Liutikas74b74902016-05-10 18:53:54 -070065#endif
srs5694bf8950c2011-03-12 01:23:12 -050066
srs5694e7b4ff92009-08-18 13:16:10 -040067// Get a numeric value from the user, between low and high (inclusive).
68// Keeps looping until the user enters a value within that range.
69// If user provides no input, def (default value) is returned.
70// (If def is outside of the low-high range, an explicit response
71// is required.)
srs5694fed16d02010-01-27 23:03:40 -050072int GetNumber(int low, int high, int def, const string & prompt) {
srs5694e7b4ff92009-08-18 13:16:10 -040073 int response, num;
74 char line[255];
75
76 if (low != high) { // bother only if low and high differ...
srs56940873e9d2010-10-07 13:00:45 -040077 do {
srs5694fed16d02010-01-27 23:03:40 -050078 cout << prompt;
79 cin.getline(line, 255);
srs5694a6297b82012-03-25 16:13:16 -040080 if (!cin.good())
81 exit(5);
srs5694e7b4ff92009-08-18 13:16:10 -040082 num = sscanf(line, "%d", &response);
83 if (num == 1) { // user provided a response
84 if ((response < low) || (response > high))
srs5694fed16d02010-01-27 23:03:40 -050085 cout << "Value out of range\n";
srs5694e7b4ff92009-08-18 13:16:10 -040086 } else { // user hit enter; return default
87 response = def;
88 } // if/else
srs56940873e9d2010-10-07 13:00:45 -040089 } while ((response < low) || (response > high));
srs5694e7b4ff92009-08-18 13:16:10 -040090 } else { // low == high, so return this value
srs5694fed16d02010-01-27 23:03:40 -050091 cout << "Using " << low << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -040092 response = low;
93 } // else
94 return (response);
95} // GetNumber()
96
97// Gets a Y/N response (and converts lowercase to uppercase)
98char GetYN(void) {
srs56940873e9d2010-10-07 13:00:45 -040099 char response;
srs56945a608532011-03-17 13:53:01 -0400100 string line;
Roderick W. Smith84aaff62014-02-17 16:17:11 -0500101 bool again = 0 ;
srs5694e7b4ff92009-08-18 13:16:10 -0400102
srs56940873e9d2010-10-07 13:00:45 -0400103 do {
Roderick W. Smith84aaff62014-02-17 16:17:11 -0500104 if ( again ) { cout << "Your option? " ; }
105 again = 1 ;
srs5694fed16d02010-01-27 23:03:40 -0500106 cout << "(Y/N): ";
srs56945a608532011-03-17 13:53:01 -0400107 line = ReadString();
srs569401f7f082011-03-15 23:53:31 -0400108 response = toupper(line[0]);
srs56940873e9d2010-10-07 13:00:45 -0400109 } while ((response != 'Y') && (response != 'N'));
srs5694e7b4ff92009-08-18 13:16:10 -0400110 return response;
111} // GetYN(void)
112
srs5694e4ac11e2009-08-31 10:13:04 -0400113// Obtains a sector number, between low and high, from the
srs5694e7b4ff92009-08-18 13:16:10 -0400114// user, accepting values prefixed by "+" to add sectors to low,
srs56940873e9d2010-10-07 13:00:45 -0400115// or the same with "K", "M", "G", "T", or "P" as suffixes to add
116// kilobytes, megabytes, gigabytes, terabytes, or petabytes,
117// respectively. If a "-" prefix is used, use the high value minus
118// the user-specified number of sectors (or KiB, MiB, etc.). Use the
119// def value as the default if the user just hits Enter. The sSize is
120// the sector size of the device.
srs5694df9d3632011-01-08 18:33:24 -0500121uint64_t GetSectorNum(uint64_t low, uint64_t high, uint64_t def, uint64_t sSize,
122 const string & prompt) {
123 uint64_t response;
124 char line[255];
srs56940873e9d2010-10-07 13:00:45 -0400125
126 do {
srs5694fed16d02010-01-27 23:03:40 -0500127 cout << prompt;
128 cin.getline(line, 255);
srs5694a6297b82012-03-25 16:13:16 -0400129 if (!cin.good())
130 exit(5);
srs569401f7f082011-03-15 23:53:31 -0400131 response = IeeeToInt(line, sSize, low, high, def);
srs56940873e9d2010-10-07 13:00:45 -0400132 } while ((response < low) || (response > high));
srs569455d92612010-03-07 22:16:07 -0500133 return response;
srs5694e4ac11e2009-08-31 10:13:04 -0400134} // GetSectorNum()
srs5694e7b4ff92009-08-18 13:16:10 -0400135
srs569401f7f082011-03-15 23:53:31 -0400136// Convert an IEEE-1541-2002 value (K, M, G, T, P, or E) to its equivalent in
srs5694df9d3632011-01-08 18:33:24 -0500137// number of sectors. If no units are appended, interprets as the number
138// of sectors; otherwise, interprets as number of specified units and
139// converts to sectors. For instance, with 512-byte sectors, "1K" converts
140// to 2. If value includes a "+", adds low and subtracts 1; if SIValue
srs569401f7f082011-03-15 23:53:31 -0400141// inclues a "-", subtracts from high. If IeeeValue is empty, returns def.
srs56946aae2a92011-06-10 01:16:51 -0400142// Returns final sector value. In case inValue is invalid, returns 0 (a
srs5694a17fe692011-09-10 20:30:20 -0400143// sector value that's always in use on GPT and therefore invalid); and if
srs56946aae2a92011-06-10 01:16:51 -0400144// inValue works out to something outside the range low-high, returns the
145// computed value; the calling function is responsible for checking the
146// validity of this value.
147// NOTE: There's a difference in how GCC and VC++ treat oversized values
148// (say, "999999999999999999999") read via the ">>" operator; GCC turns
149// them into the maximum value for the type, whereas VC++ turns them into
150// 0 values. The result is that IeeeToInt() returns UINT64_MAX when
151// compiled with GCC (and so the value is rejected), whereas when VC++
152// is used, the default value is returned.
srs569401f7f082011-03-15 23:53:31 -0400153uint64_t IeeeToInt(string inValue, uint64_t sSize, uint64_t low, uint64_t high, uint64_t def) {
154 uint64_t response = def, bytesPerUnit = 1, mult = 1, divide = 1;
155 size_t foundAt = 0;
Aurimas Liutikas74b74902016-05-10 18:53:54 -0700156 char suffix = ' ', plusFlag = ' ';
srs569401f7f082011-03-15 23:53:31 -0400157 string suffixes = "KMGTPE";
srs56946aae2a92011-06-10 01:16:51 -0400158 int badInput = 0; // flag bad input; once this goes to 1, other values are irrelevant
srs5694df9d3632011-01-08 18:33:24 -0500159
160 if (sSize == 0) {
161 sSize = SECTOR_SIZE;
Roderick W. Smithf6948032014-03-29 00:27:33 -0400162 cerr << "Bug: Sector size invalid in IeeeToInt()!\n";
srs5694df9d3632011-01-08 18:33:24 -0500163 } // if
164
165 // Remove leading spaces, if present
srs569401f7f082011-03-15 23:53:31 -0400166 while (inValue[0] == ' ')
167 inValue.erase(0, 1);
srs5694df9d3632011-01-08 18:33:24 -0500168
srs569401f7f082011-03-15 23:53:31 -0400169 // If present, flag and remove leading plus or minus sign
170 if ((inValue[0] == '+') || (inValue[0] == '-')) {
171 plusFlag = inValue[0];
172 inValue.erase(0, 1);
srs5694df9d3632011-01-08 18:33:24 -0500173 } // if
174
175 // Extract numeric response and, if present, suffix
srs569401f7f082011-03-15 23:53:31 -0400176 istringstream inString(inValue);
srs56946aae2a92011-06-10 01:16:51 -0400177 if (((inString.peek() < '0') || (inString.peek() > '9')) && (inString.peek() != -1))
178 badInput = 1;
179 inString >> response >> suffix;
180 suffix = toupper(suffix);
181
182 // If no response, or if response == 0, use default (def)
183 if ((inValue.length() == 0) || (response == 0)) {
184 response = def;
185 suffix = ' ';
186 plusFlag = ' ';
187 } // if
188
189 // Find multiplication and division factors for the suffix
190 foundAt = suffixes.find(suffix);
191 if (foundAt != string::npos) {
192 bytesPerUnit = UINT64_C(1) << (10 * (foundAt + 1));
193 mult = bytesPerUnit / sSize;
194 divide = sSize / bytesPerUnit;
195 } // if
196
197 // Adjust response based on multiplier and plus flag, if present
198 if (mult > 1) {
199 if (response > (UINT64_MAX / mult))
200 badInput = 1;
201 else
srs569401f7f082011-03-15 23:53:31 -0400202 response *= mult;
srs56946aae2a92011-06-10 01:16:51 -0400203 } else if (divide > 1) {
srs569401f7f082011-03-15 23:53:31 -0400204 response /= divide;
srs56946aae2a92011-06-10 01:16:51 -0400205 } // if/elseif
206
207 if (plusFlag == '+') {
208 // Recompute response based on low part of range (if default == high
209 // value, which should be the case when prompting for the end of a
210 // range) or the defaut value (if default != high, which should be
211 // the case for the first sector of a partition).
212 if (def == high) {
213 if (response > 0)
214 response--;
215 if (response > (UINT64_MAX - low))
216 badInput = 1;
217 else
218 response = response + low;
219 } else {
220 if (response > (UINT64_MAX - def))
221 badInput = 1;
srs569401f7f082011-03-15 23:53:31 -0400222 else
223 response = response + def;
srs56946aae2a92011-06-10 01:16:51 -0400224 } // if/else
225 } else if (plusFlag == '-') {
226 if (response > high)
227 badInput = 1;
228 else
srs569401f7f082011-03-15 23:53:31 -0400229 response = high - response;
srs56946aae2a92011-06-10 01:16:51 -0400230 } // if
231
232 if (badInput)
233 response = UINT64_C(0);
srs5694df9d3632011-01-08 18:33:24 -0500234
235 return response;
srs569401f7f082011-03-15 23:53:31 -0400236} // IeeeToInt()
srs5694df9d3632011-01-08 18:33:24 -0500237
srs569401f7f082011-03-15 23:53:31 -0400238// Takes a size and converts this to a size in IEEE-1541-2002 units (KiB, MiB,
239// GiB, TiB, PiB, or EiB), returned in C++ string form. The size is either in
240// units of the sector size or, if that parameter is omitted, in bytes.
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400241// (sectorSize defaults to 1). Note that this function uses peculiar
242// manual computation of decimal value rather than simply setting
243// theValue.precision() because this isn't possible using the available
244// EFI library.
srs569401f7f082011-03-15 23:53:31 -0400245string BytesToIeee(uint64_t size, uint32_t sectorSize) {
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400246 uint64_t sizeInIeee;
247 uint64_t previousIeee;
248 float decimalIeee;
Aurimas Liutikas74b74902016-05-10 18:53:54 -0700249 uint64_t index = 0;
srs56946aae2a92011-06-10 01:16:51 -0400250 string units, prefixes = " KMGTPEZ";
srs569408bb0da2010-02-19 17:19:55 -0500251 ostringstream theValue;
srs5694e7b4ff92009-08-18 13:16:10 -0400252
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400253 sizeInIeee = previousIeee = size * (uint64_t) sectorSize;
254 while ((sizeInIeee > 1024) && (index < (prefixes.length() - 1))) {
srs569401f7f082011-03-15 23:53:31 -0400255 index++;
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400256 previousIeee = sizeInIeee;
257 sizeInIeee /= 1024;
srs569401f7f082011-03-15 23:53:31 -0400258 } // while
srs569401f7f082011-03-15 23:53:31 -0400259 if (prefixes[index] == ' ') {
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400260 theValue << sizeInIeee << " bytes";
srs5694fed16d02010-01-27 23:03:40 -0500261 } else {
srs569401f7f082011-03-15 23:53:31 -0400262 units = " iB";
263 units[1] = prefixes[index];
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400264 decimalIeee = ((float) previousIeee -
265 ((float) sizeInIeee * 1024.0) + 51.2) / 102.4;
266 if (decimalIeee >= 10.0) {
267 decimalIeee = 0.0;
268 sizeInIeee++;
269 }
270 theValue << sizeInIeee << "." << (uint32_t) decimalIeee << units;
srs5694fed16d02010-01-27 23:03:40 -0500271 } // if/else
srs569408bb0da2010-02-19 17:19:55 -0500272 return theValue.str();
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400273} // BytesToIeee()
srs5694e7b4ff92009-08-18 13:16:10 -0400274
srs56946699b012010-02-04 00:55:30 -0500275// Converts two consecutive characters in the input string into a
276// number, interpreting the string as a hexadecimal number, starting
277// at the specified position.
278unsigned char StrToHex(const string & input, unsigned int position) {
279 unsigned char retval = 0x00;
280 unsigned int temp;
srs5694e7b4ff92009-08-18 13:16:10 -0400281
srs56945a608532011-03-17 13:53:01 -0400282 if (input.length() > position) {
srs56946699b012010-02-04 00:55:30 -0500283 sscanf(input.substr(position, 2).c_str(), "%x", &temp);
284 retval = (unsigned char) temp;
srs5694e7b4ff92009-08-18 13:16:10 -0400285 } // if
srs56946699b012010-02-04 00:55:30 -0500286 return retval;
287} // StrToHex()
srs5694e7b4ff92009-08-18 13:16:10 -0400288
srs56940873e9d2010-10-07 13:00:45 -0400289// Returns 1 if input can be interpreted as a hexadecimal number --
290// all characters must be spaces, digits, or letters A-F (upper- or
srs56946aae2a92011-06-10 01:16:51 -0400291// lower-case), with at least one valid hexadecimal digit; with the
292// exception of the first two characters, which may be "0x"; otherwise
srs56940873e9d2010-10-07 13:00:45 -0400293// returns 0.
srs56946aae2a92011-06-10 01:16:51 -0400294int IsHex(string input) {
srs56940873e9d2010-10-07 13:00:45 -0400295 int isHex = 1, foundHex = 0, i;
296
srs56946aae2a92011-06-10 01:16:51 -0400297 if (input.substr(0, 2) == "0x")
298 input.erase(0, 2);
srs56940873e9d2010-10-07 13:00:45 -0400299 for (i = 0; i < (int) input.length(); i++) {
300 if ((input[i] < '0') || (input[i] > '9')) {
301 if ((input[i] < 'A') || (input[i] > 'F')) {
302 if ((input[i] < 'a') || (input[i] > 'f')) {
303 if ((input[i] != ' ') && (input[i] != '\n')) {
304 isHex = 0;
305 }
306 } else foundHex = 1;
307 } else foundHex = 1;
308 } else foundHex = 1;
309 } // for
310 if (!foundHex)
311 isHex = 0;
312 return isHex;
313} // IsHex()
314
srs56942a9f5da2009-08-26 00:48:01 -0400315// Return 1 if the CPU architecture is little endian, 0 if it's big endian....
316int IsLittleEndian(void) {
317 int littleE = 1; // assume little-endian (Intel-style)
318 union {
319 uint32_t num;
320 unsigned char uc[sizeof(uint32_t)];
321 } endian;
322
323 endian.num = 1;
324 if (endian.uc[0] != (unsigned char) 1) {
325 littleE = 0;
326 } // if
327 return (littleE);
328} // IsLittleEndian()
329
330// Reverse the byte order of theValue; numBytes is number of bytes
srs5694221e0872009-08-29 15:00:31 -0400331void ReverseBytes(void* theValue, int numBytes) {
srs5694fed16d02010-01-27 23:03:40 -0500332 char* tempValue = NULL;
srs56942a9f5da2009-08-26 00:48:01 -0400333 int i;
334
srs5694cb76c672010-02-11 22:22:22 -0500335 tempValue = new char [numBytes];
srs5694fed16d02010-01-27 23:03:40 -0500336 if (tempValue != NULL) {
337 memcpy(tempValue, theValue, numBytes);
338 for (i = 0; i < numBytes; i++)
339 ((char*) theValue)[i] = tempValue[numBytes - i - 1];
srs5694cb76c672010-02-11 22:22:22 -0500340 delete[] tempValue;
srs56946aae2a92011-06-10 01:16:51 -0400341 } else {
342 cerr << "Could not allocate memory in ReverseBytes()! Terminating\n";
343 exit(1);
344 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -0400345} // ReverseBytes()
srs5694a17fe692011-09-10 20:30:20 -0400346
347// On Windows, display a warning and ask whether to continue. If the user elects
348// not to continue, exit immediately.
349void WinWarning(void) {
350 #ifdef _WIN32
351 cout << "\a************************************************************************\n"
Roderick W. Smitha9203982014-03-29 00:45:59 -0400352 << "Most versions of Windows cannot boot from a GPT disk except on a UEFI-based\n"
353 << "computer, and most varieties prior to Vista cannot read GPT disks. Therefore,\n"
354 << "you should exit now unless you understand the implications of converting MBR\n"
355 << "to GPT or creating a new GPT disk layout!\n"
356 << "************************************************************************\n\n";
srs5694a17fe692011-09-10 20:30:20 -0400357 cout << "Are you SURE you want to continue? ";
358 if (GetYN() != 'Y')
359 exit(0);
360 #endif
361} // WinWarning()