Skip to content

[Macros] Copy the evaluated source into an owned memory buffer. #62440

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

Merged
merged 1 commit into from
Dec 8, 2022

Conversation

DougGregor
Copy link
Member

Plugs a memory leak (rdar://103035316).

@DougGregor
Copy link
Member Author

@swift-ci please smoke test

Copy link
Member

@rintaro rintaro left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you! This is still a little scary, but it fixes the current issue, at least

unsigned macroBufferID = sourceMgr.addNewSourceBuffer(std::move(macroBuffer));
free((void*)evaluatedSource.data());
Copy link
Member

@rintaro rintaro Dec 7, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We know it works. But still a little scary.

It would be great if there's a way to pass C++ lambda to swift_ASTGen_evaluateMacro where

  • the lambda receives a temporary C string (i.e. handler callback)
    swift_ASTGen_evaluateMacro( ..., [&](unsigned char *utf8Start, size_t length) {
      // utf8Start is valid only while this lambda.
      macroBuffer = llvm::MemoryBuffer::getMemBufferCopy({utf8Start, length});
    });
  • or, the lambda receives a size and returns a buffer pointer of the size (i.e. factory)
    swift_ASTGen_evaluateMacro( ..., [&](size_t utf8Length) {
      macroBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(utf8Length + 1, bufferIdentifier);
      return macroBuffer->getBufferStart();
      // the caller initializes the buffer.
    });

So the size that allocates the memory has the responsibility to free it.

But I guess there's no way to pass C++ lambda to Swift, at this point?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can pass through a C function pointer and a context pointer, which would eliminate a copy and not have a malloc/free pair across languages.

@DougGregor DougGregor merged commit 0704918 into swiftlang:main Dec 8, 2022
@DougGregor DougGregor deleted the macros-plug-leak branch December 8, 2022 04:06
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

Successfully merging this pull request may close these issues.

2 participants