2 EFI versions of NetBSD system calls.
4 Copyright (c) 2010 - 2011, Intel Corporation. All rights reserved.<BR>
5 This program and the accompanying materials are licensed and made available under
6 the terms and conditions of the BSD License that accompanies this distribution.
7 The full text of the license may be found at
8 http://opensource.org/licenses/bsd-license.
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.
15 #include <Library/UefiLib.h>
16 #include <Library/BaseLib.h>
17 #include <Library/MemoryAllocationLib.h>
18 #include <Library/ShellLib.h>
20 #include <LibConfig.h>
21 #include <sys/EfiCdefs.h>
28 #include <sys/fcntl.h>
30 #include <sys/syslimits.h>
33 #include <extern.h> // Library/include/extern.h: Private to implementation
34 #include <Efi/Console.h>
36 /* Macros only used in this file. */
37 // Parameters for the ValidateFD function.
39 #define VALID_CLOSED 0
40 #define VALID_DONT_CARE -1
43 /* EFI versions of BSD system calls used in stdio */
45 /* Normalize path so that forward slashes are replaced with backslashes.
46 Backslashes are required for UEFI.
49 NormalizePath( const CHAR16
*path
)
53 for( temp
= (CHAR16
*)path
; *temp
; ++temp
) {
60 /* Validate that fd refers to a valid file descriptor.
61 IsOpen is interpreted as follows:
62 - Positive fd must be OPEN
63 - Zero fd must be CLOSED
64 - Negative fd may be OPEN or CLOSED
66 @retval TRUE fd is VALID
67 @retval FALSE fd is INVALID
70 ValidateFD( int fd
, int IsOpen
)
72 BOOLEAN retval
= FALSE
;
74 if((fd
>= 0) && (fd
< OPEN_MAX
)) {
77 retval
= (BOOLEAN
)(gMD
->fdarray
[fd
].State
!= 0); // TRUE if OPEN
78 if(IsOpen
== VALID_CLOSED
) {
79 retval
= (BOOLEAN
)!retval
; // We want TRUE if CLOSED
86 /* Find and reserve a free File Descriptor.
88 Returns the first free File Descriptor greater than or equal to the,
89 already validated, fd specified by Minfd.
91 @return Returns -1 if there are no free FDs. Otherwise returns the
95 FindFreeFD( int MinFd
)
97 struct __filedes
*Mfd
;
103 // Get an available fd
104 for(i
=MinFd
; i
< OPEN_MAX
; ++i
) {
105 if(Mfd
[i
].State
== 0) {
106 Mfd
[i
].State
= S_ISYSTEM
; // Temporarily mark this fd as reserved
114 /** The isatty() function tests whether fildes, an open file descriptor,
115 is associated with a terminal device.
117 @retval 1 fildes is associated with a terminal.
118 @retval 0 fildes is not associated with a terminal. errno is set to
119 EBADF if fildes is not a valid open FD.
125 EFI_FILE_HANDLE FileHandle
;
127 if(ValidateFD( fildes
, VALID_OPEN
)) {
128 FileHandle
= gMD
->fdarray
[fildes
].FileHandle
;
129 retval
= (FileHandle
>= &gMD
->StdIo
[0].Abstraction
) &&
130 (FileHandle
<= &gMD
->StdIo
[2].Abstraction
);
141 EFI_FILE_HANDLE FileHandle
;
145 if(ValidateFD( fd
, VALID_OPEN
)) {
146 FileHandle
= gMD
->fdarray
[fd
].FileHandle
;
147 for(i
=0; i
< OPEN_MAX
; ++i
) {
148 if(i
== fd
) continue;
149 if(gMD
->fdarray
[i
].State
!= 0) { // TRUE if fd is OPEN
150 if(gMD
->fdarray
[i
].FileHandle
== FileHandle
) {
161 _closeX (int fd
, int NewState
)
163 struct __filedes
*Mfd
;
164 RETURN_STATUS Status
;
167 Status
= EFIerrno
= RETURN_SUCCESS
; // In case of error before the EFI call.
169 // Verify my pointers and get my FD.
170 if(ValidateFD( fd
, VALID_OPEN
)) {
171 Mfd
= &gMD
->fdarray
[fd
];
172 // Check if there are duplicates using this FileHandle
174 // Only do the close if no one else is using the FileHandle
176 Status
= Mfd
->FileHandle
->Close( Mfd
->FileHandle
);
179 Status
= ShellCloseFile( (SHELL_FILE_HANDLE
*)&Mfd
->FileHandle
);
182 Mfd
->State
= NewState
; // Close this FD or reserve it
183 if(Status
!= RETURN_SUCCESS
) {
184 errno
= EFI2errno(Status
);
197 /** The close() function shall deallocate the file descriptor indicated by fd.
198 To deallocate means to make the file descriptor available for return by
199 subsequent calls to open() or other functions that allocate file
200 descriptors. All outstanding record locks owned by the process on the file
201 associated with the file descriptor shall be removed (that is, unlocked).
203 @return Upon successful completion, 0 shall be returned; otherwise,
204 -1 shall be returned and errno set to indicate the error.
209 //Print(L"Closing fd %d\n", fd);
210 return _closeX(fd
, 0);
213 /* Wide character version of unlink */
215 Uunlink (const wchar_t *Path
)
217 EFI_FILE_HANDLE FileHandle
;
218 RETURN_STATUS Status
;
220 EFIerrno
= RETURN_SUCCESS
;
222 NormalizePath( Path
);
223 // We can only delete open files.
224 Status
= ShellOpenFileByName( Path
, (SHELL_FILE_HANDLE
*)&FileHandle
, 3, 0);
225 if(Status
!= RETURN_SUCCESS
) {
226 errno
= EFI2errno(Status
);
230 Status
= ShellDeleteFile( (SHELL_FILE_HANDLE
*)&FileHandle
);
231 if(Status
!= RETURN_SUCCESS
) {
232 errno
= EFI2errno(Status
);
242 unlink (const char *path
)
244 // Convert path from MBCS to WCS
245 (void)AsciiStrToUnicodeStr( path
, gMD
->UString
);
247 return Uunlink(gMD
->UString
);
250 /** The fcntl() function shall perform the operations described below on open
251 files. The fildes argument is a file descriptor.
253 The available values for cmd are defined in <fcntl.h> and are as follows:
254 - F_DUPFD - Return a new file descriptor which shall be the lowest
255 numbered available (that is, not already open) file
256 descriptor greater than or equal to the third argument, arg,
257 taken as an integer of type int. The new file descriptor
258 shall refer to the same open file description as the original
259 file descriptor, and shall share any locks. The FD_CLOEXEC
260 flag associated with the new file descriptor shall be cleared
261 to keep the file open across calls to one of the exec functions.
262 - F_GETFD - Get the file descriptor flags defined in <fcntl.h> that are
263 associated with the file descriptor fildes. File descriptor
264 flags are associated with a single file descriptor and do not
265 affect other file descriptors that refer to the same file.
266 - F_SETFD - Set the file descriptor flags defined in <fcntl.h>, that are
267 associated with fildes, to the third argument, arg, taken
268 as type int. If the FD_CLOEXEC flag in the third argument
269 is 0, the file shall remain open across the exec
270 functions; otherwise, the file shall be closed upon
271 successful execution of one of the exec functions.
272 - F_GETFL - Get the file status flags and file access modes, defined in
273 <fcntl.h>, for the file description associated with fildes.
274 The file access modes can be extracted from the return
275 value using the mask O_ACCMODE, which is defined in
276 <fcntl.h>. File status flags and file access modes are
277 associated with the file description and do not affect
278 other file descriptors that refer to the same file with
279 different open file descriptions.
280 - F_SETFL - Set the file status flags, defined in <fcntl.h>, for the file
281 description associated with fildes from the corresponding
282 bits in the third argument, arg, taken as type int. Bits
283 corresponding to the file access mode and the file creation
284 flags, as defined in <fcntl.h>, that are set in arg shall
285 be ignored. If any bits in arg other than those mentioned
286 here are changed by the application, the result is unspecified.
287 - F_GETOWN - If fildes refers to a socket, get the process or process group
288 ID specified to receive SIGURG signals when out-of-band
289 data is available. Positive values indicate a process ID;
290 negative values, other than -1, indicate a process group
291 ID. If fildes does not refer to a socket, the results are
293 - F_SETOWN - If fildes refers to a socket, set the process or process
294 group ID specified to receive SIGURG signals when
295 out-of-band data is available, using the value of the third
296 argument, arg, taken as type int. Positive values indicate
297 a process ID; negative values, other than -1, indicate a
298 process group ID. If fildes does not refer to a socket, the
299 results are unspecified.
301 The fcntl() function shall fail if:
303 [EBADF] The fildes argument is not a valid open file descriptor.
304 [EINVAL] The cmd argument is invalid, or the cmd argument is F_DUPFD
305 and arg is negative or greater than or equal to {OPEN_MAX}.
306 [EMFILE] The argument cmd is F_DUPFD and {OPEN_MAX} file descriptors
307 are currently open in the calling process, or no file
308 descriptors greater than or equal to arg are available.
309 [EOVERFLOW] One of the values to be returned cannot be represented correctly.
311 @return Upon successful completion, the value returned shall depend on
313 - F_DUPFD - A new file descriptor.
314 - F_GETFD - Value of flags defined in <fcntl.h>. The return value
315 shall not be negative.
316 - F_SETFD - Value other than -1.
317 - F_GETFL - Value of file status flags and access modes. The return
318 value is not negative.
319 - F_SETFL - Value other than -1.
320 - F_GETOWN - Value of the socket owner process or process group;
322 - F_SETOWN - Value other than -1.
323 Otherwise, -1 shall be returned and errno set to indicate the error.
327 fcntl (int fildes
, int cmd
, ...)
330 struct __filedes
*MyFd
;
334 //Print(L"%a( %d, %d, ...)\n", __func__, fildes, cmd);
337 if(ValidateFD( fildes
, VALID_OPEN
)) {
338 MyFd
= &gMD
->fdarray
[fildes
];
342 temp
= va_arg(p3
, int);
343 if(ValidateFD( temp
, VALID_DONT_CARE
)) {
344 temp
= FindFreeFD( temp
);
349 /* temp is now a valid fd reserved for further use
350 so copy fd into temp.
352 (void)memcpy(&gMD
->fdarray
[temp
], MyFd
, sizeof(struct __filedes
));
361 retval
= MyFd
->Oflags
; // Get original value
362 temp
= va_arg(p3
, int);
363 temp
&= O_SETMASK
; // Only certain bits can be set
364 temp
|= retval
& O_SETMASK
;
365 MyFd
->Oflags
= temp
; // Set new value
369 retval
= MyFd
->State
;
372 retval
= MyFd
->SocProc
;
373 MyFd
->SocProc
= va_arg(p3
, int);
376 //retval = MyFd->Oflags;
377 retval
= MyFd
->State
;
380 //retval = MyFd->State;
381 retval
= MyFd
->Oflags
;
384 retval
= MyFd
->SocProc
;
399 /** The dup() function provides an alternative interface to the
400 service provided by fcntl() using the F_DUPFD command. The call:
402 shall be equivalent to:
403 - fid = fcntl(fildes, F_DUPFD, 0);
405 @return Upon successful completion a non-negative integer, namely the
406 file descriptor, shall be returned; otherwise, -1 shall be
407 returned and errno set to indicate the error.
412 return fcntl(fildes
, F_DUPFD
, 0);
415 /** The dup2() function provides an alternative interface to the
416 service provided by fcntl() using the F_DUPFD command. The call:
417 - fid = dup2(fildes, fildes2);
418 shall be equivalent to:
420 - fid = fcntl(fildes, F_DUPFD, fildes2);
421 except for the following:
422 - If fildes2 is less than 0 or greater than or equal to {OPEN_MAX},
423 dup2() shall return -1 with errno set to [EBADF].
424 - If fildes is a valid file descriptor and is equal to fildes2, dup2()
425 shall return fildes2 without closing it.
426 - If fildes is not a valid file descriptor, dup2() shall return -1 and
427 shall not close fildes2.
428 - The value returned shall be equal to the value of fildes2 upon
429 successful completion, or -1 upon failure.
431 @return Upon successful completion a non-negative integer, namely
432 fildes2, shall be returned; otherwise, -1 shall be
433 returned and errno set to EBADF indicate the error.
436 dup2 (int fildes
, int fildes2
)
440 if(ValidateFD( fildes
, VALID_OPEN
)) {
442 if( fildes
!= fildes2
) {
443 if(ValidateFD( fildes2
, VALID_DONT_CARE
)) {
444 gMD
->fdarray
[fildes2
].State
= S_ISYSTEM
; // Mark the file closed, but reserved
445 (void)memcpy(&gMD
->fdarray
[fildes2
], // Duplicate fildes into fildes2
446 &gMD
->fdarray
[fildes
], sizeof(struct __filedes
));
460 /** Reposition a file's read/write offset.
462 The lseek() function repositions the offset of the file descriptor fildes
463 to the argument offset according to the directive how. The argument
464 fildes must be an open file descriptor. lseek() repositions the file
465 pointer fildes as follows:
467 If how is SEEK_SET, the offset is set to offset bytes.
469 If how is SEEK_CUR, the offset is set to its current location
472 If how is SEEK_END, the offset is set to the size of the file
475 The lseek() function allows the file offset to be set beyond the end of
476 the existing end-of-file of the file. If data is later written at this
477 point, subsequent reads of the data in the gap return bytes of zeros
478 (until data is actually written into the gap).
480 Some devices are incapable of seeking. The value of the pointer associ-
481 ated with such a device is undefined.
483 @return Upon successful completion, lseek() returns the resulting offset
484 location as measured in bytes from the beginning of the file.
485 Otherwise, a value of -1 is returned and errno is set to
489 lseek (int fildes
, __off_t offset
, int how
)
492 RETURN_STATUS Status
= RETURN_SUCCESS
;
493 EFI_FILE_HANDLE FileHandle
;
495 EFIerrno
= RETURN_SUCCESS
; // In case of error without an EFI call
497 if( how
== SEEK_SET
|| how
== SEEK_CUR
|| how
== SEEK_END
) {
498 if(ValidateFD( fildes
, VALID_OPEN
)) {
499 // Both of our parameters have been verified as valid
500 FileHandle
= gMD
->fdarray
[fildes
].FileHandle
;
503 Status
= FileHandle
->SetPosition( FileHandle
, offset
);
507 if(how
!= SEEK_SET
) {
508 // We are doing a relative seek
509 if(how
== SEEK_END
) {
510 // seeking relative to EOF, so position there first.
511 Status
= ShellSetFilePosition( (SHELL_FILE_HANDLE
)FileHandle
, 0xFFFFFFFFFFFFFFFFULL
);
513 if(Status
== RETURN_SUCCESS
) {
514 // Now, determine our current position.
515 Status
= ShellGetFilePosition( (SHELL_FILE_HANDLE
)FileHandle
, (UINT64
*)&CurPos
);
518 if(Status
== RETURN_SUCCESS
) {
519 /* CurPos now indicates the point we are seeking from, so seek... */
520 Status
= ShellSetFilePosition( (SHELL_FILE_HANDLE
)FileHandle
, (UINT64
)(CurPos
+ offset
));
521 if(Status
== RETURN_SUCCESS
) {
522 // Now, determine our final position.
523 Status
= ShellGetFilePosition( (SHELL_FILE_HANDLE
)FileHandle
, (UINT64
*)&CurPos
);
526 if(Status
!= RETURN_SUCCESS
) {
529 if(Status
== EFI_UNSUPPORTED
) {
533 errno
= EFI2errno(Status
);
539 errno
= EBADF
; // Bad File Descriptor
543 errno
= EINVAL
; // Invalid how argument
548 /** The directory path is created with the access permissions specified by
551 The directory is closed after it is created.
553 @retval 0 The directory was created successfully.
554 @retval -1 An error occurred and an error code is stored in errno.
557 mkdir (const char *path
, __mode_t perms
)
559 EFI_FILE_HANDLE FileHandle
;
560 RETURN_STATUS Status
;
561 EFI_FILE_INFO
*FileInfo
;
563 // Convert name from MBCS to WCS
564 (void)AsciiStrToUnicodeStr( path
, gMD
->UString
);
565 NormalizePath( gMD
->UString
);
567 //Print(L"%a( \"%s\", 0x%8X)\n", __func__, gMD->UString, perms);
568 Status
= ShellCreateDirectory( gMD
->UString
, (SHELL_FILE_HANDLE
*)&FileHandle
);
569 if(Status
== RETURN_SUCCESS
) {
570 FileInfo
= ShellGetFileInfo( FileHandle
);
571 if(FileInfo
!= NULL
) {
572 FileInfo
->Attribute
= Omode2EFI(perms
);
573 Status
= ShellSetFileInfo( FileHandle
, FileInfo
);
575 if(Status
== RETURN_SUCCESS
) {
576 (void)ShellCloseFile((SHELL_FILE_HANDLE
*)&FileHandle
);
581 errno
= EFI2errno(Status
);
589 The EFI ShellOpenFileByName() function is used to perform the low-level
590 file open operation. The primary task of open() is to translate from the
591 flags used in the <stdio.h> environment to those used by the EFI function.
593 The only valid flag combinations for ShellOpenFileByName() are:
598 The mode value is saved in the FD to indicate permissions for further operations.
600 O_RDONLY -- flags = EFI_FILE_MODE_READ -- this is always done
601 O_WRONLY -- flags |= EFI_FILE_MODE_WRITE
602 O_RDWR -- flags |= EFI_FILE_MODE_WRITE -- READ is already set
604 O_NONBLOCK -- ignored
605 O_APPEND -- Seek to EOF before every write
606 O_CREAT -- flags |= EFI_FILE_MODE_CREATE
607 O_TRUNC -- delete first then create new
608 O_EXCL -- if O_CREAT is also set, open will fail if the file already exists.
611 open (const char *name
, int oflags
, int mode
)
613 EFI_FILE_HANDLE FileHandle
;
614 struct __filedes
*Mfd
;
615 RETURN_STATUS Status
;
621 EFIerrno
= RETURN_SUCCESS
;
624 // Convert name from MBCS to WCS
625 (void)AsciiStrToUnicodeStr( name
, gMD
->UString
);
626 NormalizePath( gMD
->UString
);
628 // Convert oflags to Attributes
629 OpenMode
= Oflags2EFI(oflags
);
635 //Attributes = Omode2EFI(mode);
638 // Could add a test to see if the file name begins with a period.
639 // If it does, then add the HIDDEN flag to Attributes.
641 // Get an available fd
642 fd
= FindFreeFD( 0 );
645 // All available FDs are in use
650 Status
= ConOpen( NULL
, &FileHandle
, gMD
->UString
, OpenMode
, Attributes
);
651 if(Status
== RETURN_NO_MAPPING
) {
652 // Not a console device, how about a regular file device?
654 /* Do we care if the file already exists?
655 If O_TRUNC, then delete the file. It will be created anew subsequently.
656 If O_EXCL, then error if the file exists and O_CREAT is set.
658 !!!!!!!!! Change this to use ShellSetFileInfo() to actually truncate the file
659 !!!!!!!!! instead of deleting and re-creating it.
661 if((oflags
& O_TRUNC
) || ((oflags
& (O_EXCL
| O_CREAT
)) == (O_EXCL
| O_CREAT
))) {
662 Status
= ShellIsFile( gMD
->UString
);
663 if(Status
== RETURN_SUCCESS
) {
665 if(oflags
& O_TRUNC
) {
666 // We do a truncate by deleting the existing file and creating a new one.
667 if(Uunlink(gMD
->UString
) != 0) {
668 Mfd
[fd
].State
= 0; // Release our reservation on this FD
669 return -1; // errno and EFIerrno are already set.
672 else if(oflags
& (O_EXCL
| O_CREAT
)) {
675 Mfd
[fd
].State
= 0; // Release our reservation on this FD
680 // Call the EFI Shell's Open function
681 Status
= ShellOpenFileByName( gMD
->UString
, (SHELL_FILE_HANDLE
*)&FileHandle
, OpenMode
, Attributes
);
682 if(RETURN_ERROR(Status
)) {
683 Mfd
[fd
].State
= 0; // Release our reservation on this FD
684 // Set errno based upon Status
685 errno
= EFI2errno(Status
);
689 // Successfully got a regular File
692 else if(Status
!= RETURN_SUCCESS
) {
693 // Set errno based upon Status
694 errno
= EFI2errno(Status
);
699 // Succesfully got a Console stream
700 NewState
= S_IFREG
| _S_ITTY
| _S_IFCHR
;
703 // Update the info in the fd
704 Mfd
[fd
].FileHandle
= FileHandle
;
705 Mfd
[fd
].Oflags
= oflags
;
706 Mfd
[fd
].Omode
= mode
;
708 // Re-use OpenMode in order to build our final State value
709 OpenMode
= ( mode
& S_ACC_READ
) ? S_ACC_READ
: 0;
710 OpenMode
|= ( mode
& S_ACC_WRITE
) ? S_ACC_WRITE
: 0;
712 Mfd
[fd
].State
= NewState
| (UINT32
)OpenMode
;
714 // return the fd of our now open file
718 /** The rename() function changes the name of a file.
719 The old argument points to the pathname of the file to be renamed. The new
720 argument points to the new pathname of the file.
722 If the old argument points to the pathname of a file that is not a
723 directory, the new argument shall not point to the pathname of a
724 directory. If the file named by the new argument exists, it shall be
725 removed and old renamed to new. Write access permission is required for
726 both the directory containing old and the directory containing new.
728 If the old argument points to the pathname of a directory, the new
729 argument shall not point to the pathname of a file that is not a
730 directory. If the directory named by the new argument exists, it shall be
731 removed and old renamed to new.
733 The new pathname shall not contain a path prefix that names old. Write
734 access permission is required for the directory containing old and the
735 directory containing new. If the old argument points to the pathname of a
736 directory, write access permission may be required for the directory named
737 by old, and, if it exists, the directory named by new.
739 If the rename() function fails for any reason other than [EIO], any file
740 named by new shall be unaffected.
742 @return Upon successful completion, rename() shall return 0; otherwise,
743 -1 shall be returned, errno shall be set to indicate the error,
744 and neither the file named by old nor the file named by new
745 shall be changed or created.
748 rename (const char *old
, const char *new)
751 // RETURN_STATUS Status;
752 // EFI_FILE_INFO *NewFileInfo = NULL;
753 // EFI_FILE_INFO *OldFileInfo;
758 // OldFd = open(old, O_RDONLY, 0);
760 // NewFileInfo = malloc(sizeof(EFI_FILE_INFO) + PATH_MAX);
761 // if(NewFileInfo != NULL) {
762 // OldFileInfo = ShellGetFileInfo( FileHandle);
763 // if(OldFileInfo != NULL) {
764 // // Copy the Old file info into our new buffer, and free the old.
765 // memcpy(OldFileInfo, NewFileInfo, sizeof(EFI_FILE_INFO));
766 // FreePool(OldFileInfo);
767 // // Strip off all but the file name portion of new
768 // NewFn = strrchr(new, '/');
769 // if(NewFn == NULL) {
770 // NewFn = strrchr(new '\\');
771 // if(NewFn == NULL) {
775 // // Convert new name from MBCS to WCS
776 // (void)AsciiStrToUnicodeStr( NewFn, gMD->UString);
777 // // Copy the new file name into our new file info buffer
778 // wcsncpy(NewFileInfo->FileName, gMD->UString, wcslen(gMD->UString)+1);
779 // // Apply the new file name
780 // Status = ShellSetFileInfo(FileHandle);
781 // if(Status == EFI_SUCCESS) {
782 // // File has been successfully renamed. We are DONE!
785 // errno = EFI2errno( Status );
786 // EFIerrno = Status;
802 rmdir (const char *path
)
804 EFI_FILE_HANDLE FileHandle
;
805 RETURN_STATUS Status
;
806 EFI_FILE_INFO
*FileInfo
= NULL
;
808 BOOLEAN NoFile
= FALSE
;
810 errno
= 0; // Make it easier to see if we have an error later
812 // Convert name from MBCS to WCS
813 (void)AsciiStrToUnicodeStr( path
, gMD
->UString
);
814 NormalizePath( gMD
->UString
);
816 //Print(L"%a( \"%s\")\n", __func__, gMD->UString);
817 Status
= ShellOpenFileByName( gMD
->UString
, (SHELL_FILE_HANDLE
*)&FileHandle
,
818 (EFI_FILE_MODE_READ
|| EFI_FILE_MODE_WRITE
), 0);
819 if(Status
== RETURN_SUCCESS
) {
820 FileInfo
= ShellGetFileInfo( (SHELL_FILE_HANDLE
)FileHandle
);
821 if(FileInfo
!= NULL
) {
822 if((FileInfo
->Attribute
& EFI_FILE_DIRECTORY
) == 0) {
826 // See if the directory has any entries other than ".." and ".".
827 FreePool(FileInfo
); // Free up the buffer from ShellGetFileInfo()
828 Status
= ShellFindFirstFile( (SHELL_FILE_HANDLE
)FileHandle
, &FileInfo
);
829 if(Status
== RETURN_SUCCESS
) {
832 Status
= ShellFindNextFile( (SHELL_FILE_HANDLE
)FileHandle
, FileInfo
, &NoFile
);
833 if(Status
== RETURN_SUCCESS
) {
843 FreePool(FileInfo
); // Free buffer from ShellFindFirstFile()
845 // Directory is empty
846 Status
= ShellDeleteFile( (SHELL_FILE_HANDLE
*)&FileHandle
);
847 if(Status
== RETURN_SUCCESS
) {
848 EFIerrno
= RETURN_SUCCESS
;
850 /* ######## SUCCESSFUL RETURN ######## */
870 errno
= EFI2errno( Status
);
875 /* Internal File Info. worker function for stat and fstat. */
878 _EFI_FileInfo( EFI_FILE_INFO
*FileInfo
, struct stat
*statbuf
)
881 RETURN_STATUS Status
;
884 if(FileInfo
!= NULL
) {
885 // Got the info, now populate statbuf with it
886 statbuf
->st_blksize
= S_BLKSIZE
;
887 statbuf
->st_size
= FileInfo
->Size
;
888 statbuf
->st_physsize
= FileInfo
->PhysicalSize
;
889 statbuf
->st_birthtime
= Efi2Time( &FileInfo
->CreateTime
);
890 statbuf
->st_atime
= Efi2Time( &FileInfo
->LastAccessTime
);
891 statbuf
->st_mtime
= Efi2Time( &FileInfo
->ModificationTime
);
892 Attributes
= FileInfo
->Attribute
;
893 newmode
= (mode_t
)(Attributes
<< S_EFISHIFT
) | S_ACC_READ
;
894 if((Attributes
& EFI_FILE_DIRECTORY
) == 0) {
896 if((Attributes
& EFI_FILE_READ_ONLY
) == 0) {
897 statbuf
->st_mode
|= S_ACC_WRITE
;
903 statbuf
->st_mode
= newmode
;
904 Status
= RETURN_SUCCESS
;
907 Status
= RETURN_DEVICE_ERROR
;
912 /** The fstat() function obtains information about an open file associated
913 with the file descriptor fildes, and shall write it to the area pointed to
916 The buf argument is a pointer to a stat structure, as defined
917 in <sys/stat.h>, into which information is placed concerning the file.
919 The structure members st_mode, st_ino, st_dev, st_uid, st_gid, st_atime,
920 st_ctime, and st_mtime shall have meaningful values. The value of the
921 member st_nlink shall be set to the number of links to the file.
923 The fstat() function shall update any time-related fields before writing
924 into the stat structure.
926 The fstat() function is implemented using the ShellGetFileInfo()
929 The stat structure members which don't have direct analogs to EFI file
930 information are filled in as follows:
931 - st_mode Populated with information from fildes
932 - st_ino Set to zero. (inode)
933 - st_dev Set to zero.
934 - st_uid Set to zero.
935 - st_gid Set to zero.
936 - st_nlink Set to one.
938 @param[in] fildes File descriptor as returned from open().
939 @param[out] statbuf Buffer in which the file status is put.
941 @retval 0 Successful Completion.
942 @retval -1 An error has occurred and errno has been set to
946 fstat (int fildes
, struct stat
*statbuf
)
948 EFI_FILE_HANDLE FileHandle
;
949 RETURN_STATUS Status
= RETURN_SUCCESS
;
950 EFI_FILE_INFO
*FileInfo
= NULL
;
951 UINTN FinfoSize
= sizeof(EFI_FILE_INFO
);
953 if(ValidateFD( fildes
, VALID_OPEN
)) {
954 FileHandle
= gMD
->fdarray
[fildes
].FileHandle
;
956 FileInfo
= AllocateZeroPool(FinfoSize
);
957 if(FileInfo
!= NULL
) {
958 Status
= FileHandle
->GetInfo( FileHandle
, 0, &FinfoSize
, FileInfo
);
961 Status
= RETURN_OUT_OF_RESOURCES
;
965 FileInfo
= ShellGetFileInfo( FileHandle
);
967 Status
= _EFI_FileInfo( FileInfo
, statbuf
);
969 errno
= EFI2errno(Status
);
972 if(FileInfo
!= NULL
) {
973 FreePool(FileInfo
); // Release the buffer allocated by the GetInfo function
976 return errno
? -1 : 0;
979 /** Obtains information about the file pointed to by path.
981 Opens the file pointed to by path, calls _EFI_FileInfo with the file's handle,
982 then closes the file.
984 @retval 0 Successful Completion.
985 @retval -1 An error has occurred and errno has been set to
989 stat (const char *path
, void *statbuf
)
991 EFI_FILE_HANDLE FileHandle
;
992 RETURN_STATUS Status
;
993 EFI_FILE_INFO
*FileInfo
;
995 errno
= 0; // Make it easier to see if we have an error later
997 // Convert name from MBCS to WCS
998 (void)AsciiStrToUnicodeStr( path
, gMD
->UString
);
999 NormalizePath( gMD
->UString
);
1001 Status
= ShellOpenFileByName( gMD
->UString
, (SHELL_FILE_HANDLE
*)&FileHandle
, EFI_FILE_MODE_READ
, 0ULL);
1002 if(Status
== RETURN_SUCCESS
) {
1003 FileInfo
= ShellGetFileInfo( FileHandle
);
1004 Status
= _EFI_FileInfo( FileInfo
, (struct stat
*)statbuf
);
1005 (void)ShellCloseFile( (SHELL_FILE_HANDLE
*)&FileHandle
);
1007 errno
= EFI2errno(Status
);
1010 return errno
? -1 : 0;
1013 /** Same as stat since EFI doesn't have symbolic links. **/
1015 lstat (const char *path
, struct stat
*statbuf
)
1017 return stat(path
, statbuf
);
1020 /** Read from a file.
1022 The read() function shall attempt to read nbyte bytes from the file
1023 associated with the open file descriptor, fildes, into the buffer pointed
1026 Before any action described below is taken, and if nbyte is zero, the
1027 read() function may detect and return errors as described below. In the
1028 absence of errors, or if error detection is not performed, the read()
1029 function shall return zero and have no other results.
1031 On files that support seeking (for example, a regular file), the read()
1032 shall start at a position in the file given by the file offset associated
1033 with fildes. The file offset shall be incremented by the number of bytes
1036 Files that do not support seeking - for example, terminals - always read
1037 from the current position. The value of a file offset associated with
1038 such a file is undefined.
1040 No data transfer shall occur past the current end-of-file. If the
1041 starting position is at or after the end-of-file, 0 shall be returned.
1043 The read() function reads data previously written to a file. If any
1044 portion of a regular file prior to the end-of-file has not been written,
1045 read() shall return bytes with value 0. For example, lseek() allows the
1046 file offset to be set beyond the end of existing data in the file. If data
1047 is later written at this point, subsequent reads in the gap between the
1048 previous end of data and the newly written data shall return bytes with
1049 value 0 until data is written into the gap.
1051 Upon successful completion, where nbyte is greater than 0, read() shall
1052 mark for update the st_atime field of the file, and shall return the
1053 number of bytes read. This number shall never be greater than nbyte. The
1054 value returned may be less than nbyte if the number of bytes left in the
1055 file is less than nbyte, if the read() request was interrupted by a
1056 signal, or if the file is a pipe or FIFO or special file and has fewer
1057 than nbyte bytes immediately available for reading. For example, a read()
1058 from a file associated with a terminal may return one typed line of data.
1060 If fildes does not refer to a directory, the function reads the requested
1061 number of bytes from the file at the file\92s current position and returns
1062 them in buf. If the read goes beyond the end of the file, the read
1063 length is truncated to the end of the file. The file\92s current position is
1064 increased by the number of bytes returned.
1066 If fildes refers to a directory, the function reads the directory entry at
1067 the file\92s current position and returns the entry in buf. If buf
1068 is not large enough to hold the current directory entry, then
1069 errno is set to EBUFSIZE, EFIerrno is set to EFI_BUFFER_TOO_SMALL, and the
1070 current file position is not updated. The size of the buffer needed to read
1071 the entry will be returned as a negative number. On success, the current
1072 position is updated to the next directory entry. If there are no more
1073 directory entries, the read returns a zero-length buffer.
1074 EFI_FILE_INFO is the structure returned as the directory entry.
1076 @return Upon successful completion, read() returns a non-negative integer
1077 indicating the number of bytes actually read. Otherwise, the
1078 functions return a negative value and sets errno to indicate the
1079 error. If errno is EBUFSIZE, the absolute value of the
1080 return value indicates the size of the buffer needed to read
1081 the directory entry.
1084 read (int fildes
, void *buf
, size_t nbyte
)
1087 EFI_FILE_HANDLE FileHandle
;
1088 RETURN_STATUS Status
;
1090 BufSize
= (ssize_t
)nbyte
;
1091 if(ValidateFD( fildes
, VALID_OPEN
)) {
1092 FileHandle
= gMD
->fdarray
[fildes
].FileHandle
;
1093 if(isatty(fildes
)) {
1094 Status
= FileHandle
->Read( FileHandle
, (UINTN
*)&BufSize
, buf
);
1097 Status
= ShellReadFile( FileHandle
, (UINTN
*)&BufSize
, buf
);
1099 if(Status
!= RETURN_SUCCESS
) {
1101 errno
= EFI2errno(Status
);
1102 if(Status
== RETURN_BUFFER_TOO_SMALL
) {
1117 WideTtyCvt( CHAR16
*dest
, const char *buf
, size_t n
)
1122 for(i
= 0; i
< n
; ++i
) {
1128 wc
= BLOCKELEMENT_LIGHT_SHADE
;
1133 *dest
++ = (CHAR16
)wc
;
1139 /** Write data to a file.
1141 This function writes the specified number of bytes to the file at the current
1142 file position. The current file position is advanced the actual number of bytes
1143 written, which is returned in BufferSize. Partial writes only occur when there
1144 has been a data error during the write attempt (such as "volume space full").
1145 The file is automatically grown to hold the data if required. Direct writes to
1146 opened directories are not supported.
1148 If fildes refers to a terminal device, isatty() returns TRUE, a partial write
1149 will occur if a NULL or EOF character is encountered before n characters have
1150 been written. Characters inserted due to line-end translations will not be
1151 counted. Unconvertable characters are translated into the UEFI character
1152 BLOCKELEMENT_LIGHT_SHADE.
1154 Since the UEFI console device works on wide characters, the buffer is assumed
1155 to contain a single-byte character stream which is then translated to wide
1156 characters using the btowc() functions. The resulting wide character stream
1157 is what is actually sent to the UEFI console.
1159 QUESTION: Should writes to stdout or stderr always succeed?
1162 write (int fildes
, const void *buf
, size_t n
)
1165 EFI_FILE_HANDLE FileHandle
;
1166 RETURN_STATUS Status
= RETURN_SUCCESS
;
1169 BufSize
= (ssize_t
)n
;
1171 if(ValidateFD( fildes
, VALID_OPEN
)) {
1172 FileHandle
= gMD
->fdarray
[fildes
].FileHandle
;
1173 if(isatty(fildes
)) {
1174 // Convert string from MBCS to WCS and translate \n to \r\n.
1175 UniBufSz
= WideTtyCvt(gMD
->UString
, (const char *)buf
, n
);
1177 BufSize
= (ssize_t
)(UniBufSz
* sizeof(CHAR16
));
1178 Status
= FileHandle
->Write( FileHandle
, (UINTN
*)&BufSize
, (void *)gMD
->UString
);
1179 BufSize
= (ssize_t
)n
; // Always pretend all was output
1183 Status
= ShellWriteFile( FileHandle
, (UINTN
*)&BufSize
, (void *)buf
);
1185 if(Status
!= RETURN_SUCCESS
) {
1187 errno
= EFI2errno(Status
);
1188 if(Status
== EFI_UNSUPPORTED
) {