PVS-Studio: warning V595 is generated even if COM methods results are checked - pvs-studio

(1) If a result of IMoniker::BindToObject is S_OK then returned pointer is valid. But PVS-Studio marks it as V595. Why?
(2) If QueryInterface is succeeded then returned pointer is valid. But PVS-Studio marks it as V595. Why?
HRESULT sc;
if (featureValidateSource)
{
sc = lpmk->BindToObject(lpbc, NULL, IID_IOleObject, (void**)&lpObject);
if (FAILED(sc))
{
lpbc->Release();
lpmk->Release();
if (lpObject) lpObject->Release();
return sc;
}
lpObject->GetUserClassID(&clsid); // (1) <<< V595
}
LPOLELINK lpOleLink;
if (SUCCEEDED(m_pObject->QueryInterface(IID_IOleLink,(void**)&lpOleLink)))
{
sc = lpOleLink->SetSourceMoniker(lpmk, clsid); // (2) <<< V595
}
...
if (lpObject != NULL) // (1) <<< V595
{
lpObject->Update();
lpObject->Release();
}
if (lpOleLink) // (2) <<< V595
{
lpOleLink->Release();
}

This is a fault of our function annotation system. PVS-Studio analyzer currently has annotations for over 6000 functions from the most popular libraries. These annotations allow the tool to perform a lot of diagnostics. However, we haven't yet annotated the functions BindToObject and QueryInterface. But even if we had, it wouldn't have helped. There are no annotations currently specifying how a returned poitner is related to the status of type HRESULT. There must be a connection: if certain functions have executed successfully, then non-null pointers are returned. There is no such thing now, but we'll gradually implement this algorithm. Then the false positives will go away.
Since there is no such connection now, the analyzer views the code in the following way:
if (X)
{
GetPtr(&ptr1);
if (Y)
return;
ptr1->foo(); // (1) <<< V595
}
if (GetPtr(&ptr2))
{
ptr2->foo(); // (2) <<< V595
}
if (ptr1 != NULL) // (1) <<< V595
;
if (ptr2 != NULL) // (1) <<< V595
;
The pointers are initialized somehow. After that, they are dereferenced and then checked for NULL. It looks suspicious, so the analyzer issues the warning.
So, yes, there is a fault on our part. We'll improve analysis of such constructs in time. Thank you for pointing this code out.
As for now, we suggest using one of the means of false positive suppression or use suppression base.

Related

Responsive asynchronous search-as-you-type in Java 8

I'm trying to implement a "search as you type" pattern in Java.
The goal of the design is that no change gets lost but at the same time, the (time consuming) search operation should be able to abort early and try with the updated pattern.
Here is what I've come up so far (Java 8 pseudocode):
AtomicReference<String> patternRef
AtomicLong modificationCount
ReentrantLock busy;
Consumer<List<ResultType>> resultConsumer;
// This is called in a background thread every time the user presses a key
void search(String pattern) {
// Update the pattern
synchronized {
patternRef.set(pattern)
modificationCount.inc()
}
try {
if (!busy.tryLock()) {
// Another search is already running, let it handle the change
return;
}
// Get local copy of the pattern and modCount
synchronized {
String patternCopy = patternRef.get();
long modCount = modificationCount.get()
}
while (true) {
// Try the search. It will return false when modificationCount changes before the search is finished
boolean success = doSearch(patternCopy, modCount)
if (success) {
// Search completed before modCount was changed again
break
}
// Try again with new pattern+modCount
synchronized {
patternCopy = patternRef.get();
modCount = modificationCount.get()
}
}
} finally {
busy.unlock();
}
}
boolean doSearch(String pattern, long modCount)
... search database ...
if (modCount != modificationCount.get()) {
return false;
}
... prepare results ...
if (modCount != modificationCount.get()) {
return false;
}
resultConsumer.accept(result); // Consumer for the UI code to do something
return modCount == modificationCount.get();
}
Did I miss some important point? A race condition or something similar?
Is there something in Java 8 which would make the code above more simple?
The fundamental problem of this code can be summarized as “trying to achieve atomicity by multiple distinct atomic constructs”. The combination of multiple atomic constructs is not atomic and trying to reestablish atomicity leads to very complicated, usually broken, and inefficient code.
In your case, doSearch’s last check modCount == modificationCount.get() happens while still holding the lock. After that, another thread (or multiple other threads) could update the search string and mod count, followed by finding the lock occupied, hence, concluding that another search is running and will take care.
But that thread doesn’t care after that last modCount == modificationCount.get() check. The caller just does if (success) { break; }, followed by the finally { busy.unlock(); } and returns.
So the answer is, yes, you have potential race conditions.
So, instead of settling on two atomic variables, synchronized blocks, and a ReentrantLock, you should use one atomic construct, e.g. a single atomic variable:
final AtomicReference<String> patternRef = new AtomicReference<>();
Consumer<List<ResultType>> resultConsumer;
// This is called in a background thread every time the user presses a key
void search(String pattern) {
if(patternRef.getAndSet(pattern) != null) return;
// Try the search. doSearch will return false when not completed
while(!doSearch(pattern) || !patternRef.compareAndSet(pattern, null))
pattern = patternRef.get();
}
boolean doSearch(String pattern) {
//... search database ...
if(pattern != (Object)patternRef.get()) {
return false;
}
//... prepare results ...
if(pattern != (Object)patternRef.get()) {
return false;
}
resultConsumer.accept(result); // Consumer for the UI code to do something
return true;
}
Here, a value of null indicates that no search is running, so if a background thread sets this to a non-null value and finds the old value to be null (in an atomic operation), it knows it has to perform the actual search. After the search, it tries to set the reference to null again, using compareAndSet with the pattern used for the search. Thus, it can only succeed if it has not changed again. Otherwise, it will fetch the new value and repeat.
These two atomic updates are already sufficient to ensure that there is only a single search operation at a time while not missing an updated search pattern. The ability of doSearch to return early when it detects a change, is just a nice to have and not required by the caller’s loop.
Note that in this example, the check within doSearch has been reduced to a reference comparison (using a cast to Object to prevent compiler warnings), to demonstrate that it can be as cheap as the int comparison of your original approach. As long as no new string has been set, the reference will be the same.
But, in fact, you could also use a string comparison, i.e. if(!pattern.equals(patternRef.get())) { return false; } without a significant performance degradation. String comparison is not (necessarily) expensive in Java. The first thing, the implementation of String’s equals does, is a reference comparison. So if the string has not changed, it will return true immediately here. Otherwise, it will check the lengths then (unlike C strings, the length is known beforehand) and return false immediately on a mismatch. So in the typical scenario of the user typing another character or pressing backspace, the lengths will differ and the comparison bail out immediately.

How do you cycle through items in a Relationship?

This is the current code:
Class %Utcov.Test Extends %RegisteredObject
{
ClassMethod listClasses(ns As %String, projectName As %String)
{
// Switch namespaces to the new one
new $namespace
set $namespace = ns
// Grab our project, by name; fail otherwise
// TODO: failing is CRUDE at this point...
#dim project as %Studio.Project
#dim status as %Status
// TODO: note sure what the "concurrency" parameter is; leave the default
// which is -1
set project = ##class(%Studio.Project).%OpenId(projectName, /* default */, .status)
if ('status) {
write "Argh; failed to load", !
halt // meh... Ugly, f*ing ugly
}
w project.Items
}
ClassMethod main()
{
do ..listClasses("USER", "cache-tort-git")
}
}
First things first: I know that the code sucks... But that's the learning curve, I will eventually do better... The problem I want to solve here is this line:
w project.Items
At the console, it currently prints:
2#%Library.RelationshiptObject
but what I'd like to do is of course to cycle through these objects, which, according to the documentation, are "instances" of %Studio.ProjectItem.
How do I cycle through these? WRITE doesn't cut it, and in fact I surmised from the start that it would not... I just cannot figure out how this is done in ObjectScript :/
When your writed object with w project.Items, you got such string 2#%Library.RelationshiptObject, this string may help in understanding what the object we got, and in this case it is an object of class %Library.RelationshiptObject, when you open this class in documentation, you may find some methods which could help you.
Here you can find some examples, how to work with relationships, in objects way and with sql.
Set tKey = ""
For {
;tItem will be the first item in your list which will be ordered by OREF
Set tItem = project.Items.GetNext(.tKey)
Quit:(tKey = "")
;Do whatever you want with tItem
}

Checking, if optional parameter is provided in Dart

I'm new to Dart and just learning the basics.
The Dart-Homepage shows following:
It turns out that Dart does indeed have a way to ask if an optional
parameter was provided when the method was called. Just use the
question mark parameter syntax.
Here is an example:
void alignDingleArm(num axis, [num rotations]) {
if (?rotations) {
// the parameter was really used
}
}
So I've wrote a simple testing script for learning:
import 'dart:html';
void main() {
String showLine(String string, {String printBefore : "Line: ", String printAfter}){
// check, if parameter was set manually:
if(?printBefore){
// check, if parameter was set to null
if(printBefore == null){
printBefore = "";
}
}
String line = printBefore + string + printAfter;
output.appendText(line);
output.appendHtml("<br />\n");
return line;
}
showLine("Hallo Welt!",printBefore: null);
}
The Dart-Editor already marks the questionmark as Error:
Multiple markers at this line
- Unexpected token '?'
- Conditions must have a static type of
'bool'
When running the script in Dartium, the JS-Console shows folloing Error:
Internal error: 'http://localhost:8081/main.dart': error: line 7 pos 8: unexpected token '?'
if(?printBefore){
^
I know, that it would be enough to check if printBefore is null, but I want to learn the language.
Does anyone know the reason for this problem?
How to check, if the parameter is set manually?
The feature existed at some point in Dart's development, but it was removed again because it caused more complication than it removed, without solving the problem that actually needed solving - forwarding of default parameters.
If you have a function foo([x = 42]) and you want a function to forward to it, bar([x]) => f(x);, then, since foo could actually tell if x is passed or not, you actually ended up writing bar([x]) => ?x ? foo(x) : foo();. That was worse than what you had to do without the ?: operator.
Ideas came up about having a bar([x]) => foo(?:x) or something which pased on x if it was present and not if it was absent (I no longer remember the actual proposed syntax), but that got complicated fast, fx converting named arguments to positional - bar({x,y}) => foo(?:x, ?:y); - what if y was provided and x was not. It was really just a bad solution for a self-inflicted problem.
So, the ?x feature was rolled back. All optional parameters have a default value which is passed if there is no matching argument in a call. If you want to forward an optional parameter, you need to know the default value of the function you are forwarding to.
For most function arguments, the declared default value is null, with an internal if (arg == null) arg = defaultValue; statement to fix it. That means that the null value can be forwarded directly without any confusion.
Some arguments have a non-null default value. It's mostly boolean arguments, but there are other cases too. I recommend using null for everything except named boolean parameters (because they are really meant to be named more than they are meant to be optional). At least unless there is a good reason not to - like ensuring that all subclasses will have the same default value for a method parameter (which may be a good reason, or not, and should be used judiciosuly).
If you have an optional parameter that can also accept null as a value ... consider whether it should really be optional, or if you just need a different function with one more argument. Or maybe you can introduce a different "missing argument" default value. Example:
abstract class C { foo([D something]); }
class _DMarker implements D { const _DMarker(); }
class _ActualC {
foo([D something = const _DMarker()]) {
if (something == const _DMarker()) {
// No argument passed, because user cannot create a _DMarker.
} else {
// Argument passed, may be null.
}
}
}
This is a big workaround, and hardly ever worth it. In general, just use null as default value, it's simpler.
I was trying something similar:
This does not work
widget.optionalStringParameter ? widget.optionalStringParameter : 'default string'
This works
widget.optionalStringParameter != null ? widget.optionalStringParameter : 'default string'
This also works
widget.optionalStringParameter ?? 'default string'
There was support for checking if an optional parameter was actually provider in early Dart days (pre 1.0) but was removed because it causes some troubles.

If not let - in Swift

is there is a way to negate the "if let" in swift?
This looks silly to me:
if let type = json.type {
} else {
XCTFail("There is no type in the root element")
}
I can't use XCTAssertNotNil, because json.type is a enum.
enum JSONDataTypes {
case Object
case Array
case Number
case String
}
Thanks a lot
EDIT: it is a:
var type: JSONDataTypes? = nil
Swift 2.0 (Xcode 7) and later have the new guard statement, which sort of works like an "if not let" -- you can conditionally bind a variable in the remainder of the enclosing scope, keeping the "good path" in your code the least-indented.
guard let type = json.type else {
XCTFail("There is no type in the root element")
}
// do something with `type` here
The catch to this is that the else clause of a guard must exit that scope (because otherwise you'd fall into code after that clause, where the guarded variables, like type above, are unbound). So it has to end with something like return, break, continue or a function that is known to the compiler to never return (i.e. annotated #noreturn, like abort()... I don't recall offhand if that includes XCTFail, but it should (file a bug if it's not).
For details, see Early Exit in The Swift Programming Language.
As for really-old stuff... There's no negated form of if-let in Swift 1.x. But since you're working with XCTest anyway, you can just make testing the optional part of an assertion expression:
XCTAssert(json.type != nil, "There is no type in the root element")
Here's how you do it:
if json.type == nil {
// fail
}
Another alternative I've used a few times:
switch json.type
{
case .None: // ...
case .Some(.Object): // ...
case .Some(.Array): // ...
case .Some(.Number): // ...
case .Some(.String): // ...
}
Since the ? is actually Optional<T> which is an enum on its own, defined as:
enum Optional<T> : Reflectable, NilLiteralConvertible
{
case None
case Some(T)
...
}

How to avoid Linq chaining to return null?

I have a problem with code contracts and linq. I managed to narrow the issue to the following code sample. And now I am stuck.
public void SomeMethod()
{
var list = new List<Question>();
if (list.Take(5) == null) { }
// resharper hints that condition can never be true
if (list.ForPerson(12) == null) { }
// resharper does not hint that condition can never be true
}
public static IQueryable<Question> ForPerson(this IQueryable<Question> source, int personId)
{
if(source == null) throw new ArgumentNullException();
return from q in source
where q.PersonId == personId
select q;
}
What is wrong with my linq chain? Why doesn't resharper 'complain' when analyzing the ForPerson call?
EDIT: return type for ForPerson method changed from string to IQueryable, which I meant. (my bad)
Reshaper is correct that the result of a Take or Skip is never null - if there are no items the result is an IEnumerable<Question> which has no elements. I think to do what you want you should check Any.
var query = list.Take(5);
if (!query.Any())
{
// Code here executes only if there were no items in the list.
}
But how does this warning work? Resharper cannot know that the method never returns null from only looking at the method definition, and I assume that it does not reverse engineer the method body to determine that it never returns null. I assume therefore that it has been specially hard-coded with a rule specifying that the .NET methods Skip and Take do not return null.
When you write your own custom methods Reflector can make assumptions about your method behaviour from the interface, but your interface allows it to return null. Therefore it issues no warnings. If it analyzed the method body then it could see that null is impossible and would be able to issue a warning. But analyzing code to determine its possible behaviour is an incredibly difficult task and I doubt that Red Gate are willing to spend the money on solving this problem when they could add more useful features elsewhere with a much lower development cost.
To determine whether a boolean expression can ever return true is called the Boolean satisfiability problem and is an NP-hard problem.
You want Resharper to determine whether general method bodies can ever return null. This is a generalization of the above mentioned NP-hard problem. It's unlikely any tool will ever be able to do this correctly in 100% of cases.
if(source == null) throw new ArgumentNullException();
That's not the code contract way, do you instead mean:
Contract.Require(source != null);

Resources