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