AndroidFastbootApp.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. /** @file
  2. Copyright (c) 2013-2014, ARM Ltd. All rights reserved.<BR>
  3. SPDX-License-Identifier: BSD-2-Clause-Patent
  4. **/
  5. #include "AndroidFastbootApp.h"
  6. #include <Protocol/AndroidFastbootTransport.h>
  7. #include <Protocol/AndroidFastbootPlatform.h>
  8. #include <Protocol/SimpleTextOut.h>
  9. #include <Protocol/SimpleTextIn.h>
  10. #include <Library/PcdLib.h>
  11. #include <Library/UefiRuntimeServicesTableLib.h>
  12. #include <Library/BaseMemoryLib.h>
  13. #include <Library/UefiBootServicesTableLib.h>
  14. #include <Library/UefiApplicationEntryPoint.h>
  15. #include <Library/PrintLib.h>
  16. /*
  17. * UEFI Application using the FASTBOOT_TRANSPORT_PROTOCOL and
  18. * FASTBOOT_PLATFORM_PROTOCOL to implement the Android Fastboot protocol.
  19. */
  20. STATIC FASTBOOT_TRANSPORT_PROTOCOL *mTransport;
  21. STATIC FASTBOOT_PLATFORM_PROTOCOL *mPlatform;
  22. STATIC EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *mTextOut;
  23. typedef enum {
  24. ExpectCmdState,
  25. ExpectDataState,
  26. FastbootStateMax
  27. } ANDROID_FASTBOOT_STATE;
  28. STATIC ANDROID_FASTBOOT_STATE mState = ExpectCmdState;
  29. // When in ExpectDataState, the number of bytes of data to expect:
  30. STATIC UINT64 mNumDataBytes;
  31. // .. and the number of bytes so far received this data phase
  32. STATIC UINT64 mBytesReceivedSoFar;
  33. // .. and the buffer to save data into
  34. STATIC UINT8 *mDataBuffer = NULL;
  35. // Event notify functions, from which gBS->Exit shouldn't be called, can signal
  36. // this event when the application should exit
  37. STATIC EFI_EVENT mFinishedEvent;
  38. STATIC EFI_EVENT mFatalSendErrorEvent;
  39. // This macro uses sizeof - only use it on arrays (i.e. string literals)
  40. #define SEND_LITERAL(Str) mTransport->Send ( \
  41. sizeof (Str) - 1, \
  42. Str, \
  43. &mFatalSendErrorEvent \
  44. )
  45. #define MATCH_CMD_LITERAL(Cmd, Buf) !AsciiStrnCmp (Cmd, Buf, sizeof (Cmd) - 1)
  46. #define IS_LOWERCASE_ASCII(Char) (Char >= 'a' && Char <= 'z')
  47. #define FASTBOOT_STRING_MAX_LENGTH 256
  48. #define FASTBOOT_COMMAND_MAX_LENGTH 64
  49. STATIC
  50. VOID
  51. HandleGetVar (
  52. IN CHAR8 *CmdArg
  53. )
  54. {
  55. CHAR8 Response[FASTBOOT_COMMAND_MAX_LENGTH + 1] = "OKAY";
  56. EFI_STATUS Status;
  57. // Respond to getvar:version with 0.4 (version of Fastboot protocol)
  58. if (!AsciiStrnCmp ("version", CmdArg, sizeof ("version") - 1)) {
  59. SEND_LITERAL ("OKAY" ANDROID_FASTBOOT_VERSION);
  60. } else {
  61. // All other variables are assumed to be platform specific
  62. Status = mPlatform->GetVar (CmdArg, Response + 4);
  63. if (EFI_ERROR (Status)) {
  64. SEND_LITERAL ("FAILSomething went wrong when looking up the variable");
  65. } else {
  66. mTransport->Send (AsciiStrLen (Response), Response, &mFatalSendErrorEvent);
  67. }
  68. }
  69. }
  70. STATIC
  71. VOID
  72. HandleDownload (
  73. IN CHAR8 *NumBytesString
  74. )
  75. {
  76. CHAR8 Response[13];
  77. CHAR16 OutputString[FASTBOOT_STRING_MAX_LENGTH];
  78. // Argument is 8-character ASCII string hex representation of number of bytes
  79. // that will be sent in the data phase.
  80. // Response is "DATA" + that same 8-character string.
  81. // Replace any previously downloaded data
  82. if (mDataBuffer != NULL) {
  83. FreePool (mDataBuffer);
  84. mDataBuffer = NULL;
  85. }
  86. // Parse out number of data bytes to expect
  87. mNumDataBytes = AsciiStrHexToUint64 (NumBytesString);
  88. if (mNumDataBytes == 0) {
  89. mTextOut->OutputString (mTextOut, L"ERROR: Fail to get the number of bytes to download.\r\n");
  90. SEND_LITERAL ("FAILFailed to get the number of bytes to download");
  91. return;
  92. }
  93. UnicodeSPrint (OutputString, sizeof (OutputString), L"Downloading %d bytes\r\n", mNumDataBytes);
  94. mTextOut->OutputString (mTextOut, OutputString);
  95. mDataBuffer = AllocatePool (mNumDataBytes);
  96. if (mDataBuffer == NULL) {
  97. SEND_LITERAL ("FAILNot enough memory");
  98. } else {
  99. ZeroMem (Response, sizeof Response);
  100. AsciiSPrint (
  101. Response,
  102. sizeof Response,
  103. "DATA%x",
  104. (UINT32)mNumDataBytes
  105. );
  106. mTransport->Send (sizeof Response - 1, Response, &mFatalSendErrorEvent);
  107. mState = ExpectDataState;
  108. mBytesReceivedSoFar = 0;
  109. }
  110. }
  111. STATIC
  112. VOID
  113. HandleFlash (
  114. IN CHAR8 *PartitionName
  115. )
  116. {
  117. EFI_STATUS Status;
  118. CHAR16 OutputString[FASTBOOT_STRING_MAX_LENGTH];
  119. // Build output string
  120. UnicodeSPrint (OutputString, sizeof (OutputString), L"Flashing partition %a\r\n", PartitionName);
  121. mTextOut->OutputString (mTextOut, OutputString);
  122. if (mDataBuffer == NULL) {
  123. // Doesn't look like we were sent any data
  124. SEND_LITERAL ("FAILNo data to flash");
  125. return;
  126. }
  127. Status = mPlatform->FlashPartition (
  128. PartitionName,
  129. mNumDataBytes,
  130. mDataBuffer
  131. );
  132. if (Status == EFI_NOT_FOUND) {
  133. SEND_LITERAL ("FAILNo such partition.");
  134. mTextOut->OutputString (mTextOut, L"No such partition.\r\n");
  135. } else if (EFI_ERROR (Status)) {
  136. SEND_LITERAL ("FAILError flashing partition.");
  137. mTextOut->OutputString (mTextOut, L"Error flashing partition.\r\n");
  138. DEBUG ((DEBUG_ERROR, "Couldn't flash image: %r\n", Status));
  139. } else {
  140. mTextOut->OutputString (mTextOut, L"Done.\r\n");
  141. SEND_LITERAL ("OKAY");
  142. }
  143. }
  144. STATIC
  145. VOID
  146. HandleErase (
  147. IN CHAR8 *PartitionName
  148. )
  149. {
  150. EFI_STATUS Status;
  151. CHAR16 OutputString[FASTBOOT_STRING_MAX_LENGTH];
  152. // Build output string
  153. UnicodeSPrint (OutputString, sizeof (OutputString), L"Erasing partition %a\r\n", PartitionName);
  154. mTextOut->OutputString (mTextOut, OutputString);
  155. Status = mPlatform->ErasePartition (PartitionName);
  156. if (EFI_ERROR (Status)) {
  157. SEND_LITERAL ("FAILCheck device console.");
  158. DEBUG ((DEBUG_ERROR, "Couldn't erase image: %r\n", Status));
  159. } else {
  160. SEND_LITERAL ("OKAY");
  161. }
  162. }
  163. STATIC
  164. VOID
  165. HandleBoot (
  166. VOID
  167. )
  168. {
  169. EFI_STATUS Status;
  170. mTextOut->OutputString (mTextOut, L"Booting downloaded image\r\n");
  171. if (mDataBuffer == NULL) {
  172. // Doesn't look like we were sent any data
  173. SEND_LITERAL ("FAILNo image in memory");
  174. return;
  175. }
  176. // We don't really have any choice but to report success, because once we
  177. // boot we lose control of the system.
  178. SEND_LITERAL ("OKAY");
  179. Status = BootAndroidBootImg (mNumDataBytes, mDataBuffer);
  180. if (EFI_ERROR (Status)) {
  181. DEBUG ((DEBUG_ERROR, "Failed to boot downloaded image: %r\n", Status));
  182. }
  183. // We shouldn't get here
  184. }
  185. STATIC
  186. VOID
  187. HandleOemCommand (
  188. IN CHAR8 *Command
  189. )
  190. {
  191. EFI_STATUS Status;
  192. Status = mPlatform->DoOemCommand (Command);
  193. if (Status == EFI_NOT_FOUND) {
  194. SEND_LITERAL ("FAILOEM Command not recognised.");
  195. } else if (Status == EFI_DEVICE_ERROR) {
  196. SEND_LITERAL ("FAILError while executing command");
  197. } else if (EFI_ERROR (Status)) {
  198. SEND_LITERAL ("FAIL");
  199. } else {
  200. SEND_LITERAL ("OKAY");
  201. }
  202. }
  203. STATIC
  204. VOID
  205. AcceptCmd (
  206. IN UINTN Size,
  207. IN CONST CHAR8 *Data
  208. )
  209. {
  210. CHAR8 Command[FASTBOOT_COMMAND_MAX_LENGTH + 1];
  211. // Max command size is 64 bytes
  212. if (Size > FASTBOOT_COMMAND_MAX_LENGTH) {
  213. SEND_LITERAL ("FAILCommand too large");
  214. return;
  215. }
  216. // Commands aren't null-terminated. Let's get a null-terminated version.
  217. AsciiStrnCpyS (Command, sizeof Command, Data, Size);
  218. // Parse command
  219. if (MATCH_CMD_LITERAL ("getvar", Command)) {
  220. HandleGetVar (Command + sizeof ("getvar"));
  221. } else if (MATCH_CMD_LITERAL ("download", Command)) {
  222. HandleDownload (Command + sizeof ("download"));
  223. } else if (MATCH_CMD_LITERAL ("verify", Command)) {
  224. SEND_LITERAL ("FAILNot supported");
  225. } else if (MATCH_CMD_LITERAL ("flash", Command)) {
  226. HandleFlash (Command + sizeof ("flash"));
  227. } else if (MATCH_CMD_LITERAL ("erase", Command)) {
  228. HandleErase (Command + sizeof ("erase"));
  229. } else if (MATCH_CMD_LITERAL ("boot", Command)) {
  230. HandleBoot ();
  231. } else if (MATCH_CMD_LITERAL ("continue", Command)) {
  232. SEND_LITERAL ("OKAY");
  233. mTextOut->OutputString (mTextOut, L"Received 'continue' command. Exiting Fastboot mode\r\n");
  234. gBS->SignalEvent (mFinishedEvent);
  235. } else if (MATCH_CMD_LITERAL ("reboot", Command)) {
  236. if (MATCH_CMD_LITERAL ("reboot-booloader", Command)) {
  237. // fastboot_protocol.txt:
  238. // "reboot-bootloader Reboot back into the bootloader."
  239. // I guess this means reboot back into fastboot mode to save the user
  240. // having to do whatever they did to get here again.
  241. // Here we just reboot normally.
  242. SEND_LITERAL ("INFOreboot-bootloader not supported, rebooting normally.");
  243. }
  244. SEND_LITERAL ("OKAY");
  245. gRT->ResetSystem (EfiResetCold, EFI_SUCCESS, 0, NULL);
  246. // Shouldn't get here
  247. DEBUG ((DEBUG_ERROR, "Fastboot: gRT->ResetSystem didn't work\n"));
  248. } else if (MATCH_CMD_LITERAL ("powerdown", Command)) {
  249. SEND_LITERAL ("OKAY");
  250. gRT->ResetSystem (EfiResetShutdown, EFI_SUCCESS, 0, NULL);
  251. // Shouldn't get here
  252. DEBUG ((DEBUG_ERROR, "Fastboot: gRT->ResetSystem didn't work\n"));
  253. } else if (MATCH_CMD_LITERAL ("oem", Command)) {
  254. // The "oem" command isn't in the specification, but it was observed in the
  255. // wild, followed by a space, followed by the actual command.
  256. HandleOemCommand (Command + sizeof ("oem"));
  257. } else if (IS_LOWERCASE_ASCII (Command[0])) {
  258. // Commands starting with lowercase ASCII characters are reserved for the
  259. // Fastboot protocol. If we don't recognise it, it's probably the future
  260. // and there are new commands in the protocol.
  261. // (By the way, the "oem" command mentioned above makes this reservation
  262. // redundant, but we handle it here to be spec-compliant)
  263. SEND_LITERAL ("FAILCommand not recognised. Check Fastboot version.");
  264. } else {
  265. HandleOemCommand (Command);
  266. }
  267. }
  268. STATIC
  269. VOID
  270. AcceptData (
  271. IN UINTN Size,
  272. IN VOID *Data
  273. )
  274. {
  275. UINT32 RemainingBytes = mNumDataBytes - mBytesReceivedSoFar;
  276. CHAR16 OutputString[FASTBOOT_STRING_MAX_LENGTH];
  277. STATIC UINTN Count = 0;
  278. // Protocol doesn't say anything about sending extra data so just ignore it.
  279. if (Size > RemainingBytes) {
  280. Size = RemainingBytes;
  281. }
  282. CopyMem (&mDataBuffer[mBytesReceivedSoFar], Data, Size);
  283. mBytesReceivedSoFar += Size;
  284. // Show download progress. Don't do it for every packet as outputting text
  285. // might be time consuming - do it on the last packet and on every 32nd packet
  286. if (((Count++ % 32) == 0) || (Size == RemainingBytes)) {
  287. // (Note no newline in format string - it will overwrite the line each time)
  288. UnicodeSPrint (
  289. OutputString,
  290. sizeof (OutputString),
  291. L"\r%8d / %8d bytes downloaded (%d%%)",
  292. mBytesReceivedSoFar,
  293. mNumDataBytes,
  294. (mBytesReceivedSoFar * 100) / mNumDataBytes // percentage
  295. );
  296. mTextOut->OutputString (mTextOut, OutputString);
  297. }
  298. if (mBytesReceivedSoFar == mNumDataBytes) {
  299. // Download finished.
  300. mTextOut->OutputString (mTextOut, L"\r\n");
  301. SEND_LITERAL ("OKAY");
  302. mState = ExpectCmdState;
  303. }
  304. }
  305. /*
  306. This is the NotifyFunction passed to CreateEvent in the FastbootAppEntryPoint
  307. It will be called by the UEFI event framework when the transport protocol
  308. implementation signals that data has been received from the Fastboot host.
  309. The parameters are ignored.
  310. */
  311. STATIC
  312. VOID
  313. DataReady (
  314. IN EFI_EVENT Event,
  315. IN VOID *Context
  316. )
  317. {
  318. UINTN Size;
  319. VOID *Data;
  320. EFI_STATUS Status;
  321. do {
  322. Status = mTransport->Receive (&Size, &Data);
  323. if (!EFI_ERROR (Status)) {
  324. if (mState == ExpectCmdState) {
  325. AcceptCmd (Size, (CHAR8 *)Data);
  326. } else if (mState == ExpectDataState) {
  327. AcceptData (Size, Data);
  328. } else {
  329. ASSERT (FALSE);
  330. }
  331. FreePool (Data);
  332. }
  333. } while (!EFI_ERROR (Status));
  334. // Quit if there was a fatal error
  335. if (Status != EFI_NOT_READY) {
  336. ASSERT (Status == EFI_DEVICE_ERROR);
  337. // (Put a newline at the beginning as we are probably in the data phase,
  338. // so the download progress line, with no '\n' is probably on the console)
  339. mTextOut->OutputString (mTextOut, L"\r\nFatal error receiving data. Exiting.\r\n");
  340. gBS->SignalEvent (mFinishedEvent);
  341. }
  342. }
  343. /*
  344. Event notify for a fatal error in transmission.
  345. */
  346. STATIC
  347. VOID
  348. FatalErrorNotify (
  349. IN EFI_EVENT Event,
  350. IN VOID *Context
  351. )
  352. {
  353. mTextOut->OutputString (mTextOut, L"Fatal error sending command response. Exiting.\r\n");
  354. gBS->SignalEvent (mFinishedEvent);
  355. }
  356. EFI_STATUS
  357. EFIAPI
  358. FastbootAppEntryPoint (
  359. IN EFI_HANDLE ImageHandle,
  360. IN EFI_SYSTEM_TABLE *SystemTable
  361. )
  362. {
  363. EFI_STATUS Status;
  364. EFI_EVENT ReceiveEvent;
  365. EFI_EVENT WaitEventArray[2];
  366. UINTN EventIndex;
  367. EFI_SIMPLE_TEXT_INPUT_PROTOCOL *TextIn;
  368. EFI_INPUT_KEY Key;
  369. mDataBuffer = NULL;
  370. Status = gBS->LocateProtocol (
  371. &gAndroidFastbootTransportProtocolGuid,
  372. NULL,
  373. (VOID **)&mTransport
  374. );
  375. if (EFI_ERROR (Status)) {
  376. DEBUG ((DEBUG_ERROR, "Fastboot: Couldn't open Fastboot Transport Protocol: %r\n", Status));
  377. return Status;
  378. }
  379. Status = gBS->LocateProtocol (&gAndroidFastbootPlatformProtocolGuid, NULL, (VOID **)&mPlatform);
  380. if (EFI_ERROR (Status)) {
  381. DEBUG ((DEBUG_ERROR, "Fastboot: Couldn't open Fastboot Platform Protocol: %r\n", Status));
  382. return Status;
  383. }
  384. Status = mPlatform->Init ();
  385. if (EFI_ERROR (Status)) {
  386. DEBUG ((DEBUG_ERROR, "Fastboot: Couldn't initialise Fastboot Platform Protocol: %r\n", Status));
  387. return Status;
  388. }
  389. Status = gBS->LocateProtocol (&gEfiSimpleTextOutProtocolGuid, NULL, (VOID **)&mTextOut);
  390. if (EFI_ERROR (Status)) {
  391. DEBUG ((
  392. DEBUG_ERROR,
  393. "Fastboot: Couldn't open Text Output Protocol: %r\n",
  394. Status
  395. ));
  396. return Status;
  397. }
  398. Status = gBS->LocateProtocol (&gEfiSimpleTextInProtocolGuid, NULL, (VOID **)&TextIn);
  399. if (EFI_ERROR (Status)) {
  400. DEBUG ((DEBUG_ERROR, "Fastboot: Couldn't open Text Input Protocol: %r\n", Status));
  401. return Status;
  402. }
  403. // Disable watchdog
  404. Status = gBS->SetWatchdogTimer (0, 0x10000, 0, NULL);
  405. if (EFI_ERROR (Status)) {
  406. DEBUG ((DEBUG_ERROR, "Fastboot: Couldn't disable watchdog timer: %r\n", Status));
  407. }
  408. // Create event for receipt of data from the host
  409. Status = gBS->CreateEvent (
  410. EVT_NOTIFY_SIGNAL,
  411. TPL_CALLBACK,
  412. DataReady,
  413. NULL,
  414. &ReceiveEvent
  415. );
  416. ASSERT_EFI_ERROR (Status);
  417. // Create event for exiting application when "continue" command is received
  418. Status = gBS->CreateEvent (0, TPL_CALLBACK, NULL, NULL, &mFinishedEvent);
  419. ASSERT_EFI_ERROR (Status);
  420. // Create event to pass to FASTBOOT_TRANSPORT_PROTOCOL.Send, signalling a
  421. // fatal error
  422. Status = gBS->CreateEvent (
  423. EVT_NOTIFY_SIGNAL,
  424. TPL_CALLBACK,
  425. FatalErrorNotify,
  426. NULL,
  427. &mFatalSendErrorEvent
  428. );
  429. ASSERT_EFI_ERROR (Status);
  430. // Start listening for data
  431. Status = mTransport->Start (
  432. ReceiveEvent
  433. );
  434. if (EFI_ERROR (Status)) {
  435. DEBUG ((DEBUG_ERROR, "Fastboot: Couldn't start transport: %r\n", Status));
  436. return Status;
  437. }
  438. // Talk to the user
  439. mTextOut->OutputString (
  440. mTextOut,
  441. L"Android Fastboot mode - version " ANDROID_FASTBOOT_VERSION ". Press RETURN or SPACE key to quit.\r\n"
  442. );
  443. // Quit when the user presses any key, or mFinishedEvent is signalled
  444. WaitEventArray[0] = mFinishedEvent;
  445. WaitEventArray[1] = TextIn->WaitForKey;
  446. while (1) {
  447. gBS->WaitForEvent (2, WaitEventArray, &EventIndex);
  448. Status = TextIn->ReadKeyStroke (gST->ConIn, &Key);
  449. if (Key.ScanCode == SCAN_NULL) {
  450. if ((Key.UnicodeChar == CHAR_CARRIAGE_RETURN) ||
  451. (Key.UnicodeChar == L' '))
  452. {
  453. break;
  454. }
  455. }
  456. }
  457. mTransport->Stop ();
  458. if (EFI_ERROR (Status)) {
  459. DEBUG ((DEBUG_ERROR, "Warning: Fastboot Transport Stop: %r\n", Status));
  460. }
  461. mPlatform->UnInit ();
  462. return EFI_SUCCESS;
  463. }