<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/141494>141494</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            llvm-objcopy calculates section locations incorrectly for MachO files
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            new issue
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          peledins-zimperium
      </td>
    </tr>
</table>

<pre>
    https://github.com/llvm/llvm-project/pull/130517/files introduced a change

```
          if (RequiresFirstSectionOutsideFirstPage) {
            SectOffset = alignToPowerOf2(SectOffset, PageSize);
 RequiresFirstSectionOutsideFirstPage = false;
          }
```

This is an issue for several reasons:
1) If the first section is outside of first page (0x4000), but starts at (0x4004), then this gets aligned to (0x8000), which is not necessary. Here a fix could be 
```
if (RequiresFirstSectionOutsideFirstPage && SectOffset < PageSize) {
```
2) However, if the block is actually entered, then trouble happens with next sections: they do not get moved together with this section. Then we  can get to a state of `truncated or malformed object (section contents at offset 20160 with a size of 111316, overlaps section contents at offset 32768 with a size of 228)`


</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJyUVM2O4zgPfBr5Qkwg0785-JCZRjDf4UMPdvoFZJm2NatIXklOOv30C8npZLuxh1nDQBCJLLKqTArv1WSIOlZ9ZdVTJtYwW9ctpGlQxn95U6eFnFpPWW-HazeHsHhWHBgeGR4nFea130l7YnjU-vz-82Vx9hfJwPC4rFozPOYFr_KG4XFUmjwoE5wdVkkDCJCzMBMxfohvzW8vP8D9USMwbP-gv1blyB-V8-EnyaCseV6DVwOlox9iIoZ7YM3XD9kAMfh5HD0FYMUTCK0m82J_2Au55xEZto8Aht8gAv1UbxGMFQnrd0on6FFoT7ek-8Oap0_UGD-8zMqD8iAMKO9XgtE68HQmJzQ4Et6aJDQ_5JHU_0YIM8EYq4HfOojpdusC7Hi7W1Ir2PLXknMeKeA36NcAPggXPIhwvy1vt2EmAyH2M1GMiPLQAMFuke0D5zIrOceyxgYwJMl74a47-E6OQMCoXkHaVQ_QE3yi_PseAsOaYf3RtQ-u3Cz-JzzG4-_2EgWMnapNr15b-WeSWYZVaH0FMoEcDQ_ezq69JpjFspDxcFFhBkOvd5WjCzH0CoNNvCcKcLLnpNBEYSa3JSUFb0k7eIngFwKQwqSUYEFEE0Iyi9U8uNVIEWgA6-Ak9GjdKf7p4-hEsd5tltYEMpt3dhMEeV7zrawAr94SZp7nRV5HZvZMTovl3s6_QRTY1O1nCMQ2Wv3-kWZDVwz7Yi8y6vKmbLFuqrLN5g4rKng_ir7Fscr3_VA0shBjyZuR-L6pMtUhx4pXWOdFhdjucKzKep_32OZtQ0PPSk4nofQuLoyddVOWxqDLy7zcl5kWPWmfthKiocs2JAwxLinXpS3Tr5NnJdfKB_-ACSpo2gJs_0va5QpSaLlqEeghiLZSJHdBGWmdIxn0Nc3g_4WcnyHtqWx1-r-vvNSpj0tvo3Lu8O8AAAD__3grvkk">