Proguard retrace stack variants - proguard

Can I use the retrace for stack is different from:
Exception in thread "main" java.lang.Error: Random exception
at pro.bY.a(ProGuard:576)
at pro.bO.a(ProGuard:431)
at pro.bj.a(ProGuard:145)
at pro.bY.a(ProGuard:522)
at pro.bj.a(ProGuard:129)
E.g, I have this stack:
NullPointerException
MessageController
getMessage
0*7h3f33
MessageModel
getCurrentPlace
0*1F3f14
after obfuscate it is:
NullPointerException
b
ab
0*7h3f33
a
ac_
0*1F3f14

You can specify your own regular expression with the ReTrace option -regex. Cfr. ProGuard manual > ReTrace Usage.
The expression is applied per line of stack trace, so you probably have to concatenate some lines from your input trace to get each class/method name pair on a single line.

Related

kotlin singleton exception is bad or good?

i'm studying kotlin.
I have a question about using exception.
which is better to use object exception or class exception in kotlin?
object CustomDuplicateId : RuntimeException("Invalid user with Id")
class CustomDuplicateId : RuntimeException("Invalid user with Id")
if im using this exception only one location, than stacktrace is always same.
so i think... it doesn't need to use class. is it right?
or is it bad to use singleton exception?
can anyone let me know what's better code to write exception?
There are multiple reasons why it's incorrect to use object.
the stacktrace is wrong in several ways:
It's created at instantiation time, so you'll see <clinit> as first line in the stacktrace because it's created when initializing the object's class for the first time
Even if you throw it from the same place, it won't necessarily be when called from the same caller, so the bottom (root) of the stacktrace will be incorrect if this exception is thrown multiple times across the life of your application
technically the exception class has mutable parts and it would be dangerous/incorrect to allow user code to tamper with this. A very concrete example of this is that user code could add suppressed exceptions to your exception instance (which would only be valid for one throw and yet persist in your object). This is technically a memory leak.
it's likely you would need different messages with more information about why it was thrown (in that case the duplicate ID is very much needed) - so you need different instances with different data anyway
you might throw it from different places in the future (even now in tests/mocks maybe?), and in that case the stacktrace would be even more wrong
independently of technicalities like the above, class vs object also sends a message to the reader that is a bit unclear - why an object here? This exception is not inherently unique. It just so happens that you throw it in one specific place right now and rely on the stacktrace being the same.
Here is an example for the major issue (#1):
object MyExceptionObject : RuntimeException("boom")
fun main() {
try {
caller1() // line 7
} catch (e: Exception) {
}
caller2() // line 10
}
fun caller1() = doStuff() // line 13
fun caller2() = doStuff() // line 14
fun doStuff() {
throw MyExceptionObject // line 17
}
The caller1() throws the exception but that one is caught. The caller2() throws the exception again and that one is not caught. The stacktrace we get for the uncaught exception incorrectly shows the caller 1 (with lines 7 and 13) but the correct one should be caller 2 (with lines 10 and 14):
Exception in thread "main" com.example.MyExceptionObject: boom
at com.example.MyExceptionObject.<clinit>(ExceptionObjectExample.kt)
at com.example.ExceptionObjectExampleKt.doStuff(ExceptionObjectExample.kt:17)
at com.example.ExceptionObjectExampleKt.caller1(ExceptionObjectExample.kt:13)
at com.example.ExceptionObjectExampleKt.main(ExceptionObjectExample.kt:7)
at com.example.ExceptionObjectExampleKt.main(ExceptionObjectExample.kt)
All in all, just use a class.

listing all API errors with flask/qwagger [duplicate]

Is there a way knowing (at coding time) which exceptions to expect when executing python code?
I end up catching the base Exception class 90% of the time since I don't know which exception type might be thrown (reading the documentation doesn't always help, since many times an exception can be propagated from the deep. And many times the documentation is not updated or correct).
Is there some kind of tool to check this (like by reading the Python code and libs)?
I guess a solution could be only imprecise because of lack of static typing rules.
I'm not aware of some tool that checks exceptions, but you could come up with your own tool matching your needs (a good chance to play a little with static analysis).
As a first attempt, you could write a function that builds an AST, finds all Raise nodes, and then tries to figure out common patterns of raising exceptions (e. g. calling a constructor directly)
Let x be the following program:
x = '''\
if f(x):
raise IOError(errno.ENOENT, 'not found')
else:
e = g(x)
raise e
'''
Build the AST using the compiler package:
tree = compiler.parse(x)
Then define a Raise visitor class:
class RaiseVisitor(object):
def __init__(self):
self.nodes = []
def visitRaise(self, n):
self.nodes.append(n)
And walk the AST collecting Raise nodes:
v = RaiseVisitor()
compiler.walk(tree, v)
>>> print v.nodes
[
Raise(
CallFunc(
Name('IOError'),
[Getattr(Name('errno'), 'ENOENT'), Const('not found')],
None, None),
None, None),
Raise(Name('e'), None, None),
]
You may continue by resolving symbols using compiler symbol tables, analyzing data dependencies, etc. Or you may just deduce, that CallFunc(Name('IOError'), ...) "should definitely mean raising IOError", which is quite OK for quick practical results :)
You should only catch exceptions that you will handle.
Catching all exceptions by their concrete types is nonsense. You should catch specific exceptions you can and will handle. For other exceptions, you may write a generic catch that catches "base Exception", logs it (use str() function) and terminates your program (or does something else that's appropriate in a crashy situation).
If you really gonna handle all exceptions and are sure none of them are fatal (for example, if you're running the code in some kind of a sandboxed environment), then your approach of catching generic BaseException fits your aims.
You might be also interested in language exception reference, not a reference for the library you're using.
If the library reference is really poor and it doesn't re-throw its own exceptions when catching system ones, the only useful approach is to run tests (maybe add it to test suite, because if something is undocumented, it may change!). Delete a file crucial for your code and check what exception is being thrown. Supply too much data and check what error it yields.
You will have to run tests anyway, since, even if the method of getting the exceptions by source code existed, it wouldn't give you any idea how you should handle any of those. Maybe you should be showing error message "File needful.txt is not found!" when you catch IndexError? Only test can tell.
The correct tool to solve this problem is unittests. If you are having exceptions raised by real code that the unittests do not raise, then you need more unittests.
Consider this
def f(duck):
try:
duck.quack()
except ??? could be anything
duck can be any object
Obviously you can have an AttributeError if duck has no quack, a TypeError if duck has a quack but it is not callable. You have no idea what duck.quack() might raise though, maybe even a DuckError or something
Now supposing you have code like this
arr[i] = get_something_from_database()
If it raises an IndexError you don't know whether it has come from arr[i] or from deep inside the database function. usually it doesn't matter so much where the exception occurred, rather that something went wrong and what you wanted to happen didn't happen.
A handy technique is to catch and maybe reraise the exception like this
except Exception as e
#inspect e, decide what to do
raise
Noone explained so far, why you can't have a full, 100% correct list of exceptions, so I thought it's worth commenting on. One of the reasons is a first-class function. Let's say that you have a function like this:
def apl(f,arg):
return f(arg)
Now apl can raise any exception that f raises. While there are not many functions like that in the core library, anything that uses list comprehension with custom filters, map, reduce, etc. are affected.
The documentation and the source analysers are the only "serious" sources of information here. Just keep in mind what they cannot do.
I ran into this when using socket, I wanted to find out all the error conditions I would run in to (so rather than trying to create errors and figure out what socket does I just wanted a concise list). Ultimately I ended up grep'ing "/usr/lib64/python2.4/test/test_socket.py" for "raise":
$ grep raise test_socket.py
Any exceptions raised by the clients during their tests
raise TypeError, "test_func must be a callable function"
raise NotImplementedError, "clientSetUp must be implemented."
def raise_error(*args, **kwargs):
raise socket.error
def raise_herror(*args, **kwargs):
raise socket.herror
def raise_gaierror(*args, **kwargs):
raise socket.gaierror
self.failUnlessRaises(socket.error, raise_error,
self.failUnlessRaises(socket.error, raise_herror,
self.failUnlessRaises(socket.error, raise_gaierror,
raise socket.error
# Check that setting it to an invalid value raises ValueError
# Check that setting it to an invalid type raises TypeError
def raise_timeout(*args, **kwargs):
self.failUnlessRaises(socket.timeout, raise_timeout,
def raise_timeout(*args, **kwargs):
self.failUnlessRaises(socket.timeout, raise_timeout,
Which is a pretty concise list of errors. Now of course this only works on a case by case basis and depends on the tests being accurate (which they usually are). Otherwise you need to pretty much catch all exceptions, log them and dissect them and figure out how to handle them (which with unit testing wouldn't be to difficult).
There are two ways that I found informative. The first one, run the code in iPython, which will display the exception type.
n = 2
str = 'me '
str + 2
TypeError: unsupported operand type(s) for +: 'int' and 'str'
In the second way we settle for catching too much and improve on it over time. Include a try expression in your code and catch except Exception as err. Print sufficient data to know what exception was thrown. As exceptions are thrown improve your code by adding a more precise except clause. When you feel that you have caught all relevant exceptions remove the all inclusive one. A good thing to do anyway because it swallows programming errors.
try:
so something
except Exception as err:
print "Some message"
print err.__class__
print err
exit(1)
normally, you'd need to catch exception only around a few lines of code. You wouldn't want to put your whole main function into the try except clause. for every few line you always should now (or be able easily to check) what kind of exception might be raised.
docs have an exhaustive list of built-in exceptions. don't try to except those exception that you're not expecting, they might be handled/expected in the calling code.
edit: what might be thrown depends on obviously on what you're doing! accessing random element of a sequence: IndexError, random element of a dict: KeyError, etc.
Just try to run those few lines in IDLE and cause an exception. But unittest would be a better solution, naturally.
This is a copy and pasted answer I wrote for How to list all exceptions a function could raise in Python 3?, I hope that is allowed.
I needed to do something similar and found this post. I decided I
would write a little library to help.
Say hello to Deep-AST. It's very early alpha but it is pip
installable. It has all of the limitations mentioned in this post
and some additional ones but its already off to a really good start.
For example when parsing HTTPConnection.getresponse() from
http.client it parses 24489 AST Nodes. It finds 181 total raised
Exceptions (this includes duplicates) and 8 unique Exceptions were
raised. A working code example.
The biggest flaw is this it currently does work with a bare raise:
def foo():
try:
bar()
except TypeError:
raise
But I think this will be easy to solve and I plan on fixing it.
The library can handle more than just figuring out exceptions, what
about listing all Parent classes? It can handle that too!

Prevent "Execution was interrupted, reason: internal ObjC exception breakpoint(-3)" on lldb

I've written some code that dumps all ivars of a class into a dictionary in Objective C. This uses valueForKey: to get the data from the class. Sometimes, KVC throws an internal exception that is also captured properly - but this disrupts lldb's feature and all I get is:
error: Execution was interrupted, reason: internal ObjC exception breakpoint(-3)..
The process has been returned to the state before expression evaluation.
There are no breakpoints set. I even tried with -itrue -ufalse as expression options, but it doesn't make a difference. This totally defeats for what I want to use lldb for, and it seems like such a tiny issue. How can I bring clang to simply ignore if there are internal, captured ObjC exceptions while calling a method?
I tried this both from within Xcode, and directly via calling clang from the terminal and connecting to a remote debug server - no difference.
I ran into the same issue. My solution was to wrap a try/catch around it (I only use this code for debugging). See: DALIntrospection.m line #848
NSDictionary *DALPropertyNamesAndValuesMemoryAddressesForObject(NSObject *instance)
Or, if you're running on iOS 7, the private instance method _ivarDescription will print all the ivars for you (similar instance methods are _methodDescription and _shortMethodDescription).
I met the same problem.
My solution is simply alloc init the property before assigning it to the value which caused the crash.
Myself and coworkers ran into this today, and we eventually found a workaround using lldb's python API. The manual way is to run script, and enter:
options = lldb.SBExpressionOptions()
options.SetTrapExceptions(False)
print lldb.frame.EvaluateExpression('ThisThrowsAndCatches()', options).value
This could be packaged into its own command via command script add.
error: Execution was interrupted, reason: internal ObjC exception breakpoint(-3).. The process has been returned to the state before expression evaluation.
Note that lldb specifically points to the internal breakpoint -3 that caused the interruption.
To see the list of all internal breakpoints, run:
(lldb) breakpoint list --internal
...
Kind: ObjC exception
-3: Exception breakpoint (catch: off throw: on) using: name = 'objc_exception_throw', module = libobjc.A.dylib, locations = 1
-3.1: where = libobjc.A.dylib`objc_exception_throw, address = 0x00007ff81bd27be3, unresolved, hit count = 4
Internal breakpoints can be disabled like regular ones:
(lldb) breakpoint disable -3
1 breakpoints disabled.
In case lldb continues getting interrupted you might also need to disable the conditions of the breakpoint:
(lldb) breakpoint disable -3.*
1 breakpoints disabled.
In my particular case there were multiple exception breakpoints I had to disable before I finally got the expected result:
(lldb) breakpoint disable -4 -4.* -5 -5.*
6 breakpoints disabled.

Lua: no stack trace when calling error() without arguments?

In Lua, calling the standard error() function with a message argument outputs the provided error message and also prints stack trace, e.g. executing the following code:
print("hello")
error("oops!")
print("world")
would result in the following output:
$ lua test.lua
hello
lua: test.lua:2: oops!
stack traceback:
[C]: in function 'error'
test.lua:2: in main chunk
[C]: ?
However, calling error() without arguments seems to make Lua die silently without printing stack trace. Executing this code:
print("hello")
error() // no arguments provided
print("world")
would result in this output:
$ lua test2.lua
hello
The documentation doesn't say anything about omitting the first message argument:
error (message [, level])
Terminates the last protected function called and returns message as
the error message. Function error never returns. Usually, error adds
some information about the error position at the beginning of the
message. The level argument specifies how to get the error position.
With level 1 (the default), the error position is where the error
function was called. Level 2 points the error to where the function
that called error was called; and so on. Passing a level 0 avoids the
addition of error position information to the message.
I'm wondering if this is intended behavior or no? IMO it would make sense to still print stack trace (and maybe output some default text e.g. error) even if no message is provided, because that's how the assert() function works.
The documentation doesn't say anything about omitting the first message argument:
Yes, it does, error() has a prototype like this:
error (message [, level])
Notice that only the arguments inside [] is optional, in this case level, otherwise the arguments are mandatory, in this case, message.
Comparing with the prototype of assert():
assert (v [, message])
As you can see, message in assert() is optional.

Raising IO Exceptions in SML

Exception IO has structure:
Exception IO of {
name: string
....
...}
some other arguments that I do not understand.
Do I have to assign all these. I mean what do I do after this?
exception IO of {inputfile}
I usually define exception and then raise. but I do not even define an exception this way.
All I want to do is raise an exception if input file is not existant. What do I do here?
Thank You
Yes, you have to supply all three fields when creating an exception of type Io. The meanings of the fields are explained in the documentation:
This is the principal exception raised when an error occurs in the I/O subsystem. The components of Io are:
name: The name component of the reader or writer.
function: The name of the function raising the exception.
cause: The underlying exception raised by the reader or writer, or detected at the stream I/O level.
Some of the standard causes are:
OS.SysErr if an actual system call was done and failed.
*Subscript if ill-formed arguments are given.
BlockingNotSupported
NonblockingNotSupported
ClosedStream
The cause field of Io is not limited to these particular exceptions. Users who create their own readers or writers may raise any exception they like, which will be reported as the cause field of the resulting Io exception.
Note that openIn already raises an Io exception if the file does not exist (with "openIn" as the function, the filename as the name and a SysErr as the cause), so there's no need for you to raise your own.