Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The critical handling of circular buffer overflow carries the risk of memory misalignment and access exceptions. #162

Open
zelzmz opened this issue Oct 30, 2024 · 1 comment

Comments

@zelzmz
Copy link

zelzmz commented Oct 30, 2024

Hi,
In buffer. c, the handling of overflow situations by the buffer_push_tail function is as follows:

if (tail_end < rb->tail) {

    if (rb->head < align_size) {

      LOGE("no enough space");
      return -1;
    }

    int *p = (int*)(rb->data + rb->tail);
    *p = size;
    memcpy(rb->data, data, size);    
    rb->tail = size;

  }

Size is the true length of the data and is not aligned.

@zelzmz
Copy link
Author

zelzmz commented Oct 30, 2024

My modification is like this:

int buffer_push_tail(Buffer* rb, const uint8_t* data, int size) {
  int free_space = (rb->size + rb->head - rb->tail - 1) % rb->size;

  int align_size = ALIGN32(size) + 4;

  if (align_size > free_space) {
    LOGE("no enough space");
    return -1;
  }

  int tail_end = (rb->tail + align_size) % rb->size;

  if (tail_end < rb->tail) {

    if (rb->head < align_size) {
      LOGE("no enough space");
      return -1;
    }

    int* p = (int*)(rb->data + rb->tail);
    *p = size;
    memcpy(rb->data, data, size);
    rb->tail = ALIGN32(size);

  } else {
    int* p = (int*)(rb->data + rb->tail);
    *p = size;
    memcpy(rb->data + rb->tail + 4, data, size);
    rb->tail = tail_end;
  }

  return size;
}

uint8_t* buffer_peak_head(Buffer* rb, int* size) {
  if (!rb || rb->head == rb->tail) {

    return NULL;
  }

  *size = *((int*)(rb->data + rb->head));

  int align_size = ALIGN32(*size) + 4;

  int head_end = (rb->head + align_size) % rb->size;

  if (head_end < rb->head) {
    return rb->data;

  } else {

    return rb->data + (rb->head + 4);
  }
}

void buffer_pop_head(Buffer* rb) {
  if (!rb || rb->head == rb->tail) {
    return;
  }

  int* size = (int*)(rb->data + rb->head);

  int align_size = ALIGN32(*size) + 4;

  int head_end = (rb->head + align_size) % rb->size;

  if (head_end < rb->head) {
    rb->head = ALIGN32(*size);

  } else {

    rb->head = rb->head + align_size;
  }
}

This modification is relatively simple but wastes space. Let's see if we need to further optimize it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant