3

I thought this would be an easy question, but I can't find the answer. I've mainly been reading these specs:

http://www.nongnu.org/ext2-doc/ext2.html

It doesn't seem to mention if a directory entry's name is supposed to be null-terminated. I'm thinking that it's undefined. There is a name_len field, so you can easily print the name anyway.

Are ext2 directory names guaranteed to be null-terminated?

I ask because in testing my ext2 driver on my hobby OS I noticed when I printed some directory names some garbage characters came out on the end. If I simply print name_len characters everything is fine, although it'd be nice if it was null-terminated.

Thanks!

Mr. Shickadance
  • 5,283
  • 9
  • 45
  • 61

1 Answers1

7

I know this is an old question, but for anyone else who might find this:

No, it is not guaranteed to be null terminated. In fact, it should only be null terminated if the length of the name (name_len) is not a multiple of 4.

From Understanding the Linux Kernel, 3rd edition:

... the length of a directory entry is always a multiple of 4 and, therefore, null characters (\0) are added for padding at the end of the filename, if necessary. The name_len field stores the actual filename length

With an example below (from the book). Notice that the name "sbin" has no null termination, because the length (4) is a multiple of 4:

enter image description here

xdumaine
  • 10,096
  • 6
  • 62
  • 103
  • Do you know why this is necessary for padding? – user129393192 May 19 '23 at 21:41
  • What I mean is why they must be initialized to null. I understand why it is a multiple of 4 (since the largest primitive data type in the struct is 4 bytes otherwise), but is initialization to null necessary if `name_len` covers this? – user129393192 May 19 '23 at 21:56