AndroidFastbootApp.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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 (Response, sizeof Response, "DATA%x",
  101. (UINT32)mNumDataBytes);
  102. mTransport->Send (sizeof Response - 1, Response, &mFatalSendErrorEvent);
  103. mState = ExpectDataState;
  104. mBytesReceivedSoFar = 0;
  105. }
  106. }
  107. STATIC
  108. VOID
  109. HandleFlash (
  110. IN CHAR8 *PartitionName
  111. )
  112. {
  113. EFI_STATUS Status;
  114. CHAR16 OutputString[FASTBOOT_STRING_MAX_LENGTH];
  115. // Build output string
  116. UnicodeSPrint (OutputString, sizeof (OutputString), L"Flashing partition %a\r\n", PartitionName);
  117. mTextOut->OutputString (mTextOut, OutputString);
  118. if (mDataBuffer == NULL) {
  119. // Doesn't look like we were sent any data
  120. SEND_LITERAL ("FAILNo data to flash");
  121. return;
  122. }
  123. Status = mPlatform->FlashPartition (
  124. PartitionName,
  125. mNumDataBytes,
  126. mDataBuffer
  127. );
  128. if (Status == EFI_NOT_FOUND) {
  129. SEND_LITERAL ("FAILNo such partition.");
  130. mTextOut->OutputString (mTextOut, L"No such partition.\r\n");
  131. } else if (EFI_ERROR (Status)) {
  132. SEND_LITERAL ("FAILError flashing partition.");
  133. mTextOut->OutputString (mTextOut, L"Error flashing partition.\r\n");
  134. DEBUG ((EFI_D_ERROR, "Couldn't flash image: %r\n", Status));
  135. } else {
  136. mTextOut->OutputString (mTextOut, L"Done.\r\n");
  137. SEND_LITERAL ("OKAY");
  138. }
  139. }
  140. STATIC
  141. VOID
  142. HandleErase (
  143. IN CHAR8 *PartitionName
  144. )
  145. {
  146. EFI_STATUS Status;
  147. CHAR16 OutputString[FASTBOOT_STRING_MAX_LENGTH];
  148. // Build output string
  149. UnicodeSPrint (OutputString, sizeof (OutputString), L"Erasing partition %a\r\n", PartitionName);
  150. mTextOut->OutputString (mTextOut, OutputString);
  151. Status = mPlatform->ErasePartition (PartitionName);
  152. if (EFI_ERROR (Status)) {
  153. SEND_LITERAL ("FAILCheck device console.");
  154. DEBUG ((EFI_D_ERROR, "Couldn't erase image: %r\n", Status));
  155. } else {
  156. SEND_LITERAL ("OKAY");
  157. }
  158. }
  159. STATIC
  160. VOID
  161. HandleBoot (
  162. VOID
  163. )
  164. {
  165. EFI_STATUS Status;
  166. mTextOut->OutputString (mTextOut, L"Booting downloaded image\r\n");
  167. if (mDataBuffer == NULL) {
  168. // Doesn't look like we were sent any data
  169. SEND_LITERAL ("FAILNo image in memory");
  170. return;
  171. }
  172. // We don't really have any choice but to report success, because once we
  173. // boot we lose control of the system.
  174. SEND_LITERAL ("OKAY");
  175. Status = BootAndroidBootImg (mNumDataBytes, mDataBuffer);
  176. if (EFI_ERROR (Status)) {
  177. DEBUG ((EFI_D_ERROR, "Failed to boot downloaded image: %r\n", Status));
  178. }
  179. // We shouldn't get here
  180. }
  181. STATIC
  182. VOID
  183. HandleOemCommand (
  184. IN CHAR8 *Command
  185. )
  186. {
  187. EFI_STATUS Status;
  188. Status = mPlatform->DoOemCommand (Command);
  189. if (Status == EFI_NOT_FOUND) {
  190. SEND_LITERAL ("FAILOEM Command not recognised.");
  191. } else if (Status == EFI_DEVICE_ERROR) {
  192. SEND_LITERAL ("FAILError while executing command");
  193. } else if (EFI_ERROR (Status)) {
  194. SEND_LITERAL ("FAIL");
  195. } else {
  196. SEND_LITERAL ("OKAY");
  197. }
  198. }
  199. STATIC
  200. VOID
  201. AcceptCmd (
  202. IN UINTN Size,
  203. IN CONST CHAR8 *Data
  204. )
  205. {
  206. CHAR8 Command[FASTBOOT_COMMAND_MAX_LENGTH + 1];
  207. // Max command size is 64 bytes
  208. if (Size > FASTBOOT_COMMAND_MAX_LENGTH) {
  209. SEND_LITERAL ("FAILCommand too large");
  210. return;
  211. }
  212. // Commands aren't null-terminated. Let's get a null-terminated version.
  213. AsciiStrnCpyS (Command, sizeof Command, Data, Size);
  214. // Parse command
  215. if (MATCH_CMD_LITERAL ("getvar", Command)) {
  216. HandleGetVar (Command + sizeof ("getvar"));
  217. } else if (MATCH_CMD_LITERAL ("download", Command)) {
  218. HandleDownload (Command + sizeof ("download"));
  219. } else if (MATCH_CMD_LITERAL ("verify", Command)) {
  220. SEND_LITERAL ("FAILNot supported");
  221. } else if (MATCH_CMD_LITERAL ("flash", Command)) {
  222. HandleFlash (Command + sizeof ("flash"));
  223. } else if (MATCH_CMD_LITERAL ("erase", Command)) {
  224. HandleErase (Command + sizeof ("erase"));
  225. } else if (MATCH_CMD_LITERAL ("boot", Command)) {
  226. HandleBoot ();
  227. } else if (MATCH_CMD_LITERAL ("continue", Command)) {
  228. SEND_LITERAL ("OKAY");
  229. mTextOut->OutputString (mTextOut, L"Received 'continue' command. Exiting Fastboot mode\r\n");
  230. gBS->SignalEvent (mFinishedEvent);
  231. } else if (MATCH_CMD_LITERAL ("reboot", Command)) {
  232. if (MATCH_CMD_LITERAL ("reboot-booloader", Command)) {
  233. // fastboot_protocol.txt:
  234. // "reboot-bootloader Reboot back into the bootloader."
  235. // I guess this means reboot back into fastboot mode to save the user
  236. // having to do whatever they did to get here again.
  237. // Here we just reboot normally.
  238. SEND_LITERAL ("INFOreboot-bootloader not supported, rebooting normally.");
  239. }
  240. SEND_LITERAL ("OKAY");
  241. gRT->ResetSystem (EfiResetCold, EFI_SUCCESS, 0, NULL);
  242. // Shouldn't get here
  243. DEBUG ((EFI_D_ERROR, "Fastboot: gRT->ResetSystem didn't work\n"));
  244. } else if (MATCH_CMD_LITERAL ("powerdown", Command)) {
  245. SEND_LITERAL ("OKAY");
  246. gRT->ResetSystem (EfiResetShutdown, EFI_SUCCESS, 0, NULL);
  247. // Shouldn't get here
  248. DEBUG ((EFI_D_ERROR, "Fastboot: gRT->ResetSystem didn't work\n"));
  249. } else if (MATCH_CMD_LITERAL ("oem", Command)) {
  250. // The "oem" command isn't in the specification, but it was observed in the
  251. // wild, followed by a space, followed by the actual command.
  252. HandleOemCommand (Command + sizeof ("oem"));
  253. } else if (IS_LOWERCASE_ASCII (Command[0])) {
  254. // Commands starting with lowercase ASCII characters are reserved for the
  255. // Fastboot protocol. If we don't recognise it, it's probably the future
  256. // and there are new commmands in the protocol.
  257. // (By the way, the "oem" command mentioned above makes this reservation
  258. // redundant, but we handle it here to be spec-compliant)
  259. SEND_LITERAL ("FAILCommand not recognised. Check Fastboot version.");
  260. } else {
  261. HandleOemCommand (Command);
  262. }
  263. }
  264. STATIC
  265. VOID
  266. AcceptData (
  267. IN UINTN Size,
  268. IN VOID *Data
  269. )
  270. {
  271. UINT32 RemainingBytes = mNumDataBytes - mBytesReceivedSoFar;
  272. CHAR16 OutputString[FASTBOOT_STRING_MAX_LENGTH];
  273. STATIC UINTN Count = 0;
  274. // Protocol doesn't say anything about sending extra data so just ignore it.
  275. if (Size > RemainingBytes) {
  276. Size = RemainingBytes;
  277. }
  278. CopyMem (&mDataBuffer[mBytesReceivedSoFar], Data, Size);
  279. mBytesReceivedSoFar += Size;
  280. // Show download progress. Don't do it for every packet as outputting text
  281. // might be time consuming - do it on the last packet and on every 32nd packet
  282. if ((Count++ % 32) == 0 || Size == RemainingBytes) {
  283. // (Note no newline in format string - it will overwrite the line each time)
  284. UnicodeSPrint (
  285. OutputString,
  286. sizeof (OutputString),
  287. L"\r%8d / %8d bytes downloaded (%d%%)",
  288. mBytesReceivedSoFar,
  289. mNumDataBytes,
  290. (mBytesReceivedSoFar * 100) / mNumDataBytes // percentage
  291. );
  292. mTextOut->OutputString (mTextOut, OutputString);
  293. }
  294. if (mBytesReceivedSoFar == mNumDataBytes) {
  295. // Download finished.
  296. mTextOut->OutputString (mTextOut, L"\r\n");
  297. SEND_LITERAL ("OKAY");
  298. mState = ExpectCmdState;
  299. }
  300. }
  301. /*
  302. This is the NotifyFunction passed to CreateEvent in the FastbootAppEntryPoint
  303. It will be called by the UEFI event framework when the transport protocol
  304. implementation signals that data has been received from the Fastboot host.
  305. The parameters are ignored.
  306. */
  307. STATIC
  308. VOID
  309. DataReady (
  310. IN EFI_EVENT Event,
  311. IN VOID *Context
  312. )
  313. {
  314. UINTN Size;
  315. VOID *Data;
  316. EFI_STATUS Status;
  317. do {
  318. Status = mTransport->Receive (&Size, &Data);
  319. if (!EFI_ERROR (Status)) {
  320. if (mState == ExpectCmdState) {
  321. AcceptCmd (Size, (CHAR8 *) Data);
  322. } else if (mState == ExpectDataState) {
  323. AcceptData (Size, Data);
  324. } else {
  325. ASSERT (FALSE);
  326. }
  327. FreePool (Data);
  328. }
  329. } while (!EFI_ERROR (Status));
  330. // Quit if there was a fatal error
  331. if (Status != EFI_NOT_READY) {
  332. ASSERT (Status == EFI_DEVICE_ERROR);
  333. // (Put a newline at the beginning as we are probably in the data phase,
  334. // so the download progress line, with no '\n' is probably on the console)
  335. mTextOut->OutputString (mTextOut, L"\r\nFatal error receiving data. Exiting.\r\n");
  336. gBS->SignalEvent (mFinishedEvent);
  337. }
  338. }
  339. /*
  340. Event notify for a fatal error in transmission.
  341. */
  342. STATIC
  343. VOID
  344. FatalErrorNotify (
  345. IN EFI_EVENT Event,
  346. IN VOID *Context
  347. )
  348. {
  349. mTextOut->OutputString (mTextOut, L"Fatal error sending command response. Exiting.\r\n");
  350. gBS->SignalEvent (mFinishedEvent);
  351. }
  352. EFI_STATUS
  353. EFIAPI
  354. FastbootAppEntryPoint (
  355. IN EFI_HANDLE ImageHandle,
  356. IN EFI_SYSTEM_TABLE *SystemTable
  357. )
  358. {
  359. EFI_STATUS Status;
  360. EFI_EVENT ReceiveEvent;
  361. EFI_EVENT WaitEventArray[2];
  362. UINTN EventIndex;
  363. EFI_SIMPLE_TEXT_INPUT_PROTOCOL *TextIn;
  364. EFI_INPUT_KEY Key;
  365. mDataBuffer = NULL;
  366. Status = gBS->LocateProtocol (
  367. &gAndroidFastbootTransportProtocolGuid,
  368. NULL,
  369. (VOID **) &mTransport
  370. );
  371. if (EFI_ERROR (Status)) {
  372. DEBUG ((EFI_D_ERROR, "Fastboot: Couldn't open Fastboot Transport Protocol: %r\n", Status));
  373. return Status;
  374. }
  375. Status = gBS->LocateProtocol (&gAndroidFastbootPlatformProtocolGuid, NULL, (VOID **) &mPlatform);
  376. if (EFI_ERROR (Status)) {
  377. DEBUG ((EFI_D_ERROR, "Fastboot: Couldn't open Fastboot Platform Protocol: %r\n", Status));
  378. return Status;
  379. }
  380. Status = mPlatform->Init ();
  381. if (EFI_ERROR (Status)) {
  382. DEBUG ((EFI_D_ERROR, "Fastboot: Couldn't initialise Fastboot Platform Protocol: %r\n", Status));
  383. return Status;
  384. }
  385. Status = gBS->LocateProtocol (&gEfiSimpleTextOutProtocolGuid, NULL, (VOID **) &mTextOut);
  386. if (EFI_ERROR (Status)) {
  387. DEBUG ((EFI_D_ERROR,
  388. "Fastboot: Couldn't open Text Output Protocol: %r\n", Status
  389. ));
  390. return Status;
  391. }
  392. Status = gBS->LocateProtocol (&gEfiSimpleTextInProtocolGuid, NULL, (VOID **) &TextIn);
  393. if (EFI_ERROR (Status)) {
  394. DEBUG ((EFI_D_ERROR, "Fastboot: Couldn't open Text Input Protocol: %r\n", Status));
  395. return Status;
  396. }
  397. // Disable watchdog
  398. Status = gBS->SetWatchdogTimer (0, 0x10000, 0, NULL);
  399. if (EFI_ERROR (Status)) {
  400. DEBUG ((EFI_D_ERROR, "Fastboot: Couldn't disable watchdog timer: %r\n", Status));
  401. }
  402. // Create event for receipt of data from the host
  403. Status = gBS->CreateEvent (
  404. EVT_NOTIFY_SIGNAL,
  405. TPL_CALLBACK,
  406. DataReady,
  407. NULL,
  408. &ReceiveEvent
  409. );
  410. ASSERT_EFI_ERROR (Status);
  411. // Create event for exiting application when "continue" command is received
  412. Status = gBS->CreateEvent (0, TPL_CALLBACK, NULL, NULL, &mFinishedEvent);
  413. ASSERT_EFI_ERROR (Status);
  414. // Create event to pass to FASTBOOT_TRANSPORT_PROTOCOL.Send, signalling a
  415. // fatal error
  416. Status = gBS->CreateEvent (
  417. EVT_NOTIFY_SIGNAL,
  418. TPL_CALLBACK,
  419. FatalErrorNotify,
  420. NULL,
  421. &mFatalSendErrorEvent
  422. );
  423. ASSERT_EFI_ERROR (Status);
  424. // Start listening for data
  425. Status = mTransport->Start (
  426. ReceiveEvent
  427. );
  428. if (EFI_ERROR (Status)) {
  429. DEBUG ((EFI_D_ERROR, "Fastboot: Couldn't start transport: %r\n", Status));
  430. return Status;
  431. }
  432. // Talk to the user
  433. mTextOut->OutputString (mTextOut,
  434. L"Android Fastboot mode - version " ANDROID_FASTBOOT_VERSION ". Press RETURN or SPACE key to quit.\r\n");
  435. // Quit when the user presses any key, or mFinishedEvent is signalled
  436. WaitEventArray[0] = mFinishedEvent;
  437. WaitEventArray[1] = TextIn->WaitForKey;
  438. while (1) {
  439. gBS->WaitForEvent (2, WaitEventArray, &EventIndex);
  440. Status = TextIn->ReadKeyStroke (gST->ConIn, &Key);
  441. if (Key.ScanCode == SCAN_NULL) {
  442. if ((Key.UnicodeChar == CHAR_CARRIAGE_RETURN) ||
  443. (Key.UnicodeChar == L' ')) {
  444. break;
  445. }
  446. }
  447. }
  448. mTransport->Stop ();
  449. if (EFI_ERROR (Status)) {
  450. DEBUG ((EFI_D_ERROR, "Warning: Fastboot Transport Stop: %r\n", Status));
  451. }
  452. mPlatform->UnInit ();
  453. return EFI_SUCCESS;
  454. }