Why is fwrite throwing me an Access Violation?

0

I'm recompiling and debugging Yara but for some reason, the Access Violation is thrown when Yara's yr_rules_save function tries to execute fwrite of the hdr struct into the file.

typedef struct _YR_STREAM
{
  void* user_data;

  YR_STREAM_READ_FUNC read;
  YR_STREAM_WRITE_FUNC write;

} YR_STREAM;

typedef size_t (*YR_STREAM_WRITE_FUNC)(
    const void* ptr,
    size_t size,
    size_t count,
    void* user_data);

YR_API int yr_rules_save(
    YR_RULES* rules,
    const char* filename)
{
  int result;

  YR_STREAM stream;
  FILE* fh = fopen(filename, "wb");

  if (fh == NULL)
    return ERROR_COULD_NOT_OPEN_FILE;

  stream.user_data = fh;
  stream.write = (YR_STREAM_WRITE_FUNC) fwrite; // As write method, uses fwrite

  result = yr_rules_save_stream(rules, &stream); // Here the error

  fclose(fh);
  return result;
}

In fact, if we go into yr_rules_save_stream in the function being shown, is the line the exception is thrown:

  [...]
  if (yr_stream_write(&hdr, sizeof(hdr), 1, stream) != 1)
    return ERROR_WRITING_FILE;
  [...]

What is the exception:

Exception thrown at 0x00007FFED05072A6 (ntdll.dll) in ubi-yarac64.exe: 0xC0000005: Access violation writing location 0x00007FF653018A46.

For details such as the line and the call stack check the screenshot.

The file is not locked (no software uses it), it does not exists (even if I put "w+b" on fopen) and the pointer to the buffer appears to exists if I check on HxD manually.

Does anybody have any idea of what is going on here?

The error shown from Visual Studio

c++
crash
filesystems
locking
fwrite
asked on Stack Overflow Aug 20, 2020 by d3vil401

1 Answer

-1

The reason is, because the fwrite function wrapped by YR_STREAM_WRITE_FUNC takes a pointer to a FILE type, while in the function yr_stream_write it passes a pointer to the YR_STREAM struct instead of YR_STREAM->user_data (the FILE handle previously saved by yr_rules_save)

the f. solution

answered on Stack Overflow Aug 20, 2020 by d3vil401

User contributions licensed under CC BY-SA 3.0