[PATCH v2 15/18] mini-os: introduce get_file_from_fd()

Juergen Gross posted 18 patches 4 years ago
There is a newer version of this series
[PATCH v2 15/18] mini-os: introduce get_file_from_fd()
Posted by Juergen Gross 4 years ago
Exporting the files[] array especially for components outside the
mini-os source tree is limiting the ability to change any file handling
in mini-os.

Introduce a new function get_file_from_fd() to return the struct file
pointer (or NULL) for a given file descriptor.

Signed-off-by: Juergen Gross <jgross@suse.com>
Reviewed-by: Samuel Thibault <samuel.thibault@ens-lyon.org>
---
 include/lib.h | 1 +
 lib/sys.c     | 8 ++++++++
 2 files changed, 9 insertions(+)

diff --git a/include/lib.h b/include/lib.h
index 91364ba..7a0546b 100644
--- a/include/lib.h
+++ b/include/lib.h
@@ -198,6 +198,7 @@ struct file {
 
 extern struct file files[];
 
+struct file *get_file_from_fd(int fd);
 int alloc_fd(enum fd_type type);
 void close_all_files(void);
 extern struct thread *main_thread;
diff --git a/lib/sys.c b/lib/sys.c
index 6f2b026..0e6fe5d 100644
--- a/lib/sys.c
+++ b/lib/sys.c
@@ -98,6 +98,14 @@ struct file files[NOFILE] = {
     { .type = FTYPE_CONSOLE }, /* stderr */
 };
 
+struct file *get_file_from_fd(int fd)
+{
+    if ( fd < 0 || fd >= NOFILE )
+        return NULL;
+
+    return (files[fd].type == FTYPE_NONE) ? NULL : files + fd;
+}
+
 DECLARE_WAIT_QUEUE_HEAD(event_queue);
 
 int alloc_fd(enum fd_type type)
-- 
2.26.2


Re: [PATCH v2 15/18] mini-os: introduce get_file_from_fd()
Posted by Andrew Cooper 4 years ago
On 11/01/2022 14:58, Juergen Gross wrote:
> diff --git a/lib/sys.c b/lib/sys.c
> index 6f2b026..0e6fe5d 100644
> --- a/lib/sys.c
> +++ b/lib/sys.c
> @@ -98,6 +98,14 @@ struct file files[NOFILE] = {
>      { .type = FTYPE_CONSOLE }, /* stderr */
>  };
>  
> +struct file *get_file_from_fd(int fd)
> +{
> +    if ( fd < 0 || fd >= NOFILE )

fd >= ARRAY_SIZE(files)  ?

Generates slightly safer code in the event that `struct file
files[NOFILE]` gets refactored.

~Andrew

> +        return NULL;
> +
> +    return (files[fd].type == FTYPE_NONE) ? NULL : files + fd;
> +}
> +
>  DECLARE_WAIT_QUEUE_HEAD(event_queue);
>  
>  int alloc_fd(enum fd_type type)


Re: [PATCH v2 15/18] mini-os: introduce get_file_from_fd()
Posted by Juergen Gross 4 years ago
On 11.01.22 19:17, Andrew Cooper wrote:
> On 11/01/2022 14:58, Juergen Gross wrote:
>> diff --git a/lib/sys.c b/lib/sys.c
>> index 6f2b026..0e6fe5d 100644
>> --- a/lib/sys.c
>> +++ b/lib/sys.c
>> @@ -98,6 +98,14 @@ struct file files[NOFILE] = {
>>       { .type = FTYPE_CONSOLE }, /* stderr */
>>   };
>>   
>> +struct file *get_file_from_fd(int fd)
>> +{
>> +    if ( fd < 0 || fd >= NOFILE )
> 
> fd >= ARRAY_SIZE(files)  ?
> 
> Generates slightly safer code in the event that `struct file
> files[NOFILE]` gets refactored.

Fine with me.


Juergen