Zeroing an Unusual Array

120 views Asked by At

I have a bit of C code, reproduced below. It is my understanding that it is setting certain bits of the BootPML4 array to a certain value. Could someone please explain how the BootPML4 array below is filled? Also, how do I ensure that unused values in the array are zeroed, while ensuring that the two settings below remain intact?

typedef uint64_t pml4_entry_t;
#define PML4_PROT (INTEL_PTE_VALID | INTEL_PTE_WRITE)
pml4_entry_t BootPML4[PTE_PER_PAGE] __attribute__((section("__HIB, __bootPT"))) = {
    [0]                 = ((uint64_t)(PAGE_SIZE) | PML4_PROT),
    [KERNEL_PML4_INDEX] = ((uint64_t)(PAGE_SIZE) | PML4_PROT),
};
1

There are 1 answers

5
Shafik Yaghmour On BEST ANSWER

This is using designated initializers which was added in C99, The Forward section of the C99 draft standard in paragraph 5 says:

[...] Major changes from the previous edition include:

and has the following bullet:

— designated initializers

and the details are covered in section 6.7.8 Initialization and provides the following example in paragraph 36 and 37:

EXAMPLE 12 Space can be ‘‘allocated’’ from both ends of an array by using a single designator:

int a[MAX] = {
  1, 3, 5, 7, 9, [MAX-5] = 8, 6, 4, 2, 0
};

In the above, if MAX is greater than ten, there will be some zero-valued elements in the middle; if it is less than ten, some of the values provided by the first five initializers will be overridden by the second five.

The gcc doc on designated initializers has a better example:

To specify an array index, write ‘[index] =’ before the element value. For example,

int a[6] = { [4] = 29, [2] = 15 };

is equivalent to

int a[6] = { 0, 0, 15, 0, 29, 0 };

The index values must be constant expressions, even if the array being initialized is automatic.