-
Notifications
You must be signed in to change notification settings - Fork 29
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
A prototype for solve dividing two integers #66
Open
r888800009
wants to merge
8
commits into
MatthieuDartiailh:main
Choose a base branch
from
r888800009:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 4 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
a97fc32
Add tastecase for integer
r888800009 6617969
Add more test case
r888800009 d02ee92
Add More division test cases
r888800009 f5f8bf8
Proof of concept for c division
r888800009 44daba6
Support for octal numbers and add tests
r888800009 a7f7624
Use int() instead of eval() for security
r888800009 8e7eed1
coding style fixed
r888800009 a946a50
make sure wrap_int() return CInt instance
r888800009 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -35,6 +35,91 @@ | |
__all__ = ['win_defs', 'CParser'] | ||
|
||
|
||
def wrap_int(t): | ||
logger.debug('wrap_int: {} {}'.format(t.dump(), type(t))) | ||
t[0] = "CInt({})".format(eval(t[0])) | ||
return t | ||
|
||
class CInt(int): | ||
def __new__(cls, base=10, *args, **kwargs): | ||
return super(CInt, cls).__new__(cls, base, *args, **kwargs) | ||
|
||
def __truediv__(self, other): | ||
if isinstance(other, CInt): | ||
is_positive = self >= 0 and other >= 0 | ||
return CInt(int(self) // int(other)) if is_positive else -CInt(-int(self) // int(other)) | ||
else: | ||
return super(CInt, self).__truediv__(other) | ||
|
||
def __rtruediv__(self, other): | ||
if isinstance(other, CInt): | ||
is_positive = self >= 0 and other >= 0 | ||
return CInt(int(other) // int(self)) if is_positive else -CInt(-int(other) // int(self)) | ||
else: | ||
return super(CInt, self).__rtruediv__(other) | ||
|
||
def __mod__(self, other): | ||
if isinstance(other, CInt): | ||
is_positive = self >= 0 and other >= 0 | ||
return CInt(int(self) % int(other)) if is_positive else -CInt(-int(self) % int(other)) | ||
else: | ||
return super(CInt, self).__mod__(other) | ||
|
||
def __rmod__(self, other): | ||
if isinstance(other, CInt): | ||
is_positive = self >= 0 and other >= 0 | ||
return CInt(int(other) % int(self)) if is_positive else -CInt(-int(other) % int(self)) | ||
else: | ||
return super(CInt, self).__rmod__(other) | ||
|
||
def __sub__(self, other): | ||
if isinstance(other, CInt): | ||
return CInt(int(self) - int(other)) | ||
else: | ||
return super(CInt, self).__sub__(other) | ||
|
||
def __rsub__(self, other): | ||
if isinstance(other, CInt): | ||
return CInt(int(other) - int(self)) | ||
else: | ||
return super(CInt, self).__rsub__(other) | ||
|
||
def __add__(self, other): | ||
if isinstance(other, CInt): | ||
return CInt(int(self) + int(other)) | ||
else: | ||
return super(CInt, self).__add__(other) | ||
|
||
def __radd__(self, other): | ||
if isinstance(other, CInt): | ||
return CInt(int(other) + int(self)) | ||
else: | ||
return super(CInt, self).__radd__(other) | ||
|
||
def __mul__(self, other): | ||
if isinstance(other, CInt): | ||
return CInt(int(self) * int(other)) | ||
else: | ||
return super(CInt, self).__mul__(other) | ||
|
||
def __rmul__(self, other): | ||
if isinstance(other, CInt): | ||
return CInt(int(other) * int(self)) | ||
else: | ||
return super(CInt, self).__rmul__(other) | ||
|
||
def __str__(self): | ||
return "CInt({})".format(super(CInt, self).__str__()) | ||
|
||
def __repr__(self): | ||
return "CInt({})".format(super(CInt, self).__repr__()) | ||
|
||
def __neg__(self): | ||
return CInt(-int(self)) | ||
|
||
def __pos__(self): | ||
return CInt(+int(self)) | ||
|
||
class Type(tuple): | ||
""" | ||
Representation of a C type. CParser uses this class to store the parsed | ||
|
@@ -1508,7 +1593,7 @@ def eval(self, expr, *args): | |
expr = expr.strip() | ||
cast = (lparen + self.type_spec + self.abstract_declarator + | ||
rparen).suppress() | ||
expr = (quotedString | number | cast).transformString(expr) | ||
expr = (quotedString | number_in_expr | cast).transformString(expr) | ||
if expr == '': | ||
return None | ||
return eval(expr, *args) | ||
|
@@ -1651,10 +1736,14 @@ def print_parse_results(pr, depth=0, name=''): | |
hexint = Regex(r'[+-]?\s*0[xX][{}]+[UL]*'.format(hexnums)).setParseAction(int_strip) | ||
decint = Regex(r'[+-]?\s*[0-9]+[UL]*').setParseAction(int_strip) | ||
integer = (hexint | decint) | ||
integer.setParseAction(wrap_int) | ||
# in eval expr would not match identifier, it would match a number cause error | ||
integer_in_expr = (hexint | decint) | ||
# The floating regex is ugly but it is because we do not want to match | ||
# integer to it. | ||
floating = Regex(r'[+-]?\s*((((\d(\.\d*)?)|(\.\d+))[eE][+-]?\d+)|((\d\.\d*)|(\.\d+)))') | ||
number = (floating | integer) | ||
number = (floating |integer) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. coding style: use spaces around binary operators |
||
number_in_expr = (floating |integer_in_expr) | ||
|
||
# Miscelaneous | ||
bi_operator = oneOf("+ - / * | & || && ! ~ ^ % == != > < >= <= -> . :: << >> = ? :") | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -566,6 +566,24 @@ def test_variables(self): | |||||
assert ('x2' in variables and | ||||||
variables['x2'] == (88342528, Type('int'))) | ||||||
|
||||||
# Test int div 9 / 2 should be 4 | ||||||
assert ('x3' in variables and | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
the indexing will anyway if the key does not exist in the dict. No need to test it separately. |
||||||
variables['x3'] == (4.5, Type('float'))) | ||||||
assert ('x4' in variables and | ||||||
variables['x4'] == (4, Type('int'))) | ||||||
assert ('x5' in variables and | ||||||
variables['x5'] == (4., Type('float'))) | ||||||
assert ('x6' in variables and | ||||||
variables['x6'] == (4., Type('float'))) | ||||||
assert ('x7' in variables and | ||||||
variables['x7'] == (4.5, Type('float'))) | ||||||
assert ('x8' in variables and | ||||||
variables['x8'] == (9., Type('float'))) | ||||||
assert ('x9' in variables and | ||||||
variables['x9'] == (-4, Type('int'))) | ||||||
assert ('x10' in variables and | ||||||
variables['x10'] == (-1, Type('int'))) | ||||||
|
||||||
# Test array handling | ||||||
assert ('array' in variables and | ||||||
variables['array'] == ([1, 3141500.0], Type('float', [2]))) | ||||||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please rewrite without using eval.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
hello @kalvdans,
Thanks for your reply, avoiding using eval is a very good simple suggestion to avoid security issues and everyone should know.
One solution is to write a C integer parser, but I'm not sure it's worth writing. Because my purpose is to bind existing open source c libraries. If some people who want to use untrusted libraries may be worried about this.
Also, I think must write in clean code for better maintenance, but I don't know of any python built-in function that can convert C integer string to a Python integer. If you know a function, I will appreciate if you tell me :)
See also this code https://github.com/r888800009/pyclibrary/blob/f5f8bf80113b9deb247e92705bb4b73529b95912/pyclibrary/c_parser.py#L1736-L1739
The token passed in by wrapper must match the regular expression. If you know how to bypass this regex to achieve python execute code, please tell me and I will be able to confirm that this is indeed a bad approach
Of course, to avoid misuse, we'd better avoiding using eval, but we also need have a good enough solution to make it easy to maintain.
For your concerns, maybe you'll want to look at the existing code in c_parser.py
pyclibrary/pyclibrary/c_parser.py
Line 1514 in 1d4dbfc
If we care about security issues, maybe we can consider rewriting the eval function of the entire project
Best regards
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I did not check in depth but could you use ast.literal_eval ?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
hmm,
int(t[0], 0)
should handle 0x prefixes fine, but doesn't work with octal.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It seems we can simply write an octal parser 44daba6 to solve this problem without too much complexity.
new patch a7f7624 uses
int(t[0], 0)
, which can restrict the input of only integer.