Does clang-tidy make scan-build redundant? - clang

I have a project that currently uses both scan-build and clang-tidy (enabled via CMake).
If I enable clang-analyzer-* in my set of clang-tidy checks, is the usage of scan-build redundant?
For reference, there is a similar question asked here about the usage of clang-tidy with clang-check.

These are the available checks reported by scan-build --help (the "+" indicates that the check is enabled by default):
+ core.CallAndMessage Check for logical errors for function calls and Objective-C message expressions (e.g., uninitialized arguments, null function pointers)
+ core.DivideZero Check for division by zero
+ core.NonNullParamChecker Check for null pointers passed as arguments to a function whose arguments are references or marked with the 'nonnull' attribute
+ core.NullDereference Check for dereferences of null pointers
+ core.StackAddressEscape Check that addresses to stack memory do not escape the function
+ core.UndefinedBinaryOperatorResult
Check for undefined results of binary operators
+ core.VLASize Check for declarations of VLA of undefined or zero size
+ core.uninitialized.ArraySubscript
Check for uninitialized values used as array subscripts
+ core.uninitialized.Assign Check for assigning uninitialized values
+ core.uninitialized.Branch Check for uninitialized values used as branch conditions
+ core.uninitialized.CapturedBlockVariable
Check for blocks that capture uninitialized values
+ core.uninitialized.UndefReturn Check for uninitialized values being returned to the caller
+ cplusplus.InnerPointer Check for inner pointers of C++ containers used after re/deallocation
+ cplusplus.Move Find use-after-move bugs in C++
+ cplusplus.NewDelete Check for double-free and use-after-free problems. Traces memory managed by new/delete.
+ cplusplus.NewDeleteLeaks Check for memory leaks. Traces memory managed by new/delete.
+ cplusplus.PlacementNew Check if default placement new is provided with pointers to sufficient storage capacity
+ cplusplus.PureVirtualCall Check pure virtual function calls during construction/destruction
+ deadcode.DeadStores Check for values stored to variables that are never read afterwards
fuchsia.HandleChecker A Checker that detect leaks related to Fuchsia handles
+ nullability.NullPassedToNonnull
Warns when a null pointer is passed to a pointer which has a _Nonnull type.
+ nullability.NullReturnedFromNonnull
Warns when a null pointer is returned from a function that has _Nonnull return type.
nullability.NullableDereferenced
Warns when a nullable pointer is dereferenced.
nullability.NullablePassedToNonnull
Warns when a nullable pointer is passed to a pointer which has a _Nonnull type.
nullability.NullableReturnedFromNonnull
Warns when a nullable pointer is returned from a function that has _Nonnull return type.
optin.cplusplus.UninitializedObject
Reports uninitialized fields after object construction
optin.cplusplus.VirtualCall Check virtual function calls during construction/destruction
optin.mpi.MPI-Checker Checks MPI code
optin.osx.OSObjectCStyleCast Checker for C-style casts of OSObjects
optin.osx.cocoa.localizability.EmptyLocalizationContextChecker
Check that NSLocalizedString macros include a comment for context
optin.osx.cocoa.localizability.NonLocalizedStringChecker
Warns about uses of non-localized NSStrings passed to UI methods expecting localized NSStrings
optin.performance.GCDAntipattern
Check for performance anti-patterns when using Grand Central Dispatch
optin.performance.Padding Check for excessively padded structs.
optin.portability.UnixAPI Finds implementation-defined behavior in UNIX/Posix functions
osx.API Check for proper uses of various Apple APIs
osx.MIG Find violations of the Mach Interface Generator calling convention
osx.NumberObjectConversion Check for erroneous conversions of objects representing numbers into numbers
osx.OSObjectRetainCount Check for leaks and improper reference count management for OSObject
osx.ObjCProperty Check for proper uses of Objective-C properties
osx.SecKeychainAPI Check for proper uses of Secure Keychain APIs
osx.cocoa.AtSync Check for nil pointers used as mutexes for #synchronized
osx.cocoa.AutoreleaseWrite Warn about potentially crashing writes to autoreleasing objects from different autoreleasing pools in Objective-C
osx.cocoa.ClassRelease Check for sending 'retain', 'release', or 'autorelease' directly to a Class
osx.cocoa.Dealloc Warn about Objective-C classes that lack a correct implementation of -dealloc
osx.cocoa.IncompatibleMethodTypes
Warn about Objective-C method signatures with type incompatibilities
osx.cocoa.Loops Improved modeling of loops using Cocoa collection types
osx.cocoa.MissingSuperCall Warn about Objective-C methods that lack a necessary call to super
osx.cocoa.NSAutoreleasePool Warn for suboptimal uses of NSAutoreleasePool in Objective-C GC mode
osx.cocoa.NSError Check usage of NSError** parameters
osx.cocoa.NilArg Check for prohibited nil arguments to ObjC method calls
osx.cocoa.NonNilReturnValue Model the APIs that are guaranteed to return a non-nil value
osx.cocoa.ObjCGenerics Check for type errors when using Objective-C generics
osx.cocoa.RetainCount Check for leaks and improper reference count management
osx.cocoa.RunLoopAutoreleaseLeak
Check for leaked memory in autorelease pools that will never be drained
osx.cocoa.SelfInit Check that 'self' is properly initialized inside an initializer method
osx.cocoa.SuperDealloc Warn about improper use of '[super dealloc]' in Objective-C
osx.cocoa.UnusedIvars Warn about private ivars that are never used
osx.cocoa.VariadicMethodTypes Check for passing non-Objective-C types to variadic collection initialization methods that expect only Objective-C types
osx.coreFoundation.CFError Check usage of CFErrorRef* parameters
osx.coreFoundation.CFNumber Check for proper uses of CFNumber APIs
osx.coreFoundation.CFRetainRelease
Check for null arguments to CFRetain/CFRelease/CFMakeCollectable
osx.coreFoundation.containers.OutOfBounds
Checks for index out-of-bounds when using 'CFArray' API
osx.coreFoundation.containers.PointerSizedValues
Warns if 'CFArray', 'CFDictionary', 'CFSet' are created with non-pointer-size values
security.FloatLoopCounter Warn on using a floating point value as a loop counter (CERT: FLP30-C, FLP30-CPP)
security.insecureAPI.DeprecatedOrUnsafeBufferHandling
Warn on uses of unsecure or deprecated buffer manipulating functions
+ security.insecureAPI.UncheckedReturn
Warn on uses of functions whose return values must be always checked
security.insecureAPI.bcmp Warn on uses of the 'bcmp' function
security.insecureAPI.bcopy Warn on uses of the 'bcopy' function
security.insecureAPI.bzero Warn on uses of the 'bzero' function
security.insecureAPI.decodeValueOfObjCType
Warn on uses of the '-decodeValueOfObjCType:at:' method
+ security.insecureAPI.getpw Warn on uses of the 'getpw' function
+ security.insecureAPI.gets Warn on uses of the 'gets' function
+ security.insecureAPI.mkstemp Warn when 'mkstemp' is passed fewer than 6 X's in the format string
+ security.insecureAPI.mktemp Warn on uses of the 'mktemp' function
security.insecureAPI.rand Warn on uses of the 'rand', 'random', and related functions
security.insecureAPI.strcpy Warn on uses of the 'strcpy' and 'strcat' functions
+ security.insecureAPI.vfork Warn on uses of the 'vfork' function
+ unix.API Check calls to various UNIX/Posix functions
+ unix.Malloc Check for memory leaks, double free, and use-after-free problems. Traces memory managed by malloc()/free().
+ unix.MallocSizeof Check for dubious malloc arguments involving sizeof
+ unix.MismatchedDeallocator Check for mismatched deallocators.
+ unix.Vfork Check for proper usage of vfork
+ unix.cstring.BadSizeArg Check the size argument passed into C string functions for common erroneous patterns
+ unix.cstring.NullArg Check for null pointers being passed as arguments to C string functions
valist.CopyToSelf Check for va_lists which are copied onto itself.
valist.Uninitialized Check for usages of uninitialized (or already released) va_lists.
valist.Unterminated Check for va_lists which are not released by a va_end call.
webkit.NoUncountedMemberChecker
Check for no uncounted member variables.
webkit.RefCntblBaseVirtualDtor Check for any ref-countable base class having virtual destructor.
webkit.UncountedLambdaCapturesChecker
Check uncounted lambda captures.
And this is the output of clang-tidy --list-checks | grep clang-analyzer-:
clang-analyzer-apiModeling.StdCLibraryFunctions
clang-analyzer-apiModeling.TrustNonnull
clang-analyzer-apiModeling.google.GTest
clang-analyzer-apiModeling.llvm.CastValue
clang-analyzer-apiModeling.llvm.ReturnValue
clang-analyzer-core.CallAndMessage
clang-analyzer-core.CallAndMessageModeling
clang-analyzer-core.DivideZero
clang-analyzer-core.DynamicTypePropagation
clang-analyzer-core.NonNullParamChecker
clang-analyzer-core.NonnilStringConstants
clang-analyzer-core.NullDereference
clang-analyzer-core.StackAddrEscapeBase
clang-analyzer-core.StackAddressEscape
clang-analyzer-core.UndefinedBinaryOperatorResult
clang-analyzer-core.VLASize
clang-analyzer-core.builtin.BuiltinFunctions
clang-analyzer-core.builtin.NoReturnFunctions
clang-analyzer-core.uninitialized.ArraySubscript
clang-analyzer-core.uninitialized.Assign
clang-analyzer-core.uninitialized.Branch
clang-analyzer-core.uninitialized.CapturedBlockVariable
clang-analyzer-core.uninitialized.UndefReturn
clang-analyzer-cplusplus.InnerPointer
clang-analyzer-cplusplus.Move
clang-analyzer-cplusplus.NewDelete
clang-analyzer-cplusplus.NewDeleteLeaks
clang-analyzer-cplusplus.PlacementNew
clang-analyzer-cplusplus.PureVirtualCall
clang-analyzer-cplusplus.SelfAssignment
clang-analyzer-cplusplus.SmartPtrModeling
clang-analyzer-cplusplus.VirtualCallModeling
clang-analyzer-deadcode.DeadStores
clang-analyzer-fuchsia.HandleChecker
clang-analyzer-nullability.NullPassedToNonnull
clang-analyzer-nullability.NullReturnedFromNonnull
clang-analyzer-nullability.NullabilityBase
clang-analyzer-nullability.NullableDereferenced
clang-analyzer-nullability.NullablePassedToNonnull
clang-analyzer-nullability.NullableReturnedFromNonnull
clang-analyzer-optin.cplusplus.UninitializedObject
clang-analyzer-optin.cplusplus.VirtualCall
clang-analyzer-optin.mpi.MPI-Checker
clang-analyzer-optin.osx.OSObjectCStyleCast
clang-analyzer-optin.osx.cocoa.localizability.EmptyLocalizationContextChecker
clang-analyzer-optin.osx.cocoa.localizability.NonLocalizedStringChecker
clang-analyzer-optin.performance.GCDAntipattern
clang-analyzer-optin.performance.Padding
clang-analyzer-optin.portability.UnixAPI
clang-analyzer-osx.API
clang-analyzer-osx.MIG
clang-analyzer-osx.NSOrCFErrorDerefChecker
clang-analyzer-osx.NumberObjectConversion
clang-analyzer-osx.OSObjectRetainCount
clang-analyzer-osx.ObjCProperty
clang-analyzer-osx.SecKeychainAPI
clang-analyzer-osx.cocoa.AtSync
clang-analyzer-osx.cocoa.AutoreleaseWrite
clang-analyzer-osx.cocoa.ClassRelease
clang-analyzer-osx.cocoa.Dealloc
clang-analyzer-osx.cocoa.IncompatibleMethodTypes
clang-analyzer-osx.cocoa.Loops
clang-analyzer-osx.cocoa.MissingSuperCall
clang-analyzer-osx.cocoa.NSAutoreleasePool
clang-analyzer-osx.cocoa.NSError
clang-analyzer-osx.cocoa.NilArg
clang-analyzer-osx.cocoa.NonNilReturnValue
clang-analyzer-osx.cocoa.ObjCGenerics
clang-analyzer-osx.cocoa.RetainCount
clang-analyzer-osx.cocoa.RetainCountBase
clang-analyzer-osx.cocoa.RunLoopAutoreleaseLeak
clang-analyzer-osx.cocoa.SelfInit
clang-analyzer-osx.cocoa.SuperDealloc
clang-analyzer-osx.cocoa.UnusedIvars
clang-analyzer-osx.cocoa.VariadicMethodTypes
clang-analyzer-osx.coreFoundation.CFError
clang-analyzer-osx.coreFoundation.CFNumber
clang-analyzer-osx.coreFoundation.CFRetainRelease
clang-analyzer-osx.coreFoundation.containers.OutOfBounds
clang-analyzer-osx.coreFoundation.containers.PointerSizedValues
clang-analyzer-security.FloatLoopCounter
clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling
clang-analyzer-security.insecureAPI.SecuritySyntaxChecker
clang-analyzer-security.insecureAPI.UncheckedReturn
clang-analyzer-security.insecureAPI.bcmp
clang-analyzer-security.insecureAPI.bcopy
clang-analyzer-security.insecureAPI.bzero
clang-analyzer-security.insecureAPI.decodeValueOfObjCType
clang-analyzer-security.insecureAPI.getpw
clang-analyzer-security.insecureAPI.gets
clang-analyzer-security.insecureAPI.mkstemp
clang-analyzer-security.insecureAPI.mktemp
clang-analyzer-security.insecureAPI.rand
clang-analyzer-security.insecureAPI.strcpy
clang-analyzer-security.insecureAPI.vfork
clang-analyzer-unix.API
clang-analyzer-unix.DynamicMemoryModeling
clang-analyzer-unix.Malloc
clang-analyzer-unix.MallocSizeof
clang-analyzer-unix.MismatchedDeallocator
clang-analyzer-unix.Vfork
clang-analyzer-unix.cstring.BadSizeArg
clang-analyzer-unix.cstring.CStringModeling
clang-analyzer-unix.cstring.NullArg
clang-analyzer-valist.CopyToSelf
clang-analyzer-valist.Uninitialized
clang-analyzer-valist.Unterminated
clang-analyzer-valist.ValistBase
clang-analyzer-webkit.NoUncountedMemberChecker
clang-analyzer-webkit.RefCntblBaseVirtualDtor
clang-analyzer-webkit.UncountedLambdaCapturesChecker
The clang-tidy version is 12.0.0.
So, it seems like scan-build is a subset of clang-tidy (as far as the available checks are concerned), and the answer to your question is "yes".

Related

`Error: request to generate code for .compileTime proc`

I have a small helper proc that is supposed to tell me at compile-time whether a type is an object-type or not.
func isObject*[T](val: typedesc[T]): bool {.compileTime.} = T is (object or ref object)
However, when I call this proc with a simple echo to see whether it works, I receive an error:
type A = object
echo isObject(A)
Error: request to generate code for .compileTime proc: isObject
Why is that? It should be perfectly valid to just call this, isObject should just compile to true and in the end what's written there is echo true, why does this cause this cryptic error?
The problem here is that runtime code (The echo call) is trying to work with a compiletime proc.
That is not valid, as the compiler would not replace the function-call with its result, but try to actually call the function at runtime instead. The compiler knows this is invalid behaviour and thus prohibits it by throwing an error, albeit one that isn't that useful.
The only way this can be allowed is if you store the result of the compile-time proc in a compile-time variable, aka a const. These are allowed to be used at runtime.
So the calling code would look more like this instead:
type A = object
const x = isObject(A)
echo x
EDIT:
As Elegantbeef pointed out on nim's discord:
Another alternative is to just do what I thought would happen initially and have that isObject(A) call evaluate fully at compile-time, so that at runtime it goes away and all that's left is it's result, true.
To do so, just use static:
type A = object
echo static(isObject(A))

Why is Dafny allowing uninitialized return result?

In this method:
datatype Results = Foo | Bar
method test() returns (r:Result)
{
}
Dafny verifies OK and test() returns Foo. Which is technically correct (it does return a value of the correct type) however I was expecting Dafny to complain that the result has not been set by the method itself. What test() is doing is similar to doing:
return;
in a C function that is supposed to return an int.
Is there a way to make Dafny verify that a methods results are always set before the method returns?
The flag you want is /definiteAssignment:2:
/definiteAssignment:<n>
0 - ignores definite-assignment rules; this mode is for testing only--it is
not sound
1 (default) - enforces definite-assignment rules for compiled variables and fields
whose types do not support auto-initialization and for ghost variables
and fields whose type is possibly empty
2 - enforces definite-assignment for all non-yield-parameter
variables and fields, regardless of their types
3 - like 2, but also performs checks in the compiler that no nondeterministic
statements are used; thus, a program that passes at this level 3 is one
that the language guarantees that values seen during execution will be
the same in every run of the program
This is what Dafny says on your code says with that flag:
test.dfy(5,0): Error: out-parameter 'r', which is subject to definite-assignment rules, might be uninitialized at this return point

HackLang by Facebook is not strict

Good day,
I have problem. I want to simulate some errors in hacklang.
<?hh
namespace Exsys\HHVM;
class HHVMFacade{
private $vector = Vector {1,2,3};
public function echoProduct() : Vector<string>{
return $this->vector;
}
public function test(Vector<string> $vector) : void{
var_dump($vector);
}
}
Function echoProduct() returns Vector of strings. But private property $vector is Vector of integers. When I call echoFunction and returning value use as argument for function test(). I get
object(HH\Vector)#35357 (3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
Why? I am expecting some error because types mismatch.
There's two things at play here:
Generics aren't reified, so the runtime has no information about them. This means the runtime is only checking that you're returning a Vector.
$this->vector itself isn't typed. This means the type checker (hh_client) treats it as a unknown type. Unknown types match against everything, so there's no problem returning an unknown type where a Vector<string> is expected.
This is to allow you to gradually type your code. Whenever a type isn't known, the type checker just assumes that the developer knows what's happening.
The first thing I'd do is change the file from partial mode to strict mode, which simply involves changing from <?hh to <?hh // strict. This causes the type checker to complain about any missing type information (as well as a couple of other things, like no superglobals and you can't call non-Hack code).
This produces the error:
test.hh:6:13,19: Please add a type hint (Naming[2001])
If you then type $vector as Vector<int> (private Vector<int> $vector), hh_client then produces:
test.hh:9:16,28: Invalid return type (Typing[4110])
test.hh:8:44,49: This is a string
test.hh:6:20,22: It is incompatible with an int
test.hh:8:44,49: Considering that this type argument is invariant with respect to Vector
Which is the error you expected. You can also get this error simply by adding the type to $vector, without switching to strict mode, though I prefer to write my Hack in the strongest mode that the code supports.
With more recent versions of HHVM, the type checker is called whenever Hack code is run (there's an INI flag to turn this off), so causing the type mismatch will also cause execution of the code to fail.

Using Corba string_dup versus using pointer to const

There is something I don't get, please enlighten me.
Is there a difference between the following (client side code)?
1) blah = (const char *)"dummy";
2) blah = CORBA::string_dup("dummy");
... just googling a bit I see string_dup() returns a char * so the 2 may be equivalent.
I was thinking 2) does 2 deep copies and not 1.
I'm firing the question anyway now, please briefly confirm.
Thanks!
const char* blah = "dummy";
The C++ compiler generates a constant array of characters, null-terminated, somewhere in a data section of your executable. blah gets a pointer to it.
char* blah = CORBA::string_dup("dummy");
The function string_dup() is called with an argument that is a pointer to that constant array of characters. string_dup() then allocates memory from the free store and copies the string data into the free-store-allocated memory. The pointer to the free-store memory is returned to the caller. It is the caller's job to dispose of the memory when finished with CORBA::string_free(). Technically the ORB implementation is allowed to use some special free-store, but most likely it is just using the standard heap / free-store that the rest of your application is using.
It is often much better to do this:
CORBA::String_var s = CORBA::string_dup("dummy");
The String_var's destructor will automatically call string_free() when s goes out of scope.

Protobuf message and memcpy inside erlang nif

I'm using protobuf inside nif function (erlang nif) and need to create resource of protobuf message type. I wrote something like this:
ERL_NIF_TERM create_resource(ErlNifEnv *env, const MyClass &msg)
{
size_t size = sizeof(MyClass);
MyClass *class = (MyClass *)enif_alloc_resource(MY_CLASS, size);
memcpy(class, &msg, size);
// class->CopyFrom(&msg);
ERL_NIF_TERM term = enif_make_resource(env, class);
enif_release_resource(class);
return term;
}
The question is.. is it legal for the protobuf message to be copied like this and in cleanup just release it with:
delete pointer
?
Seems that everything is right here, but I'm not shure, cause the constructor of the copied object was not invoked and may be there is some magick with static vars and etc...
Also.. do I need to call CopyFrom after memcpy?
upd: MyClass is C++ class not C
enif_alloc_resource, enif_release_resource, and enif_make_resource do all the memory management for you. You can make it somewhat easier by making your resource type a pointer, in which case you call delete from your defined resource destructor (the function pointer you pass when calling enif_open_resource_type).
As far as what you're doing with memcpy, it's not safe for complex objects. For instance, if one of your class members is a pointer to a dynamically allocated resource which it destroys in its destructor, and you memcpy it, two objects are now sharing that same resource. When one of the objects is destroyed (falling out of scope, delete operator), the other object is left with a pointer to freed memory.
This is why you define copy and assignment constructors if you have a complex class. I'm guessing CopyFrom should, in fact, be both your assignment and copy constructor.

Resources