VirtualBox

source: vbox/trunk/src/VBox/Frontends/VBoxManage/VBoxInternalManage.cpp@ 42699

Last change on this file since 42699 was 41245, checked in by vboxsync, 13 years ago

Frontends/VBoxManage: fix incorrect debug only code which can crash before creating a raw disk vmdk.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 78.9 KB
Line 
1/* $Id: VBoxInternalManage.cpp 41245 2012-05-10 16:57:08Z vboxsync $ */
2/** @file
3 * VBoxManage - The 'internalcommands' command.
4 *
5 * VBoxInternalManage used to be a second CLI for doing special tricks,
6 * not intended for general usage, only for assisting VBox developers.
7 * It is now integrated into VBoxManage.
8 */
9
10/*
11 * Copyright (C) 2006-2010 Oracle Corporation
12 *
13 * This file is part of VirtualBox Open Source Edition (OSE), as
14 * available from http://www.virtualbox.org. This file is free software;
15 * you can redistribute it and/or modify it under the terms of the GNU
16 * General Public License (GPL) as published by the Free Software
17 * Foundation, in version 2 as it comes in the "COPYING" file of the
18 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
19 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
20 */
21
22
23
24/*******************************************************************************
25* Header Files *
26*******************************************************************************/
27#include <VBox/com/com.h>
28#include <VBox/com/string.h>
29#include <VBox/com/Guid.h>
30#include <VBox/com/ErrorInfo.h>
31#include <VBox/com/errorprint.h>
32
33#include <VBox/com/VirtualBox.h>
34
35#include <VBox/vd.h>
36#include <VBox/sup.h>
37#include <VBox/err.h>
38#include <VBox/log.h>
39
40#include <iprt/file.h>
41#include <iprt/getopt.h>
42#include <iprt/stream.h>
43#include <iprt/string.h>
44#include <iprt/uuid.h>
45#include <iprt/sha.h>
46
47#include "VBoxManage.h"
48
49/* Includes for the raw disk stuff. */
50#ifdef RT_OS_WINDOWS
51# include <windows.h>
52# include <winioctl.h>
53#elif defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) \
54 || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
55# include <errno.h>
56# include <sys/ioctl.h>
57# include <sys/types.h>
58# include <sys/stat.h>
59# include <fcntl.h>
60# include <unistd.h>
61#endif
62#ifdef RT_OS_LINUX
63# include <sys/utsname.h>
64# include <linux/hdreg.h>
65# include <linux/fs.h>
66# include <stdlib.h> /* atoi() */
67#endif /* RT_OS_LINUX */
68#ifdef RT_OS_DARWIN
69# include <sys/disk.h>
70#endif /* RT_OS_DARWIN */
71#ifdef RT_OS_SOLARIS
72# include <stropts.h>
73# include <sys/dkio.h>
74# include <sys/vtoc.h>
75#endif /* RT_OS_SOLARIS */
76#ifdef RT_OS_FREEBSD
77# include <sys/disk.h>
78#endif /* RT_OS_FREEBSD */
79
80using namespace com;
81
82
83/** Macro for checking whether a partition is of extended type or not. */
84#define PARTTYPE_IS_EXTENDED(x) ((x) == 0x05 || (x) == 0x0f || (x) == 0x85)
85
86/** Maximum number of partitions we can deal with.
87 * Ridiculously large number, but the memory consumption is rather low so who
88 * cares about never using most entries. */
89#define HOSTPARTITION_MAX 100
90
91
92typedef struct HOSTPARTITION
93{
94 unsigned uIndex;
95 /** partition type */
96 unsigned uType;
97 /** CHS/cylinder of the first sector */
98 unsigned uStartCylinder;
99 /** CHS/head of the first sector */
100 unsigned uStartHead;
101 /** CHS/head of the first sector */
102 unsigned uStartSector;
103 /** CHS/cylinder of the last sector */
104 unsigned uEndCylinder;
105 /** CHS/head of the last sector */
106 unsigned uEndHead;
107 /** CHS/sector of the last sector */
108 unsigned uEndSector;
109 /** start sector of this partition relative to the beginning of the hard
110 * disk or relative to the beginning of the extended partition table */
111 uint64_t uStart;
112 /** numer of sectors of the partition */
113 uint64_t uSize;
114 /** start sector of this partition _table_ */
115 uint64_t uPartDataStart;
116 /** numer of sectors of this partition _table_ */
117 uint64_t cPartDataSectors;
118} HOSTPARTITION, *PHOSTPARTITION;
119
120typedef struct HOSTPARTITIONS
121{
122 unsigned cPartitions;
123 HOSTPARTITION aPartitions[HOSTPARTITION_MAX];
124} HOSTPARTITIONS, *PHOSTPARTITIONS;
125
126/** flag whether we're in internal mode */
127bool g_fInternalMode;
128
129/**
130 * Print the usage info.
131 */
132void printUsageInternal(USAGECATEGORY u64Cmd, PRTSTREAM pStrm)
133{
134 RTStrmPrintf(pStrm,
135 "Usage: VBoxManage internalcommands <command> [command arguments]\n"
136 "\n"
137 "Commands:\n"
138 "\n"
139 "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s"
140 "WARNING: This is a development tool and shall only be used to analyse\n"
141 " problems. It is completely unsupported and will change in\n"
142 " incompatible ways without warning.\n",
143
144 (u64Cmd & USAGE_LOADMAP)
145 ? " loadmap <vmname>|<uuid> <symfile> <address> [module] [subtrahend] [segment]\n"
146 " This will instruct DBGF to load the given map file\n"
147 " during initialization. (See also loadmap in the debugger.)\n"
148 "\n"
149 : "",
150 (u64Cmd & USAGE_LOADSYMS)
151 ? " loadsyms <vmname>|<uuid> <symfile> [delta] [module] [module address]\n"
152 " This will instruct DBGF to load the given symbol file\n"
153 " during initialization.\n"
154 "\n"
155 : "",
156 (u64Cmd & USAGE_SETHDUUID)
157 ? " sethduuid <filepath> [<uuid>]\n"
158 " Assigns a new UUID to the given image file. This way, multiple copies\n"
159 " of a container can be registered.\n"
160 "\n"
161 : "",
162 (u64Cmd & USAGE_SETHDPARENTUUID)
163 ? " sethdparentuuid <filepath> <uuid>\n"
164 " Assigns a new parent UUID to the given image file.\n"
165 "\n"
166 : "",
167 (u64Cmd & USAGE_DUMPHDINFO)
168 ? " dumphdinfo <filepath>\n"
169 " Prints information about the image at the given location.\n"
170 "\n"
171 : "",
172 (u64Cmd & USAGE_LISTPARTITIONS)
173 ? " listpartitions -rawdisk <diskname>\n"
174 " Lists all partitions on <diskname>.\n"
175 "\n"
176 : "",
177 (u64Cmd & USAGE_CREATERAWVMDK)
178 ? " createrawvmdk -filename <filename> -rawdisk <diskname>\n"
179 " [-partitions <list of partition numbers> [-mbr <filename>] ]\n"
180 " [-relative]\n"
181 " Creates a new VMDK image which gives access to an entite host disk (if\n"
182 " the parameter -partitions is not specified) or some partitions of a\n"
183 " host disk. If access to individual partitions is granted, then the\n"
184 " parameter -mbr can be used to specify an alternative MBR to be used\n"
185 " (the partitioning information in the MBR file is ignored).\n"
186 " The diskname is on Linux e.g. /dev/sda, and on Windows e.g.\n"
187 " \\\\.\\PhysicalDrive0).\n"
188 " On Linux or FreeBSD host the parameter -relative causes a VMDK file to\n"
189 " be created which refers to individual partitions instead to the entire\n"
190 " disk.\n"
191 " The necessary partition numbers can be queried with\n"
192 " VBoxManage internalcommands listpartitions\n"
193 "\n"
194 : "",
195 (u64Cmd & USAGE_RENAMEVMDK)
196 ? " renamevmdk -from <filename> -to <filename>\n"
197 " Renames an existing VMDK image, including the base file and all its extents.\n"
198 "\n"
199 : "",
200 (u64Cmd & USAGE_CONVERTTORAW)
201 ? " converttoraw [-format <fileformat>] <filename> <outputfile>"
202#ifdef ENABLE_CONVERT_RAW_TO_STDOUT
203 "|stdout"
204#endif /* ENABLE_CONVERT_RAW_TO_STDOUT */
205 "\n"
206 " Convert image to raw, writing to file"
207#ifdef ENABLE_CONVERT_RAW_TO_STDOUT
208 " or stdout"
209#endif /* ENABLE_CONVERT_RAW_TO_STDOUT */
210 ".\n"
211 "\n"
212 : "",
213 (u64Cmd & USAGE_CONVERTHD)
214 ? " converthd [-srcformat VDI|VMDK|VHD|RAW]\n"
215 " [-dstformat VDI|VMDK|VHD|RAW]\n"
216 " <inputfile> <outputfile>\n"
217 " converts hard disk images between formats\n"
218 "\n"
219 : "",
220 (u64Cmd & USAGE_REPAIRHD)
221 ? " repairhd [-dry-run]\n"
222 " [-format VDI|VMDK|VHD|...]\n"
223 " <filename>\n"
224 " Tries to repair corrupted disk images\n"
225 "\n"
226 : "",
227#ifdef RT_OS_WINDOWS
228 (u64Cmd & USAGE_MODINSTALL)
229 ? " modinstall\n"
230 " Installs the necessary driver for the host OS\n"
231 "\n"
232 : "",
233 (u64Cmd & USAGE_MODUNINSTALL)
234 ? " moduninstall\n"
235 " Deinstalls the driver\n"
236 "\n"
237 : "",
238#else
239 "",
240 "",
241#endif
242 (u64Cmd & USAGE_DEBUGLOG)
243 ? " debuglog <vmname>|<uuid> [--enable|--disable] [--flags todo]\n"
244 " [--groups todo] [--destinations todo]\n"
245 " Controls debug logging.\n"
246 "\n"
247 : "",
248 (u64Cmd & USAGE_PASSWORDHASH)
249 ? " passwordhash <passsword>\n"
250 " Generates a password hash.\n"
251 "\n"
252 : "",
253 (u64Cmd & USAGE_GUESTSTATS)
254 ? " gueststats <vmname>|<uuid> [--interval <seconds>]\n"
255 " Obtains and prints internal guest statistics.\n"
256 " Sets the update interval if specified.\n"
257 "\n"
258 : ""
259 );
260}
261
262/** @todo this is no longer necessary, we can enumerate extra data */
263/**
264 * Finds a new unique key name.
265 *
266 * I don't think this is 100% race condition proof, but we assumes
267 * the user is not trying to push this point.
268 *
269 * @returns Result from the insert.
270 * @param pMachine The Machine object.
271 * @param pszKeyBase The base key.
272 * @param rKey Reference to the string object in which we will return the key.
273 */
274static HRESULT NewUniqueKey(ComPtr<IMachine> pMachine, const char *pszKeyBase, Utf8Str &rKey)
275{
276 Bstr KeyBase(pszKeyBase);
277 Bstr Keys;
278 HRESULT hrc = pMachine->GetExtraData(KeyBase.raw(), Keys.asOutParam());
279 if (FAILED(hrc))
280 return hrc;
281
282 /* if there are no keys, it's simple. */
283 if (Keys.isEmpty())
284 {
285 rKey = "1";
286 return pMachine->SetExtraData(KeyBase.raw(), Bstr(rKey).raw());
287 }
288
289 /* find a unique number - brute force rulez. */
290 Utf8Str KeysUtf8(Keys);
291 const char *pszKeys = RTStrStripL(KeysUtf8.c_str());
292 for (unsigned i = 1; i < 1000000; i++)
293 {
294 char szKey[32];
295 size_t cchKey = RTStrPrintf(szKey, sizeof(szKey), "%#x", i);
296 const char *psz = strstr(pszKeys, szKey);
297 while (psz)
298 {
299 if ( ( psz == pszKeys
300 || psz[-1] == ' ')
301 && ( psz[cchKey] == ' '
302 || !psz[cchKey])
303 )
304 break;
305 psz = strstr(psz + cchKey, szKey);
306 }
307 if (!psz)
308 {
309 rKey = szKey;
310 Utf8StrFmt NewKeysUtf8("%s %s", pszKeys, szKey);
311 return pMachine->SetExtraData(KeyBase.raw(),
312 Bstr(NewKeysUtf8).raw());
313 }
314 }
315 RTMsgError("Cannot find unique key for '%s'!", pszKeyBase);
316 return E_FAIL;
317}
318
319
320#if 0
321/**
322 * Remove a key.
323 *
324 * I don't think this isn't 100% race condition proof, but we assumes
325 * the user is not trying to push this point.
326 *
327 * @returns Result from the insert.
328 * @param pMachine The machine object.
329 * @param pszKeyBase The base key.
330 * @param pszKey The key to remove.
331 */
332static HRESULT RemoveKey(ComPtr<IMachine> pMachine, const char *pszKeyBase, const char *pszKey)
333{
334 Bstr Keys;
335 HRESULT hrc = pMachine->GetExtraData(Bstr(pszKeyBase), Keys.asOutParam());
336 if (FAILED(hrc))
337 return hrc;
338
339 /* if there are no keys, it's simple. */
340 if (Keys.isEmpty())
341 return S_OK;
342
343 char *pszKeys;
344 int rc = RTUtf16ToUtf8(Keys.raw(), &pszKeys);
345 if (RT_SUCCESS(rc))
346 {
347 /* locate it */
348 size_t cchKey = strlen(pszKey);
349 char *psz = strstr(pszKeys, pszKey);
350 while (psz)
351 {
352 if ( ( psz == pszKeys
353 || psz[-1] == ' ')
354 && ( psz[cchKey] == ' '
355 || !psz[cchKey])
356 )
357 break;
358 psz = strstr(psz + cchKey, pszKey);
359 }
360 if (psz)
361 {
362 /* remove it */
363 char *pszNext = RTStrStripL(psz + cchKey);
364 if (*pszNext)
365 memmove(psz, pszNext, strlen(pszNext) + 1);
366 else
367 *psz = '\0';
368 psz = RTStrStrip(pszKeys);
369
370 /* update */
371 hrc = pMachine->SetExtraData(Bstr(pszKeyBase), Bstr(psz));
372 }
373
374 RTStrFree(pszKeys);
375 return hrc;
376 }
377 else
378 RTMsgError("Failed to delete key '%s' from '%s', string conversion error %Rrc!",
379 pszKey, pszKeyBase, rc);
380
381 return E_FAIL;
382}
383#endif
384
385
386/**
387 * Sets a key value, does necessary error bitching.
388 *
389 * @returns COM status code.
390 * @param pMachine The Machine object.
391 * @param pszKeyBase The key base.
392 * @param pszKey The key.
393 * @param pszAttribute The attribute name.
394 * @param pszValue The string value.
395 */
396static HRESULT SetString(ComPtr<IMachine> pMachine, const char *pszKeyBase, const char *pszKey, const char *pszAttribute, const char *pszValue)
397{
398 HRESULT hrc = pMachine->SetExtraData(BstrFmt("%s/%s/%s", pszKeyBase,
399 pszKey, pszAttribute).raw(),
400 Bstr(pszValue).raw());
401 if (FAILED(hrc))
402 RTMsgError("Failed to set '%s/%s/%s' to '%s'! hrc=%#x",
403 pszKeyBase, pszKey, pszAttribute, pszValue, hrc);
404 return hrc;
405}
406
407
408/**
409 * Sets a key value, does necessary error bitching.
410 *
411 * @returns COM status code.
412 * @param pMachine The Machine object.
413 * @param pszKeyBase The key base.
414 * @param pszKey The key.
415 * @param pszAttribute The attribute name.
416 * @param u64Value The value.
417 */
418static HRESULT SetUInt64(ComPtr<IMachine> pMachine, const char *pszKeyBase, const char *pszKey, const char *pszAttribute, uint64_t u64Value)
419{
420 char szValue[64];
421 RTStrPrintf(szValue, sizeof(szValue), "%#RX64", u64Value);
422 return SetString(pMachine, pszKeyBase, pszKey, pszAttribute, szValue);
423}
424
425
426/**
427 * Sets a key value, does necessary error bitching.
428 *
429 * @returns COM status code.
430 * @param pMachine The Machine object.
431 * @param pszKeyBase The key base.
432 * @param pszKey The key.
433 * @param pszAttribute The attribute name.
434 * @param i64Value The value.
435 */
436static HRESULT SetInt64(ComPtr<IMachine> pMachine, const char *pszKeyBase, const char *pszKey, const char *pszAttribute, int64_t i64Value)
437{
438 char szValue[64];
439 RTStrPrintf(szValue, sizeof(szValue), "%RI64", i64Value);
440 return SetString(pMachine, pszKeyBase, pszKey, pszAttribute, szValue);
441}
442
443
444/**
445 * Identical to the 'loadsyms' command.
446 */
447static int CmdLoadSyms(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
448{
449 HRESULT rc;
450
451 /*
452 * Get the VM
453 */
454 ComPtr<IMachine> machine;
455 CHECK_ERROR_RET(aVirtualBox, FindMachine(Bstr(argv[0]).raw(),
456 machine.asOutParam()), 1);
457
458 /*
459 * Parse the command.
460 */
461 const char *pszFilename;
462 int64_t offDelta = 0;
463 const char *pszModule = NULL;
464 uint64_t ModuleAddress = ~0;
465 uint64_t ModuleSize = 0;
466
467 /* filename */
468 if (argc < 2)
469 return errorArgument("Missing the filename argument!\n");
470 pszFilename = argv[1];
471
472 /* offDelta */
473 if (argc >= 3)
474 {
475 int irc = RTStrToInt64Ex(argv[2], NULL, 0, &offDelta);
476 if (RT_FAILURE(irc))
477 return errorArgument(argv[0], "Failed to read delta '%s', rc=%Rrc\n", argv[2], rc);
478 }
479
480 /* pszModule */
481 if (argc >= 4)
482 pszModule = argv[3];
483
484 /* ModuleAddress */
485 if (argc >= 5)
486 {
487 int irc = RTStrToUInt64Ex(argv[4], NULL, 0, &ModuleAddress);
488 if (RT_FAILURE(irc))
489 return errorArgument(argv[0], "Failed to read module address '%s', rc=%Rrc\n", argv[4], rc);
490 }
491
492 /* ModuleSize */
493 if (argc >= 6)
494 {
495 int irc = RTStrToUInt64Ex(argv[5], NULL, 0, &ModuleSize);
496 if (RT_FAILURE(irc))
497 return errorArgument(argv[0], "Failed to read module size '%s', rc=%Rrc\n", argv[5], rc);
498 }
499
500 /*
501 * Add extra data.
502 */
503 Utf8Str KeyStr;
504 HRESULT hrc = NewUniqueKey(machine, "VBoxInternal/DBGF/loadsyms", KeyStr);
505 if (SUCCEEDED(hrc))
506 hrc = SetString(machine, "VBoxInternal/DBGF/loadsyms", KeyStr.c_str(), "Filename", pszFilename);
507 if (SUCCEEDED(hrc) && argc >= 3)
508 hrc = SetInt64(machine, "VBoxInternal/DBGF/loadsyms", KeyStr.c_str(), "Delta", offDelta);
509 if (SUCCEEDED(hrc) && argc >= 4)
510 hrc = SetString(machine, "VBoxInternal/DBGF/loadsyms", KeyStr.c_str(), "Module", pszModule);
511 if (SUCCEEDED(hrc) && argc >= 5)
512 hrc = SetUInt64(machine, "VBoxInternal/DBGF/loadsyms", KeyStr.c_str(), "ModuleAddress", ModuleAddress);
513 if (SUCCEEDED(hrc) && argc >= 6)
514 hrc = SetUInt64(machine, "VBoxInternal/DBGF/loadsyms", KeyStr.c_str(), "ModuleSize", ModuleSize);
515
516 return FAILED(hrc);
517}
518
519
520/**
521 * Identical to the 'loadmap' command.
522 */
523static int CmdLoadMap(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
524{
525 HRESULT rc;
526
527 /*
528 * Get the VM
529 */
530 ComPtr<IMachine> machine;
531 CHECK_ERROR_RET(aVirtualBox, FindMachine(Bstr(argv[0]).raw(),
532 machine.asOutParam()), 1);
533
534 /*
535 * Parse the command.
536 */
537 const char *pszFilename;
538 uint64_t ModuleAddress = UINT64_MAX;
539 const char *pszModule = NULL;
540 uint64_t offSubtrahend = 0;
541 uint32_t iSeg = UINT32_MAX;
542
543 /* filename */
544 if (argc < 2)
545 return errorArgument("Missing the filename argument!\n");
546 pszFilename = argv[1];
547
548 /* address */
549 if (argc < 3)
550 return errorArgument("Missing the module address argument!\n");
551 int irc = RTStrToUInt64Ex(argv[2], NULL, 0, &ModuleAddress);
552 if (RT_FAILURE(irc))
553 return errorArgument(argv[0], "Failed to read module address '%s', rc=%Rrc\n", argv[2], rc);
554
555 /* name (optional) */
556 if (argc > 3)
557 pszModule = argv[3];
558
559 /* subtrahend (optional) */
560 if (argc > 4)
561 {
562 irc = RTStrToUInt64Ex(argv[4], NULL, 0, &offSubtrahend);
563 if (RT_FAILURE(irc))
564 return errorArgument(argv[0], "Failed to read subtrahend '%s', rc=%Rrc\n", argv[4], rc);
565 }
566
567 /* segment (optional) */
568 if (argc > 5)
569 {
570 irc = RTStrToUInt32Ex(argv[5], NULL, 0, &iSeg);
571 if (RT_FAILURE(irc))
572 return errorArgument(argv[0], "Failed to read segment number '%s', rc=%Rrc\n", argv[5], rc);
573 }
574
575 /*
576 * Add extra data.
577 */
578 Utf8Str KeyStr;
579 HRESULT hrc = NewUniqueKey(machine, "VBoxInternal/DBGF/loadmap", KeyStr);
580 if (SUCCEEDED(hrc))
581 hrc = SetString(machine, "VBoxInternal/DBGF/loadmap", KeyStr.c_str(), "Filename", pszFilename);
582 if (SUCCEEDED(hrc))
583 hrc = SetUInt64(machine, "VBoxInternal/DBGF/loadmap", KeyStr.c_str(), "Address", ModuleAddress);
584 if (SUCCEEDED(hrc) && pszModule != NULL)
585 hrc = SetString(machine, "VBoxInternal/DBGF/loadmap", KeyStr.c_str(), "Name", pszModule);
586 if (SUCCEEDED(hrc) && offSubtrahend != 0)
587 hrc = SetUInt64(machine, "VBoxInternal/DBGF/loadmap", KeyStr.c_str(), "Subtrahend", offSubtrahend);
588 if (SUCCEEDED(hrc) && iSeg != UINT32_MAX)
589 hrc = SetUInt64(machine, "VBoxInternal/DBGF/loadmap", KeyStr.c_str(), "Segment", iSeg);
590
591 return FAILED(hrc);
592}
593
594
595static DECLCALLBACK(void) handleVDError(void *pvUser, int rc, RT_SRC_POS_DECL, const char *pszFormat, va_list va)
596{
597 RTMsgErrorV(pszFormat, va);
598 RTMsgError("Error code %Rrc at %s(%u) in function %s", rc, RT_SRC_POS_ARGS);
599}
600
601static int handleVDMessage(void *pvUser, const char *pszFormat, va_list va)
602{
603 NOREF(pvUser);
604 return RTPrintfV(pszFormat, va);
605}
606
607static int CmdSetHDUUID(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
608{
609 Guid uuid;
610 RTUUID rtuuid;
611 enum eUuidType {
612 HDUUID,
613 HDPARENTUUID
614 } uuidType;
615
616 if (!strcmp(argv[0], "sethduuid"))
617 {
618 uuidType = HDUUID;
619 if (argc != 3 && argc != 2)
620 return errorSyntax(USAGE_SETHDUUID, "Not enough parameters");
621 /* if specified, take UUID, otherwise generate a new one */
622 if (argc == 3)
623 {
624 if (RT_FAILURE(RTUuidFromStr(&rtuuid, argv[2])))
625 return errorSyntax(USAGE_SETHDUUID, "Invalid UUID parameter");
626 uuid = argv[2];
627 } else
628 uuid.create();
629 }
630 else if (!strcmp(argv[0], "sethdparentuuid"))
631 {
632 uuidType = HDPARENTUUID;
633 if (argc != 3)
634 return errorSyntax(USAGE_SETHDPARENTUUID, "Not enough parameters");
635 if (RT_FAILURE(RTUuidFromStr(&rtuuid, argv[2])))
636 return errorSyntax(USAGE_SETHDPARENTUUID, "Invalid UUID parameter");
637 uuid = argv[2];
638 }
639 else
640 return errorSyntax(USAGE_SETHDUUID, "Invalid invocation");
641
642 /* just try it */
643 char *pszFormat = NULL;
644 VDTYPE enmType = VDTYPE_INVALID;
645 int rc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
646 argv[1], &pszFormat, &enmType);
647 if (RT_FAILURE(rc))
648 {
649 RTMsgError("Format autodetect failed: %Rrc", rc);
650 return 1;
651 }
652
653 PVBOXHDD pDisk = NULL;
654
655 PVDINTERFACE pVDIfs = NULL;
656 VDINTERFACEERROR vdInterfaceError;
657 vdInterfaceError.pfnError = handleVDError;
658 vdInterfaceError.pfnMessage = handleVDMessage;
659
660 rc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
661 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
662 AssertRC(rc);
663
664 rc = VDCreate(pVDIfs, enmType, &pDisk);
665 if (RT_FAILURE(rc))
666 {
667 RTMsgError("Cannot create the virtual disk container: %Rrc", rc);
668 return 1;
669 }
670
671 /* Open the image */
672 rc = VDOpen(pDisk, pszFormat, argv[1], VD_OPEN_FLAGS_NORMAL, NULL);
673 if (RT_FAILURE(rc))
674 {
675 RTMsgError("Cannot open the image: %Rrc", rc);
676 return 1;
677 }
678
679 if (uuidType == HDUUID)
680 rc = VDSetUuid(pDisk, VD_LAST_IMAGE, uuid.raw());
681 else
682 rc = VDSetParentUuid(pDisk, VD_LAST_IMAGE, uuid.raw());
683 if (RT_FAILURE(rc))
684 RTMsgError("Cannot set a new UUID: %Rrc", rc);
685 else
686 RTPrintf("UUID changed to: %s\n", uuid.toString().c_str());
687
688 VDCloseAll(pDisk);
689
690 return RT_FAILURE(rc);
691}
692
693
694static int CmdDumpHDInfo(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
695{
696 /* we need exactly one parameter: the image file */
697 if (argc != 1)
698 {
699 return errorSyntax(USAGE_DUMPHDINFO, "Not enough parameters");
700 }
701
702 /* just try it */
703 char *pszFormat = NULL;
704 VDTYPE enmType = VDTYPE_INVALID;
705 int rc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
706 argv[0], &pszFormat, &enmType);
707 if (RT_FAILURE(rc))
708 {
709 RTMsgError("Format autodetect failed: %Rrc", rc);
710 return 1;
711 }
712
713 PVBOXHDD pDisk = NULL;
714
715 PVDINTERFACE pVDIfs = NULL;
716 VDINTERFACEERROR vdInterfaceError;
717 vdInterfaceError.pfnError = handleVDError;
718 vdInterfaceError.pfnMessage = handleVDMessage;
719
720 rc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
721 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
722 AssertRC(rc);
723
724 rc = VDCreate(pVDIfs, enmType, &pDisk);
725 if (RT_FAILURE(rc))
726 {
727 RTMsgError("Cannot create the virtual disk container: %Rrc", rc);
728 return 1;
729 }
730
731 /* Open the image */
732 rc = VDOpen(pDisk, pszFormat, argv[0], VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO, NULL);
733 if (RT_FAILURE(rc))
734 {
735 RTMsgError("Cannot open the image: %Rrc", rc);
736 return 1;
737 }
738
739 VDDumpImages(pDisk);
740
741 VDCloseAll(pDisk);
742
743 return RT_FAILURE(rc);
744}
745
746static int partRead(RTFILE File, PHOSTPARTITIONS pPart)
747{
748 uint8_t aBuffer[512];
749 int rc;
750
751 pPart->cPartitions = 0;
752 memset(pPart->aPartitions, '\0', sizeof(pPart->aPartitions));
753 rc = RTFileReadAt(File, 0, &aBuffer, sizeof(aBuffer), NULL);
754 if (RT_FAILURE(rc))
755 return rc;
756 if (aBuffer[510] != 0x55 || aBuffer[511] != 0xaa)
757 return VERR_INVALID_PARAMETER;
758
759 unsigned uExtended = (unsigned)-1;
760
761 for (unsigned i = 0; i < 4; i++)
762 {
763 uint8_t *p = &aBuffer[0x1be + i * 16];
764 if (p[4] == 0)
765 continue;
766 PHOSTPARTITION pCP = &pPart->aPartitions[pPart->cPartitions++];
767 pCP->uIndex = i + 1;
768 pCP->uType = p[4];
769 pCP->uStartCylinder = (uint32_t)p[3] + ((uint32_t)(p[2] & 0xc0) << 2);
770 pCP->uStartHead = p[1];
771 pCP->uStartSector = p[2] & 0x3f;
772 pCP->uEndCylinder = (uint32_t)p[7] + ((uint32_t)(p[6] & 0xc0) << 2);
773 pCP->uEndHead = p[5];
774 pCP->uEndSector = p[6] & 0x3f;
775 pCP->uStart = RT_MAKE_U32_FROM_U8(p[8], p[9], p[10], p[11]);
776 pCP->uSize = RT_MAKE_U32_FROM_U8(p[12], p[13], p[14], p[15]);
777 pCP->uPartDataStart = 0; /* will be filled out later properly. */
778 pCP->cPartDataSectors = 0;
779
780 if (PARTTYPE_IS_EXTENDED(p[4]))
781 {
782 if (uExtended == (unsigned)-1)
783 uExtended = (unsigned)(pCP - pPart->aPartitions);
784 else
785 {
786 RTMsgError("More than one extended partition");
787 return VERR_INVALID_PARAMETER;
788 }
789 }
790 }
791
792 if (uExtended != (unsigned)-1)
793 {
794 unsigned uIndex = 5;
795 uint64_t uStart = pPart->aPartitions[uExtended].uStart;
796 uint64_t uOffset = 0;
797 if (!uStart)
798 {
799 RTMsgError("Inconsistency for logical partition start");
800 return VERR_INVALID_PARAMETER;
801 }
802
803 do
804 {
805 rc = RTFileReadAt(File, (uStart + uOffset) * 512, &aBuffer, sizeof(aBuffer), NULL);
806 if (RT_FAILURE(rc))
807 return rc;
808
809 if (aBuffer[510] != 0x55 || aBuffer[511] != 0xaa)
810 {
811 RTMsgError("Logical partition without magic");
812 return VERR_INVALID_PARAMETER;
813 }
814 uint8_t *p = &aBuffer[0x1be];
815
816 if (p[4] == 0)
817 {
818 RTMsgError("Logical partition with type 0 encountered");
819 return VERR_INVALID_PARAMETER;
820 }
821
822 PHOSTPARTITION pCP = &pPart->aPartitions[pPart->cPartitions++];
823 pCP->uIndex = uIndex;
824 pCP->uType = p[4];
825 pCP->uStartCylinder = (uint32_t)p[3] + ((uint32_t)(p[2] & 0xc0) << 2);
826 pCP->uStartHead = p[1];
827 pCP->uStartSector = p[2] & 0x3f;
828 pCP->uEndCylinder = (uint32_t)p[7] + ((uint32_t)(p[6] & 0xc0) << 2);
829 pCP->uEndHead = p[5];
830 pCP->uEndSector = p[6] & 0x3f;
831 uint32_t uStartOffset = RT_MAKE_U32_FROM_U8(p[8], p[9], p[10], p[11]);
832 if (!uStartOffset)
833 {
834 RTMsgError("Invalid partition start offset");
835 return VERR_INVALID_PARAMETER;
836 }
837 pCP->uStart = uStart + uOffset + uStartOffset;
838 pCP->uSize = RT_MAKE_U32_FROM_U8(p[12], p[13], p[14], p[15]);
839 /* Fill out partitioning location info for EBR. */
840 pCP->uPartDataStart = uStart + uOffset;
841 pCP->cPartDataSectors = uStartOffset;
842 p += 16;
843 if (p[4] == 0)
844 uExtended = (unsigned)-1;
845 else if (PARTTYPE_IS_EXTENDED(p[4]))
846 {
847 uExtended = uIndex++;
848 uOffset = RT_MAKE_U32_FROM_U8(p[8], p[9], p[10], p[11]);
849 }
850 else
851 {
852 RTMsgError("Logical partition chain broken");
853 return VERR_INVALID_PARAMETER;
854 }
855 } while (uExtended != (unsigned)-1);
856 }
857
858 /* Sort partitions in ascending order of start sector, plus a trivial
859 * bit of consistency checking. */
860 for (unsigned i = 0; i < pPart->cPartitions-1; i++)
861 {
862 unsigned uMinIdx = i;
863 uint64_t uMinVal = pPart->aPartitions[i].uStart;
864 for (unsigned j = i + 1; j < pPart->cPartitions; j++)
865 {
866 if (pPart->aPartitions[j].uStart < uMinVal)
867 {
868 uMinIdx = j;
869 uMinVal = pPart->aPartitions[j].uStart;
870 }
871 else if (pPart->aPartitions[j].uStart == uMinVal)
872 {
873 RTMsgError("Two partitions start at the same place");
874 return VERR_INVALID_PARAMETER;
875 }
876 else if (pPart->aPartitions[j].uStart == 0)
877 {
878 RTMsgError("Partition starts at sector 0");
879 return VERR_INVALID_PARAMETER;
880 }
881 }
882 if (uMinIdx != i)
883 {
884 /* Swap entries at index i and uMinIdx. */
885 memcpy(&pPart->aPartitions[pPart->cPartitions],
886 &pPart->aPartitions[i], sizeof(HOSTPARTITION));
887 memcpy(&pPart->aPartitions[i],
888 &pPart->aPartitions[uMinIdx], sizeof(HOSTPARTITION));
889 memcpy(&pPart->aPartitions[uMinIdx],
890 &pPart->aPartitions[pPart->cPartitions], sizeof(HOSTPARTITION));
891 }
892 }
893
894 /* Fill out partitioning location info for MBR. */
895 pPart->aPartitions[0].uPartDataStart = 0;
896 pPart->aPartitions[0].cPartDataSectors = pPart->aPartitions[0].uStart;
897
898 /* Now do a some partition table consistency checking, to reject the most
899 * obvious garbage which can lead to trouble later. */
900 uint64_t uPrevEnd = 0;
901 for (unsigned i = 0; i < pPart->cPartitions-1; i++)
902 {
903 if (pPart->aPartitions[i].cPartDataSectors)
904 uPrevEnd = pPart->aPartitions[i].uPartDataStart + pPart->aPartitions[i].cPartDataSectors;
905 if (pPart->aPartitions[i].uStart < uPrevEnd)
906 {
907 RTMsgError("Overlapping partitions");
908 return VERR_INVALID_PARAMETER;
909 }
910 if (!PARTTYPE_IS_EXTENDED(pPart->aPartitions[i].uType))
911 uPrevEnd = pPart->aPartitions[i].uStart + pPart->aPartitions[i].uSize;
912 }
913
914 return VINF_SUCCESS;
915}
916
917static int CmdListPartitions(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
918{
919 Utf8Str rawdisk;
920
921 /* let's have a closer look at the arguments */
922 for (int i = 0; i < argc; i++)
923 {
924 if (strcmp(argv[i], "-rawdisk") == 0)
925 {
926 if (argc <= i + 1)
927 {
928 return errorArgument("Missing argument to '%s'", argv[i]);
929 }
930 i++;
931 rawdisk = argv[i];
932 }
933 else
934 {
935 return errorSyntax(USAGE_LISTPARTITIONS, "Invalid parameter '%s'", argv[i]);
936 }
937 }
938
939 if (rawdisk.isEmpty())
940 return errorSyntax(USAGE_LISTPARTITIONS, "Mandatory parameter -rawdisk missing");
941
942 RTFILE hRawFile;
943 int vrc = RTFileOpen(&hRawFile, rawdisk.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
944 if (RT_FAILURE(vrc))
945 {
946 RTMsgError("Cannot open the raw disk: %Rrc", vrc);
947 return vrc;
948 }
949
950 HOSTPARTITIONS partitions;
951 vrc = partRead(hRawFile, &partitions);
952 /* Don't bail out on errors, print the table and return the result code. */
953
954 RTPrintf("Number Type StartCHS EndCHS Size (MiB) Start (Sect)\n");
955 for (unsigned i = 0; i < partitions.cPartitions; i++)
956 {
957 /* Don't show the extended partition, otherwise users might think they
958 * can add it to the list of partitions for raw partition access. */
959 if (PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
960 continue;
961
962 RTPrintf("%-7u %#04x %-4u/%-3u/%-2u %-4u/%-3u/%-2u %10llu %10llu\n",
963 partitions.aPartitions[i].uIndex,
964 partitions.aPartitions[i].uType,
965 partitions.aPartitions[i].uStartCylinder,
966 partitions.aPartitions[i].uStartHead,
967 partitions.aPartitions[i].uStartSector,
968 partitions.aPartitions[i].uEndCylinder,
969 partitions.aPartitions[i].uEndHead,
970 partitions.aPartitions[i].uEndSector,
971 partitions.aPartitions[i].uSize / 2048,
972 partitions.aPartitions[i].uStart);
973 }
974
975 return vrc;
976}
977
978static PVBOXHDDRAWPARTDESC appendPartDesc(uint32_t *pcPartDescs, PVBOXHDDRAWPARTDESC *ppPartDescs)
979{
980 (*pcPartDescs)++;
981 PVBOXHDDRAWPARTDESC p;
982 p = (PVBOXHDDRAWPARTDESC)RTMemRealloc(*ppPartDescs,
983 *pcPartDescs * sizeof(VBOXHDDRAWPARTDESC));
984 *ppPartDescs = p;
985 if (p)
986 {
987 p = p + *pcPartDescs - 1;
988 memset(p, '\0', sizeof(VBOXHDDRAWPARTDESC));
989 }
990
991 return p;
992}
993
994static int CmdCreateRawVMDK(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
995{
996 HRESULT rc = S_OK;
997 Utf8Str filename;
998 const char *pszMBRFilename = NULL;
999 Utf8Str rawdisk;
1000 const char *pszPartitions = NULL;
1001 bool fRelative = false;
1002
1003 uint64_t cbSize = 0;
1004 PVBOXHDD pDisk = NULL;
1005 VBOXHDDRAW RawDescriptor;
1006 PVDINTERFACE pVDIfs = NULL;
1007
1008 /* let's have a closer look at the arguments */
1009 for (int i = 0; i < argc; i++)
1010 {
1011 if (strcmp(argv[i], "-filename") == 0)
1012 {
1013 if (argc <= i + 1)
1014 {
1015 return errorArgument("Missing argument to '%s'", argv[i]);
1016 }
1017 i++;
1018 filename = argv[i];
1019 }
1020 else if (strcmp(argv[i], "-mbr") == 0)
1021 {
1022 if (argc <= i + 1)
1023 {
1024 return errorArgument("Missing argument to '%s'", argv[i]);
1025 }
1026 i++;
1027 pszMBRFilename = argv[i];
1028 }
1029 else if (strcmp(argv[i], "-rawdisk") == 0)
1030 {
1031 if (argc <= i + 1)
1032 {
1033 return errorArgument("Missing argument to '%s'", argv[i]);
1034 }
1035 i++;
1036 rawdisk = argv[i];
1037 }
1038 else if (strcmp(argv[i], "-partitions") == 0)
1039 {
1040 if (argc <= i + 1)
1041 {
1042 return errorArgument("Missing argument to '%s'", argv[i]);
1043 }
1044 i++;
1045 pszPartitions = argv[i];
1046 }
1047#if defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
1048 else if (strcmp(argv[i], "-relative") == 0)
1049 {
1050 fRelative = true;
1051 }
1052#endif /* RT_OS_LINUX || RT_OS_FREEBSD */
1053 else
1054 return errorSyntax(USAGE_CREATERAWVMDK, "Invalid parameter '%s'", argv[i]);
1055 }
1056
1057 if (filename.isEmpty())
1058 return errorSyntax(USAGE_CREATERAWVMDK, "Mandatory parameter -filename missing");
1059 if (rawdisk.isEmpty())
1060 return errorSyntax(USAGE_CREATERAWVMDK, "Mandatory parameter -rawdisk missing");
1061 if (!pszPartitions && pszMBRFilename)
1062 return errorSyntax(USAGE_CREATERAWVMDK, "The parameter -mbr is only valid when the parameter -partitions is also present");
1063
1064#ifdef RT_OS_DARWIN
1065 fRelative = true;
1066#endif /* RT_OS_DARWIN */
1067 RTFILE hRawFile;
1068 int vrc = RTFileOpen(&hRawFile, rawdisk.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
1069 if (RT_FAILURE(vrc))
1070 {
1071 RTMsgError("Cannot open the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1072 goto out;
1073 }
1074
1075#ifdef RT_OS_WINDOWS
1076 /* Windows NT has no IOCTL_DISK_GET_LENGTH_INFORMATION ioctl. This was
1077 * added to Windows XP, so we have to use the available info from DriveGeo.
1078 * Note that we cannot simply use IOCTL_DISK_GET_DRIVE_GEOMETRY as it
1079 * yields a slightly different result than IOCTL_DISK_GET_LENGTH_INFO.
1080 * We call IOCTL_DISK_GET_DRIVE_GEOMETRY first as we need to check the media
1081 * type anyway, and if IOCTL_DISK_GET_LENGTH_INFORMATION is supported
1082 * we will later override cbSize.
1083 */
1084 DISK_GEOMETRY DriveGeo;
1085 DWORD cbDriveGeo;
1086 if (DeviceIoControl((HANDLE)RTFileToNative(hRawFile),
1087 IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0,
1088 &DriveGeo, sizeof(DriveGeo), &cbDriveGeo, NULL))
1089 {
1090 if ( DriveGeo.MediaType == FixedMedia
1091 || DriveGeo.MediaType == RemovableMedia)
1092 {
1093 cbSize = DriveGeo.Cylinders.QuadPart
1094 * DriveGeo.TracksPerCylinder
1095 * DriveGeo.SectorsPerTrack
1096 * DriveGeo.BytesPerSector;
1097 }
1098 else
1099 {
1100 RTMsgError("File '%s' is no fixed/removable medium device", rawdisk.c_str());
1101 vrc = VERR_INVALID_PARAMETER;
1102 goto out;
1103 }
1104
1105 GET_LENGTH_INFORMATION DiskLenInfo;
1106 DWORD junk;
1107 if (DeviceIoControl((HANDLE)RTFileToNative(hRawFile),
1108 IOCTL_DISK_GET_LENGTH_INFO, NULL, 0,
1109 &DiskLenInfo, sizeof(DiskLenInfo), &junk, (LPOVERLAPPED)NULL))
1110 {
1111 /* IOCTL_DISK_GET_LENGTH_INFO is supported -- override cbSize. */
1112 cbSize = DiskLenInfo.Length.QuadPart;
1113 }
1114 }
1115 else
1116 {
1117 /*
1118 * Could be raw image, remember error code and try to get the size first
1119 * before failing.
1120 */
1121 vrc = RTErrConvertFromWin32(GetLastError());
1122 if (RT_FAILURE(RTFileGetSize(hRawFile, &cbSize)))
1123 {
1124 RTMsgError("Cannot get the geometry of the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1125 goto out;
1126 }
1127 else
1128 vrc = VINF_SUCCESS;
1129 }
1130#elif defined(RT_OS_LINUX)
1131 struct stat DevStat;
1132 if(!fstat(RTFileToNative(hRawFile), &DevStat))
1133 {
1134 if (S_ISBLK(DevStat.st_mode))
1135 {
1136#ifdef BLKGETSIZE64
1137 /* BLKGETSIZE64 is broken up to 2.4.17 and in many 2.5.x. In 2.6.0
1138 * it works without problems. */
1139 struct utsname utsname;
1140 if ( uname(&utsname) == 0
1141 && ( (strncmp(utsname.release, "2.5.", 4) == 0 && atoi(&utsname.release[4]) >= 18)
1142 || (strncmp(utsname.release, "2.", 2) == 0 && atoi(&utsname.release[2]) >= 6)))
1143 {
1144 uint64_t cbBlk;
1145 if (!ioctl(RTFileToNative(hRawFile), BLKGETSIZE64, &cbBlk))
1146 cbSize = cbBlk;
1147 }
1148#endif /* BLKGETSIZE64 */
1149 if (!cbSize)
1150 {
1151 long cBlocks;
1152 if (!ioctl(RTFileToNative(hRawFile), BLKGETSIZE, &cBlocks))
1153 cbSize = (uint64_t)cBlocks << 9;
1154 else
1155 {
1156 vrc = RTErrConvertFromErrno(errno);
1157 RTMsgError("Cannot get the size of the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1158 goto out;
1159 }
1160 }
1161 }
1162 else if (S_ISREG(DevStat.st_mode))
1163 {
1164 vrc = RTFileGetSize(hRawFile, &cbSize);
1165 if (RT_FAILURE(vrc))
1166 {
1167 RTMsgError("Failed to get size of file '%s': %Rrc", rawdisk.c_str(), vrc);
1168 goto out;
1169 }
1170 else if (fRelative)
1171 {
1172 RTMsgError("The -relative parameter is invalid for raw images");
1173 vrc = VERR_INVALID_PARAMETER;
1174 goto out;
1175 }
1176 }
1177 else
1178 {
1179 RTMsgError("File '%s' is no block device", rawdisk.c_str());
1180 vrc = VERR_INVALID_PARAMETER;
1181 goto out;
1182 }
1183 }
1184 else
1185 {
1186 vrc = RTErrConvertFromErrno(errno);
1187 RTMsgError("Failed to get file informtation for raw disk '%s': %Rrc",
1188 rawdisk.c_str(), vrc);
1189 }
1190#elif defined(RT_OS_DARWIN)
1191 struct stat DevStat;
1192 if (!fstat(RTFileToNative(hRawFile), &DevStat))
1193 {
1194 if (S_ISBLK(DevStat.st_mode))
1195 {
1196 uint64_t cBlocks;
1197 uint32_t cbBlock;
1198 if (!ioctl(RTFileToNative(hRawFile), DKIOCGETBLOCKCOUNT, &cBlocks))
1199 {
1200 if (!ioctl(RTFileToNative(hRawFile), DKIOCGETBLOCKSIZE, &cbBlock))
1201 cbSize = cBlocks * cbBlock;
1202 else
1203 {
1204 RTMsgError("Cannot get the block size for file '%s': %Rrc", rawdisk.c_str(), vrc);
1205 vrc = RTErrConvertFromErrno(errno);
1206 goto out;
1207 }
1208 }
1209 else
1210 {
1211 vrc = RTErrConvertFromErrno(errno);
1212 RTMsgError("Cannot get the block count for file '%s': %Rrc", rawdisk.c_str(), vrc);
1213 goto out;
1214 }
1215 }
1216 else if (S_ISREG(DevStat.st_mode))
1217 {
1218 fRelative = false; /* Must be false for raw image files. */
1219 vrc = RTFileGetSize(hRawFile, &cbSize);
1220 if (RT_FAILURE(vrc))
1221 {
1222 RTMsgError("Failed to get size of file '%s': %Rrc", rawdisk.c_str(), vrc);
1223 goto out;
1224 }
1225 }
1226 else
1227 {
1228 RTMsgError("File '%s' is neither block device nor regular file", rawdisk.c_str());
1229 vrc = VERR_INVALID_PARAMETER;
1230 goto out;
1231 }
1232 }
1233 else
1234 {
1235 vrc = RTErrConvertFromErrno(errno);
1236 RTMsgError("Failed to get file informtation for raw disk '%s': %Rrc",
1237 rawdisk.c_str(), vrc);
1238 }
1239#elif defined(RT_OS_SOLARIS)
1240 struct stat DevStat;
1241 if (!fstat(RTFileToNative(hRawFile), &DevStat))
1242 {
1243 if (S_ISBLK(DevStat.st_mode) || S_ISCHR(DevStat.st_mode))
1244 {
1245 struct dk_minfo mediainfo;
1246 if (!ioctl(RTFileToNative(hRawFile), DKIOCGMEDIAINFO, &mediainfo))
1247 cbSize = mediainfo.dki_capacity * mediainfo.dki_lbsize;
1248 else
1249 {
1250 vrc = RTErrConvertFromErrno(errno);
1251 RTMsgError("Cannot get the size of the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1252 goto out;
1253 }
1254 }
1255 else if (S_ISREG(DevStat.st_mode))
1256 {
1257 vrc = RTFileGetSize(hRawFile, &cbSize);
1258 if (RT_FAILURE(vrc))
1259 {
1260 RTMsgError("Failed to get size of file '%s': %Rrc", rawdisk.c_str(), vrc);
1261 goto out;
1262 }
1263 }
1264 else
1265 {
1266 RTMsgError("File '%s' is no block or char device", rawdisk.c_str());
1267 vrc = VERR_INVALID_PARAMETER;
1268 goto out;
1269 }
1270 }
1271 else
1272 {
1273 vrc = RTErrConvertFromErrno(errno);
1274 RTMsgError("Failed to get file informtation for raw disk '%s': %Rrc",
1275 rawdisk.c_str(), vrc);
1276 }
1277#elif defined(RT_OS_FREEBSD)
1278 struct stat DevStat;
1279 if (!fstat(RTFileToNative(hRawFile), &DevStat))
1280 {
1281 if (S_ISCHR(DevStat.st_mode))
1282 {
1283 off_t cbMedia = 0;
1284 if (!ioctl(RTFileToNative(hRawFile), DIOCGMEDIASIZE, &cbMedia))
1285 cbSize = cbMedia;
1286 else
1287 {
1288 vrc = RTErrConvertFromErrno(errno);
1289 RTMsgError("Cannot get the block count for file '%s': %Rrc", rawdisk.c_str(), vrc);
1290 goto out;
1291 }
1292 }
1293 else if (S_ISREG(DevStat.st_mode))
1294 {
1295 if (fRelative)
1296 {
1297 RTMsgError("The -relative parameter is invalid for raw images");
1298 vrc = VERR_INVALID_PARAMETER;
1299 goto out;
1300 }
1301 cbSize = DevStat.st_size;
1302 }
1303 else
1304 {
1305 RTMsgError("File '%s' is neither character device nor regular file", rawdisk.c_str());
1306 vrc = VERR_INVALID_PARAMETER;
1307 goto out;
1308 }
1309 }
1310 else
1311 {
1312 vrc = RTErrConvertFromErrno(errno);
1313 RTMsgError("Failed to get file informtation for raw disk '%s': %Rrc",
1314 rawdisk.c_str(), vrc);
1315 }
1316#else /* all unrecognized OSes */
1317 /* Hopefully this works on all other hosts. If it doesn't, it'll just fail
1318 * creating the VMDK, so no real harm done. */
1319 vrc = RTFileGetSize(hRawFile, &cbSize);
1320 if (RT_FAILURE(vrc))
1321 {
1322 RTMsgError("Cannot get the size of the raw disk '%s': %Rrc", rawdisk.c_str(), vrc);
1323 goto out;
1324 }
1325#endif
1326
1327 /* Check whether cbSize is actually sensible. */
1328 if (!cbSize || cbSize % 512)
1329 {
1330 RTMsgError("Detected size of raw disk '%s' is %s, an invalid value", rawdisk.c_str(), cbSize);
1331 vrc = VERR_INVALID_PARAMETER;
1332 goto out;
1333 }
1334
1335 RawDescriptor.szSignature[0] = 'R';
1336 RawDescriptor.szSignature[1] = 'A';
1337 RawDescriptor.szSignature[2] = 'W';
1338 RawDescriptor.szSignature[3] = '\0';
1339 if (!pszPartitions)
1340 {
1341 RawDescriptor.fRawDisk = true;
1342 RawDescriptor.pszRawDisk = rawdisk.c_str();
1343 }
1344 else
1345 {
1346 RawDescriptor.fRawDisk = false;
1347 RawDescriptor.pszRawDisk = NULL;
1348 RawDescriptor.cPartDescs = 0;
1349 RawDescriptor.pPartDescs = NULL;
1350
1351 uint32_t uPartitions = 0;
1352
1353 const char *p = pszPartitions;
1354 char *pszNext;
1355 uint32_t u32;
1356 while (*p != '\0')
1357 {
1358 vrc = RTStrToUInt32Ex(p, &pszNext, 0, &u32);
1359 if (RT_FAILURE(vrc))
1360 {
1361 RTMsgError("Incorrect value in partitions parameter");
1362 goto out;
1363 }
1364 uPartitions |= RT_BIT(u32);
1365 p = pszNext;
1366 if (*p == ',')
1367 p++;
1368 else if (*p != '\0')
1369 {
1370 RTMsgError("Incorrect separator in partitions parameter");
1371 vrc = VERR_INVALID_PARAMETER;
1372 goto out;
1373 }
1374 }
1375
1376 HOSTPARTITIONS partitions;
1377 vrc = partRead(hRawFile, &partitions);
1378 if (RT_FAILURE(vrc))
1379 {
1380 RTMsgError("Cannot read the partition information from '%s'", rawdisk.c_str());
1381 goto out;
1382 }
1383
1384 for (unsigned i = 0; i < partitions.cPartitions; i++)
1385 {
1386 if ( uPartitions & RT_BIT(partitions.aPartitions[i].uIndex)
1387 && PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
1388 {
1389 /* Some ignorant user specified an extended partition.
1390 * Bad idea, as this would trigger an overlapping
1391 * partitions error later during VMDK creation. So warn
1392 * here and ignore what the user requested. */
1393 RTMsgWarning("It is not possible (and necessary) to explicitly give access to the "
1394 "extended partition %u. If required, enable access to all logical "
1395 "partitions inside this extended partition.",
1396 partitions.aPartitions[i].uIndex);
1397 uPartitions &= ~RT_BIT(partitions.aPartitions[i].uIndex);
1398 }
1399 }
1400
1401 for (unsigned i = 0; i < partitions.cPartitions; i++)
1402 {
1403 PVBOXHDDRAWPARTDESC pPartDesc = NULL;
1404
1405 /* first dump the MBR/EPT data area */
1406 if (partitions.aPartitions[i].cPartDataSectors)
1407 {
1408 pPartDesc = appendPartDesc(&RawDescriptor.cPartDescs,
1409 &RawDescriptor.pPartDescs);
1410 if (!pPartDesc)
1411 {
1412 RTMsgError("Out of memory allocating the partition list for '%s'", rawdisk.c_str());
1413 vrc = VERR_NO_MEMORY;
1414 goto out;
1415 }
1416
1417 /** @todo the clipping below isn't 100% accurate, as it should
1418 * actually clip to the track size. However, that's easier said
1419 * than done as figuring out the track size is heuristics. In
1420 * any case the clipping is adjusted later after sorting, to
1421 * prevent overlapping data areas on the resulting image. */
1422 pPartDesc->cbData = RT_MIN(partitions.aPartitions[i].cPartDataSectors, 63) * 512;
1423 pPartDesc->uStart = partitions.aPartitions[i].uPartDataStart * 512;
1424 Assert(pPartDesc->cbData - (size_t)pPartDesc->cbData == 0);
1425 void *pPartData = RTMemAlloc((size_t)pPartDesc->cbData);
1426 if (!pPartData)
1427 {
1428 RTMsgError("Out of memory allocating the partition descriptor for '%s'", rawdisk.c_str());
1429 vrc = VERR_NO_MEMORY;
1430 goto out;
1431 }
1432 vrc = RTFileReadAt(hRawFile, partitions.aPartitions[i].uPartDataStart * 512,
1433 pPartData, (size_t)pPartDesc->cbData, NULL);
1434 if (RT_FAILURE(vrc))
1435 {
1436 RTMsgError("Cannot read partition data from raw device '%s': %Rrc", rawdisk.c_str(), vrc);
1437 goto out;
1438 }
1439 /* Splice in the replacement MBR code if specified. */
1440 if ( partitions.aPartitions[i].uPartDataStart == 0
1441 && pszMBRFilename)
1442 {
1443 RTFILE MBRFile;
1444 vrc = RTFileOpen(&MBRFile, pszMBRFilename, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
1445 if (RT_FAILURE(vrc))
1446 {
1447 RTMsgError("Cannot open replacement MBR file '%s' specified with -mbr: %Rrc", pszMBRFilename, vrc);
1448 goto out;
1449 }
1450 vrc = RTFileReadAt(MBRFile, 0, pPartData, 0x1be, NULL);
1451 RTFileClose(MBRFile);
1452 if (RT_FAILURE(vrc))
1453 {
1454 RTMsgError("Cannot read replacement MBR file '%s': %Rrc", pszMBRFilename, vrc);
1455 goto out;
1456 }
1457 }
1458 pPartDesc->pvPartitionData = pPartData;
1459 }
1460
1461 if (PARTTYPE_IS_EXTENDED(partitions.aPartitions[i].uType))
1462 {
1463 /* Suppress exporting the actual extended partition. Only
1464 * logical partitions should be processed. However completely
1465 * ignoring it leads to leaving out the EBR data. */
1466 continue;
1467 }
1468
1469 /* set up values for non-relative device names */
1470 const char *pszRawName = rawdisk.c_str();
1471 uint64_t uStartOffset = partitions.aPartitions[i].uStart * 512;
1472
1473 pPartDesc = appendPartDesc(&RawDescriptor.cPartDescs,
1474 &RawDescriptor.pPartDescs);
1475 if (!pPartDesc)
1476 {
1477 RTMsgError("Out of memory allocating the partition list for '%s'", rawdisk.c_str());
1478 vrc = VERR_NO_MEMORY;
1479 goto out;
1480 }
1481
1482 if (uPartitions & RT_BIT(partitions.aPartitions[i].uIndex))
1483 {
1484 if (fRelative)
1485 {
1486#if defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
1487 /* Refer to the correct partition and use offset 0. */
1488 char *psz;
1489 RTStrAPrintf(&psz,
1490#if defined(RT_OS_LINUX)
1491 "%s%u",
1492#elif defined(RT_OS_FREEBSD)
1493 "%ss%u",
1494#endif
1495 rawdisk.c_str(),
1496 partitions.aPartitions[i].uIndex);
1497 if (!psz)
1498 {
1499 vrc = VERR_NO_STR_MEMORY;
1500 RTMsgError("Cannot create reference to individual partition %u, rc=%Rrc",
1501 partitions.aPartitions[i].uIndex, vrc);
1502 goto out;
1503 }
1504 pszRawName = psz;
1505 uStartOffset = 0;
1506#elif defined(RT_OS_DARWIN)
1507 /* Refer to the correct partition and use offset 0. */
1508 char *psz;
1509 RTStrAPrintf(&psz, "%ss%u", rawdisk.c_str(),
1510 partitions.aPartitions[i].uIndex);
1511 if (!psz)
1512 {
1513 vrc = VERR_NO_STR_MEMORY;
1514 RTMsgError("Cannot create reference to individual partition %u, rc=%Rrc",
1515 partitions.aPartitions[i].uIndex, vrc);
1516 goto out;
1517 }
1518 pszRawName = psz;
1519 uStartOffset = 0;
1520#else
1521 /** @todo not implemented for other hosts. Treat just like
1522 * not specified (this code is actually never reached). */
1523#endif
1524 }
1525
1526 pPartDesc->pszRawDevice = pszRawName;
1527 pPartDesc->uStartOffset = uStartOffset;
1528 }
1529 else
1530 {
1531 pPartDesc->pszRawDevice = NULL;
1532 pPartDesc->uStartOffset = 0;
1533 }
1534
1535 pPartDesc->uStart = partitions.aPartitions[i].uStart * 512;
1536 pPartDesc->cbData = partitions.aPartitions[i].uSize * 512;
1537 }
1538
1539 /* Sort data areas in ascending order of start. */
1540 for (unsigned i = 0; i < RawDescriptor.cPartDescs-1; i++)
1541 {
1542 unsigned uMinIdx = i;
1543 uint64_t uMinVal = RawDescriptor.pPartDescs[i].uStart;
1544 for (unsigned j = i + 1; j < RawDescriptor.cPartDescs; j++)
1545 {
1546 if (RawDescriptor.pPartDescs[j].uStart < uMinVal)
1547 {
1548 uMinIdx = j;
1549 uMinVal = RawDescriptor.pPartDescs[j].uStart;
1550 }
1551 }
1552 if (uMinIdx != i)
1553 {
1554 /* Swap entries at index i and uMinIdx. */
1555 VBOXHDDRAWPARTDESC tmp;
1556 memcpy(&tmp, &RawDescriptor.pPartDescs[i], sizeof(tmp));
1557 memcpy(&RawDescriptor.pPartDescs[i], &RawDescriptor.pPartDescs[uMinIdx], sizeof(tmp));
1558 memcpy(&RawDescriptor.pPartDescs[uMinIdx], &tmp, sizeof(tmp));
1559 }
1560 }
1561
1562 /* Have a second go at MBR/EPT area clipping. Now that the data areas
1563 * are sorted this is much easier to get 100% right. */
1564 for (unsigned i = 0; i < RawDescriptor.cPartDescs-1; i++)
1565 {
1566 if (RawDescriptor.pPartDescs[i].pvPartitionData)
1567 {
1568 RawDescriptor.pPartDescs[i].cbData = RT_MIN(RawDescriptor.pPartDescs[i+1].uStart - RawDescriptor.pPartDescs[i].uStart, RawDescriptor.pPartDescs[i].cbData);
1569 if (!RawDescriptor.pPartDescs[i].cbData)
1570 {
1571 RTMsgError("MBR/EPT overlaps with data area");
1572 vrc = VERR_INVALID_PARAMETER;
1573 goto out;
1574 }
1575 }
1576 }
1577 }
1578
1579 RTFileClose(hRawFile);
1580
1581#ifdef DEBUG_klaus
1582 if (!RawDescriptor.fRawDisk)
1583 {
1584 RTPrintf("# start length startoffset partdataptr device\n");
1585 for (unsigned i = 0; i < RawDescriptor.cPartDescs; i++)
1586 {
1587 RTPrintf("%2u %14RU64 %14RU64 %14RU64 %#18p %s\n", i,
1588 RawDescriptor.pPartDescs[i].uStart,
1589 RawDescriptor.pPartDescs[i].cbData,
1590 RawDescriptor.pPartDescs[i].uStartOffset,
1591 RawDescriptor.pPartDescs[i].pvPartitionData,
1592 RawDescriptor.pPartDescs[i].pszRawDevice);
1593 }
1594 }
1595#endif
1596
1597 VDINTERFACEERROR vdInterfaceError;
1598 vdInterfaceError.pfnError = handleVDError;
1599 vdInterfaceError.pfnMessage = handleVDMessage;
1600
1601 rc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1602 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
1603 AssertRC(vrc);
1604
1605 vrc = VDCreate(pVDIfs, VDTYPE_HDD, &pDisk); /* Raw VMDK's are harddisk only. */
1606 if (RT_FAILURE(vrc))
1607 {
1608 RTMsgError("Cannot create the virtual disk container: %Rrc", vrc);
1609 goto out;
1610 }
1611
1612 Assert(RT_MIN(cbSize / 512 / 16 / 63, 16383) -
1613 (unsigned int)RT_MIN(cbSize / 512 / 16 / 63, 16383) == 0);
1614 VDGEOMETRY PCHS, LCHS;
1615 PCHS.cCylinders = (unsigned int)RT_MIN(cbSize / 512 / 16 / 63, 16383);
1616 PCHS.cHeads = 16;
1617 PCHS.cSectors = 63;
1618 LCHS.cCylinders = 0;
1619 LCHS.cHeads = 0;
1620 LCHS.cSectors = 0;
1621 vrc = VDCreateBase(pDisk, "VMDK", filename.c_str(), cbSize,
1622 VD_IMAGE_FLAGS_FIXED | VD_VMDK_IMAGE_FLAGS_RAWDISK,
1623 (char *)&RawDescriptor, &PCHS, &LCHS, NULL,
1624 VD_OPEN_FLAGS_NORMAL, NULL, NULL);
1625 if (RT_FAILURE(vrc))
1626 {
1627 RTMsgError("Cannot create the raw disk VMDK: %Rrc", vrc);
1628 goto out;
1629 }
1630 RTPrintf("RAW host disk access VMDK file %s created successfully.\n", filename.c_str());
1631
1632 VDCloseAll(pDisk);
1633
1634 /* Clean up allocated memory etc. */
1635 if (pszPartitions)
1636 {
1637 for (unsigned i = 0; i < RawDescriptor.cPartDescs; i++)
1638 {
1639 /* Free memory allocated for relative device name. */
1640 if (fRelative && RawDescriptor.pPartDescs[i].pszRawDevice)
1641 RTStrFree((char *)(void *)RawDescriptor.pPartDescs[i].pszRawDevice);
1642 if (RawDescriptor.pPartDescs[i].pvPartitionData)
1643 RTMemFree((void *)RawDescriptor.pPartDescs[i].pvPartitionData);
1644 }
1645 if (RawDescriptor.pPartDescs)
1646 RTMemFree(RawDescriptor.pPartDescs);
1647 }
1648
1649 return SUCCEEDED(rc) ? 0 : 1;
1650
1651out:
1652 RTMsgError("The raw disk vmdk file was not created");
1653 return RT_SUCCESS(vrc) ? 0 : 1;
1654}
1655
1656static int CmdRenameVMDK(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1657{
1658 Utf8Str src;
1659 Utf8Str dst;
1660 /* Parse the arguments. */
1661 for (int i = 0; i < argc; i++)
1662 {
1663 if (strcmp(argv[i], "-from") == 0)
1664 {
1665 if (argc <= i + 1)
1666 {
1667 return errorArgument("Missing argument to '%s'", argv[i]);
1668 }
1669 i++;
1670 src = argv[i];
1671 }
1672 else if (strcmp(argv[i], "-to") == 0)
1673 {
1674 if (argc <= i + 1)
1675 {
1676 return errorArgument("Missing argument to '%s'", argv[i]);
1677 }
1678 i++;
1679 dst = argv[i];
1680 }
1681 else
1682 {
1683 return errorSyntax(USAGE_RENAMEVMDK, "Invalid parameter '%s'", argv[i]);
1684 }
1685 }
1686
1687 if (src.isEmpty())
1688 return errorSyntax(USAGE_RENAMEVMDK, "Mandatory parameter -from missing");
1689 if (dst.isEmpty())
1690 return errorSyntax(USAGE_RENAMEVMDK, "Mandatory parameter -to missing");
1691
1692 PVBOXHDD pDisk = NULL;
1693
1694 PVDINTERFACE pVDIfs = NULL;
1695 VDINTERFACEERROR vdInterfaceError;
1696 vdInterfaceError.pfnError = handleVDError;
1697 vdInterfaceError.pfnMessage = handleVDMessage;
1698
1699 int vrc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1700 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
1701 AssertRC(vrc);
1702
1703 vrc = VDCreate(pVDIfs, VDTYPE_HDD, &pDisk);
1704 if (RT_FAILURE(vrc))
1705 {
1706 RTMsgError("Cannot create the virtual disk container: %Rrc", vrc);
1707 return vrc;
1708 }
1709 else
1710 {
1711 vrc = VDOpen(pDisk, "VMDK", src.c_str(), VD_OPEN_FLAGS_NORMAL, NULL);
1712 if (RT_FAILURE(vrc))
1713 {
1714 RTMsgError("Cannot create the source image: %Rrc", vrc);
1715 }
1716 else
1717 {
1718 vrc = VDCopy(pDisk, 0, pDisk, "VMDK", dst.c_str(), true, 0,
1719 VD_IMAGE_FLAGS_NONE, NULL, VD_OPEN_FLAGS_NORMAL,
1720 NULL, NULL, NULL);
1721 if (RT_FAILURE(vrc))
1722 {
1723 RTMsgError("Cannot rename the image: %Rrc", vrc);
1724 }
1725 }
1726 }
1727 VDCloseAll(pDisk);
1728 return vrc;
1729}
1730
1731static int CmdConvertToRaw(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1732{
1733 Utf8Str srcformat;
1734 Utf8Str src;
1735 Utf8Str dst;
1736 bool fWriteToStdOut = false;
1737
1738 /* Parse the arguments. */
1739 for (int i = 0; i < argc; i++)
1740 {
1741 if (strcmp(argv[i], "-format") == 0)
1742 {
1743 if (argc <= i + 1)
1744 {
1745 return errorArgument("Missing argument to '%s'", argv[i]);
1746 }
1747 i++;
1748 srcformat = argv[i];
1749 }
1750 else if (src.isEmpty())
1751 {
1752 src = argv[i];
1753 }
1754 else if (dst.isEmpty())
1755 {
1756 dst = argv[i];
1757#ifdef ENABLE_CONVERT_RAW_TO_STDOUT
1758 if (!strcmp(argv[i], "stdout"))
1759 fWriteToStdOut = true;
1760#endif /* ENABLE_CONVERT_RAW_TO_STDOUT */
1761 }
1762 else
1763 {
1764 return errorSyntax(USAGE_CONVERTTORAW, "Invalid parameter '%s'", argv[i]);
1765 }
1766 }
1767
1768 if (src.isEmpty())
1769 return errorSyntax(USAGE_CONVERTTORAW, "Mandatory filename parameter missing");
1770 if (dst.isEmpty())
1771 return errorSyntax(USAGE_CONVERTTORAW, "Mandatory outputfile parameter missing");
1772
1773 PVBOXHDD pDisk = NULL;
1774
1775 PVDINTERFACE pVDIfs = NULL;
1776 VDINTERFACEERROR vdInterfaceError;
1777 vdInterfaceError.pfnError = handleVDError;
1778 vdInterfaceError.pfnMessage = handleVDMessage;
1779
1780 int vrc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1781 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
1782 AssertRC(vrc);
1783
1784 /** @todo: Support convert to raw for floppy and DVD images too. */
1785 vrc = VDCreate(pVDIfs, VDTYPE_HDD, &pDisk);
1786 if (RT_FAILURE(vrc))
1787 {
1788 RTMsgError("Cannot create the virtual disk container: %Rrc", vrc);
1789 return 1;
1790 }
1791
1792 /* Open raw output file. */
1793 RTFILE outFile;
1794 vrc = VINF_SUCCESS;
1795 if (fWriteToStdOut)
1796 vrc = RTFileFromNative(&outFile, 1);
1797 else
1798 vrc = RTFileOpen(&outFile, dst.c_str(), RTFILE_O_WRITE | RTFILE_O_CREATE | RTFILE_O_DENY_ALL);
1799 if (RT_FAILURE(vrc))
1800 {
1801 VDCloseAll(pDisk);
1802 RTMsgError("Cannot create destination file \"%s\": %Rrc", dst.c_str(), vrc);
1803 return 1;
1804 }
1805
1806 if (srcformat.isEmpty())
1807 {
1808 char *pszFormat = NULL;
1809 VDTYPE enmType = VDTYPE_INVALID;
1810 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
1811 src.c_str(), &pszFormat, &enmType);
1812 if (RT_FAILURE(vrc) || enmType != VDTYPE_HDD)
1813 {
1814 VDCloseAll(pDisk);
1815 if (!fWriteToStdOut)
1816 {
1817 RTFileClose(outFile);
1818 RTFileDelete(dst.c_str());
1819 }
1820 if (RT_FAILURE(vrc))
1821 RTMsgError("No file format specified and autodetect failed - please specify format: %Rrc", vrc);
1822 else
1823 RTMsgError("Only converting harddisk images is supported");
1824 return 1;
1825 }
1826 srcformat = pszFormat;
1827 RTStrFree(pszFormat);
1828 }
1829 vrc = VDOpen(pDisk, srcformat.c_str(), src.c_str(), VD_OPEN_FLAGS_READONLY, NULL);
1830 if (RT_FAILURE(vrc))
1831 {
1832 VDCloseAll(pDisk);
1833 if (!fWriteToStdOut)
1834 {
1835 RTFileClose(outFile);
1836 RTFileDelete(dst.c_str());
1837 }
1838 RTMsgError("Cannot open the source image: %Rrc", vrc);
1839 return 1;
1840 }
1841
1842 uint64_t cbSize = VDGetSize(pDisk, VD_LAST_IMAGE);
1843 uint64_t offFile = 0;
1844#define RAW_BUFFER_SIZE _128K
1845 size_t cbBuf = RAW_BUFFER_SIZE;
1846 void *pvBuf = RTMemAlloc(cbBuf);
1847 if (pvBuf)
1848 {
1849 RTStrmPrintf(g_pStdErr, "Converting image \"%s\" with size %RU64 bytes (%RU64MB) to raw...\n", src.c_str(), cbSize, (cbSize + _1M - 1) / _1M);
1850 while (offFile < cbSize)
1851 {
1852 size_t cb = (size_t)RT_MIN(cbSize - offFile, cbBuf);
1853 vrc = VDRead(pDisk, offFile, pvBuf, cb);
1854 if (RT_FAILURE(vrc))
1855 break;
1856 vrc = RTFileWrite(outFile, pvBuf, cb, NULL);
1857 if (RT_FAILURE(vrc))
1858 break;
1859 offFile += cb;
1860 }
1861 if (RT_FAILURE(vrc))
1862 {
1863 VDCloseAll(pDisk);
1864 if (!fWriteToStdOut)
1865 {
1866 RTFileClose(outFile);
1867 RTFileDelete(dst.c_str());
1868 }
1869 RTMsgError("Cannot copy image data: %Rrc", vrc);
1870 return 1;
1871 }
1872 }
1873 else
1874 {
1875 vrc = VERR_NO_MEMORY;
1876 VDCloseAll(pDisk);
1877 if (!fWriteToStdOut)
1878 {
1879 RTFileClose(outFile);
1880 RTFileDelete(dst.c_str());
1881 }
1882 RTMsgError("Out of memory allocating read buffer");
1883 return 1;
1884 }
1885
1886 if (!fWriteToStdOut)
1887 RTFileClose(outFile);
1888 VDCloseAll(pDisk);
1889 return 0;
1890}
1891
1892static int CmdConvertHardDisk(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
1893{
1894 Utf8Str srcformat;
1895 Utf8Str dstformat;
1896 Utf8Str src;
1897 Utf8Str dst;
1898 int vrc;
1899 PVBOXHDD pSrcDisk = NULL;
1900 PVBOXHDD pDstDisk = NULL;
1901 VDTYPE enmSrcType = VDTYPE_INVALID;
1902
1903 /* Parse the arguments. */
1904 for (int i = 0; i < argc; i++)
1905 {
1906 if (strcmp(argv[i], "-srcformat") == 0)
1907 {
1908 if (argc <= i + 1)
1909 {
1910 return errorArgument("Missing argument to '%s'", argv[i]);
1911 }
1912 i++;
1913 srcformat = argv[i];
1914 }
1915 else if (strcmp(argv[i], "-dstformat") == 0)
1916 {
1917 if (argc <= i + 1)
1918 {
1919 return errorArgument("Missing argument to '%s'", argv[i]);
1920 }
1921 i++;
1922 dstformat = argv[i];
1923 }
1924 else if (src.isEmpty())
1925 {
1926 src = argv[i];
1927 }
1928 else if (dst.isEmpty())
1929 {
1930 dst = argv[i];
1931 }
1932 else
1933 {
1934 return errorSyntax(USAGE_CONVERTHD, "Invalid parameter '%s'", argv[i]);
1935 }
1936 }
1937
1938 if (src.isEmpty())
1939 return errorSyntax(USAGE_CONVERTHD, "Mandatory input image parameter missing");
1940 if (dst.isEmpty())
1941 return errorSyntax(USAGE_CONVERTHD, "Mandatory output image parameter missing");
1942
1943
1944 PVDINTERFACE pVDIfs = NULL;
1945 VDINTERFACEERROR vdInterfaceError;
1946 vdInterfaceError.pfnError = handleVDError;
1947 vdInterfaceError.pfnMessage = handleVDMessage;
1948
1949 vrc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1950 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
1951 AssertRC(vrc);
1952
1953 do
1954 {
1955 /* Try to determine input image format */
1956 if (srcformat.isEmpty())
1957 {
1958 char *pszFormat = NULL;
1959 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
1960 src.c_str(), &pszFormat, &enmSrcType);
1961 if (RT_FAILURE(vrc))
1962 {
1963 RTMsgError("No file format specified and autodetect failed - please specify format: %Rrc", vrc);
1964 break;
1965 }
1966 srcformat = pszFormat;
1967 RTStrFree(pszFormat);
1968 }
1969
1970 vrc = VDCreate(pVDIfs, enmSrcType, &pSrcDisk);
1971 if (RT_FAILURE(vrc))
1972 {
1973 RTMsgError("Cannot create the source virtual disk container: %Rrc", vrc);
1974 break;
1975 }
1976
1977 /* Open the input image */
1978 vrc = VDOpen(pSrcDisk, srcformat.c_str(), src.c_str(), VD_OPEN_FLAGS_READONLY, NULL);
1979 if (RT_FAILURE(vrc))
1980 {
1981 RTMsgError("Cannot open the source image: %Rrc", vrc);
1982 break;
1983 }
1984
1985 /* Output format defaults to VDI */
1986 if (dstformat.isEmpty())
1987 dstformat = "VDI";
1988
1989 vrc = VDCreate(pVDIfs, enmSrcType, &pDstDisk);
1990 if (RT_FAILURE(vrc))
1991 {
1992 RTMsgError("Cannot create the destination virtual disk container: %Rrc", vrc);
1993 break;
1994 }
1995
1996 uint64_t cbSize = VDGetSize(pSrcDisk, VD_LAST_IMAGE);
1997 RTStrmPrintf(g_pStdErr, "Converting image \"%s\" with size %RU64 bytes (%RU64MB)...\n", src.c_str(), cbSize, (cbSize + _1M - 1) / _1M);
1998
1999 /* Create the output image */
2000 vrc = VDCopy(pSrcDisk, VD_LAST_IMAGE, pDstDisk, dstformat.c_str(),
2001 dst.c_str(), false, 0, VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED,
2002 NULL, VD_OPEN_FLAGS_NORMAL, NULL, NULL, NULL);
2003 if (RT_FAILURE(vrc))
2004 {
2005 RTMsgError("Cannot copy the image: %Rrc", vrc);
2006 break;
2007 }
2008 }
2009 while (0);
2010 if (pDstDisk)
2011 VDCloseAll(pDstDisk);
2012 if (pSrcDisk)
2013 VDCloseAll(pSrcDisk);
2014
2015 return RT_SUCCESS(vrc) ? 0 : 1;
2016}
2017
2018/**
2019 * Tries to repair a corrupted hard disk image.
2020 *
2021 * @returns VBox status code
2022 */
2023static int CmdRepairHardDisk(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2024{
2025 Utf8Str image;
2026 Utf8Str format;
2027 int vrc;
2028 bool fDryRun = false;
2029 PVBOXHDD pDisk = NULL;
2030
2031 /* Parse the arguments. */
2032 for (int i = 0; i < argc; i++)
2033 {
2034 if (strcmp(argv[i], "-dry-run") == 0)
2035 {
2036 fDryRun = true;
2037 }
2038 else if (strcmp(argv[i], "-format") == 0)
2039 {
2040 if (argc <= i + 1)
2041 {
2042 return errorArgument("Missing argument to '%s'", argv[i]);
2043 }
2044 i++;
2045 format = argv[i];
2046 }
2047 else if (image.isEmpty())
2048 {
2049 image = argv[i];
2050 }
2051 else
2052 {
2053 return errorSyntax(USAGE_REPAIRHD, "Invalid parameter '%s'", argv[i]);
2054 }
2055 }
2056
2057 if (image.isEmpty())
2058 return errorSyntax(USAGE_REPAIRHD, "Mandatory input image parameter missing");
2059
2060 PVDINTERFACE pVDIfs = NULL;
2061 VDINTERFACEERROR vdInterfaceError;
2062 vdInterfaceError.pfnError = handleVDError;
2063 vdInterfaceError.pfnMessage = handleVDMessage;
2064
2065 vrc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
2066 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
2067 AssertRC(vrc);
2068
2069 do
2070 {
2071 /* Try to determine input image format */
2072 if (format.isEmpty())
2073 {
2074 char *pszFormat = NULL;
2075 VDTYPE enmSrcType = VDTYPE_INVALID;
2076
2077 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
2078 image.c_str(), &pszFormat, &enmSrcType);
2079 if (RT_FAILURE(vrc) && (vrc != VERR_VD_IMAGE_CORRUPTED))
2080 {
2081 RTMsgError("No file format specified and autodetect failed - please specify format: %Rrc", vrc);
2082 break;
2083 }
2084 format = pszFormat;
2085 RTStrFree(pszFormat);
2086 }
2087
2088 uint32_t fFlags = 0;
2089 if (fDryRun)
2090 fFlags |= VD_REPAIR_DRY_RUN;
2091
2092 vrc = VDRepair(pVDIfs, NULL, image.c_str(), format.c_str(), fFlags);
2093 }
2094 while (0);
2095
2096 return RT_SUCCESS(vrc) ? 0 : 1;
2097}
2098
2099/**
2100 * Unloads the necessary driver.
2101 *
2102 * @returns VBox status code
2103 */
2104int CmdModUninstall(void)
2105{
2106 int rc;
2107
2108 rc = SUPR3Uninstall();
2109 if (RT_SUCCESS(rc))
2110 return 0;
2111 if (rc == VERR_NOT_IMPLEMENTED)
2112 return 0;
2113 return E_FAIL;
2114}
2115
2116/**
2117 * Loads the necessary driver.
2118 *
2119 * @returns VBox status code
2120 */
2121int CmdModInstall(void)
2122{
2123 int rc;
2124
2125 rc = SUPR3Install();
2126 if (RT_SUCCESS(rc))
2127 return 0;
2128 if (rc == VERR_NOT_IMPLEMENTED)
2129 return 0;
2130 return E_FAIL;
2131}
2132
2133int CmdDebugLog(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2134{
2135 /*
2136 * The first parameter is the name or UUID of a VM with a direct session
2137 * that we wish to open.
2138 */
2139 if (argc < 1)
2140 return errorSyntax(USAGE_DEBUGLOG, "Missing VM name/UUID");
2141
2142 ComPtr<IMachine> ptrMachine;
2143 HRESULT rc;
2144 CHECK_ERROR_RET(aVirtualBox, FindMachine(Bstr(argv[0]).raw(),
2145 ptrMachine.asOutParam()), 1);
2146
2147 CHECK_ERROR_RET(ptrMachine, LockMachine(aSession, LockType_Shared), 1);
2148
2149 /*
2150 * Get the debugger interface.
2151 */
2152 ComPtr<IConsole> ptrConsole;
2153 CHECK_ERROR_RET(aSession, COMGETTER(Console)(ptrConsole.asOutParam()), 1);
2154
2155 ComPtr<IMachineDebugger> ptrDebugger;
2156 CHECK_ERROR_RET(ptrConsole, COMGETTER(Debugger)(ptrDebugger.asOutParam()), 1);
2157
2158 /*
2159 * Parse the command.
2160 */
2161 bool fEnablePresent = false;
2162 bool fEnable = false;
2163 bool fFlagsPresent = false;
2164 RTCString strFlags;
2165 bool fGroupsPresent = false;
2166 RTCString strGroups;
2167 bool fDestsPresent = false;
2168 RTCString strDests;
2169
2170 static const RTGETOPTDEF s_aOptions[] =
2171 {
2172 { "--disable", 'E', RTGETOPT_REQ_NOTHING },
2173 { "--enable", 'e', RTGETOPT_REQ_NOTHING },
2174 { "--flags", 'f', RTGETOPT_REQ_STRING },
2175 { "--groups", 'g', RTGETOPT_REQ_STRING },
2176 { "--destinations", 'd', RTGETOPT_REQ_STRING }
2177 };
2178
2179 int ch;
2180 RTGETOPTUNION ValueUnion;
2181 RTGETOPTSTATE GetState;
2182 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0);
2183 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
2184 {
2185 switch (ch)
2186 {
2187 case 'e':
2188 fEnablePresent = true;
2189 fEnable = true;
2190 break;
2191
2192 case 'E':
2193 fEnablePresent = true;
2194 fEnable = false;
2195 break;
2196
2197 case 'f':
2198 fFlagsPresent = true;
2199 if (*ValueUnion.psz)
2200 {
2201 if (strFlags.isNotEmpty())
2202 strFlags.append(' ');
2203 strFlags.append(ValueUnion.psz);
2204 }
2205 break;
2206
2207 case 'g':
2208 fGroupsPresent = true;
2209 if (*ValueUnion.psz)
2210 {
2211 if (strGroups.isNotEmpty())
2212 strGroups.append(' ');
2213 strGroups.append(ValueUnion.psz);
2214 }
2215 break;
2216
2217 case 'd':
2218 fDestsPresent = true;
2219 if (*ValueUnion.psz)
2220 {
2221 if (strDests.isNotEmpty())
2222 strDests.append(' ');
2223 strDests.append(ValueUnion.psz);
2224 }
2225 break;
2226
2227 default:
2228 return errorGetOpt(USAGE_DEBUGLOG , ch, &ValueUnion);
2229 }
2230 }
2231
2232 /*
2233 * Do the job.
2234 */
2235 if (fEnablePresent && !fEnable)
2236 CHECK_ERROR_RET(ptrDebugger, COMSETTER(LogEnabled)(FALSE), 1);
2237
2238 /** @todo flags, groups destination. */
2239 if (fFlagsPresent || fGroupsPresent || fDestsPresent)
2240 RTMsgWarning("One or more of the requested features are not implemented! Feel free to do this.");
2241
2242 if (fEnablePresent && fEnable)
2243 CHECK_ERROR_RET(ptrDebugger, COMSETTER(LogEnabled)(TRUE), 1);
2244 return 0;
2245}
2246
2247/**
2248 * Generate a SHA-256 password hash
2249 */
2250int CmdGeneratePasswordHash(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2251{
2252 /* one parameter, the password to hash */
2253 if (argc != 1)
2254 return errorSyntax(USAGE_PASSWORDHASH, "password to hash required");
2255
2256 uint8_t abDigest[RTSHA256_HASH_SIZE];
2257 RTSha256(argv[0], strlen(argv[0]), abDigest);
2258 char pszDigest[RTSHA256_DIGEST_LEN + 1];
2259 RTSha256ToString(abDigest, pszDigest, sizeof(pszDigest));
2260 RTPrintf("Password hash: %s\n", pszDigest);
2261
2262 return 0;
2263}
2264
2265/**
2266 * Print internal guest statistics or
2267 * set internal guest statistics update interval if specified
2268 */
2269int CmdGuestStats(int argc, char **argv, ComPtr<IVirtualBox> aVirtualBox, ComPtr<ISession> aSession)
2270{
2271 /* one parameter, guest name */
2272 if (argc < 1)
2273 return errorSyntax(USAGE_GUESTSTATS, "Missing VM name/UUID");
2274
2275 /*
2276 * Parse the command.
2277 */
2278 ULONG aUpdateInterval = 0;
2279
2280 static const RTGETOPTDEF s_aOptions[] =
2281 {
2282 { "--interval", 'i', RTGETOPT_REQ_UINT32 }
2283 };
2284
2285 int ch;
2286 RTGETOPTUNION ValueUnion;
2287 RTGETOPTSTATE GetState;
2288 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0);
2289 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
2290 {
2291 switch (ch)
2292 {
2293 case 'i':
2294 aUpdateInterval = ValueUnion.u32;
2295 break;
2296
2297 default:
2298 return errorGetOpt(USAGE_GUESTSTATS , ch, &ValueUnion);
2299 }
2300 }
2301
2302 if (argc > 1 && aUpdateInterval == 0)
2303 return errorSyntax(USAGE_GUESTSTATS, "Invalid update interval specified");
2304
2305 RTPrintf("argc=%d interval=%u\n", argc, aUpdateInterval);
2306
2307 ComPtr<IMachine> ptrMachine;
2308 HRESULT rc;
2309 CHECK_ERROR_RET(aVirtualBox, FindMachine(Bstr(argv[0]).raw(),
2310 ptrMachine.asOutParam()), 1);
2311
2312 CHECK_ERROR_RET(ptrMachine, LockMachine(aSession, LockType_Shared), 1);
2313
2314 /*
2315 * Get the guest interface.
2316 */
2317 ComPtr<IConsole> ptrConsole;
2318 CHECK_ERROR_RET(aSession, COMGETTER(Console)(ptrConsole.asOutParam()), 1);
2319
2320 ComPtr<IGuest> ptrGuest;
2321 CHECK_ERROR_RET(ptrConsole, COMGETTER(Guest)(ptrGuest.asOutParam()), 1);
2322
2323 if (aUpdateInterval)
2324 CHECK_ERROR_RET(ptrGuest, COMSETTER(StatisticsUpdateInterval)(aUpdateInterval), 1);
2325 else
2326 {
2327 ULONG mCpuUser, mCpuKernel, mCpuIdle;
2328 ULONG mMemTotal, mMemFree, mMemBalloon, mMemShared, mMemCache, mPageTotal;
2329 ULONG ulMemAllocTotal, ulMemFreeTotal, ulMemBalloonTotal, ulMemSharedTotal;
2330
2331 CHECK_ERROR_RET(ptrGuest, InternalGetStatistics(&mCpuUser, &mCpuKernel, &mCpuIdle,
2332 &mMemTotal, &mMemFree, &mMemBalloon, &mMemShared, &mMemCache,
2333 &mPageTotal, &ulMemAllocTotal, &ulMemFreeTotal, &ulMemBalloonTotal, &ulMemSharedTotal), 1);
2334 RTPrintf("mCpuUser=%u mCpuKernel=%u mCpuIdle=%u\n"
2335 "mMemTotal=%u mMemFree=%u mMemBalloon=%u mMemShared=%u mMemCache=%u\n"
2336 "mPageTotal=%u ulMemAllocTotal=%u ulMemFreeTotal=%u ulMemBalloonTotal=%u ulMemSharedTotal=%u\n",
2337 mCpuUser, mCpuKernel, mCpuIdle,
2338 mMemTotal, mMemFree, mMemBalloon, mMemShared, mMemCache,
2339 mPageTotal, ulMemAllocTotal, ulMemFreeTotal, ulMemBalloonTotal, ulMemSharedTotal);
2340
2341 }
2342
2343 return 0;
2344}
2345
2346
2347/**
2348 * Wrapper for handling internal commands
2349 */
2350int handleInternalCommands(HandlerArg *a)
2351{
2352 g_fInternalMode = true;
2353
2354 /* at least a command is required */
2355 if (a->argc < 1)
2356 return errorSyntax(USAGE_ALL, "Command missing");
2357
2358 /*
2359 * The 'string switch' on command name.
2360 */
2361 const char *pszCmd = a->argv[0];
2362 if (!strcmp(pszCmd, "loadmap"))
2363 return CmdLoadMap(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2364 if (!strcmp(pszCmd, "loadsyms"))
2365 return CmdLoadSyms(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2366 //if (!strcmp(pszCmd, "unloadsyms"))
2367 // return CmdUnloadSyms(argc - 1 , &a->argv[1]);
2368 if (!strcmp(pszCmd, "sethduuid") || !strcmp(pszCmd, "sethdparentuuid"))
2369 return CmdSetHDUUID(a->argc, &a->argv[0], a->virtualBox, a->session);
2370 if (!strcmp(pszCmd, "dumphdinfo"))
2371 return CmdDumpHDInfo(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2372 if (!strcmp(pszCmd, "listpartitions"))
2373 return CmdListPartitions(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2374 if (!strcmp(pszCmd, "createrawvmdk"))
2375 return CmdCreateRawVMDK(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2376 if (!strcmp(pszCmd, "renamevmdk"))
2377 return CmdRenameVMDK(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2378 if (!strcmp(pszCmd, "converttoraw"))
2379 return CmdConvertToRaw(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2380 if (!strcmp(pszCmd, "converthd"))
2381 return CmdConvertHardDisk(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2382 if (!strcmp(pszCmd, "modinstall"))
2383 return CmdModInstall();
2384 if (!strcmp(pszCmd, "moduninstall"))
2385 return CmdModUninstall();
2386 if (!strcmp(pszCmd, "debuglog"))
2387 return CmdDebugLog(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2388 if (!strcmp(pszCmd, "passwordhash"))
2389 return CmdGeneratePasswordHash(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2390 if (!strcmp(pszCmd, "gueststats"))
2391 return CmdGuestStats(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2392 if (!strcmp(pszCmd, "repairhd"))
2393 return CmdRepairHardDisk(a->argc - 1, &a->argv[1], a->virtualBox, a->session);
2394
2395 /* default: */
2396 return errorSyntax(USAGE_ALL, "Invalid command '%s'", a->argv[0]);
2397}
2398
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette