Skip to content

Adopt some new C features and modernize code #433

@septatrix

Description

@septatrix

I strongly believe that as a pedagogical OS it should be an important goal for xv6 to strive for easily understandable code.
However, xv6 still uses ANSI C style in many places which comes at the cost of legibility. One could argue that this is done for the sake of portability though compiling with gcc -ansi does not work. At least gcc -std=gnu99 is required.

More recent C standards (even going only up to C11) have introduced many niceties which can improve legibility and make it easier to write correct code.

  • First and foremost is initializing loop variables inside the for header instead of outside. This makes it clearer where it is used and scopes it.
  • Another one is generally the declaration of variables inside function and not only at the start of the block. Declaring vars at the start reduces legibility and makes it harder to follow where a variable is first used.

Another things that would make to code cleaner and safer would be adopting __attribute__((cleanup(foobar)). It is widely known that while gotos are great for jumping to error handling (freeing stuff etc) they can be difficult to use correctly, especially for inexperienced programmers.
The cleanup attribute allows registering a function for a variable that will be called when the function goes out of scope. This is great as it allows automatic cleanup when writing code like (if (failure) return -1;) and all variables will be cleaned up without requiring a plethora of goto errFoo; (which requires a separate label for each stage at which stuff can fail).
Together with a helper macro it also allows returning the variable without calling the cleanup variable such as return TAKE_PTR(buf);. These are also widely adopted in popular projects like Linux itself, and systemd.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions