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

netlink: potential to optimize AttributeEncoder's buffer length calculation #191

Open
ubiquitousbyte opened this issue Nov 8, 2021 · 4 comments

Comments

@ubiquitousbyte
Copy link

ubiquitousbyte commented Nov 8, 2021

This may seem rather overanalyzed, but I was reading through the code and found a potential pitfall in the String function of the AttributeEncoder type.
Isn't the following check necessary to prevent the length field of the attribute being appended from overflowing?

if len(s) > math.MaxUint16-nlaHeaderLen {
   ae.err = errors.New("Attribute length overflow")
   return 
}
 
@mdlayher
Copy link
Owner

mdlayher commented Nov 8, 2021

It seems you're correct! A length check should be added to each of Bytes, Do, and String. Want to send a PR?

@ubiquitousbyte
Copy link
Author

ubiquitousbyte commented Nov 8, 2021

Sure thing, mate. I'll send the PR tomorrow after work.

I'm also seeing a small performance optimization that we can integrate without affecting code readability.
The AttributeEncoder can keep track of the total (aligned) buffer length and gradually increment it whenever the caller issues an append operation (via Bytes, String, Int8..64 etc).

This will effectively make this for-loop redundant, because we've already computed the length. Thus, marshalling a slice of attributes via the encoder is now an O(n) operation, instead of O(n^2).

Note that this will require refactoring the Encode function, as well as the relevant bits from MarshalAttributes into a separate function.

What do you think?

@mdlayher
Copy link
Owner

mdlayher commented Nov 8, 2021

Internal improvements are always welcome, as long as they don't dramatically impact the readability of the code! I'd be happy to take a look at what you have in mind.

mdlayher added a commit that referenced this issue Dec 2, 2021
Updates #191

Signed-off-by: Matt Layher <mdlayher@gmail.com>
@mdlayher
Copy link
Owner

mdlayher commented Dec 2, 2021

I've committed a fix for the length overflow issue, but will retitle this for the performance improvement issue.

@mdlayher mdlayher changed the title Prevent uint16 overflow when adding attributes via AttributeEncoder netlink: potential to optimize AttributeEncoder's buffer length calculation Dec 2, 2021
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

2 participants