rxi / lite

A lightweight text editor written in Lua
MIT License
7.42k stars 353 forks source link

Bad Command alignment #291

Open Jan200101 opened 3 years ago

Jan200101 commented 3 years ago

https://github.com/rxi/lite/blob/38bd9b3326c02e43f244623f97a622b11f074415/src/rencache.c#L95-L102 This function moves prev size along which can and will cause unalignment and potential errors.

On ARM devices this causes a SIGBUS.

The people who helped me figure this out suggested this fix

static Command* push_command(int type, int size) {
+  size_t alignment = alignof(max_align_t) - 1;
+  size = (size + alignment) & ~alignment; // forward align to 4
  Command *cmd = (Command*) (command_buf + command_buf_idx);
  int n = command_buf_idx + size;
  if (n > COMMAND_BUF_SIZE) {
    fprintf(stderr, "Warning: (" __FILE__ "): exhausted command buffer\n");
    return NULL;
  }
  command_buf_idx = n;
  memset(cmd, 0, sizeof(Command));
  cmd->type = type;
  cmd->size = size;
  return cmd;
}

But alignof and max_align_t have been introduced with C11 so it might be of interest to replace the alignof with a static alignment of either 4 or 16 to be safe